@weasel-js/core 1.11.1 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +184 -0
- package/dist/WeaselProvider.js +1 -1
- package/dist/affordances/pathAnchors.js +10 -6
- package/dist/affordances/pathAnchors.js.map +1 -1
- package/dist/barrel/canvas.js +3 -1
- package/dist/barrel/paint.js +4 -4
- package/dist/barrel/paths.js +8 -4
- package/dist/barrel/renderer.js +3 -2
- package/dist/barrel/routing.js +4 -4
- package/dist/barrel/scene.js +2 -1
- package/dist/barrel/text.js +2 -2
- package/dist/barrel/viewport.js +6 -2
- package/dist/canvas/Canvas.js +2 -1
- package/dist/canvas/Canvas.js.map +1 -1
- package/dist/canvas/CanvasView.js +23 -34
- package/dist/canvas/CanvasView.js.map +1 -1
- package/dist/canvas/ModalityHud.js +1 -1
- package/dist/canvas/NodeShape.js +4 -1
- package/dist/canvas/NodeShape.js.map +1 -1
- package/dist/canvas/SceneCanvas/ActionsProviderIfRoot.js +1 -1
- package/dist/canvas/SceneCanvas/DepRegistryProviderIfRoot.js +1 -1
- package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js +1 -1
- package/dist/canvas/SceneCanvas/SurfaceDeclarations.js +23 -0
- package/dist/canvas/SceneCanvas/SurfaceDeclarations.js.map +1 -0
- package/dist/canvas/SceneCanvas/canvasPassThrough.js +1 -0
- package/dist/canvas/SceneCanvas/canvasPassThrough.js.map +1 -1
- package/dist/canvas/SceneCanvas/props.js.map +1 -1
- package/dist/canvas/SceneCanvas/scenePointQuery.js +7 -3
- package/dist/canvas/SceneCanvas/scenePointQuery.js.map +1 -1
- package/dist/canvas/SceneCanvas/useActionTunings.js +6 -1
- package/dist/canvas/SceneCanvas/useActionTunings.js.map +1 -1
- package/dist/canvas/SceneCanvas/useCanvasDevtoolsRoot.js +1 -0
- package/dist/canvas/SceneCanvas/useCanvasDevtoolsRoot.js.map +1 -1
- package/dist/canvas/SceneCanvas/useCanvasTools.js +7 -2
- package/dist/canvas/SceneCanvas/useCanvasTools.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneCanvasHandle.js +9 -3
- package/dist/canvas/SceneCanvas/useSceneCanvasHandle.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js +10 -2
- package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneCanvasTools.js +1 -0
- package/dist/canvas/SceneCanvas/useSceneCanvasTools.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneGestureDispatcher.js +19 -4
- package/dist/canvas/SceneCanvas/useSceneGestureDispatcher.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneStandardActions.js +2 -1
- package/dist/canvas/SceneCanvas/useSceneStandardActions.js.map +1 -1
- package/dist/canvas/SceneCanvas.js +11 -10
- package/dist/canvas/SceneCanvas.js.map +1 -1
- package/dist/canvas/ViewMarker.js +35 -0
- package/dist/canvas/ViewMarker.js.map +1 -0
- package/dist/canvas/defaultDrawOne.js +2 -0
- package/dist/canvas/defaultDrawOne.js.map +1 -1
- package/dist/canvas/deps/booleans.js +2 -1
- package/dist/canvas/deps/booleans.js.map +1 -1
- package/dist/canvas/deps/hitTestArea.js +2 -2
- package/dist/canvas/deps/hitTestArea.js.map +1 -1
- package/dist/canvas/deps/insert.js +6 -2
- package/dist/canvas/deps/insert.js.map +1 -1
- package/dist/canvas/deps/pathEditCommits.js +3 -7
- package/dist/canvas/deps/pathEditCommits.js.map +1 -1
- package/dist/canvas/drawnBounds.js +11 -3
- package/dist/canvas/drawnBounds.js.map +1 -1
- package/dist/canvas/inheritedPaints.js +44 -0
- package/dist/canvas/inheritedPaints.js.map +1 -0
- package/dist/canvas/nodeShapes/derivedPainter.js +15 -16
- package/dist/canvas/nodeShapes/derivedPainter.js.map +1 -1
- package/dist/canvas/nodeShapes/nodePaint.js +13 -34
- package/dist/canvas/nodeShapes/nodePaint.js.map +1 -1
- package/dist/canvas/nodeShapes/pathPainter.js +9 -8
- package/dist/canvas/nodeShapes/pathPainter.js.map +1 -1
- package/dist/canvas/nodeShapes/rectFallbackPainter.js +4 -5
- package/dist/canvas/nodeShapes/rectFallbackPainter.js.map +1 -1
- package/dist/canvas/nodeShapes/shapePainter.js +11 -10
- package/dist/canvas/nodeShapes/shapePainter.js.map +1 -1
- package/dist/canvas/nodeShapes/textPainter.js +13 -12
- package/dist/canvas/nodeShapes/textPainter.js.map +1 -1
- package/dist/canvas/pickReach.js +3 -3
- package/dist/canvas/pickReach.js.map +1 -1
- package/dist/canvas/pickWalk.js +3 -1
- package/dist/canvas/pickWalk.js.map +1 -1
- package/dist/canvas/renderSceneToPixels.js +1 -1
- package/dist/canvas/renderSceneToPixels.js.map +1 -1
- package/dist/canvas/sceneSlotWiring.js +2 -1
- package/dist/canvas/sceneSlotWiring.js.map +1 -1
- package/dist/canvas/sceneViewRender.js +2 -1
- package/dist/canvas/sceneViewRender.js.map +1 -1
- package/dist/canvas/surfaceContribution.js +12 -8
- package/dist/canvas/surfaceContribution.js.map +1 -1
- package/dist/canvas/useCanvasView.js +4 -2
- package/dist/canvas/useCanvasView.js.map +1 -1
- package/dist/canvas/useLayerStack.js +6 -2
- package/dist/canvas/useLayerStack.js.map +1 -1
- package/dist/canvas/useViewAim.js +121 -0
- package/dist/canvas/useViewAim.js.map +1 -0
- package/dist/canvas/useViewNesting.js +3 -2
- package/dist/canvas/useViewNesting.js.map +1 -1
- package/dist/canvas/useViewRegistrySurface.js +4 -2
- package/dist/canvas/useViewRegistrySurface.js.map +1 -1
- package/dist/canvas/viewMarkers.js +63 -0
- package/dist/canvas/viewMarkers.js.map +1 -0
- package/dist/canvas/viewRegistry.js +27 -1
- package/dist/canvas/viewRegistry.js.map +1 -1
- package/dist/core/pages/pageEdits.js +2 -3
- package/dist/core/pages/pageEdits.js.map +1 -1
- package/dist/core/paint/meshKindLazy.js +59 -2
- package/dist/core/paint/meshKindLazy.js.map +1 -1
- package/dist/core/scene/clipNothing.js +13 -0
- package/dist/core/scene/clipNothing.js.map +1 -0
- package/dist/core/scene/depMemo.js +11 -3
- package/dist/core/scene/depMemo.js.map +1 -1
- package/dist/core/scene/dependents.js +7 -1
- package/dist/core/scene/dependents.js.map +1 -1
- package/dist/core/scene/derivedParts.js +10 -11
- package/dist/core/scene/derivedParts.js.map +1 -1
- package/dist/core/scene/effectivePose.js +7 -2
- package/dist/core/scene/effectivePose.js.map +1 -1
- package/dist/core/scene/fontReads.js +37 -0
- package/dist/core/scene/fontReads.js.map +1 -0
- package/dist/core/scene/inheritedPaint.js +75 -0
- package/dist/core/scene/inheritedPaint.js.map +1 -0
- package/dist/core/scene/kitRegistry.js +5 -0
- package/dist/core/scene/kitRegistry.js.map +1 -1
- package/dist/core/scene/nodeMemo.js +15 -7
- package/dist/core/scene/nodeMemo.js.map +1 -1
- package/dist/core/scene/pathEffects/blend.js.map +1 -1
- package/dist/core/scene/pathEffects/derive.js +7 -2
- package/dist/core/scene/pathEffects/derive.js.map +1 -1
- package/dist/core/scene/pathEffects/effects.js +3 -1
- package/dist/core/scene/pathEffects/effects.js.map +1 -1
- package/dist/core/scene/pathEffects/textAlong.js +95 -0
- package/dist/core/scene/pathEffects/textAlong.js.map +1 -0
- package/dist/{cornerHandles-BHuoMs1o.d.ts → cornerHandles-p8fDIAKt.d.ts} +2 -1
- package/dist/{depSchema-BpZNOv7q.d.ts → depSchema-mG19aEdD.d.ts} +61 -13
- package/dist/devtools/registry.js +4 -4
- package/dist/devtools/registry.js.map +1 -1
- package/dist/features/measure/measureContribution.js +4 -2
- package/dist/features/measure/measureContribution.js.map +1 -1
- package/dist/features/modes/modeTriggers.js +7 -3
- package/dist/features/modes/modeTriggers.js.map +1 -1
- package/dist/features/pathEffects/effectSources.js +60 -0
- package/dist/features/pathEffects/effectSources.js.map +1 -0
- package/dist/features/pathEffects/readSource.js +17 -1
- package/dist/features/pathEffects/readSource.js.map +1 -1
- package/dist/features/pathEffects/textItems.js +53 -0
- package/dist/features/pathEffects/textItems.js.map +1 -0
- package/dist/features/pathEffects/useEffectSourcesLayer.js +57 -0
- package/dist/features/pathEffects/useEffectSourcesLayer.js.map +1 -0
- package/dist/features/paths/pathEditState.js +5 -2
- package/dist/features/paths/pathEditState.js.map +1 -1
- package/dist/features/text/sceneTextDrafts.js +65 -0
- package/dist/features/text/sceneTextDrafts.js.map +1 -0
- package/dist/features/text/textHitAt.js +31 -2
- package/dist/features/text/textHitAt.js.map +1 -1
- package/dist/features/text/useSceneTextEdit.js +22 -18
- package/dist/features/text/useSceneTextEdit.js.map +1 -1
- package/dist/features/viewports/aim.js +105 -0
- package/dist/features/viewports/aim.js.map +1 -0
- package/dist/features/viewports/viewMarker.js +82 -0
- package/dist/features/viewports/viewMarker.js.map +1 -0
- package/dist/features/viewports/viewMarkerDrag.js +55 -0
- package/dist/features/viewports/viewMarkerDrag.js.map +1 -0
- package/dist/index.d.ts +500 -201
- package/dist/index.js +23 -12
- package/dist/interactions/actions/booleans/booleans.js +2 -1
- package/dist/interactions/actions/booleans/booleans.js.map +1 -1
- package/dist/interactions/actions/booleans/operands.js +6 -5
- package/dist/interactions/actions/booleans/operands.js.map +1 -1
- package/dist/interactions/actions/clipboard/action.js +27 -17
- package/dist/interactions/actions/clipboard/action.js.map +1 -1
- package/dist/interactions/actions/defaults/anchorEditing.js +44 -23
- package/dist/interactions/actions/defaults/anchorEditing.js.map +1 -1
- package/dist/interactions/actions/defaults/anchorJoin.js +12 -6
- package/dist/interactions/actions/defaults/anchorJoin.js.map +1 -1
- package/dist/interactions/actions/defaults/bendSegment.js +7 -4
- package/dist/interactions/actions/defaults/bendSegment.js.map +1 -1
- package/dist/interactions/actions/defaults/cancelGesture.js +11 -8
- package/dist/interactions/actions/defaults/cancelGesture.js.map +1 -1
- package/dist/interactions/actions/defaults/contextMenu.js +17 -8
- package/dist/interactions/actions/defaults/contextMenu.js.map +1 -1
- package/dist/interactions/actions/defaults/createPaintAction.js +1 -1
- package/dist/interactions/actions/defaults/createPaintAction.js.map +1 -1
- package/dist/interactions/actions/defaults/delete.js +28 -14
- package/dist/interactions/actions/defaults/delete.js.map +1 -1
- package/dist/interactions/actions/defaults/duplicate.js +11 -8
- package/dist/interactions/actions/defaults/duplicate.js.map +1 -1
- package/dist/interactions/actions/defaults/enterPathEdit.js +19 -9
- package/dist/interactions/actions/defaults/enterPathEdit.js.map +1 -1
- package/dist/interactions/actions/defaults/escape.js +11 -8
- package/dist/interactions/actions/defaults/escape.js.map +1 -1
- package/dist/interactions/actions/defaults/exitPathEdit.js +7 -4
- package/dist/interactions/actions/defaults/exitPathEdit.js.map +1 -1
- package/dist/interactions/actions/defaults/group.js +19 -13
- package/dist/interactions/actions/defaults/group.js.map +1 -1
- package/dist/interactions/actions/defaults/ingest.js +10 -4
- package/dist/interactions/actions/defaults/ingest.js.map +1 -1
- package/dist/interactions/actions/defaults/insertPathAnchor.js +7 -4
- package/dist/interactions/actions/defaults/insertPathAnchor.js.map +1 -1
- package/dist/interactions/actions/defaults/nudge.js +8 -2
- package/dist/interactions/actions/defaults/nudge.js.map +1 -1
- package/dist/interactions/actions/defaults/pathEditTools.js +11 -8
- package/dist/interactions/actions/defaults/pathEditTools.js.map +1 -1
- package/dist/interactions/actions/defaults/pinchZoom.js +7 -4
- package/dist/interactions/actions/defaults/pinchZoom.js.map +1 -1
- package/dist/interactions/actions/defaults/reorder.js +24 -6
- package/dist/interactions/actions/defaults/reorder.js.map +1 -1
- package/dist/interactions/actions/defaults/selectAll.js +8 -5
- package/dist/interactions/actions/defaults/selectAll.js.map +1 -1
- package/dist/interactions/actions/defaults/setFill.js +7 -3
- package/dist/interactions/actions/defaults/setFill.js.map +1 -1
- package/dist/interactions/actions/defaults/setFillOpacity.js +1 -1
- package/dist/interactions/actions/defaults/setStroke.js +12 -11
- package/dist/interactions/actions/defaults/setStroke.js.map +1 -1
- package/dist/interactions/actions/defaults/setStrokeOpacity.js +1 -1
- package/dist/interactions/actions/defaults/toolActivate.js +7 -1
- package/dist/interactions/actions/defaults/toolActivate.js.map +1 -1
- package/dist/interactions/actions/defaults/toolResetToDefault.js +7 -4
- package/dist/interactions/actions/defaults/toolResetToDefault.js.map +1 -1
- package/dist/interactions/actions/defaults/undoRedo.js +19 -13
- package/dist/interactions/actions/defaults/undoRedo.js.map +1 -1
- package/dist/interactions/actions/defaults/viewportWheelPan.js +16 -7
- package/dist/interactions/actions/defaults/viewportWheelPan.js.map +1 -1
- package/dist/interactions/actions/defaults/viewportZoom.js +24 -6
- package/dist/interactions/actions/defaults/viewportZoom.js.map +1 -1
- package/dist/interactions/actions/edit-anchors/action.js +7 -4
- package/dist/interactions/actions/edit-anchors/action.js.map +1 -1
- package/dist/interactions/actions/flip/action.js +8 -2
- package/dist/interactions/actions/flip/action.js.map +1 -1
- package/dist/interactions/actions/insert/repositionAction.js +2 -1
- package/dist/interactions/actions/insert/repositionAction.js.map +1 -1
- package/dist/interactions/actions/move/action.js +7 -4
- package/dist/interactions/actions/move/action.js.map +1 -1
- package/dist/interactions/actions/outlines/createOutlinesAction.js +8 -5
- package/dist/interactions/actions/outlines/createOutlinesAction.js.map +1 -1
- package/dist/interactions/actions/outlines/outlineStroke.js +5 -3
- package/dist/interactions/actions/outlines/outlineStroke.js.map +1 -1
- package/dist/interactions/actions/pathCommands/cutJoin.js +8 -5
- package/dist/interactions/actions/pathCommands/cutJoin.js.map +1 -1
- package/dist/interactions/actions/resize/cornerHandles.js +2 -1
- package/dist/interactions/actions/resize/cornerHandles.js.map +1 -1
- package/dist/interactions/actions/selectionSubtree.js +12 -7
- package/dist/interactions/actions/selectionSubtree.js.map +1 -1
- package/dist/interactions/actions/transform-again/action.js +8 -5
- package/dist/interactions/actions/transform-again/action.js.map +1 -1
- package/dist/json.d.ts +4 -0
- package/dist/json.js +3 -0
- package/dist/kitSettingsSchema.js +8 -1
- package/dist/kitSettingsSchema.js.map +1 -1
- package/dist/{math-CrJULaZI.d.ts → math-B56zxVs5.d.ts} +10 -1
- package/dist/math.d.ts +1 -1
- package/dist/math.js +2 -1
- package/dist/resize.d.ts +1 -1
- package/dist/test-seams.d.ts +2 -2
- package/dist/tools/builtin/ellipse/useEllipseTool.js +1 -0
- package/dist/tools/builtin/ellipse/useEllipseTool.js.map +1 -1
- package/dist/tools/builtin/eyedropper/useEyedropperTool.js +2 -1
- package/dist/tools/builtin/eyedropper/useEyedropperTool.js.map +1 -1
- package/dist/tools/builtin/hand/dragPanContribution.js +4 -1
- package/dist/tools/builtin/hand/dragPanContribution.js.map +1 -1
- package/dist/tools/builtin/hand/useHandTool.js +7 -4
- package/dist/tools/builtin/hand/useHandTool.js.map +1 -1
- package/dist/tools/builtin/image/useImageTool.js +1 -0
- package/dist/tools/builtin/image/useImageTool.js.map +1 -1
- package/dist/tools/builtin/lasso/useLassoTool.js +1 -0
- package/dist/tools/builtin/lasso/useLassoTool.js.map +1 -1
- package/dist/tools/builtin/line/useLineTool.js +1 -0
- package/dist/tools/builtin/line/useLineTool.js.map +1 -1
- package/dist/tools/builtin/measure/useMeasureTool.js +12 -5
- package/dist/tools/builtin/measure/useMeasureTool.js.map +1 -1
- package/dist/tools/builtin/pen/usePenTool.js +14 -6
- package/dist/tools/builtin/pen/usePenTool.js.map +1 -1
- package/dist/tools/builtin/pencil/usePencilTool.js +1 -0
- package/dist/tools/builtin/pencil/usePencilTool.js.map +1 -1
- package/dist/tools/builtin/polygon/usePolygonTool.js +13 -4
- package/dist/tools/builtin/polygon/usePolygonTool.js.map +1 -1
- package/dist/tools/builtin/rect/useRectTool.js +1 -0
- package/dist/tools/builtin/rect/useRectTool.js.map +1 -1
- package/dist/tools/builtin/select/adapterPointQuery.js +3 -2
- package/dist/tools/builtin/select/adapterPointQuery.js.map +1 -1
- package/dist/tools/builtin/select/pressDecision.js +32 -0
- package/dist/tools/builtin/select/pressDecision.js.map +1 -0
- package/dist/tools/builtin/select/selectionContributions.js +22 -13
- package/dist/tools/builtin/select/selectionContributions.js.map +1 -1
- package/dist/tools/builtin/select/useSelectTool.js +13 -10
- package/dist/tools/builtin/select/useSelectTool.js.map +1 -1
- package/dist/tools/builtin/slice/useSliceTool.js +22 -8
- package/dist/tools/builtin/slice/useSliceTool.js.map +1 -1
- package/dist/tools/builtin/star/useStarTool.js +13 -4
- package/dist/tools/builtin/star/useStarTool.js.map +1 -1
- package/dist/tools/builtin/sticky/stickyNode.js +4 -1
- package/dist/tools/builtin/sticky/stickyNode.js.map +1 -1
- package/dist/tools/builtin/sticky/useStickyTool.js +10 -5
- package/dist/tools/builtin/sticky/useStickyTool.js.map +1 -1
- package/dist/tools/builtin/text/useTextTool.js +3 -1
- package/dist/tools/builtin/text/useTextTool.js.map +1 -1
- package/dist/util/paint.js +1 -3
- package/dist/util/paint.js.map +1 -1
- package/dist/version.js +1 -1
- package/package.json +28 -24
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Canvas.js","names":[],"sources":["../../src/canvas/Canvas.tsx"],"sourcesContent":["/**\n * Low-level WebGL surface + viewport primitive. Composes layers into a single GL render pass,\n * applies a view transform, and delivers hover to the layers that ask for it. It routes no\n * gesture: `<SceneCanvas>` mounts the gesture dispatcher on this same element. Canvas owns NO\n * scene-shaped state — selection, picking, kind registry, scene-aware overlays all live in\n * `<SceneCanvas>`, which wraps it.\n *\n * The `layers` prop is a map keyed by slot name, every slot already a layer. Standard slots\n * render at a canonical position; custom entries (any other key, value carrying `.layer`) insert\n * at `after`/`before` an existing slot, defaulting to the top.\n *\n * @internal\n * @deprecated Bare `<Canvas>` is not a supported consumer surface.\n * Use `<SceneCanvas>` instead.\n */\n\nimport { forwardRef, useCallback, useEffect, useInsertionEffect, useLayoutEffect, useRef } from 'react';\nimport type React from 'react';\nimport type { CanvasExtensionApi } from './canvasExtension';\nimport { registerMountedCanvas } from './mountedCanvases';\nimport { useViewHelpers } from './useViewHelpers';\nimport { useViewLayerGate } from './useViewLayerGate';\nimport { useSurfaceInput } from './useSurfaceInput';\nimport { useOptionalViewRegistry } from './viewRegistry';\nimport { useCanvasSurface } from './useCanvasSurface';\nimport type { CanvasHelpers } from './useViewHelpers';\nimport type { CanvasProps } from './canvasProps';\nimport { useLatest } from '@weasel-js/react';\nimport { SurfaceCanvas } from './SurfaceCanvas';\nimport { useSurfaceSize } from './useSurfaceSize';\nimport type { SelectionApi } from 'core/selection/useSelection';\nimport { AUTO_POSE_DESCRIPTOR } from 'core/geometry/autoPoseDescriptor';\nimport type { PoseDescriptor } from 'interactions/actions/resize/geometry';\nimport { useDebugSink } from '../debug/useDebugSink';\nimport { useToolCursor } from './useToolCursor';\nimport { useCanvasElements } from './useCanvasElements';\nimport { alwaysVisible, useExtraLayers } from './useExtraLayers';\nimport { usePaintedCursor } from './usePaintedCursor';\nimport { useCanvasHandle } from './useCanvasHandle';\nimport { useComposedLayers, useSlotLayers } from './useLayerStack';\nimport { useViewRegistrySurface } from './useViewRegistrySurface';\nimport { useCanvasPaint, usePaintedVersion } from './useCanvasPaint';\nimport { layerHover } from './layerHover';\nimport { useClientToWorld } from './useClientToWorld';\n\nexport type { CanvasProps, CanvasRetainOptions } from './canvasProps';\n\nconst NO_SELECTION: SelectionApi['current'] = [];\n\nfunction CanvasInner<TPose>(\n props: CanvasProps<TPose>,\n ref: React.ForwardedRef<CanvasExtensionApi>,\n) {\n const {\n paintInto, inputElement, tools, viewState, style, getIsVisible, layerVisibility, layerOrder,\n helpersRef, debugSinkRef,\n poseDescriptor: geometry = AUTO_POSE_DESCRIPTOR as unknown as PoseDescriptor<TPose>,\n } = props;\n\n const { sink: debugSink, overlay: debugOverlay, frameStats, getDebug } = useDebugSink(props.debug);\n const elements = useCanvasElements(paintInto, inputElement);\n const { canvasRef, ownCanvasRef, detached } = elements;\n const { width, height } = useSurfaceSize(props, ownCanvasRef);\n\n // Read by `hitTestExtras`, which is built once and must see live values.\n const helpersForLayersRef = useRef<CanvasHelpers<TPose> | null>(null);\n const dimsRef = useLatest({ width, height });\n // Which layers reach the screen, and which chrome within them: asked by the\n // paint and by every hit-test.\n const gateRef = useLatest({ getIsVisible, layerVisibility, layerOrder });\n\n // The frame loop paints; a committed render only marks the surface dirty, so\n // no prop can reach the paint without repainting it. The thunk defers to\n // `useCanvasPaint` below, which needs inputs this render has not computed yet.\n const paintRef = useRef<() => boolean>(() => false);\n const { lease, requestRedraw, subscribeFrame, subscribeBeforePaint, subscribeResume } = useCanvasSurface(\n useCallback(() => paintRef.current(), []),\n { syncPaint: props.syncPaint ?? false, target: canvasRef, dpr: props.dpr, redrawOn: props.redrawOn, shaders: props.shaders, onCommit: 'redraw' },\n );\n const { getPaintedVersion, markPainted } = usePaintedVersion(props.contentVersion);\n const { extrasRef, extrasVersion, registerLayer, hitTestExtrasIn } = useExtraLayers(gateRef);\n\n const {\n viewRef, setView, getView, subscribeView,\n adoptControlled, announceControlled, clearSubscribers,\n } = viewState;\n\n const toWorld = useClientToWorld(canvasRef, props.clientToWorld, viewRef);\n\n useLayoutEffect(() => {\n const element = canvasRef.current;\n if (!element) return;\n return registerMountedCanvas({ element, getView });\n }, [canvasRef, detached, inputElement, getView]);\n\n const { paintedCursor, paintedCursorLayer, cursorSink } = usePaintedCursor(canvasRef, requestRedraw);\n\n const frame = { viewRef, dimsRef, helpersRef: helpersForLayersRef };\n useCanvasHandle(ref, { ...elements, inputElement, paintCanvas: paintInto?.canvas }, frame, {\n hitTestExtrasIn, clientToWorld: toWorld, requestRedraw, subscribeFrame, subscribeBeforePaint,\n subscribeResume, registerLayer, getView, setView, subscribeView,\n getPaintedVersion, paintedCursor, cursorSink, getDebug,\n });\n\n const viewRegistry = useOptionalViewRegistry();\n\n // One view's overlay-aware state. A hook, so N views are N components each\n // calling it once — not a loop in this body.\n const layers = useSlotLayers(props.layers, tools, props.backgroundFill, props.decorationLayer);\n const { helpers: viewHelpers } = useViewHelpers<TPose>({\n adapter: props.adapter, geometry, boundsOf: props.boundsOf, boundsOfPose: props.boundsOfPose,\n nodes: props.nodes, gestureSource: props.gestureSource, previewPoseExtra: props.previewPoseExtra,\n getScale: () => viewRef.current.scale,\n selection: props.selection?.current ?? NO_SELECTION,\n getIsVisible: () => gateRef.current.getIsVisible?.() ?? alwaysVisible,\n layerIsPainted: useViewLayerGate(layerVisibility, layerOrder, () => layers),\n });\n const helpersForLayers: CanvasHelpers<TPose> = { ...viewHelpers, getDebug: () => debugSink, viewId: null };\n\n useViewRegistrySurface(viewRegistry, layers, frame, { requestRedraw, hitTestExtrasIn, clientToWorld: toWorld });\n const layersWithDebug = useComposedLayers(layers, {\n viewRegistry, debugOverlay, extrasRef, extrasVersion, cursorLayer: paintedCursorLayer,\n }, requestRedraw);\n\n // Everything the paint, hit-testing and the view registry read that a React\n // render owns. `useLatest` and the insertion effect below publish committed\n // renders only, ahead of every layout effect in the commit, any of which may\n // ask for a sync paint.\n const paintInputsRef = useLatest({\n layers: layersWithDebug, width, height, debugSink, frameStats,\n dpr: props.dpr, layerGroups: props.layerGroups, shaders: props.shaders,\n flattenTolerance: props.flattenTolerance, retain: props.retain, imageMinification: props.imageMinification,\n });\n useInsertionEffect(() => {\n adoptControlled();\n helpersForLayersRef.current = helpersForLayers;\n if (helpersRef) helpersRef.current = helpersForLayers;\n if (debugSinkRef) debugSinkRef.current = debugSink;\n });\n useLayoutEffect(() => {\n announceControlled();\n });\n\n useCanvasPaint(paintRef, lease, elements, { ...frame, inputsRef: paintInputsRef, gateRef }, markPainted);\n useEffect(() => clearSubscribers, [clearSubscribers]);\n\n useToolCursor(cursorSink, tools, detached ? inputElement : null, style?.cursor);\n\n useSurfaceInput(canvasRef, {\n focusOnPress: props.autoFocusOnPointerDown ?? true,\n onFocus: props.onFocus,\n onBlur: props.onBlur,\n ...layerHover(layersWithDebug, {\n viewRef, toWorld, layerVisibility, layerOrder, dims: { width, height },\n }),\n });\n\n if (detached) return null;\n\n return (\n <SurfaceCanvas\n ref={elements.setOwnCanvas}\n width={props.width}\n height={props.height}\n tabIndex={props.tabIndex ?? 0} aria-label={props['aria-label']}\n className={props.className} style={style}\n />\n );\n}\n\n/** Forward-ref'd `<canvas>` wrapper. Generic over the pose type, inferred from the\n * `adapter` prop. */\nexport const Canvas = forwardRef(CanvasInner) as <TPose = unknown>(\n props: CanvasProps<TPose> & { ref?: React.ForwardedRef<CanvasExtensionApi> },\n) => ReturnType<typeof CanvasInner>;\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,eAAwC,CAAC;AAE/C,SAAS,YACP,OACA,KACA;CACA,MAAM,EACJ,WAAW,cAAc,OAAO,WAAW,OAAO,cAAc,iBAAiB,YACjF,YAAY,cACZ,gBAAgB,WAAW,yBACzB;CAEJ,MAAM,EAAE,MAAM,WAAW,SAAS,cAAc,YAAY,aAAa,aAAa,MAAM,KAAK;CACjG,MAAM,WAAW,kBAAkB,WAAW,YAAY;CAC1D,MAAM,EAAE,WAAW,cAAc,aAAa;CAC9C,MAAM,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY;CAG5D,MAAM,sBAAsB,OAAoC,IAAI;CACpE,MAAM,UAAU,UAAU;EAAE;EAAO;CAAO,CAAC;CAG3C,MAAM,UAAU,UAAU;EAAE;EAAc;EAAiB;CAAW,CAAC;CAKvE,MAAM,WAAW,aAA4B,KAAK;CAClD,MAAM,EAAE,OAAO,eAAe,gBAAgB,sBAAsB,oBAAoB,iBACtF,kBAAkB,SAAS,QAAQ,GAAG,CAAC,CAAC,GACxC;EAAE,WAAW,MAAM,aAAa;EAAO,QAAQ;EAAW,KAAK,MAAM;EAAK,UAAU,MAAM;EAAU,SAAS,MAAM;EAAS,UAAU;CAAS,CACjJ;CACA,MAAM,EAAE,mBAAmB,gBAAgB,kBAAkB,MAAM,cAAc;CACjF,MAAM,EAAE,WAAW,eAAe,eAAe,oBAAoB,eAAe,OAAO;CAE3F,MAAM,EACJ,SAAS,SAAS,SAAS,eAC3B,iBAAiB,oBAAoB,qBACnC;CAEJ,MAAM,UAAU,iBAAiB,WAAW,MAAM,eAAe,OAAO;CAExE,sBAA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,QAAQ,MAAM;EAAQ,mBAAmB,MAAM;CAC3F,CAAC;CACD,yBAAyB;EACvB,gBAAgB;EAChB,oBAAoB,UAAU;EAC9B,IAAI,YAAY,WAAW,UAAU;EACrC,IAAI,cAAc,aAAa,UAAU;CAC3C,CAAC;CACD,sBAAsB;EACpB,mBAAmB;CACrB,CAAC;CAED,eAAe,UAAU,OAAO,UAAU;EAAE,GAAG;EAAO,WAAW;EAAgB;CAAQ,GAAG,WAAW;CACvG,gBAAgB,kBAAkB,CAAC,gBAAgB,CAAC;CAEpD,cAAc,YAAY,OAAO,WAAW,eAAe,MAAM,OAAO,MAAM;CAE9E,gBAAgB,WAAW;EACzB,cAAc,MAAM,0BAA0B;EAC9C,SAAS,MAAM;EACf,QAAQ,MAAM;EACd,GAAG,WAAW,iBAAiB;GAC7B;GAAS;GAAS;GAAiB;GAAY,MAAM;IAAE;IAAO;GAAO;EACvE,CAAC;CACH,CAAC;CAED,IAAI,UAAU,OAAO;CAErB,OACE,oBAAC,eAAD;EACE,KAAK,SAAS;EACd,OAAO,MAAM;EACb,QAAQ,MAAM;EACd,UAAU,MAAM,YAAY;EAAG,cAAY,MAAM;EACjD,WAAW,MAAM;EAAkB;CACpC,CAAA;AAEL;;;AAIA,IAAa,SAAS,WAAW,WAAW"}
|
|
1
|
+
{"version":3,"file":"Canvas.js","names":[],"sources":["../../src/canvas/Canvas.tsx"],"sourcesContent":["/**\n * Low-level WebGL surface + viewport primitive. Composes layers into a single GL render pass,\n * applies a view transform, and delivers hover to the layers that ask for it. It routes no\n * gesture: `<SceneCanvas>` mounts the gesture dispatcher on this same element. Canvas owns NO\n * scene-shaped state — selection, picking, kind registry, scene-aware overlays all live in\n * `<SceneCanvas>`, which wraps it.\n *\n * The `layers` prop is a map keyed by slot name, every slot already a layer. Standard slots\n * render at a canonical position; custom entries (any other key, value carrying `.layer`) insert\n * at `after`/`before` an existing slot, defaulting to the top.\n *\n * @internal\n * @deprecated Bare `<Canvas>` is not a supported consumer surface.\n * Use `<SceneCanvas>` instead.\n */\n\nimport { forwardRef, useCallback, useEffect, useInsertionEffect, useLayoutEffect, useRef } from 'react';\nimport type React from 'react';\nimport type { CanvasExtensionApi } from './canvasExtension';\nimport { registerMountedCanvas } from './mountedCanvases';\nimport { useViewHelpers } from './useViewHelpers';\nimport { useViewLayerGate } from './useViewLayerGate';\nimport { useSurfaceInput } from './useSurfaceInput';\nimport { useOptionalViewRegistry } from './viewRegistry';\nimport { useCanvasSurface } from './useCanvasSurface';\nimport type { CanvasHelpers } from './useViewHelpers';\nimport type { CanvasProps } from './canvasProps';\nimport { useLatest } from '@weasel-js/react';\nimport { SurfaceCanvas } from './SurfaceCanvas';\nimport { useSurfaceSize } from './useSurfaceSize';\nimport type { SelectionApi } from 'core/selection/useSelection';\nimport { AUTO_POSE_DESCRIPTOR } from 'core/geometry/autoPoseDescriptor';\nimport type { PoseDescriptor } from 'interactions/actions/resize/geometry';\nimport { useDebugSink } from '../debug/useDebugSink';\nimport { useToolCursor } from './useToolCursor';\nimport { useCanvasElements } from './useCanvasElements';\nimport { alwaysVisible, useExtraLayers } from './useExtraLayers';\nimport { usePaintedCursor } from './usePaintedCursor';\nimport { useCanvasHandle } from './useCanvasHandle';\nimport { useComposedLayers, useSlotLayers } from './useLayerStack';\nimport { useViewRegistrySurface } from './useViewRegistrySurface';\nimport { useCanvasPaint, usePaintedVersion } from './useCanvasPaint';\nimport { layerHover } from './layerHover';\nimport { useClientToWorld } from './useClientToWorld';\n\nexport type { CanvasProps, CanvasRetainOptions } from './canvasProps';\n\nconst NO_SELECTION: SelectionApi['current'] = [];\n\nfunction CanvasInner<TPose>(\n props: CanvasProps<TPose>,\n ref: React.ForwardedRef<CanvasExtensionApi>,\n) {\n const {\n paintInto, inputElement, tools, viewState, style, getIsVisible, layerVisibility, layerOrder,\n helpersRef, debugSinkRef,\n poseDescriptor: geometry = AUTO_POSE_DESCRIPTOR as unknown as PoseDescriptor<TPose>,\n } = props;\n\n const { sink: debugSink, overlay: debugOverlay, frameStats, getDebug } = useDebugSink(props.debug);\n const elements = useCanvasElements(paintInto, inputElement);\n const { canvasRef, ownCanvasRef, detached } = elements;\n const { width, height } = useSurfaceSize(props, ownCanvasRef);\n\n // Read by `hitTestExtras`, which is built once and must see live values.\n const helpersForLayersRef = useRef<CanvasHelpers<TPose> | null>(null);\n const dimsRef = useLatest({ width, height });\n // Which layers reach the screen, and which chrome within them: asked by the\n // paint and by every hit-test.\n const gateRef = useLatest({ getIsVisible, layerVisibility, layerOrder });\n\n // The frame loop paints; a committed render only marks the surface dirty, so\n // no prop can reach the paint without repainting it. The thunk defers to\n // `useCanvasPaint` below, which needs inputs this render has not computed yet.\n const paintRef = useRef<() => boolean>(() => false);\n const { lease, requestRedraw, subscribeFrame, subscribeBeforePaint, subscribeResume } = useCanvasSurface(\n useCallback(() => paintRef.current(), []),\n { syncPaint: props.syncPaint ?? false, target: canvasRef, dpr: props.dpr, redrawOn: props.redrawOn, shaders: props.shaders, onCommit: 'redraw' },\n );\n const { getPaintedVersion, markPainted } = usePaintedVersion(props.contentVersion);\n const { extrasRef, extrasVersion, registerLayer, hitTestExtrasIn } = useExtraLayers(gateRef);\n\n const {\n viewRef, setView, getView, subscribeView,\n adoptControlled, announceControlled, clearSubscribers,\n } = viewState;\n\n const toWorld = useClientToWorld(canvasRef, props.clientToWorld, viewRef);\n\n useLayoutEffect(() => {\n const element = canvasRef.current;\n if (!element) return;\n return registerMountedCanvas({ element, getView });\n }, [canvasRef, detached, inputElement, getView]);\n\n const { paintedCursor, paintedCursorLayer, cursorSink } = usePaintedCursor(canvasRef, requestRedraw);\n\n const frame = { viewRef, dimsRef, helpersRef: helpersForLayersRef };\n useCanvasHandle(ref, { ...elements, inputElement, paintCanvas: paintInto?.canvas }, frame, {\n hitTestExtrasIn, clientToWorld: toWorld, requestRedraw, subscribeFrame, subscribeBeforePaint,\n subscribeResume, registerLayer, getView, setView, subscribeView,\n getPaintedVersion, paintedCursor, cursorSink, getDebug,\n });\n\n const viewRegistry = useOptionalViewRegistry();\n\n // One view's overlay-aware state. A hook, so N views are N components each\n // calling it once — not a loop in this body.\n const layers = useSlotLayers(props.layers, tools, props.backgroundFill, props.decorationLayer);\n const { helpers: viewHelpers } = useViewHelpers<TPose>({\n adapter: props.adapter, geometry, boundsOf: props.boundsOf, boundsOfPose: props.boundsOfPose,\n nodes: props.nodes, gestureSource: props.gestureSource, previewPoseExtra: props.previewPoseExtra,\n getScale: () => viewRef.current.scale,\n selection: props.selection?.current ?? NO_SELECTION,\n getIsVisible: () => gateRef.current.getIsVisible?.() ?? alwaysVisible,\n layerIsPainted: useViewLayerGate(layerVisibility, layerOrder, () => layers),\n });\n const helpersForLayers: CanvasHelpers<TPose> = { ...viewHelpers, getDebug: () => debugSink, viewId: null };\n\n useViewRegistrySurface(viewRegistry, layers, frame, { requestRedraw, hitTestExtrasIn, clientToWorld: toWorld, setView: viewState.setViewFromInput });\n const layersWithDebug = useComposedLayers(layers, {\n viewRegistry, debugOverlay, extrasRef, extrasVersion, cursorLayer: paintedCursorLayer,\n }, requestRedraw);\n\n // Everything the paint, hit-testing and the view registry read that a React\n // render owns. `useLatest` and the insertion effect below publish committed\n // renders only, ahead of every layout effect in the commit, any of which may\n // ask for a sync paint.\n const paintInputsRef = useLatest({\n layers: layersWithDebug, width, height, debugSink, frameStats,\n dpr: props.dpr, layerGroups: props.layerGroups, shaders: props.shaders,\n flattenTolerance: props.flattenTolerance, retain: props.retain, imageMinification: props.imageMinification,\n });\n useInsertionEffect(() => {\n adoptControlled();\n helpersForLayersRef.current = helpersForLayers;\n if (helpersRef) helpersRef.current = helpersForLayers;\n if (debugSinkRef) debugSinkRef.current = debugSink;\n });\n useLayoutEffect(() => {\n announceControlled();\n });\n\n useCanvasPaint(paintRef, lease, elements, { ...frame, inputsRef: paintInputsRef, gateRef }, markPainted);\n useEffect(() => clearSubscribers, [clearSubscribers]);\n\n useToolCursor(cursorSink, tools, detached ? inputElement : null, style?.cursor);\n\n useSurfaceInput(canvasRef, {\n focusOnPress: props.autoFocusOnPointerDown ?? true,\n onFocus: props.onFocus,\n onBlur: props.onBlur,\n ...layerHover(layersWithDebug, {\n viewRef, toWorld, layerVisibility, layerOrder, dims: { width, height },\n }),\n });\n\n if (detached) return null;\n\n return (\n <SurfaceCanvas\n ref={elements.setOwnCanvas}\n width={props.width}\n height={props.height}\n tabIndex={props.tabIndex ?? 0} aria-label={props['aria-label']}\n className={props.className} style={style}\n />\n );\n}\n\n/** Forward-ref'd `<canvas>` wrapper. Generic over the pose type, inferred from the\n * `adapter` prop. */\nexport const Canvas = forwardRef(CanvasInner) as <TPose = unknown>(\n props: CanvasProps<TPose> & { ref?: React.ForwardedRef<CanvasExtensionApi> },\n) => ReturnType<typeof CanvasInner>;\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,eAAwC,CAAC;AAE/C,SAAS,YACP,OACA,KACA;CACA,MAAM,EACJ,WAAW,cAAc,OAAO,WAAW,OAAO,cAAc,iBAAiB,YACjF,YAAY,cACZ,gBAAgB,WAAW,yBACzB;CAEJ,MAAM,EAAE,MAAM,WAAW,SAAS,cAAc,YAAY,aAAa,aAAa,MAAM,KAAK;CACjG,MAAM,WAAW,kBAAkB,WAAW,YAAY;CAC1D,MAAM,EAAE,WAAW,cAAc,aAAa;CAC9C,MAAM,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY;CAG5D,MAAM,sBAAsB,OAAoC,IAAI;CACpE,MAAM,UAAU,UAAU;EAAE;EAAO;CAAO,CAAC;CAG3C,MAAM,UAAU,UAAU;EAAE;EAAc;EAAiB;CAAW,CAAC;CAKvE,MAAM,WAAW,aAA4B,KAAK;CAClD,MAAM,EAAE,OAAO,eAAe,gBAAgB,sBAAsB,oBAAoB,iBACtF,kBAAkB,SAAS,QAAQ,GAAG,CAAC,CAAC,GACxC;EAAE,WAAW,MAAM,aAAa;EAAO,QAAQ;EAAW,KAAK,MAAM;EAAK,UAAU,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AQ,OAAO;EAAE;EAAe;EAAiB,eAAe;EAAS,SAAS,UAAU;CAAiB,CAAC;CACnJ,MAAM,kBAAkB,kBAAkB,QAAQ;EAChD;EAAc;EAAc;EAAW;EAAe,aAAa;CACrE,GAAG,aAAa;CAMhB,MAAM,iBAAiB,UAAU;EAC/B,QAAQ;EAAiB;EAAO;EAAQ;EAAW;EACnD,KAAK,MAAM;EAAK,aAAa,MAAM;EAAa,SAAS,MAAM;EAC/D,kBAAkB,MAAM;EAAkB,QAAQ,MAAM;EAAQ,mBAAmB,MAAM;CAC3F,CAAC;CACD,yBAAyB;EACvB,gBAAgB;EAChB,oBAAoB,UAAU;EAC9B,IAAI,YAAY,WAAW,UAAU;EACrC,IAAI,cAAc,aAAa,UAAU;CAC3C,CAAC;CACD,sBAAsB;EACpB,mBAAmB;CACrB,CAAC;CAED,eAAe,UAAU,OAAO,UAAU;EAAE,GAAG;EAAO,WAAW;EAAgB;CAAQ,GAAG,WAAW;CACvG,gBAAgB,kBAAkB,CAAC,gBAAgB,CAAC;CAEpD,cAAc,YAAY,OAAO,WAAW,eAAe,MAAM,OAAO,MAAM;CAE9E,gBAAgB,WAAW;EACzB,cAAc,MAAM,0BAA0B;EAC9C,SAAS,MAAM;EACf,QAAQ,MAAM;EACd,GAAG,WAAW,iBAAiB;GAC7B;GAAS;GAAS;GAAiB;GAAY,MAAM;IAAE;IAAO;GAAO;EACvE,CAAC;CACH,CAAC;CAED,IAAI,UAAU,OAAO;CAErB,OACE,oBAAC,eAAD;EACE,KAAK,SAAS;EACd,OAAO,MAAM;EACb,QAAQ,MAAM;EACd,UAAU,MAAM,YAAY;EAAG,cAAY,MAAM;EACjD,WAAW,MAAM;EAAkB;CACpC,CAAA;AAEL;;;AAIA,IAAa,SAAS,WAAW,WAAW"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { normalizeView } from "../core/viewport/view.js";
|
|
2
1
|
import { createViewportLayer } from "../features/viewports/viewportLayer.js";
|
|
3
2
|
import { useDeviceProfile } from "../core/device/useDeviceProfile.js";
|
|
4
3
|
import { viewportWorldRect } from "../core/viewport/viewportWorldRect.js";
|
|
@@ -6,14 +5,14 @@ import { clientToWorld } from "../core/viewport/clientToWorld.js";
|
|
|
6
5
|
import { useSelection } from "../core/selection/useSelection.js";
|
|
7
6
|
import { AUTO_POSE_DESCRIPTOR } from "../core/geometry/autoPoseDescriptor.js";
|
|
8
7
|
import { useViewHelpers } from "./useViewHelpers.js";
|
|
9
|
-
import {
|
|
10
|
-
import { hitAtOf } from "./deps/dispatchSources.js";
|
|
8
|
+
import { NO_RECT, sizeOf, useViewNesting } from "./useViewNesting.js";
|
|
11
9
|
import { anchorStateFrom, buildAffordanceAt, buildClassifyTarget, layerAffordance } from "./affordanceAt.js";
|
|
10
|
+
import { IDENTITY_VIEW, UNMEASURED_DIMS, surfaceLocal, useOptionalViewRegistry } from "./viewRegistry.js";
|
|
11
|
+
import { useViewAim } from "./useViewAim.js";
|
|
12
|
+
import { hitAtOf } from "./deps/dispatchSources.js";
|
|
12
13
|
import { pathFromPlane } from "./planeClips.js";
|
|
13
14
|
import { createDispatcherPreviewSources, createGestureSource } from "./SceneCanvas/dispatcherGestureBounds.js";
|
|
14
15
|
import { useOptionalViewInputs } from "./viewInputs.js";
|
|
15
|
-
import { NO_RECT, useViewNesting } from "./useViewNesting.js";
|
|
16
|
-
import { IDENTITY_VIEW, UNMEASURED_DIMS, surfaceLocal, useOptionalViewRegistry } from "./viewRegistry.js";
|
|
17
16
|
import { useCallback, useEffect, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useRef } from "react";
|
|
18
17
|
import { useLatest } from "@weasel-js/react";
|
|
19
18
|
import { createDispatcher } from "@weasel-js/routing";
|
|
@@ -35,10 +34,6 @@ var NO_INPUTS = {
|
|
|
35
34
|
boundsOf: void 0
|
|
36
35
|
};
|
|
37
36
|
var ALWAYS_VISIBLE = () => true;
|
|
38
|
-
var sizeOf = (rect) => ({
|
|
39
|
-
width: rect.w,
|
|
40
|
-
height: rect.h
|
|
41
|
-
});
|
|
42
37
|
var ALL_LAYERS = (s) => s;
|
|
43
38
|
/**
|
|
44
39
|
* One view on a shared canvas. Owns a camera, contributes the viewport node
|
|
@@ -49,7 +44,7 @@ var ALL_LAYERS = (s) => s;
|
|
|
49
44
|
* drawing. Outside a surface that mounts a view registry it is inert.
|
|
50
45
|
*/
|
|
51
46
|
function CanvasView(props) {
|
|
52
|
-
const { id, parent, bounds,
|
|
47
|
+
const { id, parent, bounds, layers = ALL_LAYERS, layerVisibility, layerOrder, background, order = Infinity, label, cameraRef, selection: selectionProp, selectionOptions, interactive = true, paint = true } = props;
|
|
53
48
|
const registry = useOptionalViewRegistry();
|
|
54
49
|
const depRegistry = useOptionalDepRegistry();
|
|
55
50
|
const depRegistryRef = useLatest(depRegistry);
|
|
@@ -63,7 +58,6 @@ function CanvasView(props) {
|
|
|
63
58
|
layers,
|
|
64
59
|
layerVisibility,
|
|
65
60
|
layerOrder,
|
|
66
|
-
viewProp,
|
|
67
61
|
viewSelection,
|
|
68
62
|
selection
|
|
69
63
|
});
|
|
@@ -74,16 +68,13 @@ function CanvasView(props) {
|
|
|
74
68
|
const surface = registry?.surface();
|
|
75
69
|
return rectAt(surface?.view() ?? IDENTITY_VIEW, surface?.dims() ?? UNMEASURED_DIMS);
|
|
76
70
|
}, [registry, rectAt]);
|
|
77
|
-
const { getView: camera, setView, setViewFromInput, subscribeView, adoptControlled, announceControlled, clearSubscribers } =
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
viewBounds,
|
|
85
|
-
dims: () => sizeOf(rectNow()),
|
|
86
|
-
requestRedraw: () => registry?.surface()?.requestRedraw()
|
|
71
|
+
const { getView: camera, setView, setViewFromInput, subscribeView, adoptControlled, announceControlled, clearSubscribers, held, aim, setAim, cameraAt } = useViewAim({
|
|
72
|
+
props,
|
|
73
|
+
id,
|
|
74
|
+
registry,
|
|
75
|
+
derivedAt,
|
|
76
|
+
rectAt,
|
|
77
|
+
rectNow
|
|
87
78
|
});
|
|
88
79
|
useInsertionEffect(adoptControlled);
|
|
89
80
|
useLayoutEffect(announceControlled);
|
|
@@ -97,16 +88,6 @@ function CanvasView(props) {
|
|
|
97
88
|
setView,
|
|
98
89
|
subscribeView
|
|
99
90
|
]);
|
|
100
|
-
/** The camera for a frame the caller names. A derived camera is asked for
|
|
101
|
-
* that frame; any other is the same whatever the surface is doing. */
|
|
102
|
-
const cameraAt = useCallback((outer, dims) => {
|
|
103
|
-
const v = live.current.viewProp;
|
|
104
|
-
return typeof v === "function" ? normalizeView(derivedAt(v, outer, dims)) : camera();
|
|
105
|
-
}, [
|
|
106
|
-
live,
|
|
107
|
-
camera,
|
|
108
|
-
derivedAt
|
|
109
|
-
]);
|
|
110
91
|
const viewApi = useMemo(() => ({
|
|
111
92
|
get: camera,
|
|
112
93
|
set: setViewFromInput,
|
|
@@ -203,9 +184,10 @@ function CanvasView(props) {
|
|
|
203
184
|
});
|
|
204
185
|
return (world) => {
|
|
205
186
|
const extra = registry?.surface()?.hitTestExtras(world.x, world.y, camera(), sizeOf(rectNow()), helpersRef.current, drawnLayers());
|
|
206
|
-
return extra ? layerAffordance(extra.layerId, extra.hit) : inner(world);
|
|
187
|
+
return extra ? layerAffordance(extra.layerId, extra.hit) : registry?.markerAt(id, world) ?? inner(world);
|
|
207
188
|
};
|
|
208
189
|
}, [
|
|
190
|
+
id,
|
|
209
191
|
getAnchorState,
|
|
210
192
|
rectNow,
|
|
211
193
|
registry,
|
|
@@ -237,10 +219,13 @@ function CanvasView(props) {
|
|
|
237
219
|
order,
|
|
238
220
|
interactive,
|
|
239
221
|
paint,
|
|
222
|
+
held,
|
|
223
|
+
aim,
|
|
224
|
+
setAim,
|
|
240
225
|
layer: createViewportLayer({
|
|
241
226
|
id,
|
|
242
227
|
label: label ?? id,
|
|
243
|
-
source: drawnLayers,
|
|
228
|
+
source: () => [...drawnLayers(), ...registry?.markerLayers(id) ?? []],
|
|
244
229
|
view: cameraAt,
|
|
245
230
|
bounds: (outer, dims) => rectAt(outer, dims),
|
|
246
231
|
...parent !== void 0 ? { clip: (outer, dims) => frameIn(outer, dims)?.clip ?? NO_RECT } : {},
|
|
@@ -273,6 +258,9 @@ function CanvasView(props) {
|
|
|
273
258
|
order,
|
|
274
259
|
interactive,
|
|
275
260
|
paint,
|
|
261
|
+
held,
|
|
262
|
+
aim,
|
|
263
|
+
setAim,
|
|
276
264
|
label,
|
|
277
265
|
background,
|
|
278
266
|
rectAt,
|
|
@@ -288,7 +276,8 @@ function CanvasView(props) {
|
|
|
288
276
|
live,
|
|
289
277
|
inputsRef,
|
|
290
278
|
helpersRef,
|
|
291
|
-
frameIn
|
|
279
|
+
frameIn,
|
|
280
|
+
registry
|
|
292
281
|
]);
|
|
293
282
|
useEffect(() => {
|
|
294
283
|
if (!registry) return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CanvasView.js","names":[],"sources":["../../src/canvas/CanvasView.tsx"],"sourcesContent":["/**\n * `<CanvasView>` — a second view on an existing canvas: its own camera over a\n * rect of the surface, with input routed to it.\n *\n * Mount one inside `<SceneCanvas>`, or declare the same thing through the\n * surface's `views` prop, which renders one of these per descriptor.\n */\nimport {\n useCallback, useEffect, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useRef,\n} from 'react';\nimport type { Dims, RenderLayer } from 'core/layers/render';\nimport { normalizeView, type View } from 'core/viewport/view';\nimport { clientToWorld } from 'core/viewport/clientToWorld';\nimport { createViewportLayer } from 'features/viewports/viewportLayer';\nimport { createDispatcher } from '@weasel-js/routing';\nimport type { IngestionDep, ViewApi } from 'interactions/actions/depSchema';\nimport { viewportWorldRect } from 'core/viewport/viewportWorldRect';\nimport { useSelection } from 'core/selection/useSelection';\nimport { AUTO_POSE_DESCRIPTOR } from 'core/geometry/autoPoseDescriptor';\nimport type { PoseDescriptor } from 'interactions/actions/resize/geometry';\nimport { useViewHelpers } from './useViewHelpers';\nimport { useCanvasView } from './useCanvasView';\nimport { hitAtOf } from './deps/dispatchSources';\nimport { anchorStateFrom, buildAffordanceAt, buildClassifyTarget, layerAffordance } from './affordanceAt';\nimport { pathFromPlane } from './planeClips';\nimport { useOptionalDepRegistry } from '@weasel-js/routing/react';\nimport { useLatest } from '@weasel-js/react';\nimport { useDeviceProfile } from 'core/device/useDeviceProfile';\nimport {\n createGestureSource,\n createDispatcherPreviewSources,\n} from './SceneCanvas/dispatcherGestureBounds';\nimport { useOptionalViewInputs, type SurfaceViewInputs, type ViewRuleInputs } from './viewInputs';\nimport type { CanvasViewProps, ViewRect } from './canvasViewProps';\nexport type { CanvasViewProps, ViewRect } from './canvasViewProps';\nimport { NO_RECT, useViewNesting } from './useViewNesting';\nimport {\n useOptionalViewRegistry,\n surfaceLocal,\n IDENTITY_VIEW,\n UNMEASURED_DIMS,\n type ViewRegistration,\n} from './viewRegistry';\n\n/** What a view builds its helpers from outside a surface: nothing but the\n * default geometry, which answers `null` for every lookup. */\n// A view outside a surface has no inputs to inherit — including a selection,\n// so it falls back to owning one.\nconst NO_INPUTS: Omit<SurfaceViewInputs, 'selectionApi'> = {\n adapter: undefined,\n geometry: AUTO_POSE_DESCRIPTOR as unknown as PoseDescriptor<unknown>,\n boundsOf: undefined,\n};\n\nconst ALWAYS_VISIBLE = (): boolean => true;\n\nconst sizeOf = (rect: ViewRect): Dims => ({ width: rect.w, height: rect.h });\n\nconst ALL_LAYERS = (s: readonly RenderLayer<unknown>[]): readonly RenderLayer<unknown>[] => s;\n\n\n/**\n * One view on a shared canvas. Owns a camera, contributes the viewport node\n * that paints it, and registers the dispatch record that sends gestures inside\n * its rect to that camera rather than to the canvas's.\n *\n * Renders nothing itself — it is a declaration, and the surface does the\n * drawing. Outside a surface that mounts a view registry it is inert.\n */\nexport function CanvasView(props: CanvasViewProps): null {\n const {\n id, parent, bounds, view: viewProp, defaultView, onViewChange, viewBounds,\n layers = ALL_LAYERS, layerVisibility, layerOrder, background, order = Infinity, label, cameraRef,\n selection: selectionProp, selectionOptions, interactive = true, paint = true,\n } = props;\n\n const registry = useOptionalViewRegistry();\n const depRegistry = useOptionalDepRegistry();\n const depRegistryRef = useLatest(depRegistry);\n\n // Hooks run unconditionally; the owned selection goes unused unless this\n // view asked for one.\n const ownSelection = useSelection(selectionOptions);\n const viewSelection = selectionProp ?? (selectionOptions ? ownSelection : undefined);\n\n const inputs = useOptionalViewInputs();\n // The selection this view acts on: its own when it has one, the surface's\n // otherwise.\n const selection = viewSelection ?? inputs?.selectionApi ?? ownSelection;\n\n // Everything the registration reads is behind a ref: the registration object\n // is registered once and must not churn, but what it answers with has to be\n // the last committed render's.\n const live = useLatest({\n parent, bounds, layers, layerVisibility, layerOrder, viewProp, viewSelection, selection,\n });\n\n const { frameIn, rectAt, derivedAt, drawnLayers, layerIsPainted } = useViewNesting(registry, live);\n\n /** The rect for the surface's current frame — what a client point and a\n * clamp are measured against outside a draw call. */\n const rectNow = useCallback((): ViewRect => {\n const surface = registry?.surface();\n return rectAt(surface?.view() ?? IDENTITY_VIEW, surface?.dims() ?? UNMEASURED_DIMS);\n }, [registry, rectAt]);\n\n const {\n getView: camera, setView, setViewFromInput, subscribeView,\n adoptControlled, announceControlled, clearSubscribers,\n } = useCanvasView({\n view: typeof viewProp === 'function'\n ? () => {\n const surface = registry?.surface();\n return derivedAt(viewProp, surface?.view() ?? IDENTITY_VIEW, surface?.dims() ?? UNMEASURED_DIMS);\n }\n : viewProp,\n defaultView,\n onViewChange,\n viewBounds,\n dims: () => sizeOf(rectNow()),\n requestRedraw: () => registry?.surface()?.requestRedraw(),\n });\n useInsertionEffect(adoptControlled);\n useLayoutEffect(announceControlled);\n useEffect(() => clearSubscribers, [clearSubscribers]);\n useImperativeHandle(cameraRef, () => ({ getView: camera, setView, subscribeView }), [camera, setView, subscribeView]);\n\n /** The camera for a frame the caller names. A derived camera is asked for\n * that frame; any other is the same whatever the surface is doing. */\n const cameraAt = useCallback((outer: View, dims: Dims): View => {\n const v = live.current.viewProp;\n return typeof v === 'function' ? normalizeView(derivedAt(v, outer, dims)) : camera();\n }, [live, camera, derivedAt]);\n\n const viewApi = useMemo<ViewApi>(() => ({\n get: camera,\n set: setViewFromInput,\n hostSize: () => sizeOf(rectNow()),\n layerIsPainted,\n }), [camera, rectNow, setViewFromInput, layerIsPainted]);\n\n // Paste placement is a camera question, so it is this view's when the paste\n // routed here. The rest of the dep — `resolveSrc`, `svg`, `clipboard` — is\n // the surface's one wiring, read live off the canvas registry.\n const ingestionApi = useMemo<IngestionDep>(() => {\n const base = (): IngestionDep | undefined => depRegistryRef.current?.get('ingestion');\n return {\n viewportWorldRect: () => viewportWorldRect(camera(), sizeOf(rectNow())),\n get resolveSrc() { return base()?.resolveSrc; },\n get svg() { return base()?.svg; },\n get clipboard() { return base()?.clipboard; },\n };\n }, [camera, rectNow, depRegistryRef]);\n\n // One dispatcher per view: in-flight handles are per-view state, and two\n // views must not be able to see each other's.\n const dispatcherRef = useRef<ReturnType<typeof createDispatcher> | null>(null);\n if (!dispatcherRef.current) dispatcherRef.current = createDispatcher();\n\n // This view's overlay-aware state. The scene half comes from the surface —\n // same adapter, same tools — but everything gesture-shaped is read off this\n // view's own dispatcher, which is where a gesture inside this view lands.\n const rotationBadge = inputs?.rotationBadge ?? null;\n const own = useMemo(() => ({\n gestureSource: createGestureSource(() => dispatcherRef.current),\n ...createDispatcherPreviewSources(() => dispatcherRef.current),\n }), []);\n\n const inputsRef = useLatest(inputs);\n\n /** The chrome-caps context this view answers for: its selection, its camera,\n * its dispatcher's in-flight action. */\n const ruleInputs = useCallback((): ViewRuleInputs => ({\n selection: live.current.selection.get(),\n view: camera(),\n action: dispatcherRef.current!.getActiveAction(),\n }), [camera, live]);\n\n // The surface's resolver, asked for this view's camera.\n const surfaceBoundsOf = inputs?.boundsOf;\n const boundsOf = useMemo(\n () => (surfaceBoundsOf ? (id: string) => surfaceBoundsOf(id, camera()) : undefined),\n [surfaceBoundsOf, camera],\n );\n const surfaceBoundsOfPose = inputs?.boundsOfPose;\n const boundsOfPose = useMemo(\n () => (surfaceBoundsOfPose\n ? (id: string, pose: unknown) => surfaceBoundsOfPose(id, pose, camera())\n : undefined),\n [surfaceBoundsOfPose, camera],\n );\n\n const { helpers } = useViewHelpers<unknown>({\n ...(inputs ?? NO_INPUTS),\n boundsOf,\n boundsOfPose,\n ...own,\n selection: selection.current,\n layerIsPainted,\n getIsVisible: () => inputsRef.current?.chromeCaps?.isVisible(ruleInputs()) ?? ALWAYS_VISIBLE,\n });\n const helpersRef = useLatest(helpers);\n\n /** A client point in this view's world. The rect moves with the outer\n * camera, so it is read per call rather than closed over. */\n const clientToWorldHere = useCallback((cx: number, cy: number): { x: number; y: number } => {\n const local = surfaceLocal(registry?.surface() ?? null, cx, cy);\n const rect = rectNow();\n const [x, y] = clientToWorld(local.x, local.y, { left: rect.x, top: rect.y }, camera());\n return { x, y };\n }, [registry, rectNow, camera]);\n\n // Anchors are hit in this view's camera world, where its plane draws them.\n const getAnchorState = useMemo(() => anchorStateFrom(\n () => depRegistryRef.current,\n (id, path) => pathFromPlane(path, inputsRef.current?.planeOfNode?.(id, camera()) ?? null),\n ), [camera, depRegistryRef, inputsRef]);\n\n const { targetScale } = useDeviceProfile();\n\n // Selection chrome hit-testing for this view: same construction the surface\n // does for its own, against this view's chrome and camera.\n const affordanceAt = useMemo(() => {\n const inner = buildAffordanceAt({\n getChromeState: () => helpersRef.current.getChromeState(),\n getView: camera,\n targetScale,\n rotationBadge, handleHitRadius: inputs?.resizeHandles?.hitRadiusPx, edgeHandles: inputs?.resizeHandles?.edges,\n getAnchorState,\n getIsVisible: () => helpersRef.current.getIsVisible(),\n });\n return (world: { x: number; y: number }) => {\n // A registered layer this view paints gets first refusal, on this\n // view's frame and envelope. One painted over the surface already had\n // its chance: it occludes the view before routing reaches here.\n const extra = registry?.surface()?.hitTestExtras(\n world.x, world.y, camera(), sizeOf(rectNow()), helpersRef.current, drawnLayers(),\n );\n return extra ? layerAffordance(extra.layerId, extra.hit) : inner(world);\n };\n }, [getAnchorState, rectNow, registry, targetScale, camera, drawnLayers, rotationBadge, inputs?.resizeHandles, helpersRef]);\n\n const classifyTarget = useMemo(() => buildClassifyTarget(\n () => live.current.selection.get(),\n (wx, wy) => {\n const i = inputsRef.current;\n // This view's camera: the dispatcher converted with `clientToWorldHere`,\n // and a screen-pixel tolerance needs the scale that produced it. The\n // layer gate is this view's too, never the surface's.\n const frame = { ...camera(), layerIsPainted };\n if (i?.pickBest) return i.pickBest(wx, wy, frame);\n const ids = i?.pickEvery?.(wx, wy, frame) ?? [];\n return ids.length > 0 ? ids[ids.length - 1]! : null;\n },\n (id) => inputsRef.current?.kindOfNode?.(id),\n (id) => inputsRef.current?.doubleClickNames?.(id) ?? id,\n ), [camera, layerIsPainted, live, inputsRef]);\n\n const registration = useMemo<ViewRegistration>(() => ({\n id,\n ...(parent !== undefined ? { parent } : {}),\n order,\n interactive,\n paint,\n layer: createViewportLayer<unknown, unknown>({\n id,\n label: label ?? id,\n source: drawnLayers,\n view: cameraAt,\n bounds: (outer, dims) => rectAt(outer, dims),\n ...(parent !== undefined ? { clip: (outer: View, dims: Dims) => frameIn(outer, dims)?.clip ?? NO_RECT } : {}),\n // The surface half of the envelope passes through; the view half is\n // this view's, so its layers paint its chrome rather than the\n // surface's.\n data: (outer) => ({ ...(outer as object), ...helpersRef.current, viewId: id }),\n ...(background !== undefined ? { background } : {}),\n }),\n layerIsPainted,\n drawnLayers,\n target: {\n dispatcher: dispatcherRef.current!,\n affordanceAt,\n classifyTarget,\n clientToWorld: clientToWorldHere,\n deps: () => ({\n view: viewApi, ingestion: ingestionApi, hitAt: hitAtOf(classifyTarget),\n // An Escape here cancels what is in flight here.\n dispatcher: { cancelAll: (reason) => dispatcherRef.current!.cancelAll(reason) },\n // Only a view with its own selection overlays that one; otherwise the\n // surface's answer stands, wrappers (`selectable`) included.\n ...(live.current.viewSelection ? { selection: live.current.viewSelection } : {}),\n }),\n // Action eligibility is chrome-caps evaluated against this view, so a\n // rule that hides an action in one panel cannot decline a gesture in\n // another.\n getRuleCtx: () => inputsRef.current?.chromeCaps?.ruleCtx(ruleInputs()),\n },\n }), [id, parent, order, interactive, paint, label, background, rectAt, cameraAt, viewApi,\n affordanceAt, classifyTarget, clientToWorldHere, ruleInputs, ingestionApi, drawnLayers,\n layerIsPainted, live, inputsRef, helpersRef, frameIn]);\n\n useEffect(() => {\n if (!registry) return;\n return registry.register(registration);\n }, [registry, registration]);\n\n // Apart from the registration, which is replaced whenever a prop it reads\n // changes: only the view going away ends what is in flight over it.\n useEffect(() => () => dispatcherRef.current?.cancelAll('cancel'), []);\n\n // The surface paints this view from `live`, so any committed render of it —\n // a controlled camera, its bounds, its layer gate — needs a frame.\n useEffect(() => {\n registry?.surface()?.requestRedraw();\n });\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAM,YAAqD;CACzD,SAAS;CACT,UAAU;CACV,UAAU;AACZ;AAEA,IAAM,uBAAgC;AAEtC,IAAM,UAAU,UAA0B;CAAE,OAAO,KAAK;CAAG,QAAQ,KAAK;AAAE;AAE1E,IAAM,cAAc,MAAwE;;;;;;;;;AAW5F,SAAgB,WAAW,OAA8B;CACvD,MAAM,EACJ,IAAI,QAAQ,QAAQ,MAAM,UAAU,aAAa,cAAc,YAC/D,SAAS,YAAY,iBAAiB,YAAY,YAAY,QAAQ,UAAU,OAAO,WACvF,WAAW,eAAe,kBAAkB,cAAc,MAAM,QAAQ,SACtE;CAEJ,MAAM,WAAW,wBAAwB;CACzC,MAAM,cAAc,uBAAuB;CAC3C,MAAM,iBAAiB,UAAU,WAAW;CAI5C,MAAM,eAAe,aAAa,gBAAgB;CAClD,MAAM,gBAAgB,kBAAkB,mBAAmB,eAAe;CAE1E,MAAM,SAAS,sBAAsB;CAGrC,MAAM,YAAY,iBAAiB,QAAQ,gBAAgB;CAK3D,MAAM,OAAO,UAAU;EACrB;EA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AI3B,sBAAsB,cAAc,SAAS,UAAU,QAAQ,GAAG,CAAC,CAAC;CAIpE,gBAAgB;EACd,UAAU,QAAQ,CAAC,EAAE,cAAc;CACrC,CAAC;CAED,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"CanvasView.js","names":[],"sources":["../../src/canvas/CanvasView.tsx"],"sourcesContent":["/**\n * `<CanvasView>` — a second view on an existing canvas: its own camera over a\n * rect of the surface, with input routed to it.\n *\n * Mount one inside `<SceneCanvas>`, or declare the same thing through the\n * surface's `views` prop, which renders one of these per descriptor.\n */\nimport {\n useCallback, useEffect, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useRef,\n} from 'react';\nimport type { Dims, RenderLayer } from 'core/layers/render';\nimport type { View } from 'core/viewport/view';\nimport { clientToWorld } from 'core/viewport/clientToWorld';\nimport { createViewportLayer } from 'features/viewports/viewportLayer';\nimport { createDispatcher } from '@weasel-js/routing';\nimport type { IngestionDep, ViewApi } from 'interactions/actions/depSchema';\nimport { viewportWorldRect } from 'core/viewport/viewportWorldRect';\nimport { useSelection } from 'core/selection/useSelection';\nimport { AUTO_POSE_DESCRIPTOR } from 'core/geometry/autoPoseDescriptor';\nimport type { PoseDescriptor } from 'interactions/actions/resize/geometry';\nimport { useViewHelpers } from './useViewHelpers';\nimport { useViewAim } from './useViewAim';\nimport { hitAtOf } from './deps/dispatchSources';\nimport { anchorStateFrom, buildAffordanceAt, buildClassifyTarget, layerAffordance } from './affordanceAt';\nimport { pathFromPlane } from './planeClips';\nimport { useOptionalDepRegistry } from '@weasel-js/routing/react';\nimport { useLatest } from '@weasel-js/react';\nimport { useDeviceProfile } from 'core/device/useDeviceProfile';\nimport {\n createGestureSource,\n createDispatcherPreviewSources,\n} from './SceneCanvas/dispatcherGestureBounds';\nimport { useOptionalViewInputs, type SurfaceViewInputs, type ViewRuleInputs } from './viewInputs';\nimport type { CanvasViewProps, ViewRect } from './canvasViewProps';\nexport type { CanvasViewProps, ViewRect } from './canvasViewProps';\nimport { NO_RECT, sizeOf, useViewNesting } from './useViewNesting';\nimport {\n useOptionalViewRegistry,\n surfaceLocal,\n IDENTITY_VIEW,\n UNMEASURED_DIMS,\n type ViewRegistration,\n} from './viewRegistry';\n\n/** What a view builds its helpers from outside a surface: nothing but the\n * default geometry, which answers `null` for every lookup. */\n// A view outside a surface has no inputs to inherit — including a selection,\n// so it falls back to owning one.\nconst NO_INPUTS: Omit<SurfaceViewInputs, 'selectionApi'> = {\n adapter: undefined,\n geometry: AUTO_POSE_DESCRIPTOR as unknown as PoseDescriptor<unknown>,\n boundsOf: undefined,\n};\n\nconst ALWAYS_VISIBLE = (): boolean => true;\n\nconst ALL_LAYERS = (s: readonly RenderLayer<unknown>[]): readonly RenderLayer<unknown>[] => s;\n\n\n/**\n * One view on a shared canvas. Owns a camera, contributes the viewport node\n * that paints it, and registers the dispatch record that sends gestures inside\n * its rect to that camera rather than to the canvas's.\n *\n * Renders nothing itself — it is a declaration, and the surface does the\n * drawing. Outside a surface that mounts a view registry it is inert.\n */\nexport function CanvasView(props: CanvasViewProps): null {\n const {\n id, parent, bounds,\n layers = ALL_LAYERS, layerVisibility, layerOrder, background, order = Infinity, label, cameraRef,\n selection: selectionProp, selectionOptions, interactive = true, paint = true,\n } = props;\n\n const registry = useOptionalViewRegistry();\n const depRegistry = useOptionalDepRegistry();\n const depRegistryRef = useLatest(depRegistry);\n\n // Hooks run unconditionally; the owned selection goes unused unless this\n // view asked for one.\n const ownSelection = useSelection(selectionOptions);\n const viewSelection = selectionProp ?? (selectionOptions ? ownSelection : undefined);\n\n const inputs = useOptionalViewInputs();\n // The selection this view acts on: its own when it has one, the surface's\n // otherwise.\n const selection = viewSelection ?? inputs?.selectionApi ?? ownSelection;\n\n // Everything the registration reads is behind a ref: the registration object\n // is registered once and must not churn, but what it answers with has to be\n // the last committed render's.\n const live = useLatest({\n parent, bounds, layers, layerVisibility, layerOrder, viewSelection, selection,\n });\n\n const { frameIn, rectAt, derivedAt, drawnLayers, layerIsPainted } = useViewNesting(registry, live);\n\n /** The rect for the surface's current frame — what a client point and a\n * clamp are measured against outside a draw call. */\n const rectNow = useCallback((): ViewRect => {\n const surface = registry?.surface();\n return rectAt(surface?.view() ?? IDENTITY_VIEW, surface?.dims() ?? UNMEASURED_DIMS);\n }, [registry, rectAt]);\n\n const {\n getView: camera, setView, setViewFromInput, subscribeView,\n adoptControlled, announceControlled, clearSubscribers, held, aim, setAim, cameraAt,\n } = useViewAim({ props, id, registry, derivedAt, rectAt, rectNow });\n useInsertionEffect(adoptControlled);\n useLayoutEffect(announceControlled);\n useEffect(() => clearSubscribers, [clearSubscribers]);\n useImperativeHandle(cameraRef, () => ({ getView: camera, setView, subscribeView }), [camera, setView, subscribeView]);\n\n const viewApi = useMemo<ViewApi>(() => ({\n get: camera,\n set: setViewFromInput,\n hostSize: () => sizeOf(rectNow()),\n layerIsPainted,\n }), [camera, rectNow, setViewFromInput, layerIsPainted]);\n\n // Paste placement is a camera question, so it is this view's when the paste\n // routed here. The rest of the dep — `resolveSrc`, `svg`, `clipboard` — is\n // the surface's one wiring, read live off the canvas registry.\n const ingestionApi = useMemo<IngestionDep>(() => {\n const base = (): IngestionDep | undefined => depRegistryRef.current?.get('ingestion');\n return {\n viewportWorldRect: () => viewportWorldRect(camera(), sizeOf(rectNow())),\n get resolveSrc() { return base()?.resolveSrc; },\n get svg() { return base()?.svg; },\n get clipboard() { return base()?.clipboard; },\n };\n }, [camera, rectNow, depRegistryRef]);\n\n // One dispatcher per view: in-flight handles are per-view state, and two\n // views must not be able to see each other's.\n const dispatcherRef = useRef<ReturnType<typeof createDispatcher> | null>(null);\n if (!dispatcherRef.current) dispatcherRef.current = createDispatcher();\n\n // This view's overlay-aware state. The scene half comes from the surface —\n // same adapter, same tools — but everything gesture-shaped is read off this\n // view's own dispatcher, which is where a gesture inside this view lands.\n const rotationBadge = inputs?.rotationBadge ?? null;\n const own = useMemo(() => ({\n gestureSource: createGestureSource(() => dispatcherRef.current),\n ...createDispatcherPreviewSources(() => dispatcherRef.current),\n }), []);\n\n const inputsRef = useLatest(inputs);\n\n /** The chrome-caps context this view answers for: its selection, its camera,\n * its dispatcher's in-flight action. */\n const ruleInputs = useCallback((): ViewRuleInputs => ({\n selection: live.current.selection.get(),\n view: camera(),\n action: dispatcherRef.current!.getActiveAction(),\n }), [camera, live]);\n\n // The surface's resolver, asked for this view's camera.\n const surfaceBoundsOf = inputs?.boundsOf;\n const boundsOf = useMemo(\n () => (surfaceBoundsOf ? (id: string) => surfaceBoundsOf(id, camera()) : undefined),\n [surfaceBoundsOf, camera],\n );\n const surfaceBoundsOfPose = inputs?.boundsOfPose;\n const boundsOfPose = useMemo(\n () => (surfaceBoundsOfPose\n ? (id: string, pose: unknown) => surfaceBoundsOfPose(id, pose, camera())\n : undefined),\n [surfaceBoundsOfPose, camera],\n );\n\n const { helpers } = useViewHelpers<unknown>({\n ...(inputs ?? NO_INPUTS),\n boundsOf,\n boundsOfPose,\n ...own,\n selection: selection.current,\n layerIsPainted,\n getIsVisible: () => inputsRef.current?.chromeCaps?.isVisible(ruleInputs()) ?? ALWAYS_VISIBLE,\n });\n const helpersRef = useLatest(helpers);\n\n /** A client point in this view's world. The rect moves with the outer\n * camera, so it is read per call rather than closed over. */\n const clientToWorldHere = useCallback((cx: number, cy: number): { x: number; y: number } => {\n const local = surfaceLocal(registry?.surface() ?? null, cx, cy);\n const rect = rectNow();\n const [x, y] = clientToWorld(local.x, local.y, { left: rect.x, top: rect.y }, camera());\n return { x, y };\n }, [registry, rectNow, camera]);\n\n // Anchors are hit in this view's camera world, where its plane draws them.\n const getAnchorState = useMemo(() => anchorStateFrom(\n () => depRegistryRef.current,\n (id, path) => pathFromPlane(path, inputsRef.current?.planeOfNode?.(id, camera()) ?? null),\n ), [camera, depRegistryRef, inputsRef]);\n\n const { targetScale } = useDeviceProfile();\n\n // Selection chrome hit-testing for this view: same construction the surface\n // does for its own, against this view's chrome and camera.\n const affordanceAt = useMemo(() => {\n const inner = buildAffordanceAt({\n getChromeState: () => helpersRef.current.getChromeState(),\n getView: camera,\n targetScale,\n rotationBadge, handleHitRadius: inputs?.resizeHandles?.hitRadiusPx, edgeHandles: inputs?.resizeHandles?.edges,\n getAnchorState,\n getIsVisible: () => helpersRef.current.getIsVisible(),\n });\n return (world: { x: number; y: number }) => {\n // A registered layer this view paints gets first refusal, on this\n // view's frame and envelope. One painted over the surface already had\n // its chance: it occludes the view before routing reaches here.\n const extra = registry?.surface()?.hitTestExtras(\n world.x, world.y, camera(), sizeOf(rectNow()), helpersRef.current, drawnLayers(),\n );\n return extra ? layerAffordance(extra.layerId, extra.hit) : registry?.markerAt(id, world) ?? inner(world);\n };\n }, [id, getAnchorState, rectNow, registry, targetScale, camera, drawnLayers, rotationBadge, inputs?.resizeHandles, helpersRef]);\n\n const classifyTarget = useMemo(() => buildClassifyTarget(\n () => live.current.selection.get(),\n (wx, wy) => {\n const i = inputsRef.current;\n // This view's camera: the dispatcher converted with `clientToWorldHere`,\n // and a screen-pixel tolerance needs the scale that produced it. The\n // layer gate is this view's too, never the surface's.\n const frame = { ...camera(), layerIsPainted };\n if (i?.pickBest) return i.pickBest(wx, wy, frame);\n const ids = i?.pickEvery?.(wx, wy, frame) ?? [];\n return ids.length > 0 ? ids[ids.length - 1]! : null;\n },\n (id) => inputsRef.current?.kindOfNode?.(id),\n (id) => inputsRef.current?.doubleClickNames?.(id) ?? id,\n ), [camera, layerIsPainted, live, inputsRef]);\n\n const registration = useMemo<ViewRegistration>(() => ({\n id,\n ...(parent !== undefined ? { parent } : {}),\n order,\n interactive,\n paint,\n held,\n aim,\n setAim,\n layer: createViewportLayer<unknown, unknown>({\n id,\n label: label ?? id,\n source: () => [...drawnLayers(), ...(registry?.markerLayers(id) ?? [])],\n view: cameraAt,\n bounds: (outer, dims) => rectAt(outer, dims),\n ...(parent !== undefined ? { clip: (outer: View, dims: Dims) => frameIn(outer, dims)?.clip ?? NO_RECT } : {}),\n // The surface half of the envelope passes through; the view half is\n // this view's, so its layers paint its chrome rather than the\n // surface's.\n data: (outer) => ({ ...(outer as object), ...helpersRef.current, viewId: id }),\n ...(background !== undefined ? { background } : {}),\n }),\n layerIsPainted,\n drawnLayers,\n target: {\n dispatcher: dispatcherRef.current!,\n affordanceAt,\n classifyTarget,\n clientToWorld: clientToWorldHere,\n deps: () => ({\n view: viewApi, ingestion: ingestionApi, hitAt: hitAtOf(classifyTarget),\n // An Escape here cancels what is in flight here.\n dispatcher: { cancelAll: (reason) => dispatcherRef.current!.cancelAll(reason) },\n // Only a view with its own selection overlays that one; otherwise the\n // surface's answer stands, wrappers (`selectable`) included.\n ...(live.current.viewSelection ? { selection: live.current.viewSelection } : {}),\n }),\n // Action eligibility is chrome-caps evaluated against this view, so a\n // rule that hides an action in one panel cannot decline a gesture in\n // another.\n getRuleCtx: () => inputsRef.current?.chromeCaps?.ruleCtx(ruleInputs()),\n },\n }), [id, parent, order, interactive, paint, held, aim, setAim, label, background, rectAt, cameraAt, viewApi,\n affordanceAt, classifyTarget, clientToWorldHere, ruleInputs, ingestionApi, drawnLayers,\n layerIsPainted, live, inputsRef, helpersRef, frameIn, registry]);\n\n useEffect(() => {\n if (!registry) return;\n return registry.register(registration);\n }, [registry, registration]);\n\n // Apart from the registration, which is replaced whenever a prop it reads\n // changes: only the view going away ends what is in flight over it.\n useEffect(() => () => dispatcherRef.current?.cancelAll('cancel'), []);\n\n // The surface paints this view from `live`, so any committed render of it —\n // a controlled camera, its bounds, its layer gate — needs a frame.\n useEffect(() => {\n registry?.surface()?.requestRedraw();\n });\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAM,YAAqD;CACzD,SAAS;CACT,UAAU;CACV,UAAU;AACZ;AAEA,IAAM,uBAAgC;AAEtC,IAAM,cAAc,MAAwE;;;;;;;;;AAW5F,SAAgB,WAAW,OAA8B;CACvD,MAAM,EACJ,IAAI,QAAQ,QACZ,SAAS,YAAY,iBAAiB,YAAY,YAAY,QAAQ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CAEpE,gBAAgB;EACd,IAAI,CAAC,UAAU;EACf,OAAO,SAAS,SAAS,YAAY;CACvC,GAAG,CAAC,UAAU,YAAY,CAAC;CAI3B,sBAAsB,cAAc,SAAS,UAAU,QAAQ,GAAG,CAAC,CAAC;CAIpE,gBAAgB;EACd,UAAU,QAAQ,CAAC,EAAE,cAAc;CACrC,CAAC;CAED,OAAO;AACT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import hud_module_default from "./hud.module.js";
|
|
2
2
|
import { useHostAnchor } from "./useHostAnchor.js";
|
|
3
|
-
import { useOptionalActiveToolContext } from "@weasel-js/routing/react";
|
|
4
3
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
4
|
+
import { useOptionalActiveToolContext } from "@weasel-js/routing/react";
|
|
5
5
|
|
|
6
6
|
//#region src/canvas/ModalityHud.tsx
|
|
7
7
|
/**
|
package/dist/canvas/NodeShape.js
CHANGED
|
@@ -130,7 +130,10 @@ function findShapeBounds(node, pose, ctx) {
|
|
|
130
130
|
function shapeCoversPoint(node, pose, x, y, opts = {}) {
|
|
131
131
|
const sil = findShapeSilhouette(node, pose, { derivedPath: opts.derivedPath });
|
|
132
132
|
if (sil === null) return true;
|
|
133
|
-
const ink = findShapeInk(node, pose, {
|
|
133
|
+
const ink = findShapeInk(node, pose, {
|
|
134
|
+
scale: opts.scale,
|
|
135
|
+
inherited: opts.inherited
|
|
136
|
+
}) ?? DEFAULT_INK;
|
|
134
137
|
const inside = pathContainsPoint(sil, x, y);
|
|
135
138
|
if (ink.filled && inside) return true;
|
|
136
139
|
const slop = widenSlop(opts.tolerance, (inside ? ink.insetPx : ink.outsetPx) ?? 0, opts.scale);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NodeShape.js","names":[],"sources":["../../src/canvas/NodeShape.ts"],"sourcesContent":["/**\n * NodeShape — the **shape trait's** registry: the per-kind `paint` + `silhouette` used by\n * `defaultDrawOne`, clipping, non-rect hit-testing, and lasso/area-select. Teaching the kit\n * about a new kind of shape goes through this registry rather than by overriding `drawOne`.\n *\n * The first entry whose `matches` predicate returns true paints the node: `'high'` entries\n * first, then the built-ins, then `'normal'` ones, in registration order within a tier. Every\n * built-in but `kit:derived` additionally requires a rect-shaped pose — a scene whose poses are\n * some other shape matches none of them, and paints through a consumer painter or not at all.\n */\nimport { glyphGeneration } from '@weasel-js/font';\nimport {\n pathContainsPoint,\n strokeHitTest,\n type Path\n} from '@weasel-js/geom';\nimport { pathThroughPoseFrame } from '@weasel-js/geom';\nimport { bumpNodeMemoGeneration, nodeMemo } from 'core/scene/nodeMemo';\nimport type { Node } from 'core/scene/types';\nimport type { Bounds } from 'core/viewport/fitViewToBounds';\nimport { hasSlop, slopForStrokeHit, widenSlop, type PickSlop } from 'core/viewport/screenSlop';\nimport { DERIVED_PAINTER } from './nodeShapes/derivedPainter';\nimport { IMAGE_PAINTER } from './nodeShapes/imagePainter';\nimport { MEASURE_PAINTER } from './nodeShapes/measurePainter';\nimport { derivesPath } from './nodeShapes/memo';\nimport { PATH_PAINTER } from './nodeShapes/pathPainter';\nimport { paintsPose } from './nodeShapes/poseBox';\nimport { RECT_FALLBACK_PAINTER } from './nodeShapes/rectFallbackPainter';\nimport { SHAPE_PAINTER } from './nodeShapes/shapePainter';\nimport { TEXT_PAINTER } from './nodeShapes/textPainter';\nimport type { NodeShapeEntry, NodeInk, NodeSilhouetteCtx, NodeInkCtx } from './nodeShapeTypes';\nexport type { NodePaintCtx, SceneViewDrawOne, NodeShapeEntry, NodeInk, NodeSilhouetteCtx, NodeInkCtx } from './nodeShapeTypes';\n\n/** What a painter that declares no `ink` is assumed to do. */\nexport const DEFAULT_INK: Readonly<NodeInk> = Object.freeze({ filled: true, outset: 0, inset: 0 });\n\n/** Options for `registerNodeShape`. */\nexport interface RegisterNodeShapeOptions {\n /** `'high'` puts the painter ahead of all normally-registered ones (so\n * it can win over a kit built-in). `'normal'` appends at the end. */\n priority?: 'high' | 'normal';\n}\n\nconst PAINTERS: { high: NodeShapeEntry[]; normal: NodeShapeEntry[] } = {\n high: [],\n normal: [],\n};\n\n// The built-ins go in on first use, not at module load: a bundler may drop an\n// import kept only for its side effect, and the registry would come up empty.\nlet builtInsRegistered = false;\nfunction ensureBuiltIns(): void {\n if (builtInsRegistered) return;\n builtInsRegistered = true;\n registerBuiltInShapePainters();\n}\n\n/** Register a shape painter. Returns a disposer that removes it. */\nexport function registerNodeShape<TData, TPose>(\n painter: NodeShapeEntry<TData, TPose>,\n opts: RegisterNodeShapeOptions = {},\n): () => void {\n ensureBuiltIns();\n const list = opts.priority === 'high' ? PAINTERS.high : PAINTERS.normal;\n list.push(painter as NodeShapeEntry);\n // The painter set is exactly the ambient state `findNodeShape` reads, and a\n // memo keyed on the node alone cannot see it change. See `nodeMemo`.\n bumpNodeMemoGeneration();\n return () => {\n const i = list.indexOf(painter as NodeShapeEntry);\n if (i >= 0) list.splice(i, 1);\n bumpNodeMemoGeneration();\n };\n}\n\n/**\n * Slot names for what picking asks per node per pointer move: which painter matches, and that\n * painter's silhouette path. Both go through {@link nodeMemo}, so they invalidate on `data`\n * (and, for the silhouette, `pose`) reference changes and on a painter registration.\n *\n * Separate slots rather than one entry: they mostly invalidate together, but not always, and a\n * shared entry would force the stricter key on both.\n */\nconst PAINTER_SLOT = 'shape:painter';\nconst PAINTER_SLOT_NONRECT = 'shape:painter:nonrect';\nconst PAINTER_SLOT_DERIVED = 'shape:painter:derived';\nconst PAINTER_SLOT_DERIVED_NONRECT = 'shape:painter:derived:nonrect';\nconst SILHOUETTE_SLOT = 'shape:silhouette';\nconst TEXT_SILHOUETTE_SLOT = 'shape:silhouette:text';\n\n/** The painter that will render `node` — first match in priority order — or undefined if\n * none accepts it. */\nexport function findNodeShape<TData, TPose>(\n node: Node<TData, string, TPose>,\n): NodeShapeEntry<TData, TPose> | undefined {\n // Built-in painters also gate on pose shape and on whether the node derives\n // its path, neither of which shows in `data`, so the key carries both.\n const rect = paintsPose(node.pose);\n const slot = derivesPath(node)\n ? (rect ? PAINTER_SLOT_DERIVED : PAINTER_SLOT_DERIVED_NONRECT)\n : (rect ? PAINTER_SLOT : PAINTER_SLOT_NONRECT);\n return nodeMemo(node as { data?: unknown }, slot, undefined, () =>\n matchNodeShape(node),\n );\n}\n\nfunction matchNodeShape<TData, TPose>(\n node: Node<TData, string, TPose>,\n): NodeShapeEntry<TData, TPose> | undefined {\n ensureBuiltIns();\n for (const p of PAINTERS.high) {\n if (p.matches(node as Node<unknown, string, unknown>)) {\n return p as NodeShapeEntry<TData, TPose>;\n }\n }\n for (const p of PAINTERS.normal) {\n if (p.matches(node as Node<unknown, string, unknown>)) {\n return p as NodeShapeEntry<TData, TPose>;\n }\n }\n return undefined;\n}\n\n/** The silhouette path of `node`, in **world** coords, or null if no painter matches or the\n * matching painter has none.\n *\n * Painters return their silhouette in the pose's local (unrotated) frame;\n * this bakes the pose's frame (`poseFrameOf`: its rotation and `transform`)\n * on top, so clips/area-select of a turned or skewed node use the boundary\n * the renderer draws. */\nexport function findShapeSilhouette<TData, TPose>(\n node: Node<TData, string, TPose>,\n pose: TPose,\n ctx?: NodeSilhouetteCtx,\n): Path | null {\n const build = (): Path | null => {\n const sil = findNodeShape(node)?.silhouette?.(node, pose, ctx) ?? null;\n return sil && pathThroughPoseFrame(sil, pose);\n };\n // `SILHOUETTE_SLOT`'s key is (node, pose, data) and cannot see\n // `ctx.derivedPath` — the same reason `kit:derived` skips `PAINT_SLOT`.\n // Memoizing here would serve one caller's silhouette to a caller that\n // passed a different path. Only an actual path skips it: a scene-backed\n // source answers `null` for every ordinary node, and treating that as a\n // reason to bypass would retire the memo for the whole scene.\n if (ctx?.derivedPath != null) return build();\n // Line boxes follow font metrics, and a face landing changes those with no\n // change to the node, so the text entry is checked against the glyph epoch.\n if (findNodeShape(node) === (TEXT_PAINTER as NodeShapeEntry<unknown, unknown>)) {\n const epoch = glyphGeneration();\n const held = nodeMemo(node as { data?: unknown }, TEXT_SILHOUETTE_SLOT, pose,\n (): { epoch: number; path: Path | null } => ({ epoch, path: build() }));\n if (held.epoch !== epoch) {\n held.epoch = epoch;\n held.path = build();\n }\n return held.path;\n }\n return nodeMemo(node as { data?: unknown }, SILHOUETTE_SLOT, pose, build);\n}\n\n/** Find the painter for `node` and ask how it inks its silhouette. Returns\n * the painter's declared {@link NodeInk}, or `null` when no painter matches\n * or it declares none — callers substitute {@link DEFAULT_INK}. */\nexport function findShapeInk<TData, TPose>(\n node: Node<TData, string, TPose>,\n pose: TPose,\n ctx?: NodeInkCtx,\n): NodeInk | null {\n return findNodeShape(node)?.ink?.(node, pose, ctx) ?? null;\n}\n\n/** Find the painter for `node` and ask for the box its paint fits in. `null`\n * when no painter matches, or the one that does cannot say — see\n * {@link NodeShapeEntry.bounds}. */\nexport function findShapeBounds<TData, TPose>(\n node: Node<TData, string, TPose>,\n pose: TPose,\n ctx?: NodeInkCtx,\n): Bounds | null {\n return findNodeShape(node)?.bounds?.(node, pose, ctx) ?? null;\n}\n\n/** Options for {@link shapeCoversPoint}. */\nexport interface ShapeCoversPointOptions {\n /** Extra grab distance around the outline: **world** units as a number,\n * or screen pixels under a view scale (`{ px, scale }`), which is measured\n * on screen and so stays exact under non-uniform zoom. Defaults to `0`,\n * where a hairline is too thin a target to hit. */\n tolerance?: PickSlop;\n /** View scale, passed to the painter's `ink`, and what a screen reach is\n * read at under a world `tolerance`. Defaults to 1. */\n scale?: number;\n /** The node's derived path — see {@link NodeSilhouetteCtx.derivedPath}.\n * Without it a derived node reports no silhouette and this answers `true`\n * everywhere, which degrades picking to the caller's AABB: for an edge,\n * a zero-sized pose. */\n derivedPath?: Path | null;\n}\n\n/**\n * Does the shape `node` actually paints cover the world point? Asks the painter's silhouette,\n * the same boundary used for clipping and area-select, rather than the pose rect.\n *\n * The ink counts too: a shape whose interior isn't filled is grabbable along its outline and\n * not through its empty middle. The outline's grab width is the stroke's half-width plus\n * `tolerance`.\n *\n * A painter with no `silhouette`, or one that returns `null` for this node, reports `true` —\n * \"no opinion\" — so callers should keep their own AABB test as a pre-filter.\n */\nexport function shapeCoversPoint<TData, TPose>(\n node: Node<TData, string, TPose>,\n pose: TPose,\n x: number,\n y: number,\n opts: ShapeCoversPointOptions = {},\n): boolean {\n const sil = findShapeSilhouette(node, pose, { derivedPath: opts.derivedPath });\n if (sil === null) return true;\n const ink = findShapeInk(node, pose, { scale: opts.scale }) ?? DEFAULT_INK;\n const inside = pathContainsPoint(sil, x, y);\n if (ink.filled && inside) return true;\n // The stroke reaches a different distance on each side, so which side the point is on\n // picks the reach. `tolerance` also makes a filled shape grabbable a few pixels outside\n // its edge.\n const slop = widenSlop(opts.tolerance, (inside ? ink.insetPx : ink.outsetPx) ?? 0, opts.scale);\n const { extra, opts: hit } = slopForStrokeHit(slop);\n const reach = (inside ? ink.inset : ink.outset) + extra;\n return (reach > 0 || hasSlop(slop)) && strokeHitTest(sil, x, y, reach, hit);\n}\n\n/** The current painters in evaluation order — `'high'` tier first, then `'normal'`. */\nexport function getNodeShapes(): readonly NodeShapeEntry[] {\n ensureBuiltIns();\n return [...PAINTERS.high, ...PAINTERS.normal];\n}\n\n/** Test-only: clear the registry and re-register the built-ins. */\nexport function _resetShapePaintersForTests(): void {\n PAINTERS.high.length = 0;\n PAINTERS.normal.length = 0;\n builtInsRegistered = false;\n ensureBuiltIns();\n // `registerNodeShape` already bumps, but the clearing above happens without one.\n bumpNodeMemoGeneration();\n}\n\nfunction registerBuiltInShapePainters(): void {\n registerNodeShape(TEXT_PAINTER);\n registerNodeShape(MEASURE_PAINTER);\n // Ahead of path/shape/image: a derived node whose `data` also carries a\n // `path`, `shape` or `image` means the derived path, and those three match\n // on the presence of the field alone.\n registerNodeShape(DERIVED_PAINTER);\n registerNodeShape(PATH_PAINTER);\n registerNodeShape(SHAPE_PAINTER);\n registerNodeShape(IMAGE_PAINTER);\n registerNodeShape(RECT_FALLBACK_PAINTER);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,cAAiC,OAAO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S,+BAAqC;CAC5C,kBAAkB,YAAY;CAC9B,kBAAkB,eAAe;CAIjC,kBAAkB,eAAe;CACjC,kBAAkB,YAAY;CAC9B,kBAAkB,aAAa;CAC/B,kBAAkB,aAAa;CAC/B,kBAAkB,qBAAqB;AACzC"}
|
|
1
|
+
{"version":3,"file":"NodeShape.js","names":[],"sources":["../../src/canvas/NodeShape.ts"],"sourcesContent":["/**\n * NodeShape — the **shape trait's** registry: the per-kind `paint` + `silhouette` used by\n * `defaultDrawOne`, clipping, non-rect hit-testing, and lasso/area-select. Teaching the kit\n * about a new kind of shape goes through this registry rather than by overriding `drawOne`.\n *\n * The first entry whose `matches` predicate returns true paints the node: `'high'` entries\n * first, then the built-ins, then `'normal'` ones, in registration order within a tier. Every\n * built-in but `kit:derived` additionally requires a rect-shaped pose — a scene whose poses are\n * some other shape matches none of them, and paints through a consumer painter or not at all.\n */\nimport { glyphGeneration } from '@weasel-js/font';\nimport {\n pathContainsPoint,\n strokeHitTest,\n type Path\n} from '@weasel-js/geom';\nimport { pathThroughPoseFrame } from '@weasel-js/geom';\nimport { bumpNodeMemoGeneration, nodeMemo } from 'core/scene/nodeMemo';\nimport type { Node } from 'core/scene/types';\nimport type { Bounds } from 'core/viewport/fitViewToBounds';\nimport { hasSlop, slopForStrokeHit, widenSlop, type PickSlop } from 'core/viewport/screenSlop';\nimport { DERIVED_PAINTER } from './nodeShapes/derivedPainter';\nimport { IMAGE_PAINTER } from './nodeShapes/imagePainter';\nimport { MEASURE_PAINTER } from './nodeShapes/measurePainter';\nimport { derivesPath } from './nodeShapes/memo';\nimport { PATH_PAINTER } from './nodeShapes/pathPainter';\nimport { paintsPose } from './nodeShapes/poseBox';\nimport { RECT_FALLBACK_PAINTER } from './nodeShapes/rectFallbackPainter';\nimport { SHAPE_PAINTER } from './nodeShapes/shapePainter';\nimport { TEXT_PAINTER } from './nodeShapes/textPainter';\nimport type { NodeShapeEntry, NodeInk, NodeSilhouetteCtx, NodeInkCtx } from './nodeShapeTypes';\nexport type { NodePaintCtx, SceneViewDrawOne, NodeShapeEntry, NodeInk, NodeSilhouetteCtx, NodeInkCtx } from './nodeShapeTypes';\nexport type { InheritedPaint } from 'core/scene/inheritedPaint';\n\n/** What a painter that declares no `ink` is assumed to do. */\nexport const DEFAULT_INK: Readonly<NodeInk> = Object.freeze({ filled: true, outset: 0, inset: 0 });\n\n/** Options for `registerNodeShape`. */\nexport interface RegisterNodeShapeOptions {\n /** `'high'` puts the painter ahead of all normally-registered ones (so\n * it can win over a kit built-in). `'normal'` appends at the end. */\n priority?: 'high' | 'normal';\n}\n\nconst PAINTERS: { high: NodeShapeEntry[]; normal: NodeShapeEntry[] } = {\n high: [],\n normal: [],\n};\n\n// The built-ins go in on first use, not at module load: a bundler may drop an\n// import kept only for its side effect, and the registry would come up empty.\nlet builtInsRegistered = false;\nfunction ensureBuiltIns(): void {\n if (builtInsRegistered) return;\n builtInsRegistered = true;\n registerBuiltInShapePainters();\n}\n\n/** Register a shape painter. Returns a disposer that removes it. */\nexport function registerNodeShape<TData, TPose>(\n painter: NodeShapeEntry<TData, TPose>,\n opts: RegisterNodeShapeOptions = {},\n): () => void {\n ensureBuiltIns();\n const list = opts.priority === 'high' ? PAINTERS.high : PAINTERS.normal;\n list.push(painter as NodeShapeEntry);\n // The painter set is exactly the ambient state `findNodeShape` reads, and a\n // memo keyed on the node alone cannot see it change. See `nodeMemo`.\n bumpNodeMemoGeneration();\n return () => {\n const i = list.indexOf(painter as NodeShapeEntry);\n if (i >= 0) list.splice(i, 1);\n bumpNodeMemoGeneration();\n };\n}\n\n/**\n * Slot names for what picking asks per node per pointer move: which painter matches, and that\n * painter's silhouette path. Both go through {@link nodeMemo}, so they invalidate on `data`\n * (and, for the silhouette, `pose`) reference changes and on a painter registration.\n *\n * Separate slots rather than one entry: they mostly invalidate together, but not always, and a\n * shared entry would force the stricter key on both.\n */\nconst PAINTER_SLOT = 'shape:painter';\nconst PAINTER_SLOT_NONRECT = 'shape:painter:nonrect';\nconst PAINTER_SLOT_DERIVED = 'shape:painter:derived';\nconst PAINTER_SLOT_DERIVED_NONRECT = 'shape:painter:derived:nonrect';\nconst SILHOUETTE_SLOT = 'shape:silhouette';\nconst TEXT_SILHOUETTE_SLOT = 'shape:silhouette:text';\n\n/** The painter that will render `node` — first match in priority order — or undefined if\n * none accepts it. */\nexport function findNodeShape<TData, TPose>(\n node: Node<TData, string, TPose>,\n): NodeShapeEntry<TData, TPose> | undefined {\n // Built-in painters also gate on pose shape and on whether the node derives\n // its path, neither of which shows in `data`, so the key carries both.\n const rect = paintsPose(node.pose);\n const slot = derivesPath(node)\n ? (rect ? PAINTER_SLOT_DERIVED : PAINTER_SLOT_DERIVED_NONRECT)\n : (rect ? PAINTER_SLOT : PAINTER_SLOT_NONRECT);\n return nodeMemo(node as { data?: unknown }, slot, undefined, () =>\n matchNodeShape(node),\n );\n}\n\nfunction matchNodeShape<TData, TPose>(\n node: Node<TData, string, TPose>,\n): NodeShapeEntry<TData, TPose> | undefined {\n ensureBuiltIns();\n for (const p of PAINTERS.high) {\n if (p.matches(node as Node<unknown, string, unknown>)) {\n return p as NodeShapeEntry<TData, TPose>;\n }\n }\n for (const p of PAINTERS.normal) {\n if (p.matches(node as Node<unknown, string, unknown>)) {\n return p as NodeShapeEntry<TData, TPose>;\n }\n }\n return undefined;\n}\n\n/** The silhouette path of `node`, in **world** coords, or null if no painter matches or the\n * matching painter has none.\n *\n * Painters return their silhouette in the pose's local (unrotated) frame;\n * this bakes the pose's frame (`poseFrameOf`: its rotation and `transform`)\n * on top, so clips/area-select of a turned or skewed node use the boundary\n * the renderer draws. */\nexport function findShapeSilhouette<TData, TPose>(\n node: Node<TData, string, TPose>,\n pose: TPose,\n ctx?: NodeSilhouetteCtx,\n): Path | null {\n const build = (): Path | null => {\n const sil = findNodeShape(node)?.silhouette?.(node, pose, ctx) ?? null;\n return sil && pathThroughPoseFrame(sil, pose);\n };\n // `SILHOUETTE_SLOT`'s key is (node, pose, data) and cannot see\n // `ctx.derivedPath` — the same reason `kit:derived` skips `PAINT_SLOT`.\n // Memoizing here would serve one caller's silhouette to a caller that\n // passed a different path. Only an actual path skips it: a scene-backed\n // source answers `null` for every ordinary node, and treating that as a\n // reason to bypass would retire the memo for the whole scene.\n if (ctx?.derivedPath != null) return build();\n // Line boxes follow font metrics, and a face landing changes those with no\n // change to the node, so the text entry is checked against the glyph epoch.\n if (findNodeShape(node) === (TEXT_PAINTER as NodeShapeEntry<unknown, unknown>)) {\n const epoch = glyphGeneration();\n const held = nodeMemo(node as { data?: unknown }, TEXT_SILHOUETTE_SLOT, pose,\n (): { epoch: number; path: Path | null } => ({ epoch, path: build() }));\n if (held.epoch !== epoch) {\n held.epoch = epoch;\n held.path = build();\n }\n return held.path;\n }\n return nodeMemo(node as { data?: unknown }, SILHOUETTE_SLOT, pose, build);\n}\n\n/** Find the painter for `node` and ask how it inks its silhouette. Returns\n * the painter's declared {@link NodeInk}, or `null` when no painter matches\n * or it declares none — callers substitute {@link DEFAULT_INK}. */\nexport function findShapeInk<TData, TPose>(\n node: Node<TData, string, TPose>,\n pose: TPose,\n ctx?: NodeInkCtx,\n): NodeInk | null {\n return findNodeShape(node)?.ink?.(node, pose, ctx) ?? null;\n}\n\n/** Find the painter for `node` and ask for the box its paint fits in. `null`\n * when no painter matches, or the one that does cannot say — see\n * {@link NodeShapeEntry.bounds}. */\nexport function findShapeBounds<TData, TPose>(\n node: Node<TData, string, TPose>,\n pose: TPose,\n ctx?: NodeInkCtx,\n): Bounds | null {\n return findNodeShape(node)?.bounds?.(node, pose, ctx) ?? null;\n}\n\n/** Options for {@link shapeCoversPoint}. */\nexport interface ShapeCoversPointOptions {\n /** Extra grab distance around the outline: **world** units as a number,\n * or screen pixels under a view scale (`{ px, scale }`), which is measured\n * on screen and so stays exact under non-uniform zoom. Defaults to `0`,\n * where a hairline is too thin a target to hit. */\n tolerance?: PickSlop;\n /** View scale, passed to the painter's `ink`, and what a screen reach is\n * read at under a world `tolerance`. Defaults to 1. */\n scale?: number;\n /** The node's derived path — see {@link NodeSilhouetteCtx.derivedPath}.\n * Without it a derived node reports no silhouette and this answers `true`\n * everywhere, which degrades picking to the caller's AABB: for an edge,\n * a zero-sized pose. */\n derivedPath?: Path | null;\n /** See {@link NodeInkCtx.inherited}. Without it an `'inherit'` field is\n * read as none. */\n inherited?: NodeInkCtx['inherited'];\n}\n\n/**\n * Does the shape `node` actually paints cover the world point? Asks the painter's silhouette,\n * the same boundary used for clipping and area-select, rather than the pose rect.\n *\n * The ink counts too: a shape whose interior isn't filled is grabbable along its outline and\n * not through its empty middle. The outline's grab width is the stroke's half-width plus\n * `tolerance`.\n *\n * A painter with no `silhouette`, or one that returns `null` for this node, reports `true` —\n * \"no opinion\" — so callers should keep their own AABB test as a pre-filter.\n */\nexport function shapeCoversPoint<TData, TPose>(\n node: Node<TData, string, TPose>,\n pose: TPose,\n x: number,\n y: number,\n opts: ShapeCoversPointOptions = {},\n): boolean {\n const sil = findShapeSilhouette(node, pose, { derivedPath: opts.derivedPath });\n if (sil === null) return true;\n const ink = findShapeInk(node, pose, { scale: opts.scale, inherited: opts.inherited }) ?? DEFAULT_INK;\n const inside = pathContainsPoint(sil, x, y);\n if (ink.filled && inside) return true;\n // The stroke reaches a different distance on each side, so which side the point is on\n // picks the reach. `tolerance` also makes a filled shape grabbable a few pixels outside\n // its edge.\n const slop = widenSlop(opts.tolerance, (inside ? ink.insetPx : ink.outsetPx) ?? 0, opts.scale);\n const { extra, opts: hit } = slopForStrokeHit(slop);\n const reach = (inside ? ink.inset : ink.outset) + extra;\n return (reach > 0 || hasSlop(slop)) && strokeHitTest(sil, x, y, reach, hit);\n}\n\n/** The current painters in evaluation order — `'high'` tier first, then `'normal'`. */\nexport function getNodeShapes(): readonly NodeShapeEntry[] {\n ensureBuiltIns();\n return [...PAINTERS.high, ...PAINTERS.normal];\n}\n\n/** Test-only: clear the registry and re-register the built-ins. */\nexport function _resetShapePaintersForTests(): void {\n PAINTERS.high.length = 0;\n PAINTERS.normal.length = 0;\n builtInsRegistered = false;\n ensureBuiltIns();\n // `registerNodeShape` already bumps, but the clearing above happens without one.\n bumpNodeMemoGeneration();\n}\n\nfunction registerBuiltInShapePainters(): void {\n registerNodeShape(TEXT_PAINTER);\n registerNodeShape(MEASURE_PAINTER);\n // Ahead of path/shape/image: a derived node whose `data` also carries a\n // `path`, `shape` or `image` means the derived path, and those three match\n // on the presence of the field alone.\n registerNodeShape(DERIVED_PAINTER);\n registerNodeShape(PATH_PAINTER);\n registerNodeShape(SHAPE_PAINTER);\n registerNodeShape(IMAGE_PAINTER);\n registerNodeShape(RECT_FALLBACK_PAINTER);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,cAAiC,OAAO,OAAO;CAAE,QAAQ;CAAM,QAAQ;CAAG,OAAO;AAAE,CAAC;AASjG,IAAM,WAAiE;CACrE,MAAM,CAAC;CACP,QAAQ,CAAC;AACX;AAIA,IAAI,qBAAqB;AACzB,SAAS,iBAAuB;CAC9B,IAAI,oBAAoB;CACxB,qBAAqB;CACrB,6BAA6B;AAC/B;;AAGA,SAAgB,kBACd,SACA,OAAiC,CAAC,GACtB;CACZ,eAAe;CACf,MAAM,OAAO,KAAK,aAAa,SAAS,SAAS,OAAO,SAAS;CACjE,KAAK,KAAK,OAAyB;CAGnC,uBAAuB;CACvB,aAAa;EACX,MAAM,IAAI,KAAK,QAAQ,OAAyB;EAChD,IAAI,KAAK,GAAG,KAAK,OAAO,GAAG,CAAC;EAC5B,uBAAuB;CACzB;AACF;;;;;;;;;AAUA,IAAM,eAAe;AACrB,IAAM,uBAAuB;AAC7B,IAAM,uBAAuB;AAC7B,IAAM,+BAA+B;AACrC,IAAM,kBAAkB;AACxB,IAAM,uBAAuB;;;AAI7B,SAAgB,cACd,MAC0C;CAG1C,MAAM,OAAO,WAAW,KAAK,IAAI;CACjC,MAAM,OAAO,YAAY,IAAI,IACxB,OAAO,uBAAuB,+BAC9B,OAAO,eAAe;CAC3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;CAAU,CAAC,KAAK;CAC1F,MAAM,SAAS,kBAAkB,KAAK,GAAG,CAAC;CAC1C,IAAI,IAAI,UAAU,QAAQ,OAAO;CAIjC,MAAM,OAAO,UAAU,KAAK,YAAY,SAAS,IAAI,UAAU,IAAI,aAAa,GAAG,KAAK,KAAK;CAC7F,MAAM,EAAE,OAAO,MAAM,QAAQ,iBAAiB,IAAI;CAClD,MAAM,SAAS,SAAS,IAAI,QAAQ,IAAI,UAAU;CAClD,QAAQ,QAAQ,KAAK,QAAQ,IAAI,MAAM,cAAc,KAAK,GAAG,GAAG,OAAO,GAAG;AAC5E;;AAGA,SAAgB,gBAA2C;CACzD,eAAe;CACf,OAAO,CAAC,GAAG,SAAS,MAAM,GAAG,SAAS,MAAM;AAC9C;AAYA,SAAS,+BAAqC;CAC5C,kBAAkB,YAAY;CAC9B,kBAAkB,eAAe;CAIjC,kBAAkB,eAAe;CACjC,kBAAkB,YAAY;CAC9B,kBAAkB,aAAa;CAC/B,kBAAkB,aAAa;CAC/B,kBAAkB,qBAAqB;AACzC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ActionsProvider, useActionsRegistry } from "@weasel-js/routing/react";
|
|
2
1
|
import { Fragment, jsx } from "react/jsx-runtime";
|
|
2
|
+
import { ActionsProvider, useActionsRegistry } from "@weasel-js/routing/react";
|
|
3
3
|
|
|
4
4
|
//#region src/canvas/SceneCanvas/ActionsProviderIfRoot.tsx
|
|
5
5
|
/** Mount an `<ActionsProvider>` only when none is already in scope. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { DepRegistryProvider, useOptionalDepRegistry } from "@weasel-js/routing/react";
|
|
2
1
|
import { Fragment, jsx } from "react/jsx-runtime";
|
|
2
|
+
import { DepRegistryProvider, useOptionalDepRegistry } from "@weasel-js/routing/react";
|
|
3
3
|
|
|
4
4
|
//#region src/canvas/SceneCanvas/DepRegistryProviderIfRoot.tsx
|
|
5
5
|
/** Mount a `<DepRegistryProvider>` only when none is already in scope, so a
|
|
@@ -2,8 +2,8 @@ import { useOptionalViewRegistry } from "../viewRegistry.js";
|
|
|
2
2
|
import { worldPointAt } from "./worldPointAt.js";
|
|
3
3
|
import { useEffect } from "react";
|
|
4
4
|
import { heldPointers } from "@weasel-js/gestures";
|
|
5
|
-
import { PointerContextProvider, usePointerContext } from "@weasel-js/routing/react";
|
|
6
5
|
import { Fragment, jsx } from "react/jsx-runtime";
|
|
6
|
+
import { PointerContextProvider, usePointerContext } from "@weasel-js/routing/react";
|
|
7
7
|
|
|
8
8
|
//#region src/canvas/SceneCanvas/PointerProviderIfRoot.tsx
|
|
9
9
|
/**
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { CanvasView } from "../CanvasView.js";
|
|
2
|
+
import { ViewMarker } from "../ViewMarker.js";
|
|
3
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
4
|
+
|
|
5
|
+
//#region src/canvas/SceneCanvas/SurfaceDeclarations.tsx
|
|
6
|
+
/** The views and markers a `<SceneCanvas>` declares on its surface: its
|
|
7
|
+
* `views` prop, its contributions' views, views added through the handle,
|
|
8
|
+
* then its contributions' markers. */
|
|
9
|
+
function SurfaceDeclarations({ views, entries, added }) {
|
|
10
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
11
|
+
views?.map((v, i) => /* @__PURE__ */ jsx(CanvasView, {
|
|
12
|
+
...v,
|
|
13
|
+
order: v.order ?? i
|
|
14
|
+
}, v.id)),
|
|
15
|
+
entries.flatMap((e) => e.views ?? []).map((v) => /* @__PURE__ */ jsx(CanvasView, { ...v }, `contribution:${v.id}`)),
|
|
16
|
+
added.map((v) => /* @__PURE__ */ jsx(CanvasView, { ...v }, `added:${v.id}`)),
|
|
17
|
+
entries.flatMap((e) => e.markers ?? []).map((m) => /* @__PURE__ */ jsx(ViewMarker, { ...m }, `contribution:${m.id}`))
|
|
18
|
+
] });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
//#endregion
|
|
22
|
+
export { SurfaceDeclarations };
|
|
23
|
+
//# sourceMappingURL=SurfaceDeclarations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SurfaceDeclarations.js","names":["_Fragment"],"sources":["../../../src/canvas/SceneCanvas/SurfaceDeclarations.tsx"],"sourcesContent":["import { CanvasView, type CanvasViewProps } from '../CanvasView';\nimport { ViewMarker } from '../ViewMarker';\nimport type { SurfaceContribution } from '../surfaceContribution';\n\n/** The views and markers a `<SceneCanvas>` declares on its surface: its\n * `views` prop, its contributions' views, views added through the handle,\n * then its contributions' markers. */\nexport function SurfaceDeclarations({ views, entries, added }: {\n views: readonly CanvasViewProps[] | undefined;\n entries: readonly SurfaceContribution[];\n added: readonly CanvasViewProps[];\n}) {\n return (\n <>\n {views?.map((v, i) => <CanvasView key={v.id} {...v} order={v.order ?? i} />)}\n {entries.flatMap((e) => e.views ?? []).map((v) => <CanvasView key={`contribution:${v.id}`} {...v} />)}\n {added.map((v) => <CanvasView key={`added:${v.id}`} {...v} />)}\n {entries.flatMap((e) => e.markers ?? []).map((m) => <ViewMarker key={`contribution:${m.id}`} {...m} />)}\n </>\n );\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,oBAAoB,EAAE,OAAO,SAAS,SAInD;CACD,OACE,qBAAAA,UAAA,EAAA,UAAA;EACG,OAAO,KAAK,GAAG,MAAM,oBAAC,YAAD;GAAuB,GAAI;GAAG,OAAO,EAAE,SAAS;EAAI,GAAnC,EAAE,EAAiC,CAAC;EAC1E,QAAQ,SAAS,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,oBAAC,YAAD,EAAyC,GAAI,EAAI,GAAhC,gBAAgB,EAAE,IAAc,CAAC;EACnG,MAAM,KAAK,MAAM,oBAAC,YAAD,EAAkC,GAAI,EAAI,GAAzB,SAAS,EAAE,IAAc,CAAC;EAC5D,QAAQ,SAAS,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,oBAAC,YAAD,EAAyC,GAAI,EAAI,GAAhC,gBAAgB,EAAE,IAAc,CAAC;CACtG,EAAA,CAAA;AAEN"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"canvasPassThrough.js","names":[],"sources":["../../../src/canvas/SceneCanvas/canvasPassThrough.ts"],"sourcesContent":["import type { SceneCanvasProps } from './props';\n\ntype Props = SceneCanvasProps<unknown, string, unknown>;\n\n/** Every prop `<SceneCanvas>` reads itself instead of handing to `<Canvas>`. */\nconst OWN_PROPS = [\n 'scene', 'geometry', 'poseDescriptor', 'selectTool', 'insertNodeFactories', 'insertPaint',\n 'ingestion', 'layoutDropTarget', 'reflowTransition', 'poseTransition', 'geometryProjection', 'routing',\n 'selection', 'selectionOptions', 'selectable', 'tools', 'features', 'enableKeybindings',\n 'claimKeys', 'enableGestureDispatcher', 'onToolsCreated', 'defaultTools', 'toolOptions',\n 'initialActiveTool', 'ambient', 'versionCheck', 'longPress', 'viewport', 'layers', 'actions',\n 'tune', 'describeKind', 'animator', 'views', 'children', 'debug', 'alphaFor', 'layerVisibility',\n 'layerOrder', 'isPointerInteractive', 'isolatedGroup', 'onDoubleClick', 'onClick', 'onHover', 'chromeVisibility', 'modes',\n 'pathEdit', 'defaultPathEdit', 'getFocused', 'cursorCoordsHud', 'pickHud', 'modalityHud', 'view',\n 'onViewChange', 'defaultView', 'viewBounds', 'redrawOn', 'snap',\n] as const satisfies readonly (keyof Props)[];\n\n/** The props `<SceneCanvas>` passes through to its `<Canvas>`: all but its own. */\nexport function canvasPassThrough<P extends object>(props: P): Omit<P, (typeof OWN_PROPS)[number] | 'presetSource'> {\n const rest = { ...props } as Record<string, unknown>;\n for (const key of OWN_PROPS) delete rest[key];\n delete rest.presetSource;\n return rest as Omit<P, (typeof OWN_PROPS)[number] | 'presetSource'>;\n}\n"],"mappings":";;AAKA,IAAM,YAAY;CAChB;CAAS;CAAY;CAAkB;CAAc;CAAuB;CAC5E;CAAa;CAAoB;CAAoB;CAAkB;CAAsB;CAC7F;CAAa;CAAoB;CAAc;CAAS;CAAY;CACpE;CAAa;CAA2B;CAAkB;CAAgB;CAC1E;CAAqB;CAAW;CAAgB;CAAa;CAAY;CAAU;CACnF;CAAQ;CAAgB;CAAY;CAAS;CAAY;CAAS;CAAY;
|
|
1
|
+
{"version":3,"file":"canvasPassThrough.js","names":[],"sources":["../../../src/canvas/SceneCanvas/canvasPassThrough.ts"],"sourcesContent":["import type { SceneCanvasProps } from './props';\n\ntype Props = SceneCanvasProps<unknown, string, unknown>;\n\n/** Every prop `<SceneCanvas>` reads itself instead of handing to `<Canvas>`. */\nconst OWN_PROPS = [\n 'scene', 'geometry', 'poseDescriptor', 'selectTool', 'insertNodeFactories', 'insertPaint',\n 'ingestion', 'layoutDropTarget', 'reflowTransition', 'poseTransition', 'geometryProjection', 'routing',\n 'selection', 'selectionOptions', 'selectable', 'tools', 'features', 'enableKeybindings',\n 'claimKeys', 'enableGestureDispatcher', 'onToolsCreated', 'defaultTools', 'toolOptions',\n 'initialActiveTool', 'ambient', 'versionCheck', 'longPress', 'viewport', 'layers', 'actions',\n 'tune', 'bindingOverrides', 'describeKind', 'animator', 'views', 'children', 'debug', 'alphaFor', 'layerVisibility',\n 'layerOrder', 'isPointerInteractive', 'isolatedGroup', 'onDoubleClick', 'onClick', 'onHover', 'chromeVisibility', 'modes',\n 'pathEdit', 'defaultPathEdit', 'getFocused', 'cursorCoordsHud', 'pickHud', 'modalityHud', 'view',\n 'onViewChange', 'defaultView', 'viewBounds', 'redrawOn', 'snap',\n] as const satisfies readonly (keyof Props)[];\n\n/** The props `<SceneCanvas>` passes through to its `<Canvas>`: all but its own. */\nexport function canvasPassThrough<P extends object>(props: P): Omit<P, (typeof OWN_PROPS)[number] | 'presetSource'> {\n const rest = { ...props } as Record<string, unknown>;\n for (const key of OWN_PROPS) delete rest[key];\n delete rest.presetSource;\n return rest as Omit<P, (typeof OWN_PROPS)[number] | 'presetSource'>;\n}\n"],"mappings":";;AAKA,IAAM,YAAY;CAChB;CAAS;CAAY;CAAkB;CAAc;CAAuB;CAC5E;CAAa;CAAoB;CAAoB;CAAkB;CAAsB;CAC7F;CAAa;CAAoB;CAAc;CAAS;CAAY;CACpE;CAAa;CAA2B;CAAkB;CAAgB;CAC1E;CAAqB;CAAW;CAAgB;CAAa;CAAY;CAAU;CACnF;CAAQ;CAAoB;CAAgB;CAAY;CAAS;CAAY;CAAS;CAAY;CAClG;CAAc;CAAwB;CAAiB;CAAiB;CAAW;CAAW;CAAoB;CAClH;CAAY;CAAmB;CAAc;CAAmB;CAAW;CAAe;CAC1F;CAAgB;CAAe;CAAc;CAAY;AAC3D;;AAGA,SAAgB,kBAAoC,OAAgE;CAClH,MAAM,OAAO,EAAE,GAAG,MAAM;CACxB,KAAK,MAAM,OAAO,WAAW,OAAO,KAAK;CACzC,OAAO,KAAK;CACZ,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"props.js","names":[],"sources":["../../../src/canvas/SceneCanvas/props.ts"],"sourcesContent":["import type { ModeRegistry } from '@weasel-js/modes';\nimport type { PathEditHost, PathEditOpening } from './pathEditHost';\nimport type { SceneCanvasGeometry } from './geometryProps';\nimport type { SceneCanvasHit, SceneCanvasPointerProps } from './pointerProps';\nimport type { Paint } from '@weasel-js/paint';\nimport type { ActionsProp, ActionTunings } from '@weasel-js/routing';\nimport { Yoke } from '@weasel-js/routing/react';\nimport type { PasteOmission } from 'core/adapters/types';\nimport type { Op } from 'core/ops/types';\nimport type { Node, Scene, SerializedScene } from 'core/scene/types';\nimport type { SelectionApi, UseSelectionOptions } from 'core/selection/useSelection';\nimport type { ContentHandlerEntry } from 'features/ingestion';\nimport type { SceneCanvasSnap } from 'features/snap/types';\nimport type { SvgIngestOptions } from 'interactions/actions/depSchema';\nimport type { GeometryProjection } from 'interactions/actions/geometryProjection';\nimport type { UseMoveOptions } from 'interactions/actions/move/options';\nimport type { PoseDescriptor } from 'interactions/actions/resize/geometry';\nimport type { UseResizeOptions } from 'interactions/actions/resize/options';\nimport type { UseRotateOptions } from 'interactions/actions/rotate/options';\nimport type { ReactNode } from 'react';\nimport type { Animator } from '@weasel-js/animator';\nimport type { PoseTransitionSeat } from '../../animation/poseTransition';\nimport { HANDLE_BASE_PX } from '../../core/device/targets';\nimport type { DeviceProfile } from '../../core/device/types';\nimport type { NodeRoutingEntry } from '../../core/scene/NodeRouting';\nimport type { DebugConfig } from '../../debug/types';\nimport type { LayoutDropTargetMode, ReflowTransition } from '../../layout/types';\nimport type { FlattenTolerance, ShaderProgramHandle } from '@weasel-js/renderer';\nimport type { Tool, ToolsApi } from '../../tools/overlayBinding';\nimport type { SceneSlotConfig } from '../buildSceneLayer';\nimport type { CanvasProps } from '../Canvas';\nimport type { LayersMap } from '../layerSlots';\nimport type { CanvasViewProps } from '../CanvasView';\nimport type { InsertNodeFactory, InsertPaint } from '../deps';\nimport type { SurfaceContribution } from '../surfaceContribution';\nimport type { CameraProps } from '../useCanvasView';\nimport type { FeatureEntry } from './features';\nimport type { BuiltinToolOptions } from './useBuiltinShapeTools';\nimport type { VersionCheck } from './useContributionRoles';\nimport type { SceneCanvasViewport } from './viewportProp';\n\n/** The adapter surface delete / duplicate / group / ungroup need, narrowed from\n * `SceneCanvasAdapter` because `useSceneStandardActions` is non-generic. */\nexport interface BridgeAdapter {\n applyOps(ops: Op[], label?: string): void;\n insertNode(node: { id: string; [k: string]: unknown }): void;\n removeNode(id: string): void;\n setSelection(ids: string[]): void;\n}\n\n/** Default size in CSS pixels for selection corner-handles AND their\n * hit-test radius, at `targetScale = 1`. Deliberately unscaled; kit-internal\n * use sites multiply by `DeviceProfile.targetScale`. */\nexport const DEFAULT_HANDLE_SIZE = HANDLE_BASE_PX;\n\n/** `<SceneCanvas longPress>`. */\nexport interface SceneCanvasLongPress {\n /**\n * Shown while a long-press is held and some binding would fire on it.\n * Default: a ring that fills around the press point\n * (`createLongPressFeedbackContribution()`), static under\n * `prefers-reduced-motion`. `false` shows nothing; a contribution replaces\n * it, reading the `longPress` dep. Installed beside `ambient`, so under a\n * `tools` takeover add it to your own `useTools` call instead.\n */\n feedback?: boolean | SurfaceContribution;\n /** Default true. A long-press some binding handled pulses\n * `navigator.vibrate` briefly, for touch and pen, where the API exists. */\n haptics?: boolean;\n /** Hold time in ms. Default `LONG_PRESS_MS` (500). */\n duration?: number;\n}\n\n/** `<SceneCanvas layers>`: a {@link LayersMap} whose scene slot may be partial,\n * since the defaults fill in whatever it leaves out. */\nexport type SceneCanvasLayers<TNode extends { id: string }, TPose> = LayersMap<\n TNode,\n TPose,\n Partial<SceneSlotConfig<TNode, TPose>>\n>;\n\nimport type { BuiltinToolId } from './builtinToolSets';\nimport type { ToolEntry } from '@weasel-js/routing';\nexport { BUILTIN_TOOL_IDS, type BuiltinToolId } from './builtinToolSets';\n\nexport type { SceneCanvasHit };\n\n/** Props for `<SceneCanvas>`. A scene is the only thing it needs. With nothing\n * else it renders that scene and keeps a selection no input sets; `features`\n * turns behavior on by preset, and the rest configures what those turn on. */\nexport type SceneCanvasProps<TData, TLayer extends string, TPose> =\n Omit<\n CanvasProps<TPose>,\n | 'adapter' | 'boundsOf' | 'selection' | 'tools'\n | 'viewState' // SceneCanvas makes the camera from the view props below\n | 'layers' // stripped so we can re-add as optional below\n | 'getIsVisible' // SceneCanvas synthesizes this from chromeVisibility\n | 'contentVersion' // SceneCanvas wires this to the scene's own version\n | 'layerVisibility' | 'layerOrder' // re-declared below: they gate picking here too\n | 'debug' // re-declared below with SceneCanvas's own `slops`\n > & CameraProps\n & {\n /** A `Scene` (typically from `useScene`) — or a `SerializedScene` JSON\n * object, which SceneCanvas bakes into a Scene on first render. The\n * serialized form is read once; pass a `key` on `<SceneCanvas>` to force\n * a fresh canvas from updated JSON.\n *\n * The JSON shape is relaxed (`version: number` rather than the `1`\n * literal) so an `import json from './x.json'` result satisfies the type\n * without an `as` cast. */\n scene:\n | Scene<TData, TLayer, TPose>\n | SerializedScene<TData, TLayer, TPose>\n | { version: number; systemLayers?: ReadonlyArray<{ id: string }>; nodes: ReadonlyArray<unknown> };\n\n /** Layer configuration. When omitted, SceneCanvas applies kit defaults\n * (a scene slot that paints `node.data.fill` rects + a default\n * selection overlay). A partial scene or selection-overlay config is\n * spread over that slot's defaults; pass `slot: null` to suppress a\n * default explicitly. */\n layers?: SceneCanvasLayers<Node<TData, TLayer, TPose>, TPose>;\n\n /** Which layout container a drag lands in when several contain the drop\n * point — the innermost (default), the topmost in paint order, or only\n * containers whose strategy declares a `dropRegion`. Decides both the\n * drag-time reflow preview and the commit. */\n layoutDropTarget?: LayoutDropTargetMode;\n\n /** Carries the siblings a layout reflow displaces to their slots over time\n * instead of snapping them — `useAnimatedReflow` builds one. Covers a\n * drag's reflow and every one the scene records (an insert, delete,\n * reorder or resize inside a laid-out container). Absent or `null`,\n * they snap. */\n reflowTransition?: ReflowTransition<TPose> | null;\n\n /** Glides what is shown when the scene writes a pose — a `scene.setPose`, an undo — and sees\n * removed nodes off with `exit`. Absent or `null`, writes snap. See {@link PoseTransitionSeat}. */\n poseTransition?: PoseTransitionSeat<TPose> | null;\n\n /**\n * Lets pose-transform actions (move, resize, nudge, flip — NOT rotate) also rewrite a\n * node's data-held geometry. Given a node and the affine `m` applied to its pose,\n * `transform(node, m)` returns updated `data`, or `null` for nodes with no data-held\n * geometry. When absent, the kit emits only the pose op and leaves `data` untouched.\n *\n * @see GeometryProjection\n */\n geometryProjection?: GeometryProjection;\n\n /**\n * Routing-trait classifiers. The kit builds a `NodeRouting` registry per `<SceneCanvas>`\n * from this prop and uses it to derive each hit's `kind`, which tool routing tables\n * (e.g. `{ target: 'rect', actionId: 'move' }`) match against. Pass `defaultNodeRouting`\n * for the kit's built-in shape kinds; spread additional entries for consumer-defined\n * kinds.\n *\n * **Memoize the `routing` value.** The registry is memoized on the prop's reference\n * identity: a fresh array each render rebuilds it and cascades into a new adapter,\n * churning gesture state.\n */\n routing?: readonly NodeRoutingEntry[];\n\n /** How to read and rewrite this scene's poses. Every built-in action,\n * the selection chrome and picking read it. Default `AUTO_POSE_DESCRIPTOR`\n * (rect poses and `Path` poses). */\n poseDescriptor?: PoseDescriptor<TPose>;\n\n // --- Geometry: hit-test + bounds overrides consumed by the internal\n // `useSelectTool`. Ignored if the consumer passes their own `tools`. ---\n geometry?: SceneCanvasGeometry;\n\n // --- Selection options. `pickBest` and `handleHitRadius` configure the\n // internal select tool, and are ignored under a `tools` takeover;\n // `move`, `resize` and `rotate` configure the `move`,\n // `resize` and `rotate` presets, and apply either way. ---\n selectTool?: {\n move?: UseMoveOptions<TPose>;\n resize?: UseResizeOptions<TPose>;\n /** Rotation options, or `false` to hide the rotation handle and bind it to\n * nothing; the `rotate` action stays, for other tools and `actions.rotate`. */\n rotate?: UseRotateOptions<TPose> | false;\n handleHitRadius?: number;\n /** Override the body-pick used on click/pointerdown. Alt-aware: receives\n * the live alt state + current selection so consumers can implement\n * alt-cycling through an overlapping stack. Default: top-most hit\n * (alt ignored). */\n pickBest?: (worldX: number, worldY: number, alt: boolean, sel: readonly string[]) => string | null;\n };\n\n /** Consumer node factories for the `insert` action, keyed by tool `kind`.\n * Each factory receives the drag AABB + tool `extras` and returns the\n * node's `data` (in this canvas's own data shape) plus an optional `pose`.\n * A factory for a kit kind (`rect`, `line`, …) replaces the kit's default\n * `{ path, fill }` node for that kind; a factory for a novel kind (e.g.\n * `text`) adds insert support the kit doesn't ship. The dep supplies id,\n * layer, and the undoable op. Return `null` to reject an insert. */\n insertNodeFactories?: Record<string, InsertNodeFactory>;\n\n /** The fill, stroke, and fill rule a kit-built shape is inserted with, by\n * tool `kind` and insert count; the kit keeps the geometry. Default\n * `paletteInsertPaint`, the kit palette in turn. A kind with a factory in\n * `insertNodeFactories` is not asked. */\n insertPaint?: InsertPaint;\n\n /** External-content ingestion (OS drop / clipboard paste / picker).\n *\n * - `handlers` — consumer content handlers registered for this canvas's\n * lifetime (priority 0 by default — they beat the kit's `image/*` /\n * `image/svg+xml` handlers at -100/-90).\n * - `resolveSrc` — overrides the image handler's `data:`-URI embed (e.g.\n * upload to an asset store, return the URL).\n * - `svg.unpack` — makes the kit SVG handler parse dropped SVG files into\n * native scene nodes instead of one embedded-image node each.\n * - `clipboard` — the kit weasel-JSON paste handler, enabled by default.\n * `reviver` restores JSON-unfriendly values the copying side encoded via\n * `jsonReplacer`. `enabled: false` opts the canvas out, but the kit\n * handler still consumes weasel-matching items and declines them inert\n * rather than letting them fall through. Also governs Cmd/Ctrl+V under\n * the `edit` preset; the rest takes the `ingest` preset.\n *\n * Memoize `handlers` and `clipboard.reviver`: an inline array literal\n * re-registers the handlers on every render. */\n ingestion?: {\n handlers?: ContentHandlerEntry[];\n resolveSrc?: (file: File) => Promise<string>;\n svg?: SvgIngestOptions;\n clipboard?: {\n reviver?: (key: string, value: unknown) => unknown;\n enabled?: boolean;\n /** Called when a paste left copied nodes out, with each one and the\n * reason. `useClipboardOps` takes the same callback as\n * `onPasteOmitted` for a paste from its own in-memory copy. */\n onOmitted?: (omitted: PasteOmission[]) => void;\n };\n };\n\n selection?: SelectionApi;\n selectionOptions?: UseSelectionOptions;\n\n /**\n * `false` stops the canvas writing the selection: no click, marquee,\n * lasso, action or tool, and no op committed through the adapter it hands\n * its tools. The consumer's own `SelectionApi` — the `selection` prop, or\n * `useSelection({ scene })` — still writes, and the canvas draws what it\n * holds. Undo and redo still restore the selection each history entry\n * recorded. Default `true`.\n *\n * Click policy (whether shift-click extends) is the selection's `mode`:\n * `useSelection({ mode: 'multi' })`, or `selectionOptions={{ mode: 'multi' }}`\n * for the selection the canvas builds itself.\n */\n selectable?: boolean;\n\n /**\n * Behavior presets to turn on, composable in any combination. A canvas\n * with none renders its scene and keeps a selection (the `selection` API\n * works) that no input sets: no tools, no standard actions or their keys,\n * no clipboard, no drop or paste, and no selection chrome. The dispatcher\n * is still mounted, so bindings a consumer adds work.\n *\n * - `view` — wheel pan and zoom, pinch, the zoom keys, and the hand tool\n * (H, or hold Space). Passing `viewport` implies it.\n * - `select` — the select tool, as the initial active tool and Escape's\n * return target: click to pick, drag on empty to marquee, click on empty\n * to clear.\n * - `outline` — the selection outline, whichever tool sets the selection.\n * - `pick` — `select` and `outline`.\n * - `move` — drag a body to move it, Alt-drag to clone it. Ambient, so it\n * runs under any tool that does not claim the drag.\n * - `resize` — resize handles, drawn and bound.\n * - `rotate` — the rotation handle, drawn and bound.\n * - `transform` — `resize` and `rotate`.\n * - `edit` — undo/redo, delete, duplicate, group/ungroup, nudge,\n * select-all, Escape, cancel-gesture, cut/copy/paste, fill and stroke,\n * and their keys. Cmd/Ctrl+V pastes nodes a kit canvas copied, from\n * this tab or another, and nothing else.\n * - `arrange` — align, distribute, reorder, flip.\n * - `paths` — pathfinder operations, path-edit entry and anchor editing.\n * - `ingest` — dropped and pasted content: images, SVG, files, and\n * whatever `ingestion.handlers` accept, on Cmd/Ctrl+V or an OS drop.\n * - `draw` — all of the above.\n *\n * Any `FeaturePreset` object goes beside the names: core's own\n * (`pathsPreset`), or one a package ships.\n * Tools add the actions they bind — a shape tool brings `insert` — so\n * `defaultTools` composes with any preset. `actions` then adds, overrides\n * or removes on top of what the presets registered.\n */\n features?: readonly FeatureEntry[];\n\n /** Extra tools or overrides keyed by id, or a full `ToolsApi` takeover.\n *\n * **Patch form** (`Record<string, Tool | true | false>`): merged\n * into the built-in registry on top of whatever `defaultTools` and\n * `features` already selected.\n * - `true` pulls in the built-in for this id (`'pen'`, `'lasso'`,\n * `'hand'`, …), the same as listing it in `defaultTools`. Unknown\n * built-in ids warn in dev and are ignored.\n * - `Tool` adds a new id or replaces an existing one in place\n * (dev-only warning if `defaultTools` also names that id).\n * - `false` omits a bundled tool entirely.\n * Auto-wiring (keybindings, dispatcher, action registry) still runs.\n *\n * **Takeover form** (`ToolsApi`): the internal registry is bypassed and\n * this `tools` value is forwarded to Canvas as-is — the consumer owns\n * active-slot management, and `pick`'s select tool is theirs to supply.\n * Every other preset still applies. Keybindings are still auto-wired\n * against the supplied registry; pass `enableKeybindings={false}` to opt\n * out. */\n tools?: ToolsApi | Record<string, Tool | true | false>;\n\n /**\n * Auto-wire keyboard shortcuts. Default `true`. When `false`, SceneCanvas still mounts\n * its tools but routes no keyboard input to them — neither tool hotkeys nor\n * keyboard-bound actions like delete / escape / nudge. Pointer, wheel, and contextmenu\n * interactions are unaffected.\n */\n enableKeybindings?: boolean;\n\n /**\n * Take the keyboard on mount, as a press in the canvas would. A key that\n * reaches the page goes to the canvas the user last pressed or scrolled\n * in, and to no canvas before the first such interaction, so a canvas in a\n * side panel does not take Space from a page that wants it. An app whose\n * canvas is the page sets this so its shortcuts work before the first\n * click. Default `false`.\n */\n claimKeys?: boolean;\n\n /**\n * Auto-mount the gesture dispatcher (`useGestureDispatcher`). Default `true`. `false` is\n * for tests or demos that drive actions another way, or that call\n * `useGestureDispatcher` themselves.\n */\n enableGestureDispatcher?: boolean;\n\n /** Called with the `ToolsApi` SceneCanvas constructs or receives, whenever its identity\n * changes. For introspection. */\n onToolsCreated?: (tools: ToolsApi) => void;\n\n /**\n * Built-in tools SceneCanvas registers in its internal `useTools`, on top\n * of the ones presets bring (`select` from `pick`, `hand` from `view`):\n * ids, or sets of them such as `SHAPE_TOOLS`, or `withoutTools(...)` of one.\n * Default: none. Each tool also registers the kit actions it binds, so\n * `['rect']` brings `insert`. Ignored when the consumer supplies their own\n * `tools` prop.\n */\n defaultTools?: readonly ToolEntry<BuiltinToolId>[];\n\n /** Per-tool option overrides for the built-in tools. Each entry is a\n * narrow subset of the underlying hook's options surface — `lasso.mode`,\n * `rig.state`, etc. */\n toolOptions?: BuiltinToolOptions;\n /** What gestures snap to, and how near it pulls. */\n snap?: SceneCanvasSnap;\n\n /** Initial active-slot tool id. Default: `'select'` when it is\n * registered, otherwise none — a canvas can run on ambient bindings\n * alone. Must be one of the registered tools. Ignored when the consumer\n * supplies their own `tools` prop. */\n initialActiveTool?: string;\n\n /** Always-on entries to register alongside the internal tools — every one\n * a `SurfaceContribution`, whose views, deps, overlay, bindings, actions\n * and `attach` all install from this one list, and uninstall when the\n * entry leaves it. A tool is a contribution too, so one can go here. If\n * you supply your own `tools` prop, this is ignored — wire `ambient`\n * through your own `useTools` call instead. */\n ambient?: readonly SurfaceContribution[];\n\n /** What an entry's `requires` does when the running kit does not meet\n * it: `'warn'` (the default) logs in development, `'strict'` throws,\n * `'off'` skips the check. */\n versionCheck?: VersionCheck;\n\n /** Touch and pen long-press: its hold time, its haptic, and the\n * feedback shown while it is held. */\n longPress?: SceneCanvasLongPress;\n\n /** Configures the `view` preset, and implies it. See {@link SceneCanvasViewport}. */\n viewport?: SceneCanvasViewport;\n\n /**\n * Tune actions on this canvas without restating them, keyed by action id:\n * `params` every invocation starts from, and `bindings` added beside the\n * action's own. A tuning applies to whichever descriptor holds the id, a\n * preset's or a tool's. Pass a stable object; a params thunk is read on\n * every call. See the core README (\"Tuning an action\").\n */\n tune?: ActionTunings;\n\n /**\n * Replace, add or mute whole action descriptors. Pass `null` to disable\n * all defaults. To change a built-in's params or add a key, use `tune`.\n */\n actions?: ActionsProp;\n\n /**\n * Given a scene node, return a short human-readable \"kind\" label (e.g. `'rectangle'`,\n * `'sticky note'`), which the kit publishes per id into any surrounding\n * `<SelectionContextProvider>`. Return `undefined` to skip an entry. When omitted,\n * each node reports its routing kind (see `routing`), and a node that routes as\n * `'unknown'` is left unlabeled.\n */\n describeKind?: (node: Node<TData, TLayer, TPose>) => string | undefined;\n\n /**\n * Animator to bind for per-frame redraws. SceneCanvas requests a redraw on every active\n * animation frame and paints `animator.colorOverrides` onto the scene's nodes: the\n * kit's path and shape painters apply them, and a custom `drawOne` receives them as\n * `ctx.vertexColors`.\n */\n animator?: Animator;\n\n /**\n * Extra views on this canvas: each is a camera over a rect of the same\n * surface, drawn through one GL context, with input routed to it. The flat\n * `view` / `onViewChange` props above stay the canvas's own camera — view\n * zero — and are unaffected by anything declared here.\n *\n * Order is paint and hit order, low to high. Each entry is a\n * `<CanvasView>`; mounting one as a child is the same declaration, and\n * children land after every entry here.\n */\n views?: readonly CanvasViewProps[];\n\n /**\n * Children rendered alongside the canvas, inside its input scope (e.g.\n * shortcuts overlays, probes).\n */\n children?: ReactNode;\n\n /** A yoke to join, from `useYoke()`: canvases on one yoke share the active tool, the gesture\n * in flight and history. Omitted, this canvas keeps its own. */\n yoke?: Yoke;\n\n /**\n * Chrome-caps visibility overrides, keyed by chrome id (`selection.outline`,\n * `selection.rotation-handle`, `gesture.marquee`, …). Each entry is a composable\n * {@link Condition} built from the `cond()` builder, merged on top of the kit's\n * `defaultVisibilityRules`. Set an id to `never` to suppress a chrome element\n * entirely (also unhittable), or to `always` to force-show.\n */\n chromeVisibility?: import('features/chrome-caps').VisibilityRules;\n\n /**\n * The app's mode registry (`createModeRegistry` in `@weasel-js/modes`).\n * The canvas reads the active mode from it to gate chrome, tool\n * activation and the dispatcher's eligibility filter, repaints when it\n * switches, and hands every registered mode to the dev-time route-conflict\n * check. Omitted, the canvas behaves as the kit's normal mode and nothing\n * revokes anchor editing.\n */\n modes?: ModeRegistry;\n\n /** Hands which path is being anchor-edited to the host. See {@link PathEditHost}. */\n pathEdit?: PathEditHost;\n /** A path to open in anchor edit as the canvas mounts, with anchors selected. Read once. */\n defaultPathEdit?: PathEditOpening;\n\n /**\n * Override detected device facts. Merged over what `matchMedia` reports;\n * `targetScale` is re-derived from the merged `coarsePointer` unless you\n * override it explicitly.\n */\n device?: Partial<DeviceProfile>;\n\n /**\n * Live focus getter for chrome-caps' `focused` ctx field, for visibility rules that\n * read the `focused` atom (the kit's default `selection.rotation-handle` rule does).\n * Omit to default `focused` to `true`.\n */\n getFocused?: () => boolean;\n\n /** Custom shader programs to compile on the renderer. See `CanvasProps.shaders`. */\n shaders?: ShaderProgramHandle[];\n\n /** Flatness tolerance for curve tessellation. See `CanvasProps.flattenTolerance`. */\n flattenTolerance?: FlattenTolerance;\n\n /** Fill for the full canvas behind the scene, drawn as a screen-space layer slotted\n * before `'scene'` — independent of pan / zoom. */\n backgroundFill?: Paint;\n /** Dev HUD: a fixed-position widget showing live cursor coords in both viewport\n * (client) and canvas (world) frames. */\n cursorCoordsHud?: boolean;\n /** Dev HUD: a fixed-position widget listing the ids `pickEvery(world)` returns under\n * the cursor. */\n pickHud?: boolean;\n /**\n * The debug overlay: `<Canvas debug>`'s config, plus `slops: true` for\n * translucent halos at every affordance hit zone. `false` turns it off;\n * absent reads `?debug=…` from the URL, as `<Canvas>` does.\n */\n debug?: (DebugConfig & { slops?: boolean }) | false;\n /**\n * Dev HUD: when true (or object), mounts a fixed-position widget below\n * the pick HUD showing the active modality mode, active-slot tool, and\n * hotkey stack. Pass `{ modeId }` to populate the mode line.\n */\n modalityHud?: boolean | { modeId?: string };\n\n /**\n * Per-id alpha multiplier for the scene-render slot: each node's draw output is wrapped\n * in a group with the returned alpha, and 1 emits no wrapper. Typical use: dimming\n * non-active nodes during a mode transition.\n */\n alphaFor?: (id: string) => number;\n\n /**\n * Show or hide render layers in this canvas's own view, by id — the map\n * `<Canvas>` takes. Each scene layer paints as its own render layer, keyed\n * `scene:<layerId>`, so `{ 'scene:guides': false }` hides one scene layer\n * here and nowhere else.\n *\n * A layer hidden this way is gone from this view: it does not paint, and a\n * click, a marquee or Cmd+A here passes over it. Another view of the same\n * scene — a `<CanvasView>`, a second canvas, a minimap — still shows it and\n * can still take it. It applies on top of the scene's own\n * `LayerRecord.visible` and cannot show a layer the scene hides.\n */\n layerVisibility?: Record<string, boolean>;\n\n /**\n * Draw order for this view, by render-layer id, bottom first. A listed\n * order is the whole list: a scene layer left out of it is neither painted\n * nor picked here. See `CanvasProps.layerOrder`.\n */\n layerOrder?: string[];\n } & SceneCanvasPointerProps;\n"],"mappings":";;;;;;;;AAqDA,IAAa,sBAAsB"}
|
|
1
|
+
{"version":3,"file":"props.js","names":[],"sources":["../../../src/canvas/SceneCanvas/props.ts"],"sourcesContent":["import type { ModeRegistry } from '@weasel-js/modes';\nimport type { PathEditHost, PathEditOpening } from './pathEditHost';\nimport type { SceneCanvasGeometry } from './geometryProps';\nimport type { SceneCanvasHit, SceneCanvasPointerProps } from './pointerProps';\nimport type { Paint } from '@weasel-js/paint';\nimport type { SceneCanvasActionProps } from './actionProps';\nimport { Yoke } from '@weasel-js/routing/react';\nimport type { PasteOmission } from 'core/adapters/types';\nimport type { Op } from 'core/ops/types';\nimport type { Node, Scene, SerializedScene } from 'core/scene/types';\nimport type { SelectionApi, UseSelectionOptions } from 'core/selection/useSelection';\nimport type { ContentHandlerEntry } from 'features/ingestion';\nimport type { SceneCanvasSnap } from 'features/snap/types';\nimport type { SvgIngestOptions } from 'interactions/actions/depSchema';\nimport type { GeometryProjection } from 'interactions/actions/geometryProjection';\nimport type { UseMoveOptions } from 'interactions/actions/move/options';\nimport type { PoseDescriptor } from 'interactions/actions/resize/geometry';\nimport type { UseResizeOptions } from 'interactions/actions/resize/options';\nimport type { UseRotateOptions } from 'interactions/actions/rotate/options';\nimport type { ReactNode } from 'react';\nimport type { Animator } from '@weasel-js/animator';\nimport type { PoseTransitionSeat } from '../../animation/poseTransition';\nimport { HANDLE_BASE_PX } from '../../core/device/targets';\nimport type { DeviceProfile } from '../../core/device/types';\nimport type { NodeRoutingEntry } from '../../core/scene/NodeRouting';\nimport type { DebugConfig } from '../../debug/types';\nimport type { LayoutDropTargetMode, ReflowTransition } from '../../layout/types';\nimport type { FlattenTolerance, ShaderProgramHandle } from '@weasel-js/renderer';\nimport type { Tool, ToolsApi } from '../../tools/overlayBinding';\nimport type { SceneSlotConfig } from '../buildSceneLayer';\nimport type { CanvasProps } from '../Canvas';\nimport type { LayersMap } from '../layerSlots';\nimport type { CanvasViewProps } from '../CanvasView';\nimport type { InsertNodeFactory, InsertPaint } from '../deps';\nimport type { SurfaceContribution } from '../surfaceContribution';\nimport type { CameraProps } from '../useCanvasView';\nimport type { FeatureEntry } from './features';\nimport type { BuiltinToolOptions } from './useBuiltinShapeTools';\nimport type { VersionCheck } from './useContributionRoles';\nimport type { SceneCanvasViewport } from './viewportProp';\n\n/** The adapter surface delete / duplicate / group / ungroup need, narrowed from\n * `SceneCanvasAdapter` because `useSceneStandardActions` is non-generic. */\nexport interface BridgeAdapter {\n applyOps(ops: Op[], label?: string): void;\n insertNode(node: { id: string; [k: string]: unknown }): void;\n removeNode(id: string): void;\n setSelection(ids: string[]): void;\n}\n\n/** Default size in CSS pixels for selection corner-handles AND their\n * hit-test radius, at `targetScale = 1`. Deliberately unscaled; kit-internal\n * use sites multiply by `DeviceProfile.targetScale`. */\nexport const DEFAULT_HANDLE_SIZE = HANDLE_BASE_PX;\n\n/** `<SceneCanvas longPress>`. */\nexport interface SceneCanvasLongPress {\n /**\n * Shown while a long-press is held and some binding would fire on it.\n * Default: a ring that fills around the press point\n * (`createLongPressFeedbackContribution()`), static under\n * `prefers-reduced-motion`. `false` shows nothing; a contribution replaces\n * it, reading the `longPress` dep. Installed beside `ambient`, so under a\n * `tools` takeover add it to your own `useTools` call instead.\n */\n feedback?: boolean | SurfaceContribution;\n /** Default true. A long-press some binding handled pulses\n * `navigator.vibrate` briefly, for touch and pen, where the API exists. */\n haptics?: boolean;\n /** Hold time in ms. Default `LONG_PRESS_MS` (500). */\n duration?: number;\n}\n\n/** `<SceneCanvas layers>`: a {@link LayersMap} whose scene slot may be partial,\n * since the defaults fill in whatever it leaves out. */\nexport type SceneCanvasLayers<TNode extends { id: string }, TPose> = LayersMap<\n TNode,\n TPose,\n Partial<SceneSlotConfig<TNode, TPose>>\n>;\n\nimport type { BuiltinToolId } from './builtinToolSets';\nimport type { ToolEntry } from '@weasel-js/routing';\nexport { BUILTIN_TOOL_IDS, type BuiltinToolId } from './builtinToolSets';\n\nexport type { SceneCanvasHit };\n\n/** Props for `<SceneCanvas>`. A scene is the only thing it needs. With nothing\n * else it renders that scene and keeps a selection no input sets; `features`\n * turns behavior on by preset, and the rest configures what those turn on. */\nexport type SceneCanvasProps<TData, TLayer extends string, TPose> =\n Omit<\n CanvasProps<TPose>,\n | 'adapter' | 'boundsOf' | 'selection' | 'tools'\n | 'viewState' // SceneCanvas makes the camera from the view props below\n | 'layers' // stripped so we can re-add as optional below\n | 'getIsVisible' // SceneCanvas synthesizes this from chromeVisibility\n | 'contentVersion' // SceneCanvas wires this to the scene's own version\n | 'layerVisibility' | 'layerOrder' // re-declared below: they gate picking here too\n | 'debug' // re-declared below with SceneCanvas's own `slops`\n > & CameraProps\n & {\n /** A `Scene` (typically from `useScene`) — or a `SerializedScene` JSON\n * object, which SceneCanvas bakes into a Scene on first render. The\n * serialized form is read once; pass a `key` on `<SceneCanvas>` to force\n * a fresh canvas from updated JSON.\n *\n * The JSON shape is relaxed (`version: number` rather than the `1`\n * literal) so an `import json from './x.json'` result satisfies the type\n * without an `as` cast. */\n scene:\n | Scene<TData, TLayer, TPose>\n | SerializedScene<TData, TLayer, TPose>\n | { version: number; systemLayers?: ReadonlyArray<{ id: string }>; nodes: ReadonlyArray<unknown> };\n\n /** Layer configuration. When omitted, SceneCanvas applies kit defaults\n * (a scene slot that paints `node.data.fill` rects + a default\n * selection overlay). A partial scene or selection-overlay config is\n * spread over that slot's defaults; pass `slot: null` to suppress a\n * default explicitly. */\n layers?: SceneCanvasLayers<Node<TData, TLayer, TPose>, TPose>;\n\n /** Which layout container a drag lands in when several contain the drop\n * point — the innermost (default), the topmost in paint order, or only\n * containers whose strategy declares a `dropRegion`. Decides both the\n * drag-time reflow preview and the commit. */\n layoutDropTarget?: LayoutDropTargetMode;\n\n /** Carries the siblings a layout reflow displaces to their slots over time\n * instead of snapping them — `useAnimatedReflow` builds one. Covers a\n * drag's reflow and every one the scene records (an insert, delete,\n * reorder or resize inside a laid-out container). Absent or `null`,\n * they snap. */\n reflowTransition?: ReflowTransition<TPose> | null;\n\n /** Glides what is shown when the scene writes a pose — a `scene.setPose`, an undo — and sees\n * removed nodes off with `exit`. Absent or `null`, writes snap. See {@link PoseTransitionSeat}. */\n poseTransition?: PoseTransitionSeat<TPose> | null;\n\n /**\n * Lets pose-transform actions (move, resize, nudge, flip — NOT rotate) also rewrite a\n * node's data-held geometry. Given a node and the affine `m` applied to its pose,\n * `transform(node, m)` returns updated `data`, or `null` for nodes with no data-held\n * geometry. When absent, the kit emits only the pose op and leaves `data` untouched.\n *\n * @see GeometryProjection\n */\n geometryProjection?: GeometryProjection;\n\n /**\n * Routing-trait classifiers. The kit builds a `NodeRouting` registry per `<SceneCanvas>`\n * from this prop and uses it to derive each hit's `kind`, which tool routing tables\n * (e.g. `{ target: 'rect', actionId: 'move' }`) match against. Pass `defaultNodeRouting`\n * for the kit's built-in shape kinds; spread additional entries for consumer-defined\n * kinds.\n *\n * **Memoize the `routing` value.** The registry is memoized on the prop's reference\n * identity: a fresh array each render rebuilds it and cascades into a new adapter,\n * churning gesture state.\n */\n routing?: readonly NodeRoutingEntry[];\n\n /** How to read and rewrite this scene's poses. Every built-in action,\n * the selection chrome and picking read it. Default `AUTO_POSE_DESCRIPTOR`\n * (rect poses and `Path` poses). */\n poseDescriptor?: PoseDescriptor<TPose>;\n\n // --- Geometry: hit-test + bounds overrides consumed by the internal\n // `useSelectTool`. Ignored if the consumer passes their own `tools`. ---\n geometry?: SceneCanvasGeometry;\n\n // --- Selection options. `pickBest` and `handleHitRadius` configure the\n // internal select tool, and are ignored under a `tools` takeover;\n // `move`, `resize` and `rotate` configure the `move`,\n // `resize` and `rotate` presets, and apply either way. ---\n selectTool?: {\n move?: UseMoveOptions<TPose>;\n resize?: UseResizeOptions<TPose>;\n /** Rotation options, or `false` to hide the rotation handle and bind it to\n * nothing; the `rotate` action stays, for other tools and `actions.rotate`. */\n rotate?: UseRotateOptions<TPose> | false;\n handleHitRadius?: number;\n /** Override the body-pick used on click/pointerdown. Alt-aware: receives\n * the live alt state + current selection so consumers can implement\n * alt-cycling through an overlapping stack. Default: top-most hit\n * (alt ignored). */\n pickBest?: (worldX: number, worldY: number, alt: boolean, sel: readonly string[]) => string | null;\n };\n\n /** Consumer node factories for the `insert` action, keyed by tool `kind`.\n * Each factory receives the drag AABB + tool `extras` and returns the\n * node's `data` (in this canvas's own data shape) plus an optional `pose`.\n * A factory for a kit kind (`rect`, `line`, …) replaces the kit's default\n * `{ path, fill }` node for that kind; a factory for a novel kind (e.g.\n * `text`) adds insert support the kit doesn't ship. The dep supplies id,\n * layer, and the undoable op. Return `null` to reject an insert. */\n insertNodeFactories?: Record<string, InsertNodeFactory>;\n\n /** The fill, stroke, and fill rule a kit-built shape is inserted with, by\n * tool `kind` and insert count; the kit keeps the geometry. Default\n * `paletteInsertPaint`, the kit palette in turn. A kind with a factory in\n * `insertNodeFactories` is not asked. */\n insertPaint?: InsertPaint;\n\n /** External-content ingestion (OS drop / clipboard paste / picker).\n *\n * - `handlers` — consumer content handlers registered for this canvas's\n * lifetime (priority 0 by default — they beat the kit's `image/*` /\n * `image/svg+xml` handlers at -100/-90).\n * - `resolveSrc` — overrides the image handler's `data:`-URI embed (e.g.\n * upload to an asset store, return the URL).\n * - `svg.unpack` — makes the kit SVG handler parse dropped SVG files into\n * native scene nodes instead of one embedded-image node each.\n * - `clipboard` — the kit weasel-JSON paste handler, enabled by default.\n * `reviver` restores JSON-unfriendly values the copying side encoded via\n * `jsonReplacer`. `enabled: false` opts the canvas out, but the kit\n * handler still consumes weasel-matching items and declines them inert\n * rather than letting them fall through. Also governs Cmd/Ctrl+V under\n * the `edit` preset; the rest takes the `ingest` preset.\n *\n * Memoize `handlers` and `clipboard.reviver`: an inline array literal\n * re-registers the handlers on every render. */\n ingestion?: {\n handlers?: ContentHandlerEntry[];\n resolveSrc?: (file: File) => Promise<string>;\n svg?: SvgIngestOptions;\n clipboard?: {\n reviver?: (key: string, value: unknown) => unknown;\n enabled?: boolean;\n /** Called when a paste left copied nodes out, with each one and the\n * reason. `useClipboardOps` takes the same callback as\n * `onPasteOmitted` for a paste from its own in-memory copy. */\n onOmitted?: (omitted: PasteOmission[]) => void;\n };\n };\n\n selection?: SelectionApi;\n selectionOptions?: UseSelectionOptions;\n\n /**\n * `false` stops the canvas writing the selection: no click, marquee,\n * lasso, action or tool, and no op committed through the adapter it hands\n * its tools. The consumer's own `SelectionApi` — the `selection` prop, or\n * `useSelection({ scene })` — still writes, and the canvas draws what it\n * holds. Undo and redo still restore the selection each history entry\n * recorded. Default `true`.\n *\n * Click policy (whether shift-click extends) is the selection's `mode`:\n * `useSelection({ mode: 'multi' })`, or `selectionOptions={{ mode: 'multi' }}`\n * for the selection the canvas builds itself.\n */\n selectable?: boolean;\n\n /**\n * Behavior presets to turn on, composable in any combination. A canvas\n * with none renders its scene and keeps a selection (the `selection` API\n * works) that no input sets: no tools, no standard actions or their keys,\n * no clipboard, no drop or paste, and no selection chrome. The dispatcher\n * is still mounted, so bindings a consumer adds work.\n *\n * - `view` — wheel pan and zoom, pinch, the zoom keys, and the hand tool\n * (H, or hold Space). Passing `viewport` implies it.\n * - `select` — the select tool, as the initial active tool and Escape's\n * return target: click to pick, drag on empty to marquee, click on empty\n * to clear.\n * - `outline` — the selection outline, whichever tool sets the selection.\n * - `pick` — `select` and `outline`.\n * - `move` — drag a body to move it, Alt-drag to clone it. Ambient, so it\n * runs under any tool that does not claim the drag.\n * - `resize` — resize handles, drawn and bound.\n * - `rotate` — the rotation handle, drawn and bound.\n * - `transform` — `resize` and `rotate`.\n * - `edit` — undo/redo, delete, duplicate, group/ungroup, nudge,\n * select-all, Escape, cancel-gesture, cut/copy/paste, fill and stroke,\n * and their keys. Cmd/Ctrl+V pastes nodes a kit canvas copied, from\n * this tab or another, and nothing else.\n * - `arrange` — align, distribute, reorder, flip.\n * - `paths` — pathfinder operations, path-edit entry and anchor editing.\n * - `ingest` — dropped and pasted content: images, SVG, files, and\n * whatever `ingestion.handlers` accept, on Cmd/Ctrl+V or an OS drop.\n * - `draw` — all of the above.\n *\n * Any `FeaturePreset` object goes beside the names: core's own\n * (`pathsPreset`), or one a package ships.\n * Tools add the actions they bind — a shape tool brings `insert` — so\n * `defaultTools` composes with any preset. `actions` then adds, overrides\n * or removes on top of what the presets registered.\n */\n features?: readonly FeatureEntry[];\n\n /** Extra tools or overrides keyed by id, or a full `ToolsApi` takeover.\n *\n * **Patch form** (`Record<string, Tool | true | false>`): merged\n * into the built-in registry on top of whatever `defaultTools` and\n * `features` already selected.\n * - `true` pulls in the built-in for this id (`'pen'`, `'lasso'`,\n * `'hand'`, …), the same as listing it in `defaultTools`. Unknown\n * built-in ids warn in dev and are ignored.\n * - `Tool` adds a new id or replaces an existing one in place\n * (dev-only warning if `defaultTools` also names that id).\n * - `false` omits a bundled tool entirely.\n * Auto-wiring (keybindings, dispatcher, action registry) still runs.\n *\n * **Takeover form** (`ToolsApi`): the internal registry is bypassed and\n * this `tools` value is forwarded to Canvas as-is — the consumer owns\n * active-slot management, and `pick`'s select tool is theirs to supply.\n * Every other preset still applies. Keybindings are still auto-wired\n * against the supplied registry; pass `enableKeybindings={false}` to opt\n * out. */\n tools?: ToolsApi | Record<string, Tool | true | false>;\n\n /**\n * Auto-wire keyboard shortcuts. Default `true`. When `false`, SceneCanvas still mounts\n * its tools but routes no keyboard input to them — neither tool hotkeys nor\n * keyboard-bound actions like delete / escape / nudge. Pointer, wheel, and contextmenu\n * interactions are unaffected.\n */\n enableKeybindings?: boolean;\n\n /**\n * Take the keyboard on mount, as a press in the canvas would. A key that\n * reaches the page goes to the canvas the user last pressed or scrolled\n * in, and to no canvas before the first such interaction, so a canvas in a\n * side panel does not take Space from a page that wants it. An app whose\n * canvas is the page sets this so its shortcuts work before the first\n * click. Default `false`.\n */\n claimKeys?: boolean;\n\n /**\n * Auto-mount the gesture dispatcher (`useGestureDispatcher`). Default `true`. `false` is\n * for tests or demos that drive actions another way, or that call\n * `useGestureDispatcher` themselves.\n */\n enableGestureDispatcher?: boolean;\n\n /** Called with the `ToolsApi` SceneCanvas constructs or receives, whenever its identity\n * changes. For introspection. */\n onToolsCreated?: (tools: ToolsApi) => void;\n\n /**\n * Built-in tools SceneCanvas registers in its internal `useTools`, on top\n * of the ones presets bring (`select` from `pick`, `hand` from `view`):\n * ids, or sets of them such as `SHAPE_TOOLS`, or `withoutTools(...)` of one.\n * Default: none. Each tool also registers the kit actions it binds, so\n * `['rect']` brings `insert`. Ignored when the consumer supplies their own\n * `tools` prop.\n */\n defaultTools?: readonly ToolEntry<BuiltinToolId>[];\n\n /** Per-tool option overrides for the built-in tools. Each entry is a\n * narrow subset of the underlying hook's options surface — `lasso.mode`,\n * `rig.state`, etc. */\n toolOptions?: BuiltinToolOptions;\n /** What gestures snap to, and how near it pulls. */\n snap?: SceneCanvasSnap;\n\n /** Initial active-slot tool id. Default: `'select'` when it is\n * registered, otherwise none — a canvas can run on ambient bindings\n * alone. Must be one of the registered tools. Ignored when the consumer\n * supplies their own `tools` prop. */\n initialActiveTool?: string;\n\n /** Always-on entries to register alongside the internal tools — every one\n * a `SurfaceContribution`, whose views, deps, overlay, bindings, actions\n * and `attach` all install from this one list, and uninstall when the\n * entry leaves it. A tool is a contribution too, so one can go here. If\n * you supply your own `tools` prop, this is ignored — wire `ambient`\n * through your own `useTools` call instead. */\n ambient?: readonly SurfaceContribution[];\n\n /** What an entry's `requires` does when the running kit does not meet\n * it: `'warn'` (the default) logs in development, `'strict'` throws,\n * `'off'` skips the check. */\n versionCheck?: VersionCheck;\n\n /** Touch and pen long-press: its hold time, its haptic, and the\n * feedback shown while it is held. */\n longPress?: SceneCanvasLongPress;\n\n /** Configures the `view` preset, and implies it. See {@link SceneCanvasViewport}. */\n viewport?: SceneCanvasViewport;\n\n /**\n * Given a scene node, return a short human-readable \"kind\" label (e.g. `'rectangle'`,\n * `'sticky note'`), which the kit publishes per id into any surrounding\n * `<SelectionContextProvider>`. Return `undefined` to skip an entry. When omitted,\n * each node reports its routing kind (see `routing`), and a node that routes as\n * `'unknown'` is left unlabeled.\n */\n describeKind?: (node: Node<TData, TLayer, TPose>) => string | undefined;\n\n /**\n * Animator to bind for per-frame redraws. SceneCanvas requests a redraw on every active\n * animation frame and paints `animator.colorOverrides` onto the scene's nodes: the\n * kit's path and shape painters apply them, and a custom `drawOne` receives them as\n * `ctx.vertexColors`.\n */\n animator?: Animator;\n\n /**\n * Extra views on this canvas: each is a camera over a rect of the same\n * surface, drawn through one GL context, with input routed to it. The flat\n * `view` / `onViewChange` props above stay the canvas's own camera — view\n * zero — and are unaffected by anything declared here.\n *\n * Order is paint and hit order, low to high. Each entry is a\n * `<CanvasView>`; mounting one as a child is the same declaration, and\n * children land after every entry here.\n */\n views?: readonly CanvasViewProps[];\n\n /**\n * Children rendered alongside the canvas, inside its input scope (e.g.\n * shortcuts overlays, probes).\n */\n children?: ReactNode;\n\n /** A yoke to join, from `useYoke()`: canvases on one yoke share the active tool, the gesture\n * in flight and history. Omitted, this canvas keeps its own. */\n yoke?: Yoke;\n\n /**\n * Chrome-caps visibility overrides, keyed by chrome id (`selection.outline`,\n * `selection.rotation-handle`, `gesture.marquee`, …). Each entry is a composable\n * {@link Condition} built from the `cond()` builder, merged on top of the kit's\n * `defaultVisibilityRules`. Set an id to `never` to suppress a chrome element\n * entirely (also unhittable), or to `always` to force-show.\n */\n chromeVisibility?: import('features/chrome-caps').VisibilityRules;\n\n /**\n * The app's mode registry (`createModeRegistry` in `@weasel-js/modes`).\n * The canvas reads the active mode from it to gate chrome, tool\n * activation and the dispatcher's eligibility filter, repaints when it\n * switches, and hands every registered mode to the dev-time route-conflict\n * check. Omitted, the canvas behaves as the kit's normal mode and nothing\n * revokes anchor editing.\n */\n modes?: ModeRegistry;\n\n /** Hands which path is being anchor-edited to the host. See {@link PathEditHost}. */\n pathEdit?: PathEditHost;\n /** A path to open in anchor edit as the canvas mounts, with anchors selected. Read once. */\n defaultPathEdit?: PathEditOpening;\n\n /**\n * Override detected device facts. Merged over what `matchMedia` reports;\n * `targetScale` is re-derived from the merged `coarsePointer` unless you\n * override it explicitly.\n */\n device?: Partial<DeviceProfile>;\n\n /**\n * Live focus getter for chrome-caps' `focused` ctx field, for visibility rules that\n * read the `focused` atom (the kit's default `selection.rotation-handle` rule does).\n * Omit to default `focused` to `true`.\n */\n getFocused?: () => boolean;\n\n /** Custom shader programs to compile on the renderer. See `CanvasProps.shaders`. */\n shaders?: ShaderProgramHandle[];\n\n /** Flatness tolerance for curve tessellation. See `CanvasProps.flattenTolerance`. */\n flattenTolerance?: FlattenTolerance;\n\n /** Fill for the full canvas behind the scene, drawn as a screen-space layer slotted\n * before `'scene'` — independent of pan / zoom. */\n backgroundFill?: Paint;\n /** Dev HUD: a fixed-position widget showing live cursor coords in both viewport\n * (client) and canvas (world) frames. */\n cursorCoordsHud?: boolean;\n /** Dev HUD: a fixed-position widget listing the ids `pickEvery(world)` returns under\n * the cursor. */\n pickHud?: boolean;\n /**\n * The debug overlay: `<Canvas debug>`'s config, plus `slops: true` for\n * translucent halos at every affordance hit zone. `false` turns it off;\n * absent reads `?debug=…` from the URL, as `<Canvas>` does.\n */\n debug?: (DebugConfig & { slops?: boolean }) | false;\n /**\n * Dev HUD: when true (or object), mounts a fixed-position widget below\n * the pick HUD showing the active modality mode, active-slot tool, and\n * hotkey stack. Pass `{ modeId }` to populate the mode line.\n */\n modalityHud?: boolean | { modeId?: string };\n\n /**\n * Per-id alpha multiplier for the scene-render slot: each node's draw output is wrapped\n * in a group with the returned alpha, and 1 emits no wrapper. Typical use: dimming\n * non-active nodes during a mode transition.\n */\n alphaFor?: (id: string) => number;\n\n /**\n * Show or hide render layers in this canvas's own view, by id — the map\n * `<Canvas>` takes. Each scene layer paints as its own render layer, keyed\n * `scene:<layerId>`, so `{ 'scene:guides': false }` hides one scene layer\n * here and nowhere else.\n *\n * A layer hidden this way is gone from this view: it does not paint, and a\n * click, a marquee or Cmd+A here passes over it. Another view of the same\n * scene — a `<CanvasView>`, a second canvas, a minimap — still shows it and\n * can still take it. It applies on top of the scene's own\n * `LayerRecord.visible` and cannot show a layer the scene hides.\n */\n layerVisibility?: Record<string, boolean>;\n\n /**\n * Draw order for this view, by render-layer id, bottom first. A listed\n * order is the whole list: a scene layer left out of it is neither painted\n * nor picked here. See `CanvasProps.layerOrder`.\n */\n layerOrder?: string[];\n } & SceneCanvasPointerProps & SceneCanvasActionProps;\n"],"mappings":";;;;;;;;AAqDA,IAAa,sBAAsB"}
|