moves to div renderer

This commit is contained in:
Steve Ruiz 2021-09-11 16:24:03 +01:00
parent bc96414bf7
commit e7987ca451
42 changed files with 1104 additions and 852 deletions

View file

@ -1,7 +1,9 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import * as React from 'react'
import type { TLBounds } from '+types'
import { Utils } from '+utils'
import { useBoundsEvents } from '+hooks'
import { useBoundsEvents, usePosition } from '+hooks'
import { Container } from '+components/container'
import { SVGContainer } from '+components/svg-container'
interface BoundsBgProps {
bounds: TLBounds
@ -11,20 +13,11 @@ interface BoundsBgProps {
export function BoundsBg({ bounds, rotation }: BoundsBgProps): JSX.Element {
const events = useBoundsEvents()
const { width, height } = bounds
const center = Utils.getBoundsCenter(bounds)
return (
<rect
className="tl-bounds-bg"
width={Math.max(1, width)}
height={Math.max(1, height)}
transform={`
rotate(${rotation * (180 / Math.PI)},${center})
translate(${bounds.minX},${bounds.minY})
rotate(${(bounds.rotation || 0) * (180 / Math.PI)}, 0, 0)`}
{...events}
/>
<Container bounds={bounds} rotation={rotation}>
<SVGContainer>
<rect className="tl-bounds-bg" width={bounds.width} height={bounds.height} {...events} />
</SVGContainer>
</Container>
)
}

View file

@ -1,10 +1,13 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import * as React from 'react'
import { TLBoundsEdge, TLBoundsCorner, TLBounds } from '+types'
import { Utils } from '+utils'
import { CenterHandle } from './center-handle'
import { RotateHandle } from './rotate-handle'
import { CornerHandle } from './corner-handle'
import { EdgeHandle } from './edge-handle'
import { usePosition } from '+hooks'
import { Container } from '+components/container'
import { SVGContainer } from '+components/svg-container'
interface BoundsProps {
zoom: number
@ -14,6 +17,27 @@ interface BoundsProps {
viewportWidth: number
}
// function setTransform(elm: SVGSVGElement, padding: number, bounds: TLBounds, rotation: number) {
// const center = Utils.getBoundsCenter(bounds)
// const transform = `
// rotate(${rotation * (180 / Math.PI)},${center})
// translate(${bounds.minX - padding},${bounds.minY - padding})
// rotate(${(bounds.rotation || 0) * (180 / Math.PI)},0,0)`
// elm.setAttribute('transform', transform)
// elm.setAttribute('width', bounds.width + padding * 2 + 'px')
// elm.setAttribute('height', bounds.height + padding * 2 + 'px')
// }
// function setTransform(elm: HTMLDivElement, bounds: TLBounds, rotation = 0) {
// const transform = `
// translate(calc(${bounds.minX}px - var(--tl-padding)),calc(${bounds.minY}px - var(--tl-padding)))
// rotate(${rotation + (bounds.rotation || 0)}rad)
// `
// elm.style.setProperty('transform', transform)
// elm.style.setProperty('width', `calc(${bounds.width}px + (var(--tl-padding) * 2))`)
// elm.style.setProperty('height', `calc(${bounds.height}px + (var(--tl-padding) * 2))`)
// }
export function Bounds({
zoom,
bounds,
@ -23,20 +47,19 @@ export function Bounds({
}: BoundsProps): JSX.Element {
const targetSize = (viewportWidth < 768 ? 16 : 8) / zoom // Touch target size
const size = 8 / zoom // Touch target size
const center = Utils.getBoundsCenter(bounds)
return (
<g
pointerEvents="all"
transform={`
rotate(${rotation * (180 / Math.PI)},${center})
translate(${bounds.minX},${bounds.minY})
rotate(${(bounds.rotation || 0) * (180 / Math.PI)}, 0, 0)`}
>
<Container className="tl-bounds" bounds={bounds} rotation={rotation}>
<SVGContainer>
<CenterHandle bounds={bounds} isLocked={isLocked} />
{!isLocked && (
<>
<EdgeHandle targetSize={targetSize} size={size} bounds={bounds} edge={TLBoundsEdge.Top} />
<EdgeHandle
targetSize={targetSize}
size={size}
bounds={bounds}
edge={TLBoundsEdge.Top}
/>
<EdgeHandle
targetSize={targetSize}
size={size}
@ -82,6 +105,7 @@ export function Bounds({
<RotateHandle targetSize={targetSize} size={size} bounds={bounds} />
</>
)}
</g>
</SVGContainer>
</Container>
)
}

View file

@ -2,7 +2,7 @@ import * as React from 'react'
import type { TLBounds } from '+types'
export class BrushUpdater {
ref = React.createRef<SVGRectElement>()
ref = React.createRef<SVGSVGElement>()
isControlled = false
@ -18,8 +18,7 @@ export class BrushUpdater {
if (!elm) return
elm.setAttribute('opacity', '1')
elm.setAttribute('x', bounds.minX.toString())
elm.setAttribute('y', bounds.minY.toString())
elm.setAttribute('transform', `translate(${bounds.minX.toString()}, ${bounds.minY.toString()})`)
elm.setAttribute('width', bounds.width.toString())
elm.setAttribute('height', bounds.height.toString())
}

View file

@ -4,5 +4,9 @@ import { BrushUpdater } from './BrushUpdater'
export const brushUpdater = new BrushUpdater()
export const Brush = React.memo((): JSX.Element | null => {
return <rect ref={brushUpdater.ref} className="tl-brush" x={0} y={0} width={0} height={0} />
return (
<svg ref={brushUpdater.ref} opacity={0}>
<rect className="tl-brush" x={0} y={0} width="100%" height="100%" />
</svg>
)
})

View file

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react'
import {
usePreventNavigation,
@ -18,24 +19,24 @@ function resetError() {
void null
}
interface CanvasProps<T extends TLShape> {
interface CanvasProps<T extends TLShape, M extends Record<string, unknown>> {
page: TLPage<T, TLBinding>
pageState: TLPageState
hideBounds?: boolean
hideHandles?: boolean
hideIndicators?: boolean
meta?: Record<string, unknown>
meta?: M
}
export function Canvas<T extends TLShape>({
export function Canvas<T extends TLShape, M extends Record<string, unknown>>({
page,
pageState,
meta,
hideHandles = false,
hideBounds = false,
hideIndicators = false,
}: CanvasProps<T>): JSX.Element {
const rCanvas = React.useRef<SVGSVGElement>(null)
}: CanvasProps<T, M>): JSX.Element {
const rCanvas = React.useRef<HTMLDivElement>(null)
const rContainer = React.useRef<HTMLDivElement>(null)
useResizeObserver(rCanvas)
@ -48,14 +49,14 @@ export function Canvas<T extends TLShape>({
const events = useCanvasEvents()
const rGroup = useCameraCss(rContainer, pageState)
const rLayer = useCameraCss(rContainer, pageState)
return (
<div className="tl-container" ref={rContainer}>
<svg id="canvas" className="tl-canvas" ref={rCanvas} {...events}>
<div id="canvas" className="tl-absolute tl-canvas" ref={rCanvas} {...events}>
<ErrorBoundary FallbackComponent={ErrorFallback} onReset={resetError}>
<Defs zoom={pageState.camera.zoom} />
<g ref={rGroup} id="tl-shapes">
{/* <Defs zoom={pageState.camera.zoom} /> */}
<div ref={rLayer} className="tl-absolute tl-layer">
<Page
page={page}
pageState={pageState}
@ -65,9 +66,9 @@ export function Canvas<T extends TLShape>({
meta={meta}
/>
<Brush />
</g>
</div>
</ErrorBoundary>
</svg>
</div>
</div>
)
}

View file

@ -0,0 +1,23 @@
import * as React from 'react'
import type { TLBounds } from '+types'
import { usePosition } from '+hooks'
interface ContainerProps {
bounds: TLBounds
rotation?: number
id?: string
className?: string
children: React.ReactNode
}
export const Container = React.memo(
({ id, bounds, rotation = 0, className, children }: ContainerProps) => {
const rBounds = usePosition(bounds, rotation)
return (
<div id={id} ref={rBounds} className={className + ' tl-positioned'}>
{children}
</div>
)
}
)

View file

@ -0,0 +1 @@
export * from './container'

View file

@ -1,24 +1,41 @@
import * as React from 'react'
import { useHandleEvents } from '+hooks'
import { Container } from '+components/container'
import Utils from '+utils'
import { SVGContainer } from '+components/svg-container'
interface HandleProps {
id: string
point: number[]
zoom: number
}
export const Handle = React.memo(({ id, point, zoom }: HandleProps) => {
export const Handle = React.memo(({ id, point }: HandleProps) => {
const events = useHandleEvents(id)
const bounds = React.useMemo(
() =>
Utils.translateBounds(
{
minX: 0,
minY: 0,
maxX: 32,
maxY: 32,
width: 32,
height: 32,
},
point
),
[point]
)
return (
<g className="tl-handles" transform={`translate(${point})`} {...events}>
<circle
id="handle-bg"
className="tl-handle-bg"
pointerEvents="all"
r={20 / Math.max(1, zoom)}
/>
<use href="#handle" />
<Container bounds={bounds}>
<SVGContainer>
<g className="tl-handles" {...events}>
<circle className="tl-handle-bg" pointerEvents="all" />
<circle className="tl-counter-scaled tl-handle" pointerEvents="none" r={4} />
</g>
</SVGContainer>
</Container>
)
})

View file

@ -4,6 +4,6 @@ import { Handles } from './handles'
describe('handles', () => {
test('mounts component without crashing', () => {
renderWithContext(<Handles zoom={1} shape={mockUtils.box.create({})} />)
renderWithContext(<Handles shape={mockUtils.box.create({ id: 'box' })} />)
})
})

View file

@ -1,35 +1,26 @@
import * as React from 'react'
import { Vec } from '+utils'
import type { TLShape } from '+types'
import { useTLContext } from '+hooks'
import { Handle } from './handle'
interface HandlesProps {
shape: TLShape
zoom: number
}
const toAngle = 180 / Math.PI
export const Handles = React.memo(({ shape, zoom }: HandlesProps): JSX.Element | null => {
const { shapeUtils } = useTLContext()
const center = shapeUtils[shape.type].getCenter(shape)
export const Handles = React.memo(({ shape }: HandlesProps): JSX.Element | null => {
if (shape.handles === undefined) {
return null
}
return (
<g transform={`rotate(${(shape.rotation || 0) * toAngle},${center})`}>
<>
{Object.values(shape.handles).map((handle) => (
<Handle
key={shape.id + '_' + handle.id}
id={handle.id}
point={Vec.add(handle.point, shape.point)}
zoom={zoom}
/>
))}
</g>
</>
)
})

View file

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react'
import type { TLBinding, TLPage, TLPageState, TLShape } from '+types'
import { useSelection, useShapeTree, useHandles, useRenderOnResize, useTLContext } from '+hooks'
@ -7,26 +8,26 @@ import { Handles } from '+components/handles'
import { ShapeNode } from '+components/shape'
import { ShapeIndicator } from '+components/shape-indicator'
interface PageProps<T extends TLShape> {
interface PageProps<T extends TLShape, M extends Record<string, unknown>> {
page: TLPage<T, TLBinding>
pageState: TLPageState
hideBounds: boolean
hideHandles: boolean
hideIndicators: boolean
meta?: Record<string, unknown>
meta?: M
}
/**
* The Page component renders the current page.
*/
export function Page<T extends TLShape>({
export function Page<T extends TLShape, M extends Record<string, unknown>>({
page,
pageState,
hideBounds,
hideHandles,
hideIndicators,
meta,
}: PageProps<T>): JSX.Element {
}: PageProps<T, M>): JSX.Element {
const { callbacks, shapeUtils, inputs } = useTLContext()
const shapeTree = useShapeTree(page, pageState, shapeUtils, inputs.size, meta, callbacks.onChange)
@ -69,7 +70,7 @@ export function Page<T extends TLShape>({
variant="hovered"
/>
)}
{!hideHandles && shapeWithHandles && <Handles shape={shapeWithHandles} zoom={zoom} />}
{!hideHandles && shapeWithHandles && <Handles shape={shapeWithHandles} />}
</>
)
}

View file

@ -13,12 +13,15 @@ import { Canvas } from '../canvas'
import { Inputs } from '../../inputs'
import { useTLTheme, TLContext, TLContextType } from '../../hooks'
export interface RendererProps<T extends TLShape, M extends Record<string, unknown>>
extends Partial<TLCallbacks> {
export interface RendererProps<
T extends TLShape,
E extends HTMLElement | SVGElement,
M extends Record<string, unknown>
> extends Partial<TLCallbacks> {
/**
* An object containing instances of your shape classes.
*/
shapeUtils: TLShapeUtils<T>
shapeUtils: TLShapeUtils<T, E>
/**
* The current page, containing shapes and bindings.
*/
@ -63,7 +66,11 @@ export interface RendererProps<T extends TLShape, M extends Record<string, unkno
* @param props
* @returns
*/
export function Renderer<T extends TLShape, M extends Record<string, unknown>>({
export function Renderer<
T extends TLShape,
E extends SVGElement | HTMLElement,
M extends Record<string, unknown>
>({
shapeUtils,
page,
pageState,
@ -73,17 +80,18 @@ export function Renderer<T extends TLShape, M extends Record<string, unknown>>({
hideIndicators = false,
hideBounds = false,
...rest
}: RendererProps<T, M>): JSX.Element {
}: RendererProps<T, E, M>): JSX.Element {
useTLTheme(theme)
const rScreenBounds = React.useRef<TLBounds>(null)
const rPageState = React.useRef<TLPageState>(pageState)
React.useEffect(() => {
rPageState.current = pageState
}, [pageState])
const [context] = React.useState<TLContextType>(() => ({
const [context] = React.useState<TLContextType<T, E>>(() => ({
callbacks: rest,
shapeUtils,
rScreenBounds,
@ -92,7 +100,7 @@ export function Renderer<T extends TLShape, M extends Record<string, unknown>>({
}))
return (
<TLContext.Provider value={context}>
<TLContext.Provider value={context as TLContextType<T, E>}>
<Canvas
page={page}
pageState={pageState}

View file

@ -4,6 +4,8 @@ import { ShapeIndicator } from './shape-indicator'
describe('shape indicator', () => {
test('mounts component without crashing', () => {
renderWithSvg(<ShapeIndicator shape={mockUtils.box.create({})} variant={'selected'} />)
renderWithSvg(
<ShapeIndicator shape={mockUtils.box.create({ id: 'box1' })} variant={'selected'} />
)
})
})

View file

@ -1,20 +1,25 @@
import * as React from 'react'
import type { TLShape } from '+types'
import { useTLContext } from '+hooks'
import { usePosition, useTLContext } from '+hooks'
export const ShapeIndicator = React.memo(
({ shape, variant }: { shape: TLShape; variant: 'selected' | 'hovered' }) => {
const { shapeUtils } = useTLContext()
const utils = shapeUtils[shape.type]
const center = utils.getCenter(shape)
const rotation = (shape.rotation || 0) * (180 / Math.PI)
const transform = `rotate(${rotation}, ${center}) translate(${shape.point})`
const bounds = utils.getBounds(shape)
const rBounds = usePosition(bounds, shape.rotation)
return (
<g className={variant === 'selected' ? 'tl-selected' : 'tl-hovered'} transform={transform}>
{shapeUtils[shape.type].renderIndicator(shape)}
</g>
<div
ref={rBounds}
className={
'tl-indicator tl-absolute ' + (variant === 'selected' ? 'tl-selected' : 'tl-hovered')
}
>
<svg width="100%" height="100%">
<g className="tl-centered-g">{utils.renderIndicator(shape)}</g>
</svg>
</div>
)
}
)

View file

@ -2,13 +2,15 @@ import { useTLContext } from '+hooks'
import * as React from 'react'
import type { TLShapeUtil, TLRenderInfo, TLShape } from '+types'
interface EditingShapeProps<T extends TLShape> extends TLRenderInfo {
interface EditingShapeProps<T extends TLShape, E extends HTMLElement | SVGElement>
extends TLRenderInfo {
shape: T
utils: TLShapeUtil<T>
utils: TLShapeUtil<T, E>
}
export function EditingTextShape({
export function EditingTextShape<T extends TLShape, E extends HTMLElement | SVGElement>({
shape,
events,
utils,
isEditing,
isBinding,
@ -16,12 +18,12 @@ export function EditingTextShape({
isSelected,
isCurrentParent,
meta,
}: EditingShapeProps<TLShape>) {
}: EditingShapeProps<T, E>) {
const {
callbacks: { onTextChange, onTextBlur, onTextFocus, onTextKeyDown, onTextKeyUp },
} = useTLContext()
const ref = React.useRef<HTMLElement>(null)
const ref = React.useRef<E>(null)
React.useEffect(() => {
// Firefox fix?
@ -32,18 +34,22 @@ export function EditingTextShape({
}, 0)
}, [shape.id])
return utils.render(shape, {
return utils.render({
ref,
shape,
isEditing,
isHovered,
isSelected,
isCurrentParent,
isBinding,
events: {
...events,
onTextChange,
onTextBlur,
onTextFocus,
onTextKeyDown,
onTextKeyUp,
},
meta,
})
}

View file

@ -1,13 +1,9 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import * as React from 'react'
import type { TLShapeUtil, TLRenderInfo, TLShape } from '+types'
interface RenderedShapeProps<T extends TLShape> extends TLRenderInfo {
shape: T
utils: TLShapeUtil<T>
}
export const RenderedShape = React.memo(
function RenderedShape({
<T extends TLShape, E extends SVGElement | HTMLElement, M extends Record<string, unknown>>({
shape,
utils,
isEditing,
@ -15,16 +11,29 @@ export const RenderedShape = React.memo(
isHovered,
isSelected,
isCurrentParent,
events,
meta,
}: RenderedShapeProps<TLShape>) {
return utils.render(shape, {
}: TLRenderInfo<M, E> & {
shape: T
utils: TLShapeUtil<T, E>
}) => {
const ref = utils.getRef(shape)
return (
<utils.render
ref={ref}
{...{
shape,
isEditing,
isBinding,
isHovered,
isSelected,
isCurrentParent,
meta,
})
events,
}}
/>
)
},
(prev, next) => {
// If these have changed, then definitely render

View file

@ -3,7 +3,7 @@ import type { IShapeTreeNode, TLShape, TLShapeUtils } from '+types'
import { Shape } from './shape'
export const ShapeNode = React.memo(
<M extends Record<string, unknown>>({
({
shape,
utils,
children,
@ -13,7 +13,7 @@ export const ShapeNode = React.memo(
isSelected,
isCurrentParent,
meta,
}: { utils: TLShapeUtils<TLShape> } & IShapeTreeNode<M>) => {
}: { utils: TLShapeUtils<TLShape, HTMLElement | SVGElement> } & IShapeTreeNode<TLShape, any>) => {
return (
<>
<Shape

View file

@ -6,7 +6,7 @@ describe('shape', () => {
test('mounts component without crashing', () => {
renderWithSvg(
<Shape
shape={mockUtils.box.create({})}
shape={mockUtils.box.create({ id: 'box' })}
utils={mockUtils[mockUtils.box.type]}
isEditing={false}
isBinding={false}
@ -17,3 +17,6 @@ describe('shape', () => {
)
})
})
// { shape: TLShape; ref: ForwardedRef<HTMLElement | SVGElement>; } & TLRenderInfo<any, any> & RefAttributes<HTMLElement | SVGElement>
// { shape: BoxShape; ref: ForwardedRef<any>; } & TLRenderInfo<any, any> & RefAttributes<any>'

View file

@ -1,10 +1,27 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import * as React from 'react'
import { useShapeEvents } from '+hooks'
import type { IShapeTreeNode, TLShape, TLShapeUtil } from '+types'
import { usePosition, useShapeEvents } from '+hooks'
import type { IShapeTreeNode, TLBounds, TLShape, TLShapeUtil } from '+types'
import { RenderedShape } from './rendered-shape'
import { EditingTextShape } from './editing-text-shape'
import { Container } from '+components/container'
import { SVGContainer } from '+components/svg-container'
export const Shape = <M extends Record<string, unknown>>({
// function setTransform(elm: HTMLDivElement, bounds: TLBounds, rotation = 0) {
// const transform = `
// translate(calc(${bounds.minX}px - var(--tl-padding)),calc(${bounds.minY}px - var(--tl-padding)))
// rotate(${rotation + (bounds.rotation || 0)}rad)
// `
// elm.style.setProperty('transform', transform)
// elm.style.setProperty('width', `calc(${bounds.width}px + (var(--tl-padding) * 2))`)
// elm.style.setProperty('height', `calc(${bounds.height}px + (var(--tl-padding) * 2))`)
// }
export const Shape = <
T extends TLShape,
E extends SVGElement | HTMLElement,
M extends Record<string, unknown>
>({
shape,
utils,
isEditing,
@ -13,19 +30,20 @@ export const Shape = <M extends Record<string, unknown>>({
isSelected,
isCurrentParent,
meta,
}: { utils: TLShapeUtil<TLShape> } & IShapeTreeNode<M>) => {
}: IShapeTreeNode<T, M> & {
utils: TLShapeUtil<T, E>
}) => {
const bounds = utils.getBounds(shape)
const events = useShapeEvents(shape.id, isCurrentParent)
const center = utils.getCenter(shape)
const rotation = (shape.rotation || 0) * (180 / Math.PI)
const transform = `rotate(${rotation}, ${center}) translate(${shape.point})`
return (
<g
className={isCurrentParent ? 'tl-shape-group tl-current-parent' : 'tl-shape-group'}
<Container
id={shape.id}
transform={transform}
{...events}
className={'tl-shape' + (isCurrentParent ? 'tl-current-parent' : '')}
bounds={bounds}
rotation={shape.rotation}
>
<SVGContainer>
{isEditing && utils.isEditableText ? (
<EditingTextShape
shape={shape}
@ -36,19 +54,22 @@ export const Shape = <M extends Record<string, unknown>>({
isSelected={isSelected}
utils={utils}
meta={meta}
events={events}
/>
) : (
<RenderedShape
shape={shape}
utils={utils}
utils={utils as any}
isBinding={isBinding}
isCurrentParent={isCurrentParent}
isEditing={isEditing}
isHovered={isHovered}
isSelected={isSelected}
meta={meta}
meta={meta as any}
events={events}
/>
)}
</g>
</SVGContainer>
</Container>
)
}

View file

@ -0,0 +1 @@
export * from './svg-container'

View file

@ -0,0 +1,13 @@
import * as React from 'react'
interface SvgContainerProps {
children: React.ReactNode
}
export const SVGContainer = React.memo(({ children }: SvgContainerProps) => {
return (
<svg className="tl-positioned-svg">
<g className="tl-centered-g">{children}</g>
</svg>
)
})

View file

@ -14,3 +14,4 @@ export * from './useHandleEvents'
export * from './useHandles'
export * from './usePreventNavigation'
export * from './useBoundsEvents'
export * from './usePosition'

View file

@ -3,21 +3,29 @@ import * as React from 'react'
import type { TLPageState } from '+types'
export function useCameraCss(ref: React.RefObject<HTMLDivElement>, pageState: TLPageState) {
const rGroup = React.useRef<SVGGElement>(null)
const rLayer = React.useRef<HTMLDivElement>(null)
// Update the tl-zoom CSS variable when the zoom changes
React.useEffect(() => {
ref.current!.style.setProperty('--tl-zoom', pageState.camera.zoom.toString())
}, [pageState.camera.zoom])
// Update the group's position when the camera moves or zooms
React.useEffect(() => {
const {
zoom,
point: [x = 0, y = 0],
} = pageState.camera
rGroup.current?.setAttribute('transform', `scale(${zoom}) translate(${x} ${y})`)
}, [pageState.camera])
ref.current!.style.setProperty('--tl-camera-x', pageState.camera.point[0] + 'px')
ref.current!.style.setProperty('--tl-camera-y', pageState.camera.point[1] + 'px')
}, [pageState.camera.point])
return rGroup
// Update the group's position when the camera moves or zooms
// React.useEffect(() => {
// const {
// zoom,
// point: [x = 0, y = 0],
// } = pageState.camera
// rLayer.current?.style.setProperty(
// 'transform',
// `scale(${zoom},${zoom}) translate(${x}px,${y}px)`
// )
// }, [pageState.camera])
return rLayer
}

View file

@ -0,0 +1,20 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import * as React from 'react'
import type { TLBounds } from '+types'
export function usePosition(bounds: TLBounds, rotation = 0) {
const rBounds = React.useRef<HTMLDivElement>(null)
React.useEffect(() => {
const elm = rBounds.current!
const transform = `
translate(calc(${bounds.minX}px - var(--tl-padding)),calc(${bounds.minY}px - var(--tl-padding)))
rotate(${rotation + (bounds.rotation || 0)}rad)
`
elm.style.setProperty('transform', transform)
elm.style.setProperty('width', `calc(${bounds.width}px + (var(--tl-padding) * 2))`)
elm.style.setProperty('height', `calc(${bounds.height}px + (var(--tl-padding) * 2))`)
}, [rBounds, bounds, rotation])
return rBounds
}

View file

@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import * as React from 'react'
export function usePreventNavigation(rCanvas: React.RefObject<SVGGElement>): void {
export function usePreventNavigation(rCanvas: React.RefObject<HTMLDivElement>): void {
React.useEffect(() => {
const preventGestureNavigation = (event: TouchEvent) => {
event.preventDefault()

View file

@ -6,10 +6,10 @@ function canvasToScreen(point: number[], camera: TLPageState['camera']): number[
return [(point[0] + camera.point[0]) * camera.zoom, (point[1] + camera.point[1]) * camera.zoom]
}
export function useSelection<T extends TLShape>(
export function useSelection<T extends TLShape, E extends HTMLElement | SVGElement>(
page: TLPage<T, TLBinding>,
pageState: TLPageState,
shapeUtils: TLShapeUtils<T>
shapeUtils: TLShapeUtils<T, E>
) {
const { rScreenBounds } = useTLContext()
const { selectedIds } = pageState

View file

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import * as React from 'react'
import type {
@ -13,8 +14,8 @@ import type {
import { Utils, Vec } from '+utils'
function addToShapeTree<T extends TLShape, M extends Record<string, unknown>>(
shape: TLShape,
branch: IShapeTreeNode<M>[],
shape: T,
branch: IShapeTreeNode<T, M>[],
shapes: TLPage<T, TLBinding>['shapes'],
pageState: {
bindingTargetId?: string
@ -27,7 +28,7 @@ function addToShapeTree<T extends TLShape, M extends Record<string, unknown>>(
},
meta?: M
) {
const node: IShapeTreeNode<M> = {
const node: IShapeTreeNode<T, M> = {
shape,
isCurrentParent: pageState.currentParentId === shape.id,
isEditing: pageState.editingId === shape.id,
@ -37,7 +38,7 @@ function addToShapeTree<T extends TLShape, M extends Record<string, unknown>>(
(shape.children ? shape.children.includes(pageState.hoveredId) : false)
: false,
isBinding: pageState.bindingTargetId === shape.id,
meta,
meta: meta as any,
}
branch.push(node)
@ -54,14 +55,18 @@ function addToShapeTree<T extends TLShape, M extends Record<string, unknown>>(
}
}
function shapeIsInViewport(shape: TLShape, bounds: TLBounds, viewport: TLBounds) {
function shapeIsInViewport(bounds: TLBounds, viewport: TLBounds) {
return Utils.boundsContain(viewport, bounds) || Utils.boundsCollide(viewport, bounds)
}
export function useShapeTree<T extends TLShape, M extends Record<string, unknown>>(
export function useShapeTree<
T extends TLShape,
E extends SVGElement | HTMLElement,
M extends Record<string, unknown>
>(
page: TLPage<T, TLBinding>,
pageState: TLPageState,
shapeUtils: TLShapeUtils<T>,
shapeUtils: TLShapeUtils<T, E>,
size: number[],
meta?: M,
onChange?: TLCallbacks['onChange']
@ -100,7 +105,7 @@ export function useShapeTree<T extends TLShape, M extends Record<string, unknown
// Don't hide selected shapes (this breaks certain drag interactions)
if (
selectedIds.includes(shape.id) ||
shapeIsInViewport(shape, shapeUtils[shape.type as T['type']].getBounds(shape), viewport)
shapeIsInViewport(shapeUtils[shape.type as T['type']].getBounds(shape), viewport)
) {
if (shape.parentId === page.id) {
shapesIdsToRender.add(shape.id)
@ -132,7 +137,7 @@ export function useShapeTree<T extends TLShape, M extends Record<string, unknown
// Populate the shape tree
const tree: IShapeTreeNode<M>[] = []
const tree: IShapeTreeNode<T, M>[] = []
const info = { ...pageState, bindingTargetId }

View file

@ -111,6 +111,9 @@ const tlcss = css`
.tl-container {
--tl-zoom: 1;
--tl-scale: calc(1 / var(--tl-zoom));
--tl-camera-x: 0px;
--tl-camera-y: 0px;
--tl-padding: calc(32px * var(--tl-scale));
position: relative;
box-sizing: border-box;
width: 100%;
@ -127,6 +130,37 @@ const tlcss = css`
box-sizing: border-box;
}
.tl-absolute {
position: absolute;
top: 0px;
left: 0px;
transform-origin: center center;
}
.tl-positioned {
position: absolute;
top: 0px;
left: 0px;
transform-origin: center center;
pointer-events: none;
display: flex;
align-items: center;
justify-content: center;
}
.tl-positioned-svg {
width: 100%;
height: 100%;
pointer-events: none;
}
.tl-layer {
transform: scale(var(--tl-zoom), var(--tl-zoom))
translate(var(--tl-camera-x), var(--tl-camera-y));
height: 0;
width: 0;
}
.tl-counter-scaled {
transform: scale(var(--tl-scale));
}
@ -190,6 +224,10 @@ const tlcss = css`
pointer-events: none;
}
.tl-bounds {
pointer-events: none;
}
.tl-bounds-center {
fill: transparent;
stroke: var(--tl-selectStroke);
@ -210,10 +248,7 @@ const tlcss = css`
}
.tl-canvas {
position: absolute;
overflow: hidden;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
touch-action: none;
@ -256,6 +291,7 @@ const tlcss = css`
fill: transparent;
stroke: none;
pointer-events: all;
r: calc(20 / max(1, var(--tl-zoom)));
}
.tl-binding-indicator {
@ -264,18 +300,22 @@ const tlcss = css`
stroke: var(--tl-selected);
}
.tl-shape-group {
.tl-shape {
outline: none;
}
.tl-shape-group > *[data-shy='true'] {
.tl-shape > *[data-shy='true'] {
opacity: 0;
}
.tl-shape-group:hover > *[data-shy='true'] {
.tl-shape:hover > *[data-shy='true'] {
opacity: 1;
}
.tl-centered-g {
transform: translate(var(--tl-padding), var(--tl-padding));
}
.tl-current-parent > *[data-shy='true'] {
opacity: 1;
}

View file

@ -2,16 +2,18 @@ import * as React from 'react'
import type { Inputs } from '+inputs'
import type { TLCallbacks, TLShape, TLBounds, TLPageState, TLShapeUtils } from '+types'
export interface TLContextType {
export interface TLContextType<T extends TLShape, E extends HTMLElement | SVGElement> {
id?: string
callbacks: Partial<TLCallbacks>
shapeUtils: TLShapeUtils<TLShape>
shapeUtils: TLShapeUtils<T, E>
rPageState: React.MutableRefObject<TLPageState>
rScreenBounds: React.MutableRefObject<TLBounds | null>
inputs: Inputs
}
export const TLContext = React.createContext<TLContextType>({} as TLContextType)
export const TLContext = React.createContext<TLContextType<any, any>>(
{} as TLContextType<TLShape, HTMLElement | SVGElement>
)
export function useTLContext() {
const context = React.useContext(TLContext)

View file

@ -1,13 +1,13 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import * as React from 'react'
import { TLShapeUtil, TLShape, TLBounds, TLRenderInfo, TLTransformInfo } from '+types'
import { TLShapeUtil, TLShape, TLShapeProps, TLBounds, TLRenderInfo, TLTransformInfo } from '+types'
import Utils, { Intersect } from '+utils'
export interface BoxShape extends TLShape {
size: number[]
}
export class Box extends TLShapeUtil<BoxShape> {
export class Box extends TLShapeUtil<BoxShape, SVGGElement> {
type = 'box'
defaultProps = {
@ -21,13 +21,15 @@ export class Box extends TLShapeUtil<BoxShape> {
rotation: 0,
}
create(props: Partial<BoxShape>) {
return { ...this.defaultProps, ...props }
}
render(shape: BoxShape, info: TLRenderInfo): JSX.Element {
return <rect width={100} height={100} fill="none" stroke="black" />
render = React.forwardRef<SVGGElement, TLShapeProps<BoxShape, SVGGElement>>(
({ shape, events }, ref) => {
return (
<g ref={ref} {...events}>
<rect width={shape.size[0]} height={shape.size[1]} fill="none" stroke="black" />
</g>
)
}
)
renderIndicator(shape: BoxShape) {
return <rect width={100} height={100} />

View file

@ -1,6 +1,6 @@
import type { TLShapeUtils } from '+types'
import { Box, BoxShape } from './box'
export const mockUtils: TLShapeUtils<BoxShape> = {
export const mockUtils: TLShapeUtils<BoxShape, SVGGElement> = {
box: new Box(),
}

View file

@ -2,6 +2,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* --------------------- Primary -------------------- */
import React, { ForwardedRef } from 'react'
export type Patch<T> = Partial<{ [P in keyof T]: T | Partial<T> | Patch<T[P]> }>
export interface TLPage<T extends TLShape, B extends TLBinding> {
@ -54,21 +56,35 @@ export interface TLShape {
isAspectRatioLocked?: boolean
}
export type TLShapeUtils<T extends TLShape> = Record<string, TLShapeUtil<T>>
export type TLShapeUtils<T extends TLShape, E extends SVGElement | HTMLElement> = Record<
string,
TLShapeUtil<T, E>
>
export interface TLRenderInfo<M = any, T extends SVGElement | HTMLElement = any> {
ref?: React.RefObject<T>
export interface TLRenderInfo<M = any, E = any> {
isEditing: boolean
isBinding: boolean
isHovered: boolean
isSelected: boolean
isCurrentParent: boolean
meta: M extends any ? M : never
events: {
onPointerDown: (e: React.PointerEvent<E>) => void
onPointerUp: (e: React.PointerEvent<E>) => void
onPointerEnter: (e: React.PointerEvent<E>) => void
onPointerMove: (e: React.PointerEvent<E>) => void
onPointerLeave: (e: React.PointerEvent<E>) => void
onTextChange?: TLCallbacks['onTextChange']
onTextBlur?: TLCallbacks['onTextBlur']
onTextFocus?: TLCallbacks['onTextFocus']
onTextKeyDown?: TLCallbacks['onTextKeyDown']
onTextKeyUp?: TLCallbacks['onTextKeyUp']
meta: M extends any ? M : never
}
}
export interface TLShapeProps<T extends TLShape, E = any, M = any> extends TLRenderInfo<M, E> {
ref: ForwardedRef<E>
shape: T
}
export interface TLTool {
@ -261,18 +277,26 @@ export interface TLBezierCurveSegment {
/* Shape Utility */
/* -------------------------------------------------- */
export abstract class TLShapeUtil<T extends TLShape> {
export abstract class TLShapeUtil<T extends TLShape, E extends HTMLElement | SVGElement> {
refMap = new Map<string, React.RefObject<E>>()
boundsCache = new WeakMap<TLShape, TLBounds>()
isEditableText = false
isAspectRatioLocked = false
canEdit = false
canBind = false
abstract type: T['type']
abstract defaultProps: T
abstract render(shape: T, info: TLRenderInfo): JSX.Element | null
abstract render: React.ForwardRefExoticComponent<
{ shape: T; ref: React.ForwardedRef<E> } & TLRenderInfo & React.RefAttributes<E>
>
abstract renderIndicator(shape: T): JSX.Element | null
@ -303,6 +327,14 @@ export abstract class TLShapeUtil<T extends TLShape> {
return [bounds.width / 2, bounds.height / 2]
}
getRef(shape: T): React.RefObject<E> {
if (!this.refMap.has(shape.id)) {
this.refMap.set(shape.id, React.createRef<E>())
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.refMap.get(shape.id)!
}
getBindingPoint(
shape: T,
fromShape: TLShape,
@ -315,7 +347,8 @@ export abstract class TLShapeUtil<T extends TLShape> {
return undefined
}
create(props: Partial<T>): T {
create(props: { id: string } & Partial<T>): T {
this.refMap.set(props.id, React.createRef<E>())
return { ...this.defaultProps, ...props }
}
@ -380,15 +413,15 @@ export abstract class TLShapeUtil<T extends TLShape> {
/* -------------------- Internal -------------------- */
export interface IShapeTreeNode<M extends Record<string, unknown>> {
shape: TLShape
children?: IShapeTreeNode<M>[]
export interface IShapeTreeNode<T extends TLShape, M extends Record<string, unknown>> {
shape: T
children?: IShapeTreeNode<TLShape, M>[]
isEditing: boolean
isBinding: boolean
isHovered: boolean
isSelected: boolean
isCurrentParent: boolean
meta?: M
meta?: M extends any ? M : never
}
/* -------------------------------------------------- */

View file

@ -8,18 +8,31 @@ export const tldrawShapeUtils: TLDrawShapeUtils = {
[TLDrawShapeType.Arrow]: new Arrow(),
[TLDrawShapeType.Text]: new Text(),
[TLDrawShapeType.Group]: new Group(),
}
} as TLDrawShapeUtils
export type ShapeByType<T extends keyof TLDrawShapeUtils> = TLDrawShapeUtils[T]
export function getShapeUtilsByType<T extends TLDrawShape>(shape: T): TLDrawShapeUtil<T> {
return tldrawShapeUtils[shape.type as T['type']] as TLDrawShapeUtil<T>
export function getShapeUtilsByType<T extends TLDrawShape>(
shape: T
): TLDrawShapeUtil<T, HTMLElement | SVGElement> {
return tldrawShapeUtils[shape.type as T['type']] as unknown as TLDrawShapeUtil<
T,
HTMLElement | SVGElement
>
}
export function getShapeUtils<T extends TLDrawShape>(shape: T): TLDrawShapeUtil<T> {
return tldrawShapeUtils[shape.type as T['type']] as TLDrawShapeUtil<T>
export function getShapeUtils<T extends TLDrawShape>(
shape: T
): TLDrawShapeUtil<T, HTMLElement | SVGElement> {
return tldrawShapeUtils[shape.type as T['type']] as unknown as TLDrawShapeUtil<
T,
HTMLElement | SVGElement
>
}
export function createShape<TLDrawShape>(type: TLDrawShapeType, props: Partial<TLDrawShape>) {
export function createShape<TLDrawShape>(
type: TLDrawShapeType,
props: { id: string } & Partial<TLDrawShape>
) {
return tldrawShapeUtils[type].create(props)
}

View file

@ -7,6 +7,7 @@ import {
Intersect,
TLHandle,
TLPointerInfo,
TLShapeProps,
} from '@tldraw/core'
import getStroke from 'perfect-freehand'
import { defaultStyle, getPerfectDashProps, getShapeStyle } from '~shape/shape-styles'
@ -22,7 +23,7 @@ import {
TLDrawRenderInfo,
} from '~types'
export class Arrow extends TLDrawShapeUtil<ArrowShape> {
export class Arrow extends TLDrawShapeUtil<ArrowShape, SVGGElement> {
type = TLDrawShapeType.Arrow as const
toolType = TLDrawToolType.Handle
canStyleFill = false
@ -70,7 +71,8 @@ export class Arrow extends TLDrawShapeUtil<ArrowShape> {
return next.handles !== prev.handles || next.style !== prev.style
}
render = (shape: ArrowShape, { meta }: TLDrawRenderInfo) => {
render = React.forwardRef<SVGGElement, TLShapeProps<ArrowShape, SVGGElement>>(
({ shape, meta, events }) => {
const {
handles: { start, bend, end },
decorations = {},
@ -218,6 +220,7 @@ export class Arrow extends TLDrawShapeUtil<ArrowShape> {
const sw = strokeWidth * 1.618
return (
<g {...events}>
<g pointerEvents="none">
{shaftPath}
{startArrowHead && (
@ -247,8 +250,10 @@ export class Arrow extends TLDrawShapeUtil<ArrowShape> {
/>
)}
</g>
</g>
)
}
)
renderIndicator(shape: ArrowShape) {
const path = Utils.getFromCache(this.simplePathCache, shape.handles, () => getArrowPath(shape))

View file

@ -1,17 +1,10 @@
import * as React from 'react'
import { TLBounds, Utils, Vec, TLTransformInfo, Intersect } from '@tldraw/core'
import { TLBounds, Utils, Vec, TLTransformInfo, Intersect, TLShapeProps } from '@tldraw/core'
import getStroke, { getStrokePoints } from 'perfect-freehand'
import { defaultStyle, getShapeStyle } from '~shape/shape-styles'
import {
DrawShape,
DashStyle,
TLDrawShapeUtil,
TLDrawShapeType,
TLDrawToolType,
TLDrawRenderInfo,
} from '~types'
import { DrawShape, DashStyle, TLDrawShapeUtil, TLDrawShapeType, TLDrawToolType } from '~types'
export class Draw extends TLDrawShapeUtil<DrawShape> {
export class Draw extends TLDrawShapeUtil<DrawShape, SVGGElement> {
type = TLDrawShapeType.Draw as const
toolType = TLDrawToolType.Draw
@ -37,7 +30,8 @@ export class Draw extends TLDrawShapeUtil<DrawShape> {
return next.points !== prev.points || next.style !== prev.style
}
render(shape: DrawShape, { meta, isEditing }: TLDrawRenderInfo): JSX.Element {
render = React.forwardRef<SVGGElement, TLShapeProps<DrawShape, SVGGElement>>(
({ shape, meta, events, isEditing }) => {
const { points, style } = shape
const styles = getShapeStyle(style, meta.isDarkMode)
@ -53,6 +47,7 @@ export class Draw extends TLDrawShapeUtil<DrawShape> {
const sw = strokeWidth * 0.618
return (
<g {...events}>
<circle
r={strokeWidth * 0.618}
fill={styles.stroke}
@ -60,6 +55,7 @@ export class Draw extends TLDrawShapeUtil<DrawShape> {
strokeWidth={sw}
pointerEvents="all"
/>
</g>
)
}
@ -80,7 +76,7 @@ export class Draw extends TLDrawShapeUtil<DrawShape> {
: Utils.getFromCache(this.drawPathCache, points, () => getDrawStrokePath(shape, false))
return (
<>
<g {...events}>
{shouldFill && (
<path
d={polygonPathData}
@ -100,7 +96,7 @@ export class Draw extends TLDrawShapeUtil<DrawShape> {
strokeLinecap="round"
pointerEvents="all"
/>
</>
</g>
)
}
@ -125,7 +121,7 @@ export class Draw extends TLDrawShapeUtil<DrawShape> {
const sw = strokeWidth * 1.618
return (
<>
<g {...events}>
<path
d={path}
fill={shouldFill ? styles.fill : 'none'}
@ -146,9 +142,10 @@ export class Draw extends TLDrawShapeUtil<DrawShape> {
strokeLinecap="round"
pointerEvents="stroke"
/>
</>
</g>
)
}
)
renderIndicator(shape: DrawShape): JSX.Element {
const { points } = shape

View file

@ -1,5 +1,5 @@
import * as React from 'react'
import { Utils, TLTransformInfo, TLBounds, Intersect, Vec } from '@tldraw/core'
import { Utils, TLTransformInfo, TLBounds, Intersect, TLShapeProps, Vec } from '@tldraw/core'
import {
ArrowShape,
DashStyle,
@ -15,7 +15,7 @@ import getStroke from 'perfect-freehand'
// TODO
// [ ] Improve indicator shape for drawn shapes
export class Ellipse extends TLDrawShapeUtil<EllipseShape> {
export class Ellipse extends TLDrawShapeUtil<EllipseShape, SVGGElement> {
type = TLDrawShapeType.Ellipse as const
toolType = TLDrawToolType.Bounds
pathCache = new WeakMap<EllipseShape, string>([])
@ -37,7 +37,8 @@ export class Ellipse extends TLDrawShapeUtil<EllipseShape> {
return next.radius !== prev.radius || next.style !== prev.style
}
render(shape: EllipseShape, { meta, isBinding }: TLDrawRenderInfo) {
render = React.forwardRef<SVGGElement, TLShapeProps<EllipseShape, SVGGElement>>(
({ shape, meta, isBinding, events }) => {
const {
radius: [radiusX, radiusY],
style,
@ -55,7 +56,7 @@ export class Ellipse extends TLDrawShapeUtil<EllipseShape> {
)
return (
<>
<g {...events}>
{isBinding && (
<ellipse
className="tl-binding-indicator"
@ -83,7 +84,7 @@ export class Ellipse extends TLDrawShapeUtil<EllipseShape> {
strokeLinecap="round"
strokeLinejoin="round"
/>
</>
</g>
)
}
@ -101,7 +102,7 @@ export class Ellipse extends TLDrawShapeUtil<EllipseShape> {
const sw = strokeWidth * 1.618
return (
<>
<g {...events}>
{isBinding && (
<ellipse
className="tl-binding-indicator"
@ -125,9 +126,10 @@ export class Ellipse extends TLDrawShapeUtil<EllipseShape> {
strokeLinecap="round"
strokeLinejoin="round"
/>
</>
</g>
)
}
)
renderIndicator(shape: EllipseShape) {
const {

View file

@ -1,12 +1,11 @@
import * as React from 'react'
import { TLBounds, Utils, Vec, TLTransformInfo, Intersect } from '@tldraw/core'
import { TLBounds, Utils, Vec, Intersect, TLShapeProps } from '@tldraw/core'
import { defaultStyle, getPerfectDashProps } from '~shape/shape-styles'
import {
GroupShape,
TLDrawShapeUtil,
TLDrawShapeType,
TLDrawToolType,
TLDrawRenderInfo,
ColorStyle,
DashStyle,
ArrowShape,
@ -15,7 +14,7 @@ import {
// TODO
// [ ] - Find bounds based on common bounds of descendants
export class Group extends TLDrawShapeUtil<GroupShape> {
export class Group extends TLDrawShapeUtil<GroupShape, SVGGElement> {
type = TLDrawShapeType.Group as const
toolType = TLDrawToolType.Bounds
canBind = true
@ -39,7 +38,8 @@ export class Group extends TLDrawShapeUtil<GroupShape> {
return next.size !== prev.size || next.style !== prev.style
}
render(shape: GroupShape, { isBinding, isHovered, isSelected }: TLDrawRenderInfo) {
render = React.forwardRef<SVGGElement, TLShapeProps<GroupShape, SVGGElement>>(
({ shape, isBinding, isHovered, isSelected, events }) => {
const { id, size } = shape
const sw = 2
@ -77,7 +77,7 @@ export class Group extends TLDrawShapeUtil<GroupShape> {
})
return (
<>
<g {...events}>
{isBinding && (
<rect
className="tl-binding-indicator"
@ -87,11 +87,19 @@ export class Group extends TLDrawShapeUtil<GroupShape> {
height={size[1] + 64}
/>
)}
<rect x={0} y={0} width={size[0]} height={size[1]} fill="transparent" pointerEvents="all" />
<rect
x={0}
y={0}
width={size[0]}
height={size[1]}
fill="transparent"
pointerEvents="all"
/>
<g pointerEvents="stroke">{paths}</g>
</>
</g>
)
}
)
renderIndicator(shape: GroupShape) {
const [width, height] = shape.size

View file

@ -1,5 +1,5 @@
import * as React from 'react'
import { TLBounds, Utils, Vec, TLTransformInfo, Intersect } from '@tldraw/core'
import { TLBounds, Utils, Vec, TLTransformInfo, Intersect, TLShapeProps } from '@tldraw/core'
import getStroke from 'perfect-freehand'
import { getPerfectDashProps, defaultStyle, getShapeStyle } from '~shape/shape-styles'
import {
@ -8,18 +8,16 @@ import {
TLDrawShapeUtil,
TLDrawShapeType,
TLDrawToolType,
TLDrawRenderInfo,
ArrowShape,
} from '~types'
// TODO
// [ ] - Make sure that fill does not extend drawn shape at corners
export class Rectangle extends TLDrawShapeUtil<RectangleShape> {
export class Rectangle extends TLDrawShapeUtil<RectangleShape, SVGGElement> {
type = TLDrawShapeType.Rectangle as const
toolType = TLDrawToolType.Bounds
canBind = true
pathCache = new WeakMap<number[], string>([])
defaultProps: RectangleShape = {
@ -38,16 +36,21 @@ export class Rectangle extends TLDrawShapeUtil<RectangleShape> {
return next.size !== prev.size || next.style !== prev.style
}
render(shape: RectangleShape, { isBinding, meta }: TLDrawRenderInfo) {
render = React.forwardRef<SVGGElement, TLShapeProps<RectangleShape, SVGGElement>>(
({ shape, isBinding, meta, events }, ref) => {
const { id, size, style } = shape
const styles = getShapeStyle(style, meta.isDarkMode)
const strokeWidth = +styles.strokeWidth
React.useEffect(() => {
console.log(this.refMap.get(shape.id))
}, [])
if (style.dash === DashStyle.Draw) {
const pathData = Utils.getFromCache(this.pathCache, shape.size, () => renderPath(shape))
return (
<>
<g ref={ref} {...events}>
{isBinding && (
<rect
className="tl-binding-indicator"
@ -73,7 +76,7 @@ export class Rectangle extends TLDrawShapeUtil<RectangleShape> {
strokeWidth={styles.strokeWidth}
pointerEvents="all"
/>
</>
</g>
)
}
@ -113,7 +116,7 @@ export class Rectangle extends TLDrawShapeUtil<RectangleShape> {
})
return (
<>
<g ref={ref} {...events}>
{isBinding && (
<rect
className="tl-binding-indicator"
@ -134,9 +137,10 @@ export class Rectangle extends TLDrawShapeUtil<RectangleShape> {
pointerEvents="all"
/>
<g pointerEvents="stroke">{paths}</g>
</>
</g>
)
}
)
renderIndicator(shape: RectangleShape) {
const {
@ -162,6 +166,7 @@ export class Rectangle extends TLDrawShapeUtil<RectangleShape> {
}
getBounds(shape: RectangleShape) {
console.log(this.refMap.get(shape.id))
const bounds = Utils.getFromCache(this.boundsCache, shape, () => {
const [width, height] = shape.size
return {

View file

@ -1,14 +1,7 @@
import * as React from 'react'
import { TLBounds, Utils, Vec, TLTransformInfo, Intersect } from '@tldraw/core'
import { TLBounds, Utils, Vec, TLTransformInfo, Intersect, TLShapeProps } from '@tldraw/core'
import { getShapeStyle, getFontSize, getFontStyle, defaultStyle } from '~shape/shape-styles'
import {
TextShape,
TLDrawShapeUtil,
TLDrawShapeType,
TLDrawRenderInfo,
TLDrawToolType,
ArrowShape,
} from '~types'
import { TextShape, TLDrawShapeUtil, TLDrawShapeType, TLDrawToolType, ArrowShape } from '~types'
import styled from '~styles'
import TextAreaUtils from './text-utils'
@ -56,7 +49,7 @@ if (typeof window !== 'undefined') {
melm = getMeasurementDiv()
}
export class Text extends TLDrawShapeUtil<TextShape> {
export class Text extends TLDrawShapeUtil<TextShape, SVGGElement> {
type = TLDrawShapeType.Text as const
toolType = TLDrawToolType.Text
isAspectRatioLocked = true
@ -90,31 +83,20 @@ export class Text extends TLDrawShapeUtil<TextShape> {
)
}
render(
shape: TextShape,
{
ref,
meta,
isEditing,
isBinding,
onTextBlur,
onTextChange,
onTextFocus,
onTextKeyDown,
onTextKeyUp,
}: TLDrawRenderInfo
): JSX.Element {
render = React.forwardRef<SVGGElement, TLShapeProps<TextShape, SVGGElement>>(
({ shape, meta, isEditing, isBinding, events }, ref) => {
const rInput = React.useRef<HTMLTextAreaElement>(null)
const { id, text, style } = shape
const styles = getShapeStyle(style, meta.isDarkMode)
const font = getFontStyle(shape.style)
const bounds = this.getBounds(shape)
function handleChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
onTextChange?.(id, normalizeText(e.currentTarget.value))
events.onTextChange?.(id, normalizeText(e.currentTarget.value))
}
function handleKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {
onTextKeyDown?.(id, e.key)
events.onTextKeyDown?.(id, e.key)
if (e.key === 'Escape') return
@ -128,12 +110,12 @@ export class Text extends TLDrawShapeUtil<TextShape> {
TextAreaUtils.indent(e.currentTarget)
}
onTextChange?.(id, normalizeText(e.currentTarget.value))
events.onTextChange?.(id, normalizeText(e.currentTarget.value))
}
}
function handleKeyUp(e: React.KeyboardEvent<HTMLTextAreaElement>) {
onTextKeyUp?.(id, e.key)
events.onTextKeyUp?.(id, e.key)
}
function handleBlur(e: React.FocusEvent<HTMLTextAreaElement>) {
@ -144,20 +126,22 @@ export class Text extends TLDrawShapeUtil<TextShape> {
}
setTimeout(() => {
onTextBlur?.(id)
events.onTextBlur?.(id)
}, 0)
}
function handleFocus(e: React.FocusEvent<HTMLTextAreaElement>) {
if (document.activeElement === e.currentTarget) {
e.currentTarget.select()
onTextFocus?.(id)
events.onTextFocus?.(id)
}
}
function handlePointerDown() {
if (ref && ref.current.selectionEnd !== 0) {
ref.current.selectionEnd = 0
const elm = rInput.current
if (!elm) return
if (elm.selectionEnd !== 0) {
elm.selectionEnd = 0
}
}
@ -167,7 +151,7 @@ export class Text extends TLDrawShapeUtil<TextShape> {
if (!isEditing) {
return (
<>
<g ref={ref} {...events}>
{isBinding && (
<rect
className="tl-binding-indicator"
@ -199,14 +183,10 @@ export class Text extends TLDrawShapeUtil<TextShape> {
{str}
</text>
))}
</>
</g>
)
}
if (ref === undefined) {
throw Error('This component should receive a ref when editing.')
}
return (
<foreignObject
width={bounds.width}
@ -215,7 +195,7 @@ export class Text extends TLDrawShapeUtil<TextShape> {
onPointerDown={(e) => e.stopPropagation()}
>
<StyledTextArea
ref={ref as React.RefObject<HTMLTextAreaElement>}
ref={rInput}
style={{
font,
color: styles.stroke,
@ -240,6 +220,7 @@ export class Text extends TLDrawShapeUtil<TextShape> {
</foreignObject>
)
}
)
renderIndicator(): JSX.Element | null {
return null

View file

@ -13,7 +13,9 @@ import type {
} from '~types'
export class TLDR {
static getShapeUtils<T extends TLDrawShape>(shape: T | T['type']): TLDrawShapeUtil<T> {
static getShapeUtils<T extends TLDrawShape>(
shape: T | T['type']
): TLDrawShapeUtil<T, HTMLElement | SVGElement> {
return getShapeUtils(typeof shape === 'string' ? ({ type: shape } as T) : shape)
}

View file

@ -72,7 +72,7 @@ const defaultState: Data = {
settings: {
isPenMode: false,
isDarkMode: false,
isZoomSnap: true,
isZoomSnap: false,
isDebugMode: process.env.NODE_ENV === 'development',
isReadonlyMode: false,
nudgeDistanceLarge: 10,

View file

@ -199,11 +199,17 @@ export type TLDrawShape =
| TextShape
| GroupShape
export abstract class TLDrawShapeUtil<T extends TLDrawShape> extends TLShapeUtil<T> {
export abstract class TLDrawShapeUtil<
T extends TLDrawShape,
E extends HTMLElement | SVGElement
> extends TLShapeUtil<T, E> {
abstract toolType: TLDrawToolType
}
export type TLDrawShapeUtils = Record<TLDrawShapeType, TLDrawShapeUtil<TLDrawShape>>
export type TLDrawShapeUtils = Record<
TLDrawShapeType,
TLDrawShapeUtil<TLDrawShape, HTMLElement | SVGElement>
>
export interface ArrowBinding extends TLBinding {
type: 'arrow'