Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore(canvas): remove old canvas code (#8033)

Seamusd6ef896a1de1
diff --git a/apps/web/src/features/block-canvas/README.md b/apps/web/src/features/block-canvas/README.md
index 70b669a84e..21afe7eaaa 100644
--- a/apps/web/src/features/block-canvas/README.md
+++ b/apps/web/src/features/block-canvas/README.md
@@ -1,19 +1,369 @@
-# block-canvas
+# block-canvas — drawing, rich text, media and document cards
-Saved documents can opt into [Canvas Next](canvas-next/README.md) with the
-`enable-canvas-next` flag. The frontend migrates legacy JSON on load and writes
-version 2 through the existing storage endpoint after editing. Unsupported legacy
-content stays available in the legacy editor; newer versions are never handed to
-it. SyncService integration is deferred.
+Canvas Next is the default editor for saved canvases, drive details, and embeds.
+No rollout flag or local override is required.
+The frontend treats unversioned JSON (and explicit version 1) as legacy Canvas.
+It converts supported records on load to `{ version: 2, document, legacy? }`.
+`document` is the graphics scene; `legacy` retains the original JSON and migration
+notes for recovery. No migration is saved merely by viewing a file. The first
+committed edit writes version 2 using the existing JSON/simple-save endpoint.
+Subsequent loads validate version 2 directly; they never replay the archived data.
+Unknown versions and invalid scenes fail closed without writing data.
-This block is a canvas where you can create, export, and import diagrams.
+Migration preserves IDs, groups, stacking order, positions, shape labels,
+Markdown text, connector bindings/styles, media references and flips, and all
+legacy entity references. Pencil samples are retained and use the new brush.
+Unsupported links, connector labels, invalid records, and interleaved group layers
+show a migration error without writing data. The legacy editor has been removed.
+There is no version 2-to-legacy downgrade. Document-level read-only mode mounts a
+selection/navigation surface without editing, paste/drop, or embedded editing handlers.
+Markdown embeds explicitly pass `isEmbedded` to the editor and use this same
+read-only surface, with Select and Hand tools and no property inspector. Selection
+does not expose transform handles or mutate the scene; embedded views cannot save
+canvas edits even when the viewer has edit permission on the original document.
+Saves are debounced and serialized; failures keep edits dirty. Save state is not
+shown in the canvas UI.
-The rewrite lives in [canvas-next](canvas-next/README.md) and uses the pure TS
-graphics package. It is exercised through saved Canvas documents behind the rollout
-flag; there is no separate local demo route.
+SyncService integration and collaboration remain a follow-up. This change keeps
+the existing whole-file save behavior. See [Graphics and Canvas parity](../../../../../docs/GRAPHICS_PARITY.md)
+for the remaining editor and collaboration work.
-The editor has drawing, rich text/mentions, connectors, media and document
-cards/embeds. Embedded documents keep their existing persistence. See the
-[parity plan](../../../../../docs/GRAPHICS_PARITY.md) for remaining collaboration,
-legacy-content support and editing work.
+## Controls
+
+The floating top toolbar uses the shared `Toolbar` and Phosphor icons for drawing
+and inserting media, document cards, and embeds. Tooltips show each tool's shortcut.
+Zoom, reset-to-100%, fit, undo, and redo live at the bottom-left. Adjacent controls
+toggle floating properties and layers panels.
+Fit Scene uses the current viewport dimensions, centers all scene geometry and
+zooms in or out to leave 100 screen pixels per side on the first axis to fill.
+Camera zoom limits still apply; padding decreases for small embedded viewports.
+Ctrl/Meta-wheel zoom is pointer-anchored, with a continuous 0.002 exponential rate
+per normalized wheel pixel and an exponent cap of 0.2 per event (about 22% zoom-in).
+Plain wheel input pans at its existing speed.
+The Canvas panel's zoom menu offers **No snapping** (the default for each session),
+**Snap to px** (1 canvas px at every zoom), and **Auto snapping** (the smallest
+currently visible dot-grid interval, including faint dots). Auto follows zoom;
+hiding the grid temporarily disables it. Drawing, moving, resizing, insertion, duplication, pasting, free
+connector endpoints and layout inspector values use the chosen interval; inspector
+scrubs preview the same snapped values they commit. Freehand and rotation keep
+their own precision, and connector bindings and aspect-ratio constraints stay exact.
+The preference is local editor state, not saved JSON or shared Loro data.
+The dot grid adapts to zoom, revealing 1, 4, 16, 64 px levels (and
+coarser levels at extreme zoom-out). Coarse dots remain steady while finer dots
+fade in gently; individual canvas pixels are faintly visible at 800%. Dots use
+fixed 1 screen-pixel SVG marks, including at fractional zoom. Marks closer than
+4 screen pixels disappear to avoid a dense texture. Their centers stay anchored
+to canvas coordinates through pan/zoom. Colors blend the theme's muted ink and
+panel tokens; the dot-grid visibility toggle hides every level.
+The shared context menu exposes clipboard, grouping, layer ordering, select-all,
+and delete actions, with normal keyboard navigation and focus restoration. Active
+embedded editors and text editing retain their own context menus.
+Selecting Arrow, Line, Connector, or Pencil repairs invisible drawing defaults:
+missing/transparent strokes use theme Ink, zero width uses 2 px, and zero opacity
+uses full opacity. Other style choices and existing shapes are preserved.
+
+## Editing
+
+| Action | Shortcut |
+| --- | --- |
+| Select / rectangle / ellipse / pencil / text / hand | V / R / O / P / T / H |
+| Temporary pan | Hold Space, or middle-button drag |
+| Add/remove selection | Shift-click; Shift-drag on empty canvas adds a marquee |
+| Draw square / circle | Hold Shift while drawing a rectangle / ellipse |
+| Move horizontally / vertically | Hold Shift while dragging; follows the dominant world axis |
+| Select inside a group | Cmd/Ctrl-click |
+| Copy / cut / paste | Cmd/Ctrl+C / X / V |
+| Duplicate | Cmd/Ctrl+D, or Option/Alt-drag |
+| Select all | Cmd/Ctrl+A |
+| Nudge | Arrows: one snap unit; Shift+arrows: ten snap units |
+| Group / ungroup | Cmd/Ctrl+G / Shift+Cmd/Ctrl+G |
+| Undo / redo | Cmd/Ctrl+Z / Shift+Cmd/Ctrl+Z |
+| Delete | Backspace / Delete |
+| Front / back | ] / [ |
+| Forward / backward | Option/Alt+] / Option/Alt+[ |
+| Cancel and return to selection | Escape |
+
+Keyboard registration uses Macro's DOM scope and respects text/number inputs.
+Native clipboard events own the actual copy/cut/paste keystrokes; proxied Macro
+commands expose those actions in the command UI without double handling.
+Clipboard context-menu actions use the browser clipboard API and report denied
+access. Fragments include whole selected subtrees, fresh IDs on insertion, stable
+relative order and world placement. Pasting repeatedly offsets by another 24 units.
+Canvas Next fragments preserve rich text. Plain text and HTML pasted onto the canvas
+create a wrapped text shape; pasting inside the editor belongs to Lexical. Image
+clipboard data uploads through the media adapter. Legacy Canvas clipboard format
+remains a later adapter.
+
+Pasting an Excalidraw selection or `.excalidraw`/`excalidraw/clipboard` JSON
+imports through `core/excalidraw.ts` (import only; export is not implemented). It
+converts rectangles, ellipses, text, freedraw and line/arrow elements, rebuilds
+flat `groupIds` membership into the nested local-transform tree, folds
+container-bound text into shape or connector labels, and keeps arrow bindings
+that resolve to imported shapes. Diamonds are approximated as rectangles; images,
+frames and embeddables are dropped. Hachure/fill styles, roughness and multi-point
+line bends are not represented. Connectors import as straight unless both endpoints
+bind to imported shapes; doubly bound connectors retain their straight, smooth or
+elbow route.
+
+Option-drag duplicates the selected roots (or selects and duplicates the clicked
+shape). It is a cancellable preview; originals stay put and retain their DOM.
+Release commits creation plus movement as one undo step; clicking without moving
+or pressing Escape leaves no copy or history entry. Hold Option at gesture start;
+live modifier toggling during a duplicate drag is not implemented.
+
+The inspector stays in a rounded floating panel on the right at the same width
+and height, including with no selection. Connector routes, endpoint styles, and
+stroke patterns have previews in both their selectors and menus. Rotation and
+flip buttons share the alignment controls’ compact grouped treatment. Sections follow Position, Layout, Appearance, Fill, Stroke,
+Connection, Typography; unavailable sections are omitted without reordering the
+others. Position and Layout remain visible but disabled for fully bound connectors.
+Compact fields share a two-column grid, opacity and corner radius share Appearance,
+and label typography appears only for existing labels or during label editing.
+The inspector supports mixed values, fill/stroke palettes, width, opacity and
+rectangle radius. Width/height edits and scrubs resize geometry through the canvas
+shape definitions, preserving label proportions and remeasuring wrapping. Text
+width reflows; text height scales proportionally. Rotated world-bound edits and
+groups with incompatible axes preserve proportions rather than introducing shear.
+Color controls compose the shared `@ui` ColorPicker field, hue
+and opacity tracks, and hex input. Canvas does not import the theme editor picker
+or Color.js; custom edits produce sRGB hex, while preset theme references stay
+as references until edited. Edits also become defaults for subsequent shapes. A group has
+no inherited style: styling it edits all descendant shapes once. Ellipses ignore
+radius. Typing numbers commits on change/blur. Dragging a numeric handle previews
+the scene continuously, then commits one undo step on release. Escape, lost pointer
+capture, or leaving the window restores the starting scene without saving a change.
+Previews always use the starting document, so rotation and resizing do not accumulate
+rounding errors between samples.
+
+Selections expose four visible corner handles and invisible targets along each full
+edge, with a 10-screen-pixel hit area and resize cursors. Corners take priority
+where they overlap an edge target. Groups and multiple selections have a dashed
+world-axis-aligned box; single shapes retain their oriented solid box. The rotation
+circle follows a single shape's oriented top edge; for groups and multiple selections
+it is centered above the world bounds. Grips stay square. Edge cursors stay EW
+(sides) or NS (top/bottom); corners use the diagonal arrow matching their world-space
+quadrant relative to the selection center. Click-drag anywhere inside
+the box moves the entire selection, including gaps; Shift/deep-select still pick
+individual shapes. Option/Alt keeps the center fixed; Shift preserves proportions.
+Shift-click toggles on release. Moving at least 3 screen pixels changes it into
+an axis-constrained drag; an unselected target is added before moving the selection.
+Shift also works when pressed/released during a move, including Option-drag duplicates.
+During rectangle/ellipse creation, Shift keeps width and height equal; pressing or
+releasing it updates the preview without losing the unconstrained pointer endpoint.
+Handles and the shared bounding box hide during the preview, and each drag is one
+undo step. Shared resizing stretches independently only when descendant axes align
+with the box, including quarter turns; incompatible child rotations force uniform
+scaling for corner and edge drags. This avoids shear and keeps the content fitted
+to the box. Nonuniform resizing edits descendant geometry and moves centers while
+retaining hierarchy; uniform resizing transforms selected roots once.
+Resizing through the opposite edge flips the contents and keeps growing on the
+other side. Each axis can invert independently; modifier changes recompute from
+the original gesture, and undo/cancel restore the original geometry and handedness.
+
+Active drags continue across pointer-capture loss and release outside the canvas;
+Escape, focus loss and pointer cancellation still discard the preview.
+
+Align uses selected roots' world bounds. Distribute makes equal gaps, keeps outer
+objects fixed, and allows negative gaps for overlapping selections. Each command
+is one undo step. Stroke width and radius are local dimensions: single-shape
+resizing and nonuniform shared resizing edit geometry; uniform group/multiselection
+scaling also scales these dimensions for rectangles and ellipses. Pencil absorbs
+scale into its samples instead, preserving nominal brush width.
+Picking accepts painted stroke pixels or the existing 3-screen-pixel minimum
+outline tolerance; a thick stroke does not gain another 3px outside its paint.
+
+## Ownership
+
+- `core/`: seed/defaults only. Editing algorithms and typed commands live in graphics.
+- `primitives/`: Solid state, mixed values, creation defaults and UI actions.
+- `components/`: inspector and layer list with explicit props.
+- `views/`: editor surface and controls composed around a supplied editor/state.
+- `canvas-next.tsx`: memory editor, Macro hotkey scope and clipboard wiring.
+- `clipboard.ts` / `hotkeys.ts`: host adapters. No browser/app dependency in the core.
+
+Core command and transform tests exercise both memory and Loro paths. Canvas Next
+currently uses memory plus versioned whole-file saves; it does not install awareness
+or production collaboration.
+
+The view/state already accept an editor. The current composition root constructs
+its own memory editor; a later collaboration checkpoint can inject Loro editors while
+retaining the same rich-text measurement, renderer, clipboard and input ownership.
+
+## Pencil checkpoint
+
+P selects the pencil tool. It stays active for repeated strokes; V or Escape
+returns to selection. Tap for a dot. Mouse strokes simulate pressure from point
+spacing; pens capture pressure, with coalesced input samples processed together.
+The `perfect-freehand` brush is an internal graphics detail. Documents contain
+local samples and pressure mode, and each completed stroke is one undo entry.
+
+Selection bounds enclose the smoothed ink; clicks and marquee target that ink,
+not raw samples or empty bounding-box space. Existing selected-box drag behavior
+is unchanged. Resize scales points and recomputes pressure/ink with nominal pen
+width retained, including uniform scaling through nested groups. Copy/paste,
+Option-drag, styles, layering and local history use the shared shape pathways.
+
+The 2026-09-28 performance fix preserves immutable core geometries for rendering
+and hit queries and retains geometry through move/rotation previews. This reuses
+derived ink during pan, hover, selection and transforms; raw samples are unchanged.
+The 11-stroke/7,041-sample regression checks brush executions, not a browser FPS
+budget. Mixed-content performance and general spatial indexing remain later work.
+
+## Rich text checkpoint
+
+T chooses text. Click for auto width, or drag horizontally to choose a wrapping
+width. Double-click an existing text shape, or select it and press Enter, to edit.
+Double-click empty canvas also creates text. Escape, Cmd/Ctrl+Enter, or a click
+outside commits the edit. Empty drafts disappear without an undo entry.
+
+The editing toolbar supports bold, italic, underline, strike, code, highlight,
+links, headings, quotes, and nested bulleted/numbered lists.
+Tab / Shift+Tab indent/outdent lists. Lexical owns IME, caret/range selection, rich
+clipboard and typing undo; canvas hotkeys and gestures are suspended while editing.
+The inspector controls font family (sans/serif/mono), size and auto/wrapped width.
+Side edges reflow at fixed font size. Corners and top/bottom scale proportionally.
+Text corners follow the pointer projected onto the box's aspect-ratio diagonal,
+so horizontal drags can shrink a wide line without vertical jitter dominating.
+Scaling preserves the measured layout; width edits remeasure wrapping. Task mention
+badges, assignee avatars, and mention spacing scale in em units with the text.
+
+Type `@` in text or a shape label to open the shared mention picker. Choose a
+person, document, or other supported reference with the mouse or arrow keys and
+Enter. Pending `@` queries use the same text width as their measured content, so
+opening the picker does not add an extra wrapped line. Escape closes the picker
+before ending editing. Mentions retain their typed
+Lexical nodes through reopening, copy/paste, and undo, and render with the shared
+mention decorators. Canvas Next currently disables backend mention tracking and
+notifications; mentions remain part of the same whole-content LWW string.
+
+Canvas Next stores a stringified Lexical editor tree in `TextGeometry.content`,
+including shape labels. `core/text-codec.ts` owns bounded tree validation, seed
+construction, serialization, plain-text extraction and empty-content detection.
+Clipboard imports validate this host format before accepting a scene. Graphics
+only checks the opaque string's size; it never interprets the tree
+or decides whether to remove empty text. The text state explicitly deletes cleared
+text items, skips empty creations and clears labels while retaining their shapes.
+Canvas Next uses the shared Markdown builder (`buildConfig` and `MarkdownShell`)
+for editing and `StaticLexical` for display and measurement, with its own markup
+styles. The tree is never converted through Markdown when loading or saving.
+Whole-string LWW and existing serialized content remain unchanged.
+Only the actively edited shape mounts an editable Lexical instance.
+The editing surface has no additional colored box outline; native text selection
+and the caret remain visible. Selection indicators return after editing finishes.
+Reordering other items therefore cannot remount the editor or replace its content.
+Draft updates do not mutate the scene. Ending the edit submits one canvas undo
+step, and undo inside the editor affects only that editing session.
+
+Rectangles, ellipses and connectors own optional rich-text labels in their geometry.
+Double-click inside a rectangle or ellipse (even with no fill), or on a connector.
+You can also use T then click, or select the item and press Enter. Connector labels
+sit at the route midpoint, follow bound targets, and size to their text; the
+connector line leaves a gap behind the label. Other labels start
+center-aligned and vertically centered, wrap to a padded interior (an inscribed
+box for ellipses), and uniformly shrink to fit small shapes. Resizing remeasures
+wrapping without changing the stored font size; labels inherit the shape's stroke color and opacity. Clicking a label
+selects its owner. Ordinary clicks elsewhere in an unfilled interior still pass
+through. Clearing a label leaves the shape. Label edits, copy/paste, duplication,
+grouping and transforms all preserve ownership; there is no separate text node.
+
+The collaboration policy is deliberately whole-content last-write-wins. Loro
+stores one `textContent` string register per text item or labeled shape, separate
+from pose. Concurrent edits choose one complete tree; no character-level merging
+or shared caret is intended. Label layout metadata is separate from pose too, so
+adding a label and moving its owner can merge. Local typing undo stays in Lexical;
+finished edits use the canvas backend's undo. Canvas Next does not yet have a
+production SyncService connection.
+
+Mixed selections containing text scale uniformly to preserve letter proportions;
+use a single text shape’s side edges to change wrapping width. Shape definitions
+express this through the `canDeform` capability used by selection-frame math.
+
+## Arrows and connectors checkpoint
+
+A selects Arrow and L selects Line; C remains available for the app's Create menu.
+Choose Elbow in the Connection inspector for a rounded connector. Drag from
+empty space or a shape. Hovering a shape reveals five small endpoint-style circles:
+its center and four edge midpoints. Only the hovered shape shows these targets.
+A center drop automatically meets the outline as the target moves; side drops stay fixed on the chosen edge. Points retain their
+screen size at any zoom. The active point gets a larger pale-blue halo, both before
+the first click and while dragging either endpoint. Near an edge point it takes
+priority; farther inside the shape, its center is active (including unfilled shapes).
+
+Select a connector to reveal two endpoint circles. Drag either to reconnect or
+release in empty space to detach it. Shift snaps free endpoints to 45 degrees;
+Escape cancels. The inspector switches between Straight, Elbow and Smooth routing
+and the legacy open/filled arrowheads and large/small dots at either end. The
+original route math lives in the pure graphics core, not in this app.
+
+Target movement, rotation, resizing, nesting, grouping, copy/paste, duplication and
+undo retain connections. Copying only the connector detaches its references at the
+visible positions. Deleting a target leaves its surviving connectors in place;
+undo restores the connection. Moving a connector body moves its free ends, keeping
+bound ends attached. Endpoint previews do not write document history.
+
+Arbitrary bend-point editing and remote endpoint preview awareness are not included
+in this checkpoint.
+
+## Media and document cards
+
+The toolbar media insertion control is currently hidden pending a UI redesign.
+Native file drop, image clipboard paste, and workspace entity drag/drop continue
+to use the existing insertion path. Media is naturally
+sized, fitted within 640 × 480 world units, and inserted in one undo step per batch.
+Uploading/loading is host-owned; only stable static-file or document references
+enter the scene. Reset/unmount invalidates pending insertion. Saved Canvas Next
+documents retain stable uploaded references;
+uploads use the existing static file service. Existing workspace file selection
+does not create a new file.
+
+Image/video shape definitions own validation, bounds, hit testing and resizing in
+core. The host resolves URLs through existing queries. Images support border,
+opacity, radius, transformations (including flips), grouping, order and clipboard.
+Select a video and use Play/Pause video in the inspector; playback is local state.
+
+Workspace document drops insert a document reference rendered with
+`DocumentPreviewContent` in a 340 × 136 card, one surface layer above its parent
+and inserted at the front of the scene. Card text uses `text-base` and reflows at
+its actual width; resizing no longer scales a 320px snapshot. Titles, menus and
+task controls remain interactive; dragging the card background moves it. Select
+the card and use Open document. Workspace drops and pasted Macro links also insert
+document cards. Preview loading/errors stay inside the card's
+Suspense/ErrorBoundary. Loading shows a pulsing icon dot and two title skeleton
+lines, shared with DocumentPreview. Signed URLs, query results, media players,
+preview contents, and upload state are never stored in core. SVG-to-editable-shape
+conversion is not part of this checkpoint; SVG files can be inserted as images.
+
+
+New embed insertion is not currently exposed in the toolbar. An existing document
+card can switch between preview and embed in the inspector. Double-click
+an embed or choose Interact to enter; Done, Escape, or a click elsewhere on this
+canvas returns input to the outer canvas. Resizing changes the editor viewport.
+The embedded block stays mounted when entering/leaving interaction mode.
+
+`block-embed-adapter.tsx` mounts the existing unmanaged block loader with its own
+panel handle, toolbar, and hotkey scope. The existing editor owns permissions and
+sync: edits inside an embed save to that referenced file independently of the outer
+Canvas Next document. The core stores only the document reference,
+box size, and optional `display` (`preview`/`embed`). Active focus, selection inside
+the embed, its editor state, and network services never enter graphics core.
+Native clipboard events, pointer/wheel events and shortcuts remain owned by the
+active embed. Full embeds currently support `md` and `canvas`; other files retain
+preview cards. Recursive Canvas Next embedding remains gated by the referenced
+document's own format and feature availability.
+
+Known prototype limit: the embedded legacy canvas still converts pointer coordinates
+against an untransformed viewport. Its drawing/resize tools need host-transform
+mapping before they can be relied on inside zoomed, rotated, or flipped outer
+scenes. Document text editing uses browser-native layout/hit testing. Browser
+verification covered editor mounting, local controls, independent canvas panning,
+preview font sizing, conversion, and input enter/exit without editing source files.
+
+## Large-scene regression coverage
+
+`packages/graphics/tests/large-scene.test.tsx` mounts 2,000 rectangles across
+three groups and checks stable shape mounts and scale computations during pan,
+selection, and group movement. Scene hierarchy, paint order, and picking bounds
+are indexed on immutable snapshots; edits and undo replace those indexes.
+Selection outlines share a camera transform so panning does not rewrite every
+outline. Mutable scene builders continue to bypass caches.
diff --git a/apps/web/src/features/block-canvas/canvas-next/block-embed-adapter.tsx b/apps/web/src/features/block-canvas/block-embed-adapter.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/block-embed-adapter.tsx
rename to apps/web/src/features/block-canvas/block-embed-adapter.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/canvas-next-document.tsx b/apps/web/src/features/block-canvas/canvas-next-document.tsx
similarity index 97%
rename from apps/web/src/features/block-canvas/canvas-next/canvas-next-document.tsx
rename to apps/web/src/features/block-canvas/canvas-next-document.tsx
index 8e9d226abc..702a96c335 100644
--- a/apps/web/src/features/block-canvas/canvas-next/canvas-next-document.tsx
+++ b/apps/web/src/features/block-canvas/canvas-next-document.tsx
@@ -8,16 +8,16 @@ import {
Show,
useContext,
} from 'solid-js';
-import type { CanvasDocumentProps } from '../component/CanvasDocument';
-import {
- fetchCanvasViewLocation,
- saveCanvasViewLocation,
-} from '../queries/canvas-document';
-import { createNumericParser } from '../util/parse';
import { CanvasNextEditor } from './canvas-next';
+import type { CanvasDocumentProps } from './component/CanvasDocument';
import { CanvasAncestry } from './context/canvas-ancestry';
import type { CanvasFile } from './core/document-format';
+import { createNumericParser } from './core/parse';
import { createDocumentPersistence } from './primitives/create-document-persistence';
+import {
+ fetchCanvasViewLocation,
+ saveCanvasViewLocation,
+} from './queries/canvas-document';
import { canvasDocumentSource } from './queries/document';
const parseLocation = createNumericParser<{
@@ -166,7 +166,6 @@ export default function CanvasNextDocument(
);
return props.children
? props.children(content, {
- mode: 'next',
savedFile: () => persistence()?.savedFile(),
location: currentLocation,
})
diff --git a/apps/web/src/features/block-canvas/canvas-next/canvas-next.tsx b/apps/web/src/features/block-canvas/canvas-next.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/canvas-next.tsx
rename to apps/web/src/features/block-canvas/canvas-next.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/README.md b/apps/web/src/features/block-canvas/canvas-next/README.md
deleted file mode 100644
index 412b2ed19e..0000000000
--- a/apps/web/src/features/block-canvas/canvas-next/README.md
+++ /dev/null
@@ -1,373 +0,0 @@
-# Canvas Next — drawing, rich text, media and document cards
-
-Canvas Next opens saved documents behind the remote `enable-canvas-next` flag.
-Use `VITE_ENABLE_CANVAS_NEXT=true` in `apps/web/.env.local` to opt in locally.
-Local analytics is disabled, so unset remote flags settle as off without waiting
-for PostHog. Deployed builds use the remote rollout when no override is set. The flag is sampled when
-opening a document, so remote refreshes cannot switch an active editing session.
-
-The frontend treats unversioned JSON (and explicit version 1) as legacy Canvas.
-It converts supported records on load to `{ version: 2, document, legacy? }`.
-`document` is the graphics scene; `legacy` retains the original JSON and migration
-notes for recovery. No migration is saved merely by viewing a file. The first
-committed edit writes version 2 using the existing JSON/simple-save endpoint.
-Subsequent loads validate version 2 directly; they never replay the archived data.
-Unknown versions and invalid scenes fail closed. With the flag off, version 2
-files show a Canvas Next requirement instead of opening in the legacy editor.
-
-Migration preserves IDs, groups, stacking order, positions, shape labels,
-Markdown text, connector bindings/styles, media references and flips, and all
-legacy entity references. Pencil samples are retained and use the new brush.
-Unsupported links, connector labels, invalid records, and interleaved group layers
-offer **Open in legacy editor** without writing data.
-There is no version 2-to-legacy downgrade. Document-level read-only mode mounts a
-selection/navigation surface without editing, paste/drop, or embedded editing handlers.
-Markdown embeds explicitly pass `isEmbedded` to the editor and use this same
-read-only surface, with Select and Hand tools and no property inspector. Selection
-does not expose transform handles or mutate the scene; embedded views cannot save
-canvas edits even when the viewer has edit permission on the original document.
-Saves are debounced and serialized; failures keep edits dirty. Save state is not
-shown in the canvas UI.
-
-SyncService integration and collaboration remain a follow-up. This change keeps
-the existing whole-file save behavior. See [Graphics and Canvas parity](../../../../../../docs/GRAPHICS_PARITY.md)
-for the remaining editor and collaboration work.
-
-## Controls
-
-The floating top toolbar uses the shared `Toolbar` and Phosphor icons for drawing
-and inserting media, document cards, and embeds. Tooltips show each tool's shortcut.
-Zoom, reset-to-100%, fit, undo, and redo live at the bottom-left. Adjacent controls
-toggle floating properties and layers panels.
-Fit Scene uses the current viewport dimensions, centers all scene geometry and
-zooms in or out to leave 100 screen pixels per side on the first axis to fill.
-Camera zoom limits still apply; padding decreases for small embedded viewports.
-Ctrl/Meta-wheel zoom is pointer-anchored, with a continuous 0.002 exponential rate
-per normalized wheel pixel and an exponent cap of 0.2 per event (about 22% zoom-in).
-Plain wheel input pans at its existing speed.
-The Canvas panel's zoom menu offers **No snapping** (the default for each session),
-**Snap to px** (1 canvas px at every zoom), and **Auto snapping** (the smallest
-currently visible dot-grid interval, including faint dots). Auto follows zoom;
-hiding the grid temporarily disables it. Drawing, moving, resizing, insertion, duplication, pasting, free
-connector endpoints and layout inspector values use the chosen interval; inspector
-scrubs preview the same snapped values they commit. Freehand and rotation keep
-their own precision, and connector bindings and aspect-ratio constraints stay exact.
-The preference is local editor state, not saved JSON or shared Loro data.
-The dot grid adapts to zoom, revealing 1, 4, 16, 64 px levels (and
-coarser levels at extreme zoom-out). Coarse dots remain steady while finer dots
-fade in gently; individual canvas pixels are faintly visible at 800%. Dots use
-fixed 1 screen-pixel SVG marks, including at fractional zoom. Marks closer than
-4 screen pixels disappear to avoid a dense texture. Their centers stay anchored
-to canvas coordinates through pan/zoom. Colors blend the theme's muted ink and
-panel tokens; the dot-grid visibility toggle hides every level.
-The shared context menu exposes clipboard, grouping, layer ordering, select-all,
-and delete actions, with normal keyboard navigation and focus restoration. Active
-embedded editors and text editing retain their own context menus.
-Selecting Arrow, Line, Connector, or Pencil repairs invisible drawing defaults:
-missing/transparent strokes use theme Ink, zero width uses 2 px, and zero opacity
-uses full opacity. Other style choices and existing shapes are preserved.
-
-## Editing
-
-| Action | Shortcut |
-| --- | --- |
-| Select / rectangle / ellipse / pencil / text / hand | V / R / O / P / T / H |
-| Temporary pan | Hold Space, or middle-button drag |
-| Add/remove selection | Shift-click; Shift-drag on empty canvas adds a marquee |
-| Draw square / circle | Hold Shift while drawing a rectangle / ellipse |
-| Move horizontally / vertically | Hold Shift while dragging; follows the dominant world axis |
-| Select inside a group | Cmd/Ctrl-click |
-| Copy / cut / paste | Cmd/Ctrl+C / X / V |
-| Duplicate | Cmd/Ctrl+D, or Option/Alt-drag |
-| Select all | Cmd/Ctrl+A |
-| Nudge | Arrows: one snap unit; Shift+arrows: ten snap units |
-| Group / ungroup | Cmd/Ctrl+G / Shift+Cmd/Ctrl+G |
-| Undo / redo | Cmd/Ctrl+Z / Shift+Cmd/Ctrl+Z |
-| Delete | Backspace / Delete |
-| Front / back | ] / [ |
-| Forward / backward | Option/Alt+] / Option/Alt+[ |
-| Cancel and return to selection | Escape |
-
-Keyboard registration uses Macro's DOM scope and respects text/number inputs.
-Native clipboard events own the actual copy/cut/paste keystrokes; proxied Macro
-commands expose those actions in the command UI without double handling.
-Clipboard context-menu actions use the browser clipboard API and report denied
-access. Fragments include whole selected subtrees, fresh IDs on insertion, stable
-relative order and world placement. Pasting repeatedly offsets by another 24 units.
-Canvas Next fragments preserve rich text. Plain text and HTML pasted onto the canvas
-create a wrapped text shape; pasting inside the editor belongs to Lexical. Image
-clipboard data uploads through the media adapter. Legacy Canvas clipboard format
-remains a later adapter.
-
-Pasting an Excalidraw selection or `.excalidraw`/`excalidraw/clipboard` JSON
-imports through `core/excalidraw.ts` (import only; export is not implemented). It
-converts rectangles, ellipses, text, freedraw and line/arrow elements, rebuilds
-flat `groupIds` membership into the nested local-transform tree, folds
-container-bound text into shape or connector labels, and keeps arrow bindings
-that resolve to imported shapes. Diamonds are approximated as rectangles; images,
-frames and embeddables are dropped. Hachure/fill styles, roughness and multi-point
-line bends are not represented. Connectors import as straight unless both endpoints
-bind to imported shapes; doubly bound connectors retain their straight, smooth or
-elbow route.
-
-Option-drag duplicates the selected roots (or selects and duplicates the clicked
-shape). It is a cancellable preview; originals stay put and retain their DOM.
-Release commits creation plus movement as one undo step; clicking without moving
-or pressing Escape leaves no copy or history entry. Hold Option at gesture start;
-live modifier toggling during a duplicate drag is not implemented.
-
-The inspector stays in a rounded floating panel on the right at the same width
-and height, including with no selection. Connector routes, endpoint styles, and
-stroke patterns have previews in both their selectors and menus. Rotation and
-flip buttons share the alignment controls’ compact grouped treatment. Sections follow Position, Layout, Appearance, Fill, Stroke,
-Connection, Typography; unavailable sections are omitted without reordering the
-others. Position and Layout remain visible but disabled for fully bound connectors.
-Compact fields share a two-column grid, opacity and corner radius share Appearance,
-and label typography appears only for existing labels or during label editing.
-The inspector supports mixed values, fill/stroke palettes, width, opacity and
-rectangle radius. Width/height edits and scrubs resize geometry through the canvas
-shape definitions, preserving label proportions and remeasuring wrapping. Text
-width reflows; text height scales proportionally. Rotated world-bound edits and
-groups with incompatible axes preserve proportions rather than introducing shear.
-Color controls compose the shared `@ui` ColorPicker field, hue
-and opacity tracks, and hex input. Canvas does not import the theme editor picker
-or Color.js; custom edits produce sRGB hex, while preset theme references stay
-as references until edited. Edits also become defaults for subsequent shapes. A group has
-no inherited style: styling it edits all descendant shapes once. Ellipses ignore
-radius. Typing numbers commits on change/blur. Dragging a numeric handle previews
-the scene continuously, then commits one undo step on release. Escape, lost pointer
-capture, or leaving the window restores the starting scene without saving a change.
-Previews always use the starting document, so rotation and resizing do not accumulate
-rounding errors between samples.
-
-Selections expose four visible corner handles and invisible targets along each full
-edge, with a 10-screen-pixel hit area and resize cursors. Corners take priority
-where they overlap an edge target. Groups and multiple selections have a dashed
-world-axis-aligned box; single shapes retain their oriented solid box. The rotation
-circle follows a single shape's oriented top edge; for groups and multiple selections
-it is centered above the world bounds. Grips stay square. Edge cursors stay EW
-(sides) or NS (top/bottom); corners use the diagonal arrow matching their world-space
-quadrant relative to the selection center. Click-drag anywhere inside
-the box moves the entire selection, including gaps; Shift/deep-select still pick
-individual shapes. Option/Alt keeps the center fixed; Shift preserves proportions.
-Shift-click toggles on release. Moving at least 3 screen pixels changes it into
-an axis-constrained drag; an unselected target is added before moving the selection.
-Shift also works when pressed/released during a move, including Option-drag duplicates.
-During rectangle/ellipse creation, Shift keeps width and height equal; pressing or
-releasing it updates the preview without losing the unconstrained pointer endpoint.
-Handles and the shared bounding box hide during the preview, and each drag is one
-undo step. Shared resizing stretches independently only when descendant axes align
-with the box, including quarter turns; incompatible child rotations force uniform
-scaling for corner and edge drags. This avoids shear and keeps the content fitted
-to the box. Nonuniform resizing edits descendant geometry and moves centers while
-retaining hierarchy; uniform resizing transforms selected roots once.
-Resizing through the opposite edge flips the contents and keeps growing on the
-other side. Each axis can invert independently; modifier changes recompute from
-the original gesture, and undo/cancel restore the original geometry and handedness.
-
-Active drags continue across pointer-capture loss and release outside the canvas;
-Escape, focus loss and pointer cancellation still discard the preview.
-
-Align uses selected roots' world bounds. Distribute makes equal gaps, keeps outer
-objects fixed, and allows negative gaps for overlapping selections. Each command
-is one undo step. Stroke width and radius are local dimensions: single-shape
-resizing and nonuniform shared resizing edit geometry; uniform group/multiselection
-scaling also scales these dimensions for rectangles and ellipses. Pencil absorbs
-scale into its samples instead, preserving nominal brush width.
-Picking accepts painted stroke pixels or the existing 3-screen-pixel minimum
-outline tolerance; a thick stroke does not gain another 3px outside its paint.
-
-## Ownership
-
-- `core/`: seed/defaults only. Editing algorithms and typed commands live in graphics.
-- `primitives/`: Solid state, mixed values, creation defaults and UI actions.
-- `components/`: inspector and layer list with explicit props.
-- `views/`: editor surface and controls composed around a supplied editor/state.
-- `canvas-next.tsx`: memory editor, Macro hotkey scope and clipboard wiring.
-- `clipboard.ts` / `hotkeys.ts`: host adapters. No browser/app dependency in the core.
-
-Core command and transform tests exercise both memory and Loro paths. Canvas Next
-currently uses memory plus versioned whole-file saves; it does not install awareness
-or production collaboration.
-
-The view/state already accept an editor. The current composition root constructs
-its own memory editor; a later collaboration checkpoint can inject Loro editors while
-retaining the same rich-text measurement, renderer, clipboard and input ownership.
-
-## Pencil checkpoint
-
-P selects the pencil tool. It stays active for repeated strokes; V or Escape
-returns to selection. Tap for a dot. Mouse strokes simulate pressure from point
-spacing; pens capture pressure, with coalesced input samples processed together.
-The `perfect-freehand` brush is an internal graphics detail. Documents contain
-local samples and pressure mode, and each completed stroke is one undo entry.
-
-Selection bounds enclose the smoothed ink; clicks and marquee target that ink,
-not raw samples or empty bounding-box space. Existing selected-box drag behavior
-is unchanged. Resize scales points and recomputes pressure/ink with nominal pen
-width retained, including uniform scaling through nested groups. Copy/paste,
-Option-drag, styles, layering and local history use the shared shape pathways.
-
-The 2026-09-28 performance fix preserves immutable core geometries for rendering
-and hit queries and retains geometry through move/rotation previews. This reuses
-derived ink during pan, hover, selection and transforms; raw samples are unchanged.
-The 11-stroke/7,041-sample regression checks brush executions, not a browser FPS
-budget. Mixed-content performance and general spatial indexing remain later work.
-
-## Rich text checkpoint
-
-T chooses text. Click for auto width, or drag horizontally to choose a wrapping
-width. Double-click an existing text shape, or select it and press Enter, to edit.
-Double-click empty canvas also creates text. Escape, Cmd/Ctrl+Enter, or a click
-outside commits the edit. Empty drafts disappear without an undo entry.
-
-The editing toolbar supports bold, italic, underline, strike, code, highlight,
-links, headings, quotes, and nested bulleted/numbered lists.
-Tab / Shift+Tab indent/outdent lists. Lexical owns IME, caret/range selection, rich
-clipboard and typing undo; canvas hotkeys and gestures are suspended while editing.
-The inspector controls font family (sans/serif/mono), size and auto/wrapped width.
-Side edges reflow at fixed font size. Corners and top/bottom scale proportionally.
-Text corners follow the pointer projected onto the box's aspect-ratio diagonal,
-so horizontal drags can shrink a wide line without vertical jitter dominating.
-Scaling preserves the measured layout; width edits remeasure wrapping. Task mention
-badges, assignee avatars, and mention spacing scale in em units with the text.
-
-Type `@` in text or a shape label to open the shared mention picker. Choose a
-person, document, or other supported reference with the mouse or arrow keys and
-Enter. Pending `@` queries use the same text width as their measured content, so
-opening the picker does not add an extra wrapped line. Escape closes the picker
-before ending editing. Mentions retain their typed
-Lexical nodes through reopening, copy/paste, and undo, and render with the shared
-mention decorators. Canvas Next currently disables backend mention tracking and
-notifications; mentions remain part of the same whole-content LWW string.
-
-Canvas Next stores a stringified Lexical editor tree in `TextGeometry.content`,
-including shape labels. `core/text-codec.ts` owns bounded tree validation, seed
-construction, serialization, plain-text extraction and empty-content detection.
-Clipboard imports validate this host format before accepting a scene. Graphics
-only checks the opaque string's size; it never interprets the tree
-or decides whether to remove empty text. The text state explicitly deletes cleared
-text items, skips empty creations and clears labels while retaining their shapes.
-Canvas Next uses the shared Markdown builder (`buildConfig` and `MarkdownShell`)
-for editing and `StaticLexical` for display and measurement, with its own markup
-styles. The tree is never converted through Markdown when loading or saving.
-Whole-string LWW and existing serialized content remain unchanged.
-Only the actively edited shape mounts an editable Lexical instance.
-The editing surface has no additional colored box outline; native text selection
-and the caret remain visible. Selection indicators return after editing finishes.
-Reordering other items therefore cannot remount the editor or replace its content.
-Draft updates do not mutate the scene. Ending the edit submits one canvas undo
-step, and undo inside the editor affects only that editing session.
-
-Rectangles, ellipses and connectors own optional rich-text labels in their geometry.
-Double-click inside a rectangle or ellipse (even with no fill), or on a connector.
-You can also use T then click, or select the item and press Enter. Connector labels
-sit at the route midpoint, follow bound targets, and size to their text; the
-connector line leaves a gap behind the label. Other labels start
-center-aligned and vertically centered, wrap to a padded interior (an inscribed
-box for ellipses), and uniformly shrink to fit small shapes. Resizing remeasures
-wrapping without changing the stored font size; labels inherit the shape's stroke color and opacity. Clicking a label
-selects its owner. Ordinary clicks elsewhere in an unfilled interior still pass
-through. Clearing a label leaves the shape. Label edits, copy/paste, duplication,
-grouping and transforms all preserve ownership; there is no separate text node.
-
-The collaboration policy is deliberately whole-content last-write-wins. Loro
-stores one `textContent` string register per text item or labeled shape, separate
-from pose. Concurrent edits choose one complete tree; no character-level merging
-or shared caret is intended. Label layout metadata is separate from pose too, so
-adding a label and moving its owner can merge. Local typing undo stays in Lexical;
-finished edits use the canvas backend's undo. Canvas Next does not yet have a
-production SyncService connection.
-
-Mixed selections containing text scale uniformly to preserve letter proportions;
-use a single text shape’s side edges to change wrapping width. Shape definitions
-express this through the `canDeform` capability used by selection-frame math.
-
-## Arrows and connectors checkpoint
-
-A selects Arrow and L selects Line; C remains available for the app's Create menu.
-Choose Elbow in the Connection inspector for a rounded connector. Drag from
-empty space or a shape. Hovering a shape reveals five small endpoint-style circles:
-its center and four edge midpoints. Only the hovered shape shows these targets.
-A center drop automatically meets the outline as the target moves; side drops stay fixed on the chosen edge. Points retain their
-screen size at any zoom. The active point gets a larger pale-blue halo, both before
-the first click and while dragging either endpoint. Near an edge point it takes
-priority; farther inside the shape, its center is active (including unfilled shapes).
-
-Select a connector to reveal two endpoint circles. Drag either to reconnect or
-release in empty space to detach it. Shift snaps free endpoints to 45 degrees;
-Escape cancels. The inspector switches between Straight, Elbow and Smooth routing
-and the legacy open/filled arrowheads and large/small dots at either end. The
-original route math lives in the pure graphics core, not in this app.
-
-Target movement, rotation, resizing, nesting, grouping, copy/paste, duplication and
-undo retain connections. Copying only the connector detaches its references at the
-visible positions. Deleting a target leaves its surviving connectors in place;
-undo restores the connection. Moving a connector body moves its free ends, keeping
-bound ends attached. Endpoint previews do not write document history.
-
-Arbitrary bend-point editing and remote endpoint preview awareness are not included
-in this checkpoint.
-
-## Media and document cards
-
-The toolbar media insertion control is currently hidden pending a UI redesign.
-Native file drop, image clipboard paste, and workspace entity drag/drop continue
-to use the existing insertion path. Media is naturally
-sized, fitted within 640 × 480 world units, and inserted in one undo step per batch.
-Uploading/loading is host-owned; only stable static-file or document references
-enter the scene. Reset/unmount invalidates pending insertion. Saved Canvas Next
-documents retain stable uploaded references;
-uploads use the existing static file service. Existing workspace file selection
-does not create a new file.
-
-Image/video shape definitions own validation, bounds, hit testing and resizing in
-core. The host resolves URLs through existing queries. Images support border,
-opacity, radius, transformations (including flips), grouping, order and clipboard.
-Select a video and use Play/Pause video in the inspector; playback is local state.
-
-Workspace document drops insert a document reference rendered with
-`DocumentPreviewContent` in a 340 × 136 card, one surface layer above its parent
-and inserted at the front of the scene. Card text uses `text-base` and reflows at
-its actual width; resizing no longer scales a 320px snapshot. Titles, menus and
-task controls remain interactive; dragging the card background moves it. Select
-the card and use Open document. Workspace drops and pasted Macro links also insert
-document cards. Preview loading/errors stay inside the card's
-Suspense/ErrorBoundary. Loading shows a pulsing icon dot and two title skeleton
-lines, shared with DocumentPreview. Signed URLs, query results, media players,
-preview contents, and upload state are never stored in core. SVG-to-editable-shape
-conversion is not part of this checkpoint; SVG files can be inserted as images.
-
-
-New embed insertion is not currently exposed in the toolbar. An existing document
-card can switch between preview and embed in the inspector. Double-click
-an embed or choose Interact to enter; Done, Escape, or a click elsewhere on this
-canvas returns input to the outer canvas. Resizing changes the editor viewport.
-The embedded block stays mounted when entering/leaving interaction mode.
-
-`block-embed-adapter.tsx` mounts the existing unmanaged block loader with its own
-panel handle, toolbar, and hotkey scope. The existing editor owns permissions and
-sync: edits inside an embed save to that referenced file independently of the outer
-Canvas Next document. The core stores only the document reference,
-box size, and optional `display` (`preview`/`embed`). Active focus, selection inside
-the embed, its editor state, and network services never enter graphics core.
-Native clipboard events, pointer/wheel events and shortcuts remain owned by the
-active embed. Full embeds currently support `md` and `canvas`; other files retain
-preview cards. Recursive Canvas Next embedding remains gated by the referenced
-document's own format and feature availability.
-
-Known prototype limit: the embedded legacy canvas still converts pointer coordinates
-against an untransformed viewport. Its drawing/resize tools need host-transform
-mapping before they can be relied on inside zoomed, rotated, or flipped outer
-scenes. Document text editing uses browser-native layout/hit testing. Browser
-verification covered editor mounting, local controls, independent canvas panning,
-preview font sizing, conversion, and input enter/exit without editing source files.
-
-## Large-scene regression coverage
-
-`packages/graphics/tests/large-scene.test.tsx` mounts 2,000 rectangles across
-three groups and checks stable shape mounts and scale computations during pan,
-selection, and group movement. Scene hierarchy, paint order, and picking bounds
-are indexed on immutable snapshots; edits and undo replace those indexes.
-Selection outlines share a camera transform so panning does not rewrite every
-outline. Mutable scene builders continue to bypass caches.
diff --git a/apps/web/src/features/block-canvas/canvas-next/clipboard.test.ts b/apps/web/src/features/block-canvas/clipboard.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/clipboard.test.ts
rename to apps/web/src/features/block-canvas/clipboard.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/clipboard.ts b/apps/web/src/features/block-canvas/clipboard.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/clipboard.ts
rename to apps/web/src/features/block-canvas/clipboard.ts
diff --git a/apps/web/src/features/block-canvas/component/BaseRenderer.tsx b/apps/web/src/features/block-canvas/component/BaseRenderer.tsx
deleted file mode 100644
index caa6266ff3..0000000000
--- a/apps/web/src/features/block-canvas/component/BaseRenderer.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { ENABLE_CANVAS_VIDEO } from '@core/constant/featureFlags';
-import { Match, Switch } from 'solid-js';
-import type { RenderMode } from '../constants';
-import {
- type CanvasEdge,
- type CanvasNode,
- type EntityMentionNode,
- type ImageNode,
- isEntityMentionNode,
- isImageNode,
- isPencilNode,
- isShapeNode,
- isTextNode,
- isVideoNode,
- type PencilNode,
- type ShapeNode,
- type TextNode,
- type VideoNode,
-} from '../model/CanvasModel';
-import { Line } from './edges/Line';
-import { DSSMedia } from './nodes/DSSMedia';
-import { File } from './nodes/EntityMention';
-import { Pencil } from './nodes/Pencil';
-import { Shape } from './nodes/Shape';
-import { TextBox } from './nodes/TextBox';
-
-export function NodeRenderer(props: { node: CanvasNode; mode: RenderMode }) {
- return (
- <Switch>
- <Match when={isShapeNode(props.node)}>
- <Shape node={props.node as ShapeNode} mode={props.mode} />
- </Match>
- <Match when={isPencilNode(props.node)}>
- <Pencil node={props.node as PencilNode} mode={props.mode} />
- </Match>
- <Match
- when={
- isImageNode(props.node) ||
- (ENABLE_CANVAS_VIDEO && isVideoNode(props.node))
- }
- >
- <DSSMedia
- node={props.node as ImageNode | VideoNode}
- mode={props.mode}
- />
- </Match>
- <Match when={isTextNode(props.node)}>
- <TextBox node={props.node as TextNode} mode={props.mode} />
- </Match>
- <Match when={isEntityMentionNode(props.node)}>
- <File node={props.node as EntityMentionNode} mode={props.mode} />
- </Match>
- </Switch>
- );
-}
-
-export function EdgeRenderer(props: { edge: CanvasEdge; mode: RenderMode }) {
- return <Line edge={props.edge} mode={props.mode} />;
-}
diff --git a/apps/web/src/features/block-canvas/component/Block.tsx b/apps/web/src/features/block-canvas/component/Block.tsx
index eaba9fe35a..7249c5f367 100644
--- a/apps/web/src/features/block-canvas/component/Block.tsx
+++ b/apps/web/src/features/block-canvas/component/Block.tsx
@@ -7,12 +7,11 @@ import {
} from '@core/block';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { createMethodRegistration } from '@core/orchestrator';
-import { blockHotkeyScopeSignal } from '@core/signal/blockElement';
import { blockFileSignal, blockHandleSignal } from '@core/signal/load';
import { useCanEdit } from '@core/signal/permissions';
import { useSearchParams } from '@solidjs/router';
import { Show } from 'solid-js';
-import type { CanvasView } from '../context/canvas-document-context';
+import type { CanvasView } from '../core/view';
import { CanvasDocument, type CanvasDocumentMethods } from './CanvasDocument';
import { TopBar } from './TopBar';
@@ -26,7 +25,6 @@ export default function BlockCanvas(props: BlockCanvasProps) {
const isNested = useIsNestedBlock();
const nestedContext = useBlockNestedContext<'canvas'>();
const canEdit = useCanEdit();
- const hotkeyScope = blockHotkeyScopeSignal.get;
const file = blockFileSignal.get;
const blockHandle = blockHandleSignal.get;
const [locationParams] = useSearchParams();
@@ -42,9 +40,7 @@ export default function BlockCanvas(props: BlockCanvasProps) {
documentId={documentId}
file={file()}
canEdit={canEdit()}
- hotkeyScope={hotkeyScope()}
isNested={isNested}
- portalScope="block"
view={props.view}
locationParams={locationParams}
onLocationChange={
@@ -64,9 +60,7 @@ export default function BlockCanvas(props: BlockCanvasProps) {
<SidePanel.Layout floating>
<FileSidePanelSections />
<div class="flex size-full min-w-0 flex-col overflow-hidden">
- <TopBar
- next={state.mode === 'next' ? state : undefined}
- />
+ <TopBar state={state} />
{content}
</div>
</SidePanel.Layout>
diff --git a/apps/web/src/features/block-canvas/component/CanvasController.tsx b/apps/web/src/features/block-canvas/component/CanvasController.tsx
deleted file mode 100644
index 0d152044d1..0000000000
--- a/apps/web/src/features/block-canvas/component/CanvasController.tsx
+++ /dev/null
@@ -1,1198 +0,0 @@
-import { useCanvasFileDrop } from '@block-canvas/signal/fileDrop';
-import type { BlockName } from '@core/block';
-import { FileDropOverlay } from '@core/component/FileDropOverlay';
-import { OldMenu, OldMenuItem } from '@core/component/OldMenu';
-import {
- blockNameToFileExtensions,
- blockNameToMimeTypes,
- fileTypeToBlockName,
-} from '@core/constant/allBlocks';
-import {
- ENABLE_CANVAS_HEIC,
- ENABLE_CANVAS_VIDEO,
-} from '@core/constant/featureFlags';
-import { fileDrop } from '@core/directive/fileDrop';
-import { observedSize } from '@core/directive/observedSize';
-import { HEIC_EXTENSIONS, HEIC_MIME_TYPES } from '@core/heic/constants';
-import { registerHotkey } from '@core/hotkey/hotkeys';
-import { TOKENS } from '@core/hotkey/tokens';
-import { HOTKEY_PRIORITY_HIGH } from '@core/hotkey/types';
-import { trackMention } from '@core/signal/mention';
-import type { EntityDragEvent } from '@entity';
-import TrashSimple from '@phosphor/trash-simple.svg';
-import Clipboard from '@phosphor-icons/core/regular/clipboard.svg?component-solid';
-import CopySimple from '@phosphor-icons/core/regular/copy-simple.svg?component-solid';
-import GridFour from '@phosphor-icons/core/regular/grid-four.svg?component-solid';
-import Scissors from '@phosphor-icons/core/regular/scissors.svg?component-solid';
-import SelectionBackground from '@phosphor-icons/core/regular/selection-background.svg?component-solid';
-import SelectionForeground from '@phosphor-icons/core/regular/selection-foreground.svg?component-solid';
-import SquaresFour from '@phosphor-icons/core/regular/squares-four.svg?component-solid';
-import Stack from '@phosphor-icons/core/regular/stack.svg?component-solid';
-import StackMinus from '@phosphor-icons/core/regular/stack-minus.svg?component-solid';
-import StackPlus from '@phosphor-icons/core/regular/stack-plus.svg?component-solid';
-import { createCallback } from '@solid-primitives/rootless';
-import { throttle } from '@solid-primitives/scheduled';
-import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';
-import { cn, Hotkey } from '@ui';
-import { usePinch } from 'solid-gesture';
-import {
- createEffect,
- createMemo,
- createSignal,
- type JSX,
- on,
- onCleanup,
- onMount,
- type ParentProps,
- Show,
-} from 'solid-js';
-import {
- MAX_PAN_FLICK_SPEED,
- ReorderOperations,
- type Tool,
- Tools,
-} from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import { useConnect } from '../operation/connect';
-import { fileHeight, fileWidth, useFile } from '../operation/file';
-import { useImage } from '../operation/image';
-import { useMove } from '../operation/move';
-import { operatorFromPartial } from '../operation/operation';
-import { usePencil } from '../operation/pencil';
-import { useRescale } from '../operation/rescale';
-import { useSelect } from '../operation/select';
-import { useShape } from '../operation/shape';
-import { useText } from '../operation/text';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useClipboard } from '../signal/clipboard';
-import { useNudge } from '../signal/nudge';
-import { useReorder } from '../signal/reorder';
-import { useSelection } from '../signal/selection';
-import { useToolManager } from '../signal/toolManager';
-import {
- useCanvasEdges,
- useCanvasNodes,
- useCreateGroup,
- useDeleteGroup,
-} from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { type Vector2, vec2 } from '../util/vector2';
-import { createContextMenu } from './ContextMenu';
-
-false && observedSize;
-false && fileDrop;
-
-function toolToCursor(tool: Tool) {
- switch (tool) {
- case Tools.Select:
- return 'cursor-auto';
- case Tools.Grab:
- return 'cursor-grab';
- case Tools.ZoomIn:
- return 'cursor-zoom-in';
- case Tools.ZoomOut:
- return 'cursor-zoom-out';
- case Tools.Shape:
- return 'cursor-crosshair';
- case Tools.Image:
- return 'cursor-crosshair';
- case Tools.File:
- return 'cursor-context-menu';
- case Tools.Line:
- return 'cursor-crosshair';
- case Tools.Move:
- return 'cursor-move';
- case Tools.Pencil:
- return `cursor-crosshair`;
- case Tools.Text:
- case Tools.Typing:
- return `cursor-text`;
- default:
- return 'cursor-auto';
- }
-}
-
-// Track unique canvas controller instances to allow drag and drop to different canvases.
-let canvasControllerId = 0;
-
-export function handleDelete() {
- const selection = useSelection();
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
- const history = useCanvasHistory();
-
- return createCallback(() => {
- if (!selection.active()) return false;
- history.open();
- nodes.batchUpdate(
- () => {
- for (let id of selection.selectedNodeIds()) {
- nodes.delete(id);
- }
- },
- { autosave: true }
- );
- edges.batchUpdate(
- () => {
- for (let id of selection.selectedEdgeIds()) {
- edges.delete(id);
- }
- },
- { autosave: true }
- );
- selection.deselectAll();
- nodes.save();
- edges.save();
- history.close();
- return true;
- });
-}
-
-export function CanvasController(props: ParentProps) {
- const canvas = useCanvasDocument();
- const scopeId = canvas.hotkeyScope;
- const canEdit = canvas.canEdit;
- const isDisabled = createMemo(() => canvas.isNested() || !canEdit());
- const renderState = useRenderState();
- const toolManager = useToolManager();
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
- const selection = useSelection();
- const select = useSelect();
- const move = useMove();
- const rescale = useRescale();
- const connect = useConnect();
- const shape = useShape();
- const image = useImage();
- const pencil = usePencil();
- const text = useText();
- const clipboard = useClipboard();
- const history = useCanvasHistory();
- const file = useFile();
- const { nudge } = useNudge();
- const reorder = useReorder();
- const createGroup = useCreateGroup();
- const deleteGroup = useDeleteGroup();
- const deleteSelection = handleDelete();
- const [middleMousePressed] = canvas.state.signals.middleMousePressed;
- const [handlersByTool] = canvas.state.signals.handlersByTool;
- const [, setConnectorTypeMenuTrigger] =
- canvas.state.signals.connectorTypeMenuTrigger;
-
- const imageExtensions = blockNameToFileExtensions.image;
- const imageMimeTypes = blockNameToMimeTypes.image;
- const videoExtensions = blockNameToFileExtensions.video;
- const videoMimeTypes = blockNameToMimeTypes.video;
-
- const canvasImageExtensions = ENABLE_CANVAS_HEIC
- ? [...imageExtensions, ...HEIC_EXTENSIONS]
- : imageExtensions;
- const canvasImageMimeTypes = ENABLE_CANVAS_HEIC
- ? [...imageMimeTypes, ...HEIC_MIME_TYPES]
- : imageMimeTypes;
-
- const acceptedMimeTypes = ENABLE_CANVAS_VIDEO
- ? [...canvasImageMimeTypes, ...videoMimeTypes]
- : canvasImageMimeTypes;
- const acceptedFileExtensions = ENABLE_CANVAS_VIDEO
- ? [...canvasImageExtensions, ...videoExtensions]
- : canvasImageExtensions;
-
- const [domRect, setDomRect] = createSignal<DOMRect | undefined>();
-
- const [ref, setRef] = createSignal<HTMLDivElement>();
-
- const cursor = createMemo(() => toolToCursor(toolManager.activeTool()));
-
- const _id = canvasControllerId++;
-
- // TODO (seamus) : Doing pan this way is messy. But ths is so much nicer than it was before
- // so I will revisit if nedded. The pan operation has to be bound to the aniamtion fram rate
- // and not the rate of the mouse move event or else we get drifting or stuttering or other jank.
- let animationFrameId: number | null = null;
- let lastMousePosition = vec2(0, 0);
- let isGrab = false;
-
- toolManager.registerMouseTool(
- Tools.Grab,
- operatorFromPartial({
- preview: () => {
- if (animationFrameId) cancelAnimationFrame(animationFrameId);
-
- if (!toolManager.mouseIsDown()) {
- isGrab = false;
- return;
- }
-
- if (!isGrab) {
- isGrab = true;
- lastMousePosition = toolManager.mousePosition().clone();
- return;
- }
-
- animationFrameId = requestAnimationFrame(() => {
- const delta = toolManager.mousePosition().subtract(lastMousePosition);
- renderState.pan(delta.x, delta.y, true);
- animationFrameId = null;
- lastMousePosition = toolManager.mousePosition().clone();
- });
- },
- start: (e) => {
- isGrab = true;
- lastMousePosition = vec2(e.pageX, e.pageY);
- if (animationFrameId) cancelAnimationFrame(animationFrameId);
- },
- abort: () => {
- isGrab = false;
- if (animationFrameId) cancelAnimationFrame(animationFrameId);
- },
- commit: (e: PointerEvent) => {
- // No momentum bases "flick" on mouse based grabs.
- if (e.pointerType === 'mouse') return;
- if (!isGrab) return;
-
- const delta = vec2(e.pageX, e.pageY).subtract(lastMousePosition);
- const mag = Math.min(delta.mag(), MAX_PAN_FLICK_SPEED);
- const dir = delta.normalize();
-
- let currentMomentum = mag;
- const decayFactor = 0.8; // Controls how quickly the momentum decays
-
- const animate = () => {
- if (currentMomentum < 0.01) {
- animationFrameId = null;
- return;
- }
- renderState.pan(
- dir.x * currentMomentum,
- dir.y * currentMomentum,
- true
- );
- currentMomentum *= decayFactor;
- animationFrameId = requestAnimationFrame(animate);
- };
- animationFrameId = requestAnimationFrame(animate);
- },
- })
- );
-
- toolManager.registerMouseTool(Tools.Select, select);
- toolManager.registerMouseTool(Tools.Resize, rescale);
- toolManager.registerMouseTool(Tools.Move, move);
- toolManager.registerMouseTool(Tools.Line, connect);
- toolManager.registerMouseTool(Tools.Shape, shape);
- toolManager.registerMouseTool(Tools.Image, image);
- toolManager.registerMouseTool(Tools.Pencil, pencil);
- toolManager.registerMouseTool(Tools.Text, text);
- toolManager.registerMouseTool(Tools.File, file);
-
- toolManager.registerMouseTool(
- Tools.ZoomIn,
- operatorFromPartial({
- start: (e) => renderState.zoom(0.1, e, true),
- })
- );
-
- toolManager.registerMouseTool(
- Tools.ZoomOut,
- operatorFromPartial({
- start: (e) => renderState.zoom(-0.1, e, true),
- })
- );
-
- onMount(() => {
- registerHotkey({
- hotkey: ['delete', 'backspace'],
- scopeId: scopeId(),
- description: 'Delete selection',
- keyDownHandler: deleteSelection,
- hotkeyToken: TOKENS.canvas.delete,
- });
-
- registerHotkey({
- hotkey: ']',
- scopeId: scopeId(),
- description: 'Bring to front',
- keyDownHandler: () => {
- if (!selection.active()) return false;
- reorder.reorder(ReorderOperations.BringToFront, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.bringToFront,
- });
-
- // opt+] / opt+[ / shift+arrows are also bound on the split scope (history
- // forward/back, focus split). Register as 'add' so the split's commands
- // survive this block, with high priority so the canvas wins while
- // mounted; a false return (no selection) falls through to the split's.
- registerHotkey({
- hotkey: 'opt+]',
- scopeId: scopeId(),
- description: 'Bring forward',
- keyDownHandler: () => {
- if (!selection.active()) return false;
- reorder.reorder(ReorderOperations.Forward, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.bringForward,
- registrationType: 'add',
- handlerPriority: HOTKEY_PRIORITY_HIGH,
- });
-
- registerHotkey({
- hotkey: '[',
- scopeId: scopeId(),
- description: 'Send to back',
- keyDownHandler: () => {
- if (!selection.active()) return false;
- reorder.reorder(ReorderOperations.SendToBack, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.sendToBack,
- });
-
- registerHotkey({
- hotkey: 'opt+[',
- scopeId: scopeId(),
- description: 'Send backward',
- keyDownHandler: () => {
- if (!selection.active()) return false;
- reorder.reorder(ReorderOperations.Backward, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.sendBackward,
- registrationType: 'add',
- handlerPriority: HOTKEY_PRIORITY_HIGH,
- });
-
- registerHotkey({
- hotkey: 'cmd+a',
- scopeId: scopeId(),
- description: 'Select all',
- keyDownHandler: () => {
- toolManager.setSelectedTool(Tools.Select);
- selection.selectAll();
- return true;
- },
- hotkeyToken: TOKENS.canvas.selectAll,
- });
-
- registerHotkey({
- hotkey: 'cmd+c',
- scopeId: scopeId(),
- description: 'Copy selection',
- keyDownHandler: () => {
- if (!selection.active()) return false;
- clipboard.copySelection(false);
- return true;
- },
- hotkeyToken: TOKENS.canvas.copy,
- });
-
- registerHotkey({
- hotkey: 'cmd+x',
- scopeId: scopeId(),
- description: 'Cut selection',
- keyDownHandler: () => {
- if (!selection.active()) return false;
- history.open();
- clipboard.copySelection(true);
- selection.deselectAll();
- history.close();
- nodes.save();
- edges.save();
- return true;
- },
- hotkeyToken: TOKENS.canvas.cut,
- });
-
- registerHotkey({
- hotkey: 'cmd+v',
- scopeId: scopeId(),
- description: 'Paste',
- keyDownHandler: () => {
- return false;
- },
- hotkeyToken: TOKENS.canvas.paste,
- });
-
- registerHotkey({
- hotkey: 'cmd+=',
- scopeId: scopeId(),
- description: 'Zoom in',
- keyDownHandler: () => {
- renderState.zoom(0.1, undefined, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.zoomIn,
- });
-
- registerHotkey({
- hotkey: 'cmd+-',
- scopeId: scopeId(),
- description: 'Zoom out',
- keyDownHandler: () => {
- renderState.zoom(-0.1, undefined, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.zoomOut,
- });
-
- registerHotkey({
- hotkey: 'cmd+z',
- scopeId: scopeId(),
- description: 'Undo',
- keyDownHandler: () => {
- history.undo();
- return true;
- },
- hotkeyToken: TOKENS.canvas.undo,
- });
-
- registerHotkey({
- hotkey: ['shift+cmd+z', 'cmd+y'],
- scopeId: scopeId(),
- description: 'Redo',
- keyDownHandler: () => {
- history.redo();
- return true;
- },
- hotkeyToken: TOKENS.canvas.redo,
- });
-
- registerHotkey({
- hotkey: 'escape',
- scopeId: scopeId(),
- description: 'Cancel/Deselect',
- keyDownHandler: () => {
- toolManager.abortAll();
- selection.deselectAll();
- return true;
- },
- hotkeyToken: TOKENS.canvas.cancel,
- });
-
- registerHotkey({
- hotkey: 'v',
- scopeId: scopeId(),
- description: 'Select tool',
- keyDownHandler: () => {
- toolManager.setSelectedTool(Tools.Select);
- return true;
- },
- hotkeyToken: TOKENS.canvas.selectTool,
- });
-
- registerHotkey({
- hotkey: 'h',
- scopeId: scopeId(),
- description: 'Hand tool',
- keyDownHandler: () => {
- toolManager.setSelectedTool(Tools.Grab);
- return true;
- },
- hotkeyToken: TOKENS.canvas.handTool,
- });
-
- registerHotkey({
- hotkey: 'r',
- scopeId: scopeId(),
- description: 'Shape tool',
- keyDownHandler: () => {
- toolManager.setSelectedTool(Tools.Shape);
- return true;
- },
- hotkeyToken: TOKENS.canvas.shapeTool,
- });
-
- registerHotkey({
- hotkey: 'p',
- scopeId: scopeId(),
- description: 'Pencil tool',
- keyDownHandler: () => {
- toolManager.setSelectedTool(Tools.Pencil);
- return true;
- },
- hotkeyToken: TOKENS.canvas.pencilTool,
- });
-
- registerHotkey({
- hotkey: 'x',
- scopeId: scopeId(),
- description: 'Line tool',
- keyDownHandler: () => {
- if (toolManager.selectedTool() === Tools.Line) {
- setConnectorTypeMenuTrigger((prev) => !prev);
- }
- toolManager.setSelectedTool(Tools.Line);
- return true;
- },
- hotkeyToken: TOKENS.canvas.lineTool,
- });
-
- registerHotkey({
- hotkey: 't',
- scopeId: scopeId(),
- description: 'Text tool',
- keyDownHandler: () => {
- toolManager.setSelectedTool(Tools.Text);
- return true;
- },
- hotkeyToken: TOKENS.canvas.textTool,
- });
-
- registerHotkey({
- hotkey: 'z',
- scopeId: scopeId(),
- description: 'Zoom in tool',
- keyDownHandler: () => {
- toolManager.setSelectedTool(Tools.ZoomIn);
- return true;
- },
- hotkeyToken: TOKENS.canvas.zoomInTool,
- });
-
- registerHotkey({
- hotkey: 'opt+z',
- scopeId: scopeId(),
- description: 'Zoom out tool',
- keyDownHandler: () => {
- toolManager.setSelectedTool(Tools.ZoomOut);
- return true;
- },
- hotkeyToken: TOKENS.canvas.zoomOutTool,
- });
-
- registerHotkey({
- hotkey: 'arrowup',
- scopeId: scopeId(),
- description: 'Nudge up',
- keyDownHandler: () => {
- nudge('up', false, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.nudgeUp,
- });
-
- registerHotkey({
- hotkey: 'shift+arrowup',
- scopeId: scopeId(),
- description: 'Nudge up more',
- keyDownHandler: () => {
- nudge('up', true, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.nudgeUpMore,
- });
-
- registerHotkey({
- hotkey: 'arrowright',
- scopeId: scopeId(),
- description: 'Nudge right',
- keyDownHandler: () => {
- nudge('right', false, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.nudgeRight,
- });
-
- registerHotkey({
- hotkey: 'shift+arrowright',
- scopeId: scopeId(),
- description: 'Nudge right more',
- keyDownHandler: () => {
- if (!selection.active()) return false;
- nudge('right', true, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.nudgeRightMore,
- registrationType: 'add',
- handlerPriority: HOTKEY_PRIORITY_HIGH,
- });
-
- registerHotkey({
- hotkey: 'arrowdown',
- scopeId: scopeId(),
- description: 'Nudge down',
- keyDownHandler: () => {
- nudge('down', false, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.nudgeDown,
- });
-
- registerHotkey({
- hotkey: 'shift+arrowdown',
- scopeId: scopeId(),
- description: 'Nudge down more',
- keyDownHandler: () => {
- nudge('down', true, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.nudgeDownMore,
- });
-
- registerHotkey({
- hotkey: 'arrowleft',
- scopeId: scopeId(),
- description: 'Nudge left',
- keyDownHandler: () => {
- nudge('left', false, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.nudgeLeft,
- });
-
- registerHotkey({
- hotkey: 'shift+arrowleft',
- scopeId: scopeId(),
- description: 'Nudge left more',
- keyDownHandler: () => {
- if (!selection.active()) return false;
- nudge('left', true, true);
- return true;
- },
- hotkeyToken: TOKENS.canvas.nudgeLeftMore,
- registrationType: 'add',
- handlerPriority: HOTKEY_PRIORITY_HIGH,
- });
-
- registerHotkey({
- hotkey: 'cmd+g',
- scopeId: scopeId(),
- description: 'Group selection',
- keyDownHandler: () => {
- history.open();
- createGroup();
- history.close();
- return true;
- },
- hotkeyToken: TOKENS.canvas.group,
- });
-
- registerHotkey({
- hotkey: 'shift+cmd+g',
- scopeId: scopeId(),
- description: 'Ungroup selection',
- keyDownHandler: () => {
- history.open();
- deleteGroup();
- history.close();
- return true;
- },
- hotkeyToken: TOKENS.canvas.ungroup,
- });
-
- let optSetZoom = false;
-
- registerHotkey({
- hotkey: 'opt',
- scopeId: scopeId(),
- description: 'Zoom in',
- keyDownHandler: () => {
- if (toolManager.selectedTool() === Tools.ZoomIn) {
- toolManager.setSelectedTool(Tools.ZoomOut);
- optSetZoom = true;
- return true;
- }
- return false;
- },
- keyUpHandler: () => {
- if (toolManager.selectedTool() === Tools.ZoomOut && optSetZoom) {
- toolManager.setSelectedTool(Tools.ZoomIn);
- optSetZoom = false;
- }
- },
- hotkeyToken: TOKENS.canvas.optZoom,
- });
-
- let spaceKeyGrab = false;
- let toolBeforeSpaceGrab: Tool = Tools.Grab;
-
- registerHotkey({
- hotkey: 'space',
- scopeId: scopeId(),
- description: 'Temporary grab tool',
- keyDownHandler: (e) => {
- if (e?.repeat) return false;
- if (!spaceKeyGrab) toolBeforeSpaceGrab = toolManager.selectedTool();
- toolManager.setSelectedTool(Tools.Grab);
- spaceKeyGrab = true;
- return true;
- },
- keyUpHandler: () => {
- if (
- toolManager.selectedTool() === Tools.Grab &&
- spaceKeyGrab &&
- !middleMousePressed()
- ) {
- const handlers = handlersByTool().get(Tools.Grab);
- if (handlers) {
- for (const handler of handlers) {
- handler.abort();
- }
- }
- toolManager.setSelectedTool(toolBeforeSpaceGrab);
- toolBeforeSpaceGrab = toolManager.selectedTool();
- spaceKeyGrab = false;
- }
- },
- hotkeyToken: TOKENS.canvas.spaceGrab,
- });
- });
-
- createEffect(
- on(domRect, (_) => {
- if (!ref()) return;
- renderState.setDomRect(ref()!.getBoundingClientRect());
- })
- );
-
- const pasteHandler = (e: ClipboardEvent) => {
- // The clipboard paste handler manages its own history state.
- e.preventDefault();
- clipboard.handlePaste({
- event: e,
- });
- };
-
- onMount(() => {
- toolManager.mount(ref()!);
- ref()!.addEventListener('paste', pasteHandler);
- });
-
- onCleanup(() => {
- toolManager.cleanup();
- ref()!.removeEventListener('paste', pasteHandler);
- });
-
- const [isDragging, setIsDragging] = createSignal(false);
- const [dragPosition, setDragPosition] = createSignal<Vector2>();
- const { handleMouseUp, handleFileDrop } = useCanvasFileDrop();
- const { setSelectedTool } = useToolManager();
- const { viewBox, clientToCanvas } = useRenderState();
- const centerVec = createMemo(() => {
- return vec2(viewBox().x + viewBox().w / 2, viewBox().y + viewBox().h / 2);
- });
- const [highestOrder] = canvas.state.signals.highestOrder;
-
- const droppable = createDroppable('canvas-input-' + _id);
- const [dragDropState, { onDragEnd, onDragMove }] = useDragDropContext() ?? [
- undefined,
- {
- onDragEnd: () => {},
- onDragMove: () => {},
- },
- ];
-
- const wrapDndEvent = (event: EntityDragEvent) => {
- const currentPos = dragDropState?.active.sensor?.coordinates?.current;
- if (!currentPos) return;
- const mousePos = {
- clientX: currentPos.x,
- clientY: currentPos.y,
- };
- const item = event.draggable.data;
- const blockName = fileTypeToBlockName(item.fileType ?? item.type);
- if (!blockName) return;
- return {
- id: event.draggable.data.id as string,
- blockName: blockName as BlockName,
- mousePos,
- item,
- };
- };
-
- const attachImageOnDrag = (event: EntityDragEvent) => {
- if (!event.droppable) return;
- nodes.createNode(
- {
- type: 'image',
- status: 'dss',
- uuid: event.draggable.data.id.toString(),
- x: dragPosition()?.x ?? centerVec().x,
- y: dragPosition()?.y ?? centerVec().y,
- width: 0,
- height: 0,
- edges: [],
- style: { strokeColor: 'transparent' },
- flipX: false,
- flipY: false,
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { autosave: true }
- );
- setSelectedTool(Tools.Select);
- };
-
- const attachVideoOnDrag = (event: EntityDragEvent) => {
- if (!event.droppable) return;
-
- nodes.createNode(
- {
- type: 'video',
- status: 'dss',
- uuid: event.draggable.data.id.toString(),
- x: dragPosition()?.x ?? centerVec().x,
- y: dragPosition()?.y ?? centerVec().y,
- width: 0,
- height: 0,
- edges: [],
- style: { strokeColor: 'transparent' },
- flipX: false,
- flipY: false,
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { autosave: true }
- );
-
- setSelectedTool(Tools.Move);
- };
-
- const attachFileOnDrag = async (event: EntityDragEvent, id: string) => {
- if (!event.droppable) return;
-
- const entityType = event.draggable.data.type;
- // TODO: add channel message support
- if (entityType === 'channel_message' || entityType === 'channel_thread') {
- return;
- }
- // Routine and foreign entities aren't yet renderable as canvas mentions.
- if (
- entityType === 'routine' ||
- entityType === 'foreign' ||
- entityType === 'initiative'
- )
- return;
- // CRM companies/contacts aren't renderable as canvas mentions.
- if (entityType === 'crm_company') return;
- if (entityType === 'crm_contact') return;
- if (entityType === 'database' || entityType === 'form') return;
- // Nor are reminders — they have no canvas representation.
- // Nor are calendar events.
- if (entityType === 'calendar_event' || entityType === 'agent_session')
- return;
-
- // Track document mention and get UUID
- let mentionUuid: string | undefined;
- if (entityType === 'document') {
- mentionUuid = await trackMention(canvas.documentId(), 'document', id);
- }
-
- nodes.createNode(
- {
- type: 'entitymention',
- file: id,
- entityType,
- mentionUuid,
- x: (dragPosition()?.x ?? centerVec().x) - fileWidth / 2,
- y: (dragPosition()?.y ?? centerVec().y) - fileHeight / 2,
- width: fileWidth,
- height: fileHeight,
- edges: [],
- style: { strokeColor: 'transparent' },
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { autosave: true }
- );
-
- setSelectedTool(Tools.Select);
- };
-
- const dndDragMove = throttle((event: EntityDragEvent) => {
- if (!droppable.isActiveDroppable) {
- setDragPosition();
- return;
- }
- const res = wrapDndEvent(event);
- if (!res) return;
- const { mousePos } = res;
- setDragPosition(clientToCanvas(mousePos));
- }, 60);
-
- const dndDragEnd = (event: EntityDragEvent) => {
- if (!dragPosition()) return;
- if (!canEdit()) return;
-
- const res = wrapDndEvent(event);
- if (!res) return;
- const position = dragPosition();
-
- if (res.blockName === undefined) return;
- if (!position) return;
-
- if (res.blockName === 'image') {
- attachImageOnDrag(event);
- } else if (res.blockName === 'video' && ENABLE_CANVAS_VIDEO) {
- attachVideoOnDrag(event);
- } else {
- attachFileOnDrag(event, res.id);
- }
- };
-
- onDragEnd((event) => {
- // Only soup entity drags create nodes (not e.g. sidebar favorite drags).
- if (event.draggable?.data.dragType !== 'entity') return;
- if (event.droppable?.id !== 'canvas-input-' + _id) return;
- dndDragEnd(event as EntityDragEvent);
- });
-
- onDragMove((event) => {
- if (event.draggable?.data.dragType !== 'entity') return;
- dndDragMove(event as EntityDragEvent);
- });
-
- const [, setMouseDownPos] = canvas.state.signals.mouseDownPosition;
-
- // TODO (seamus) : Make a beter interface with the gesute library.
- const pinch = usePinch(
- ({ origin, delta, last, event, offset }) => {
- if (event.type === 'wheel') return;
- event.preventDefault();
-
- setMouseDownPos();
-
- const [scale] = offset;
- const previousScale = scale - delta[0];
- const zoomFactor = scale / previousScale - 1;
-
- const client = { clientX: origin[0], clientY: origin[1] };
-
- renderState.zoom(zoomFactor, client, last);
- },
- {
- pointer: { touch: true },
- }
- );
-
- const {
- openContextMenu,
- closeContextMenu,
- ContextMenu,
- contextMenuPos,
- menuRef,
- } = createContextMenu(ref);
- const openContextMenuHandler: JSX.EventHandler<HTMLElement, MouseEvent> = (
- e
- ) => {
- e.preventDefault();
- e.stopPropagation();
- const { x, y } = e;
- openContextMenu({ x, y });
- };
-
- return (
- <div
- data-visual-editor={true} // Attach this attr for the cross-block focus logic
- {...pinch()}
- style={{
- 'touch-action': 'none',
- }}
- ref={setRef}
- tabIndex={0}
- use:droppable={!isDisabled()}
- use:observedSize={{ setSize: setDomRect }}
- // SCUFFED THEMING? The color-mix below is a little rough, not necessarily ideal
- class={cn('relative size-full overflow-hidden z-0', cursor())}
- use:fileDrop={{
- disabled: isDisabled(),
- acceptedMimeTypes: acceptedMimeTypes,
- acceptedFileExtensions: acceptedFileExtensions,
- onDragStart: () => setIsDragging(true),
- onDragEnd: () => setIsDragging(false),
- onDrop: (files) => {
- handleFileDrop(files);
- },
- onMouseUp: handleMouseUp,
- }}
- onContextMenu={(e) => {
- e.preventDefault();
- e.stopPropagation();
- if (isDisabled()) return;
- setMouseDownPos();
- openContextMenuHandler(e);
- }}
- >
- <ContextMenu>
- <OldMenuItem
- text="Cut"
- iconClass="text-ink-extra-muted"
- icon={Scissors}
- onClick={() => {
- history.open();
- clipboard.copySelection(true);
- selection.deselectAll();
- history.close();
- nodes.save();
- edges.save();
- closeContextMenu();
- }}
- hotkey={<Hotkey token={'canvas.cut'} />}
- disabled={!selection.active()}
- />
- <OldMenuItem
- text="Copy"
- iconClass="text-ink-extra-muted"
- icon={CopySimple}
- onClick={() => {
- clipboard.copySelection(false);
- closeContextMenu();
- }}
- hotkey={<Hotkey token={'canvas.copy'} />}
- disabled={!selection.active()}
- />
- <OldMenuItem
- text="Paste"
- iconClass="text-ink-extra-muted"
- icon={Clipboard}
- onClick={() => {
- const menuPos = contextMenuPos();
- history.open();
- clipboard.handlePaste({
- position: clientToCanvas({
- clientX: menuPos.x,
- clientY: menuPos.y,
- }),
- });
- history.close();
- nodes.save();
- edges.save();
- closeContextMenu();
- }}
- hotkey={<Hotkey token={'canvas.paste'} />}
- />
- <OldMenuItem
- text="Delete"
- iconClass="text-ink-extra-muted"
- icon={TrashSimple}
- onClick={() => {
- deleteSelection();
- closeContextMenu();
- }}
- hotkey={<Hotkey token={'canvas.delete'} />}
- disabled={!selection.active()}
- />
- <Show when={selection.active()}>
- <OldMenuItem
- spacerTop={true}
- text="Change order"
- iconClass="text-ink-extra-muted"
- icon={Stack}
- chevron={true}
- menuRef={menuRef()}
- submenu={
- <OldMenu width="md">
- <OldMenuItem
- text="Bring forward"
- iconClass="text-ink-extra-muted"
- icon={StackPlus}
- onClick={() => {
- reorder.reorder(ReorderOperations.Forward, true);
- closeContextMenu();
- }}
- hotkey={<Hotkey token={'canvas.bringForward'} />}
- />
- <OldMenuItem
- text="Send backward"
- iconClass="text-ink-extra-muted"
- icon={StackMinus}
- onClick={() => {
- reorder.reorder(ReorderOperations.Backward, true);
- closeContextMenu();
- }}
- hotkey={<Hotkey token={'canvas.sendBackward'} />}
- />
- <OldMenuItem
- text="Bring to front"
- iconClass="text-ink-extra-muted"
- icon={SelectionBackground}
- onClick={() => {
- reorder.reorder(ReorderOperations.BringToFront, true);
- closeContextMenu();
- }}
- hotkey={<Hotkey token={'canvas.bringToFront'} />}
- />
- <OldMenuItem
- text="Send to back"
- iconClass="text-ink-extra-muted"
- icon={SelectionForeground}
- onClick={() => {
- reorder.reorder(ReorderOperations.SendToBack, true);
- closeContextMenu();
- }}
- hotkey={<Hotkey token={'canvas.sendToBack'} />}
- />
- </OldMenu>
- }
- />
- <OldMenuItem
- text="Group"
- iconClass="text-ink-extra-muted"
- icon={GridFour}
- onClick={() => {
- history.open();
- createGroup();
- history.close();
- closeContextMenu();
- }}
- />
- <OldMenuItem
- text="Ungroup"
- iconClass="text-ink-extra-muted"
- icon={SquaresFour}
- onClick={() => {
- history.open();
- deleteGroup();
- history.close();
- closeContextMenu();
- }}
- />
- {/* <OldMenuItem
- text="Center on screen"
- icon={() => <GpsFix class="text-ink-extra-muted" />}
- chevron={true}
- submenu={
- <Menu width="md">
- <OldMenuItem
- text="Center horizontally"
- icon={() => <DotsThreeOutline class="text-ink-extra-muted" />}
- onClick={() => {
-
- closeContextMenu();
- }}
- />
- <OldMenuItem
- text="Center vertically"
- icon={() => (
- <DotsThreeOutlineVertical class="text-ink-extra-muted" />
- )}
- onClick={() => {
-
- closeContextMenu();
- }}
- />
- <OldMenuItem
- text="Center both"
- icon={() => <DotOutline class="text-ink-muted" />}
- onClick={() => {
-
- closeContextMenu();
- }}
- />
- </Menu>
- }
- /> */}
- </Show>
- </ContextMenu>
- <Show when={isDragging() || droppable.isActiveDroppable}>
- <FileDropOverlay valid={true}>
- Drop any file here to add it to your canvas
- </FileDropOverlay>
- </Show>
- {props.children}
- </div>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/CanvasDocument.tsx b/apps/web/src/features/block-canvas/component/CanvasDocument.tsx
index 9354cc599b..98fd4c95e4 100644
--- a/apps/web/src/features/block-canvas/component/CanvasDocument.tsx
+++ b/apps/web/src/features/block-canvas/component/CanvasDocument.tsx
@@ -1,69 +1,22 @@
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import type { PortalScope } from '@core/component/ScopedPortal';
-import { toast } from '@core/component/Toast/Toast';
-import { enableCanvasNext } from '@core/constant/featureFlags';
-import { useTauri } from '@macro/tauri';
-import { debounce } from '@solid-primitives/scheduled';
import {
type Accessor,
- createEffect,
- createMemo,
- createRenderEffect,
createResource,
- createSignal,
type JSX,
lazy,
Match,
- on,
- onCleanup,
Show,
Switch,
} from 'solid-js';
-import {
- type CanvasFile,
- canvasVersion,
-} from '../canvas-next/core/document-format';
-import {
- type CanvasLoadResult,
- loadCanvasFile,
-} from '../canvas-next/core/load-document';
-import { importCanvasMarkdown } from '../canvas-next/primitives/text-lexical';
-import {
- CanvasDocumentProvider,
- type CanvasView,
- useCanvasDocument,
-} from '../context/canvas-document-context';
-import type { Canvas } from '../model/CanvasModel';
-import { fetchCanvasViewLocation } from '../queries/canvas-document';
-import {
- useExportCanvasData,
- useLoadCanvasData,
- useSaveCanvasDataImmediate,
-} from '../store/canvasData';
-import { createNumericParser } from '../util/parse';
-import { CanvasController } from './CanvasController';
-import { CanvasRenderer } from './CanvasRenderer';
+import type { CanvasFile } from '../core/document-format';
+import { type CanvasLoadResult, loadCanvasFile } from '../core/load-document';
+import type { CanvasView } from '../core/view';
+import { importCanvasMarkdown } from '../primitives/text-lexical';
import { Loading } from './Loading';
-import { ToolBar } from './ToolBar';
-const CanvasNextDocument = lazy(
- () => import('../canvas-next/canvas-next-document')
-);
-
-const parseParams = createNumericParser<{
- x?: number;
- y?: number;
- scale?: number;
-}>({
- x: ['x', 'canvas_x'],
- y: ['y', 'canvas_y'],
- scale: ['s', 'scale', 'canvas_scale'],
-});
-
-type CanvasDataState = 'loading' | 'error' | 'initialized';
+const CanvasNextDocument = lazy(() => import('../canvas-next-document'));
export type CanvasDocumentMethods = {
- exportCanvas: () => Promise<Canvas | CanvasFile>;
+ exportCanvas: () => Promise<CanvasFile>;
goToLocationFromParams: (params: Record<string, unknown>) => void;
};
@@ -71,9 +24,7 @@ export type CanvasDocumentProps = {
documentId: string;
file?: Blob;
canEdit: boolean;
- hotkeyScope: string;
isNested?: boolean;
- portalScope?: PortalScope;
view?: CanvasView;
locationParams?: Record<string, string | string[] | undefined>;
onLocationChange?: (location: CanvasView) => void;
@@ -82,9 +33,8 @@ export type CanvasDocumentProps = {
};
export type CanvasDocumentChrome = {
- mode: 'legacy' | 'next';
savedFile: Accessor<Blob | undefined>;
- location?: () => { x: number; y: number; s: number };
+ location: () => { x: number; y: number; s: number };
};
export function CanvasDocument(props: CanvasDocumentProps) {
@@ -98,61 +48,23 @@ export function CanvasDocument(props: CanvasDocumentProps) {
}
function CanvasDocumentLoader(props: CanvasDocumentProps) {
- const flag = useFeatureFlag(enableCanvasNext);
- const [enabled, setEnabled] = createSignal<boolean>();
- // Keep an open document on one editor until it is reopened.
- createEffect(() => {
- if (enabled() === undefined && !flag().loading) setEnabled(flag().enabled);
- });
- const [legacy, setLegacy] = createSignal(false);
const [loaded] = createResource(
- () =>
- enabled() === undefined
- ? false
- : { file: props.file, enabled: enabled()! },
- async ({ file, enabled }): Promise<CanvasLoadResult> => {
- if (!file)
- return {
- kind: 'error',
- message: 'Canvas file unavailable',
- canOpenLegacy: false,
- };
+ () => ({ file: props.file }),
+ async ({ file }): Promise<CanvasLoadResult> => {
+ if (!file) return { kind: 'error', message: 'Canvas file unavailable' };
try {
return loadCanvasFile(
JSON.parse(await file.text()),
- enabled,
importCanvasMarkdown
);
} catch {
- return {
- kind: 'error',
- message: 'Could not read canvas file',
- canOpenLegacy: false,
- };
+ return { kind: 'error', message: 'Could not read canvas file' };
}
}
);
- createEffect(
- on(
- () => props.file,
- () => setLegacy(false)
- )
- );
- const legacyAllowed = () => {
- const result = loaded();
- return result?.kind === 'error' && result.canOpenLegacy;
- };
return (
- <Show
- when={enabled() !== undefined && !loaded.loading}
- fallback={<Loading />}
- >
+ <Show when={!loaded.loading} fallback={<Loading />}>
<Switch>
- <Match
- when={loaded()?.kind === 'legacy' || (legacy() && legacyAllowed())}
- >
- <LegacyCanvasDocument {...props} />
- </Match>
<Match when={loaded()?.kind === 'next' && loaded()} keyed>
{(result) =>
result.kind === 'next' && (
@@ -168,15 +80,6 @@ function CanvasDocumentLoader(props: CanvasDocumentProps) {
class="flex size-full flex-col items-center justify-center gap-3 p-6 text-sm"
>
<p>{result.message}</p>
- <Show when={result.canOpenLegacy}>
- <button
- type="button"
- class="rounded border border-edge-muted px-3 py-2"
- onClick={() => setLegacy(true)}
- >
- Open in legacy editor
- </button>
- </Show>
</div>
)
}
@@ -185,239 +88,3 @@ function CanvasDocumentLoader(props: CanvasDocumentProps) {
</Show>
);
}
-
-function LegacyCanvasDocument(props: CanvasDocumentProps) {
- return (
- <Show when={props.documentId} keyed>
- {(documentId) => (
- <CanvasDocumentProvider
- documentId={documentId}
- canEdit={props.canEdit}
- isNested={props.isNested}
- hotkeyScope={props.hotkeyScope}
- portalScope={props.portalScope}
- onLocationChange={props.onLocationChange}
- >
- <CanvasDocumentState {...props} />
- </CanvasDocumentProvider>
- )}
- </Show>
- );
-}
-
-function CanvasDocumentState(props: CanvasDocumentProps) {
- const canvas = useCanvasDocument();
- const { isNested, onLocationChange } = canvas;
- const loadCanvasData = useLoadCanvasData();
- const saveCanvasDataImmediate = useSaveCanvasDataImmediate();
- const exportCanvasData = useExportCanvasData();
- const [pending] = canvas.state.signals.pendingUpdates;
- const [renderState, setRenderState] = canvas.state.stores.render;
- const [animation] = canvas.state.stores.animation;
- const [dataState, setDataState] = createSignal<CanvasDataState>('loading');
- const [visible, setVisible] = createSignal(false);
- const unregisterUpdatePreparation =
- useTauri()?.registerNativeUpdatePreparation(async () => {
- if (pending() && !(await saveCanvasDataImmediate())) {
- throw new Error(
- 'Could not save your canvas. Please try again before restarting.'
- );
- }
- });
- onCleanup(() => unregisterUpdatePreparation?.());
- const [pendingLocationParams, setPendingLocationParams] =
- createSignal<Record<string, unknown>>();
-
- props.registerMethods?.({
- goToLocationFromParams: setPendingLocationParams,
- });
-
- createEffect(() => {
- if (dataState() !== 'initialized') return;
- props.registerMethods?.({
- exportCanvas: async () => exportCanvasData(),
- });
- });
-
- onCleanup(() => {
- if (pending()) void saveCanvasDataImmediate();
- });
-
- createEffect(() => {
- const handleBeforeUnload = () => {
- if (pending()) void saveCanvasDataImmediate();
- };
- window.addEventListener('beforeunload', handleBeforeUnload);
- onCleanup(() => {
- window.removeEventListener('beforeunload', handleBeforeUnload);
- });
- });
-
- createEffect(() => {
- const notifyLocationChange = onLocationChange();
- if (!notifyLocationChange || !visible()) return;
-
- const notify = debounce(notifyLocationChange, 100);
- let initialized = false;
- createEffect(() => {
- const { x, y, scale } = renderState;
- const state = getCanvasState({ x, y, scale });
- if (!initialized) {
- initialized = true;
- const initialView = props.view;
- if (
- initialView &&
- initialView.x === state.x &&
- initialView.y === state.y &&
- initialView.scale === state.scale
- ) {
- return;
- }
- }
- notify(state);
- });
- });
-
- const locationSource = createMemo(() => {
- if (props.view) return { type: 'view' as const, view: props.view };
- if (isNested()) return;
- return {
- type: 'document' as const,
- documentId: props.documentId,
- file: props.file,
- };
- });
- const [lastViewLocation] = createResource(locationSource, async (source) => {
- if (source.type === 'view') return source.view;
- return fetchCanvasViewLocation(source.documentId);
- });
-
- createEffect(() => {
- const file = props.file;
- setDataState('loading');
- setVisible(false);
- if (!file) {
- setDataState('error');
- return;
- }
-
- let cancelled = false;
- const loadFile = async () => {
- try {
- const data: Canvas = JSON.parse(await file.text());
- if (canvasVersion(data) !== 1)
- throw new Error('This canvas requires Canvas Next');
- const loaded = await loadCanvasData(data, () => !cancelled);
- if (loaded && !cancelled) setDataState('initialized');
- } catch (error) {
- if (cancelled) return;
- setDataState('error');
- toast.failure('Failed to parse canvas file');
- console.error(error);
- }
- };
- void loadFile();
- onCleanup(() => {
- cancelled = true;
- });
- });
-
- const computedLocation = createMemo(() => {
- if (props.view) return props.view;
- if (isNested()) return null;
-
- const pendingLocation = parseParams(pendingLocationParams() ?? {});
- if (pendingLocation) return pendingLocation;
-
- const urlLocation = parseParams(props.locationParams ?? {});
- if (urlLocation) return urlLocation;
-
- if (lastViewLocation.loading) return;
- return lastViewLocation() ?? null;
- });
-
- const [centerContentsPending, setCenterContentsPending] = createSignal(false);
-
- createEffect(
- on([dataState, computedLocation], () => {
- if (dataState() !== 'initialized') return;
-
- const location = computedLocation();
- if (location) {
- setCanvasState(location);
- setTimeout(() => setVisible(true), 10);
- } else if (location === null) {
- setCenterContentsPending(true);
- setVisible(true);
- }
- })
- );
-
- createRenderEffect((wasAnimating) => {
- if (visible() || !centerContentsPending()) return;
-
- const animating = animation.isAnimating;
- if (wasAnimating && !animating) {
- setTimeout(() => setVisible(true), 10);
- setCenterContentsPending(false);
- }
- return animating;
- });
-
- const setCanvasState = (location: {
- x?: number;
- y?: number;
- scale?: number;
- }) => {
- if (location.scale !== undefined && !Number.isNaN(location.scale)) {
- setRenderState('scale', location.scale / 100);
- }
- if (location.x !== undefined && !Number.isNaN(location.x)) {
- setRenderState('x', location.x);
- }
- if (location.y !== undefined && !Number.isNaN(location.y)) {
- setRenderState('y', location.y);
- }
- };
-
- const content = (
- <Show
- when={dataState() === 'initialized'}
- fallback={
- <div class="flex size-full items-center justify-center">
- <Loading />
- </div>
- }
- >
- <CanvasController>
- <Show when={visible()}>
- <CanvasRenderer />
- <ToolBar />
- </Show>
- </CanvasController>
- </Show>
- );
-
- return props.children
- ? props.children(content, {
- mode: 'legacy',
- savedFile: () =>
- canvas.state.signals.currentSavedFile[0]() ?? undefined,
- })
- : content;
-}
-
-function getCanvasState(state: {
- x?: number;
- y?: number;
- scale?: number;
-}): CanvasView {
- const x = state.x && !Number.isNaN(state.x) ? Math.round(state.x) : 0;
- const y = state.y && !Number.isNaN(state.y) ? Math.round(state.y) : 0;
- const scale =
- state.scale != null && !Number.isNaN(state.scale)
- ? Math.round(state.scale * 100)
- : 100;
-
- return { x, y, scale };
-}
diff --git a/apps/web/src/features/block-canvas/component/CanvasRenderer.tsx b/apps/web/src/features/block-canvas/component/CanvasRenderer.tsx
deleted file mode 100644
index 5650ecb6f9..0000000000
--- a/apps/web/src/features/block-canvas/component/CanvasRenderer.tsx
+++ /dev/null
@@ -1,308 +0,0 @@
-import { LOCAL_ONLY } from '@core/constant/featureFlags';
-import { isMobileWidth } from '@core/mobile/mobileWidth';
-import Circuitry from '@phosphor/circuitry.svg';
-import { cn } from '@ui';
-import { nanoid } from 'nanoid';
-import {
- type Accessor,
- createMemo,
- For,
- type ParentProps,
- Show,
-} from 'solid-js';
-import { type RenderMode, RenderModes } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { CanvasEdge, CanvasId, CanvasNode } from '../model/CanvasModel';
-import { useSelection } from '../signal/selection';
-import {
- debugRenderQueue,
- previewRenderQueue,
- renderQueue,
- useCanvasEdges,
- useCanvasNodes,
-} from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { clamp } from '../util/math';
-import type { RenderQueue } from '../util/renderQueue';
-import { EdgeRenderer, NodeRenderer } from './BaseRenderer';
-import { CenterContents } from './CenterContents';
-import { FloatingMenu } from './FloatingMenu';
-import { LayerContext } from './LayerContext';
-import { PanWidget } from './PanWidget';
-import { SelectionBox } from './SelectionBox';
-import { SelectionRenderer } from './SelectionRenderer';
-import { ZoomWidget } from './ZoomWidget';
-
-export function NodeMap(props: { nodes: CanvasNode[]; mode: RenderMode }) {
- return (
- <For each={props.nodes}>
- {(node) => <NodeRenderer node={node} mode={props.mode} />}
- </For>
- );
-}
-
-export function EdgeMap(props: { edges: CanvasEdge[]; mode: RenderMode }) {
- return (
- <For each={props.edges}>
- {(edge) => <EdgeRenderer edge={edge} mode={props.mode} />}
- </For>
- );
-}
-
-export function MapRender(props: {
- queue: RenderQueue;
- mode: RenderMode;
- getNode: (id: CanvasId) => CanvasNode;
- getEdge: (id: CanvasId) => CanvasEdge;
-}) {
- return (
- <For each={props.queue.sorted()}>
- {(renderable) => {
- if (renderable.type === 'node') {
- return (
- <NodeRenderer
- node={props.getNode(renderable.id)}
- mode={props.mode}
- />
- );
- }
- if (renderable.type === 'edge') {
- return (
- <EdgeRenderer
- edge={props.getEdge(renderable.id)}
- mode={props.mode}
- />
- );
- }
- }}
- </For>
- );
-}
-
-function DotPattern(props: {
- scale: Accessor<number>;
- x: Accessor<number>;
- y: Accessor<number>;
-}) {
- const size = 25;
- const patternTransform = createMemo(() => {
- return `translate(${props.x()},${props.y()}) scale(${props.scale()})`;
- });
- const radius = createMemo(() => {
- return clamp(1 / props.scale(), 1, 2);
- });
- const id = `dot-pattern-${nanoid(6)}`;
-
- return (
- <svg class="absolute inset-0 size-full">
- <defs>
- <pattern
- id={id}
- width={size.toString()}
- height={size.toString()}
- patternUnits="userSpaceOnUse"
- patternTransform={patternTransform()}
- >
- <circle
- cx={(size / 2).toString()}
- cy={(size / 2).toString()}
- r={radius().toString()}
- fill="#8B868022"
- />
- </pattern>
- </defs>
- <rect width="100%" height="100%" fill={`url(#${id})`} />
- </svg>
- );
-}
-
-function CanvasLayer(
- props: ParentProps<{
- x: Accessor<number>;
- y: Accessor<number>;
- z: Accessor<number>;
- scale: Accessor<number>;
- ref?: (el: HTMLDivElement) => void;
- inert?: boolean;
- }>
-) {
- return (
- <div
- ref={props.ref}
- class="canvas-transform-root top-0 left-0 absolute"
- style={{
- transform: `translate(${props.x()}px, ${props.y()}px) scale(${props.scale()})`,
- 'z-index': props.z(),
- }}
- inert={props.inert}
- >
- {props.children}
- </div>
- );
-}
-
-export function CanvasRenderer() {
- const { canEdit, isNested } = useCanvasDocument();
- const { currentSize, currentScale, currentPosition } = useRenderState();
- const { selectionBox } = useSelection();
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
-
- let baseLayerRef!: HTMLDivElement;
- let selectionLayerRef!: HTMLDivElement;
- let lineSelectionLayerRef!: HTMLDivElement;
-
- const canvasX = createMemo(() => {
- const w = currentSize()?.x;
- if (!w) return 0;
- return w / 2 + currentPosition().x;
- });
-
- const canvasY = createMemo(() => {
- const h = currentSize()?.y;
- if (!h) return 0;
- return h / 2 + currentPosition().y;
- });
-
- const scale = createMemo(() => currentScale());
-
- const visibleObjects = createMemo(() => {
- return nodes.visible().length > 0 || edges.visible().length > 0;
- });
-
- return (
- <LayerContext.Provider
- value={() => ({
- base: baseLayerRef,
- selection: selectionLayerRef,
- lineSelection: lineSelectionLayerRef,
- })}
- >
- <div class="absolute inset-0 size-full pointer-events-none">
- <DotPattern scale={scale} x={canvasX} y={canvasY} />
- </div>
-
- <CanvasLayer
- x={canvasX}
- y={canvasY}
- z={() => 0}
- scale={scale}
- ref={(el) => {
- baseLayerRef = el;
- }}
- inert={isNested()}
- >
- <Show when={LOCAL_ONLY}>
- <div class="pointer-events-none">
- <MapRender
- queue={debugRenderQueue()}
- mode={RenderModes.Basic}
- getNode={nodes.get}
- getEdge={edges.get}
- />
- </div>
- </Show>
-
- <MapRender
- queue={renderQueue()}
- mode={RenderModes.Basic}
- getNode={nodes.get}
- getEdge={edges.get}
- />
-
- <MapRender
- queue={previewRenderQueue()}
- mode={RenderModes.Preview}
- getNode={nodes.get}
- getEdge={edges.get}
- />
-
- {/* render the x and y axes for debugging */}
- {/* SCUFFED THEMING: how do we want to define these colors?? */}
- <Show when={LOCAL_ONLY}>
- <div
- class="absolute bg-accent/25 -z-50"
- style={{
- width: 1 / scale() + 'px',
- height: '10000px',
- top: '-5000px',
- left: 0,
- }}
- ></div>
- </Show>
- <Show when={LOCAL_ONLY}>
- <div
- class="absolute bg-failure/25 -z-50"
- style={{
- height: 1 / scale() + 'px',
- width: '10000px',
- left: '-5000px',
- top: 0,
- }}
- ></div>
- </Show>
- </CanvasLayer>
-
- <CanvasLayer
- x={canvasX}
- y={canvasY}
- z={() => 1}
- scale={scale}
- ref={(el) => {
- selectionLayerRef = el;
- }}
- inert={isNested()}
- />
-
- <CanvasLayer
- x={canvasX}
- y={canvasY}
- z={() => 2}
- scale={scale}
- inert={isNested()}
- >
- <SelectionRenderer />
- <SelectionBox rect={selectionBox()} />
- </CanvasLayer>
-
- <CanvasLayer
- x={canvasX}
- y={canvasY}
- z={() => 3}
- scale={scale}
- ref={(el) => {
- lineSelectionLayerRef = el;
- }}
- inert={isNested()}
- />
-
- <Show when={!visibleObjects()}>
- <div class="size-full absolute top-0 left-0 flex flex-col text-center items-center justify-center gap-4 z-20 pointer-events-none">
- <Circuitry class="size-12 text-canvas" />
- <div class="w-80 h-14 text-ink-extra-muted">
- Create whiteboards, diagrams, mind maps, designs and more.
- </div>
- </div>
- </Show>
-
- <Show when={!isNested() && canEdit()}>
- <div
- class={cn(
- 'w-full absolute flex',
- isMobileWidth() && 'justify-center'
- )}
- >
- <FloatingMenu />
- </div>
- </Show>
-
- <Show when={visibleObjects()}>
- <ZoomWidget />
- <CenterContents />
- <Show when={LOCAL_ONLY}>
- <PanWidget />
- </Show>
- </Show>
- </LayerContext.Provider>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/CenterContents.tsx b/apps/web/src/features/block-canvas/component/CenterContents.tsx
deleted file mode 100644
index c06d59f83c..0000000000
--- a/apps/web/src/features/block-canvas/component/CenterContents.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { createCallback } from '@solid-primitives/rootless';
-import { createMemo, onMount } from 'solid-js';
-import { useToolManager } from '../signal/toolManager';
-import {
- useBoundingBox,
- useCanvasEdges,
- useCanvasNodes,
-} from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { Rect } from '../util/rectangle';
-import { vec2 } from '../util/vector2';
-
-export const scrollToView = (animate?: boolean) => {
- const edges = useCanvasEdges();
- const nodes = useCanvasNodes();
- const renderState = useRenderState();
- const boundingBox = useBoundingBox();
-
- const visibleObjectsBounds = createMemo(() => {
- const freeEdges = edges
- .visible()
- .filter((edge) => edge.from.type === 'free' || edge.to.type === 'free');
-
- if (nodes.visible().length === 0 && freeEdges.length === 0) {
- return Rect.fromPoints(vec2(0, 0), vec2(0, 0));
- }
-
- return boundingBox(nodes.visible(), freeEdges);
- });
-
- const visible = visibleObjectsBounds();
- const center = visible.center;
- const { x: viewW, y: viewH } = renderState.currentSize();
- const wFit = visible.width === 0 ? 1 : viewW / (visible.width + 100);
- const hFit = visible.height === 0 ? 1 : viewH / (visible.height + 100);
-
- renderState.animateTo(
- {
- x: -center.x,
- y: -center.y,
- scale: Math.min(wFit, hFit),
- },
- animate ? 400 : 0,
- true
- );
-};
-
-export function CenterContents() {
- const edges = useCanvasEdges();
- const nodes = useCanvasNodes();
- const renderState = useRenderState();
- const toolManager = useToolManager();
- const boundingBox = useBoundingBox();
- let ref!: HTMLDivElement;
-
- const visibleObjectsBounds = createMemo(() => {
- const freeEdges = edges
- .visible()
- .filter((edge) => edge.from.type === 'free' || edge.to.type === 'free');
-
- if (nodes.visible().length === 0 && freeEdges.length === 0) {
- return Rect.fromPoints(vec2(0, 0), vec2(0, 0));
- }
-
- return boundingBox(nodes.visible(), freeEdges);
- });
-
- const contentVisible = createMemo(() => {
- if (nodes.visible().length === 0 && edges.visible().length === 0)
- return true;
-
- return visibleObjectsBounds().intersects(renderState.viewBox());
- });
-
- const handler = createCallback(() => {
- scrollToView(true);
- });
-
- onMount(() => {
- toolManager.ignoreMouseEvents(ref);
- });
-
- return (
- <div
- class="border-edge p-2 text-ink-muted absolute bottom-4 left-[50%] translate-x-[-50%] rounded-xl cursor-auto "
- classList={{
- invisible: contentVisible(),
- }}
- ref={ref}
- on:click={handler}
- >
- Scroll to content
- </div>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/ContextMenu.tsx b/apps/web/src/features/block-canvas/component/ContextMenu.tsx
deleted file mode 100644
index 8f4dd4dada..0000000000
--- a/apps/web/src/features/block-canvas/component/ContextMenu.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import { vec2 } from '@block-canvas/util/vector2';
-import { OldMenu } from '@core/component/OldMenu';
-import { ScopedPortal } from '@core/component/ScopedPortal';
-import clickOutside from '@core/directive/clickOutside';
-import {
- autoUpdate,
- computePosition,
- hide,
- offset,
- shift,
-} from '@floating-ui/dom';
-import {
- type Accessor,
- children,
- createEffect,
- createMemo,
- onCleanup,
- type ParentProps,
- Show,
-} from 'solid-js';
-import { useCanvasDocument } from '../context/canvas-document-context';
-
-interface BaseMenuProps {
- open: boolean;
- x: number;
- y: number;
- ref?: HTMLDivElement | ((ref: HTMLDivElement) => void);
-}
-export function BaseMenu(props: ParentProps<BaseMenuProps>) {
- const { portalScope } = useCanvasDocument();
- const safeChildren = children(() => props.open && props.children);
- return (
- <Show when={props.open}>
- <ScopedPortal scope={portalScope()}>
- <div
- style={{ left: `${props.x}px`, top: `${props.y}px` }}
- class="absolute z-item-options-menu"
- ref={props.ref}
- >
- <OldMenu width="md">{safeChildren()}</OldMenu>
- </div>
- </ScopedPortal>
- </Show>
- );
-}
-
-export function createContextMenu(
- anchorElement: Accessor<HTMLElement | undefined>
-) {
- const [contextMenu, setContextMenu] =
- useCanvasDocument().state.stores.contextMenu;
-
- const contextMenuPos = () => {
- return vec2(contextMenu.x, contextMenu.y);
- };
-
- const openContextMenu = (mousePos?: { x: number; y: number }) =>
- setContextMenu({ open: true, mousePos });
-
- const closeContextMenu = () => setContextMenu({ open: false });
-
- const ContextMenu = (props: ParentProps) => {
- createEffect(() => {
- if (contextMenu.open && contextMenu.ref)
- clickOutside(contextMenu.ref, () => closeContextMenu, true);
- });
-
- onCleanup(() => setContextMenu({ ref: undefined }));
- return (
- <BaseMenu
- open={contextMenu.open}
- x={contextMenu.x}
- y={contextMenu.y}
- children={props.children}
- ref={(ref) => {
- setContextMenu({ ref });
- }}
- />
- );
- };
-
- const offsetByMousePos = createMemo(() => {
- const referenceEl = anchorElement();
- if (!referenceEl) return;
-
- if (!contextMenu.mousePos) return;
-
- const { x, y } = contextMenu.mousePos;
- const rects = referenceEl.getBoundingClientRect();
- return offset({
- mainAxis: y - rects.y - rects.height,
- crossAxis: x - rects.x,
- });
- });
-
- const updatePosition = () => {
- const referenceEl = anchorElement();
- if (!referenceEl || !contextMenu.ref) return;
-
- const middleware = [shift({ padding: 16, crossAxis: true }), hide()];
- const offsetMiddleware = offsetByMousePos();
- if (offsetMiddleware) {
- middleware.unshift(offsetMiddleware);
- }
-
- computePosition(referenceEl, contextMenu.ref, {
- placement: 'bottom-start',
- strategy: 'absolute',
- middleware,
- }).then(({ x, y, middlewareData: { hide } }) => {
- if (hide?.referenceHidden) return closeContextMenu();
-
- setContextMenu({ x, y });
- });
- };
-
- createEffect(() => {
- const referenceEl = anchorElement();
- if (!contextMenu.open || !referenceEl || !contextMenu.ref) return;
-
- const cleanup = autoUpdate(referenceEl, contextMenu.ref, updatePosition);
- onCleanup(() => cleanup());
- });
-
- createEffect(() => {
- if (contextMenu.open) anchorElement()?.focus();
- else anchorElement()?.blur();
- });
-
- return {
- openContextMenu,
- closeContextMenu,
- ContextMenu,
- isOpen: () => contextMenu.open,
- contextMenuPos,
- menuRef: () => contextMenu.ref,
- };
-}
diff --git a/apps/web/src/features/block-canvas/component/FileSelector.tsx b/apps/web/src/features/block-canvas/component/FileSelector.tsx
deleted file mode 100644
index 24b81f064d..0000000000
--- a/apps/web/src/features/block-canvas/component/FileSelector.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import {
- EntityIcon,
- type EntityWithValidIcon,
-} from '@core/component/EntityIcon';
-import { OldMenu } from '@core/component/OldMenu';
-import { blockAcceptedFileExtensionSet } from '@core/constant/allBlocks';
-import { onKeyDownClick, onKeyUpClick } from '@core/util/click';
-import FileText from '@phosphor-icons/core/regular/file-text.svg?component-solid';
-import { useHistoryQuery } from '@queries/history/history';
-import type { ItemType } from '@service-storage/client';
-import type { FileType } from '@service-storage/generated/schemas/fileType';
-import { Dropdown } from '@ui';
-import { createEffect, createSignal, Show } from 'solid-js';
-import { VList } from 'virtua/solid';
-import { Tools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import { useSelect } from '../operation/select';
-import { useToolManager } from '../signal/toolManager';
-
-type FileItem = {
- name: string;
- id: string;
- type?: FileType;
-};
-
-function ItemOption(props: { file: FileItem; type: ItemType }) {
- const [, setSelectedFile] = useCanvasDocument().state.signals.selectedFile;
- const toolManager = useToolManager();
- const select = useSelect();
-
- const selectFile = (e: Event) => {
- e.stopPropagation();
- e.preventDefault();
- select.abort();
- setSelectedFile({
- type: props.type,
- id: props.file.id,
- });
- toolManager.setSelectedTool(Tools.File);
- };
-
- return (
- <div
- class="w-72 flex flex-row rounded hover:bg-hover hover-transition-bg p-2 text-sm select-none items-center"
- onmousedown={selectFile}
- onKeyDown={onKeyDownClick(selectFile)}
- onKeyUp={onKeyUpClick(selectFile)}
- ontouchstart={selectFile}
- tabIndex={0}
- >
- <EntityIcon
- targetType={props.file.type ?? (props.type as EntityWithValidIcon)}
- size={'sm'}
- />
- <div class="ml-2 line-clamp-1 text-ellipsis">{props.file.name}</div>
- </div>
- );
-}
-
-export function FileSelector() {
- const [userFiles, setUserFiles] = createSignal<
- { file: FileItem; type: ItemType }[]
- >([]);
- const historyQuery = useHistoryQuery();
- const { focusCanvas } = useToolManager();
-
- const [fileSelectorOpen, setFileSelectorOpen] = createSignal(false);
-
- createEffect(async () => {
- const files: { file: FileItem; type: ItemType }[] = [];
- (historyQuery.data ?? []).forEach((item) => {
- if (
- item.type === 'document' &&
- item.fileType &&
- blockAcceptedFileExtensionSet.has(item.fileType)
- ) {
- const file = {
- name: item.name,
- id: item.id,
- type: item.fileType as FileType,
- };
- files.push({ file, type: 'document' });
- }
- if (item.type === 'chat') {
- const file = { name: item.name, id: item.id };
- files.push({ file, type: 'chat' });
- }
- });
- setUserFiles(files);
- });
-
- return (
- <Dropdown open={fileSelectorOpen()} onOpenChange={setFileSelectorOpen}>
- <Dropdown.Trigger
- variant="ghost"
- size="icon-sm"
- label="File"
- tabIndex={-1}
- >
- <FileText />
- </Dropdown.Trigger>
- <Dropdown.Content onCloseAutoFocus={focusCanvas}>
- <Dropdown.Group>
- <OldMenu width="lg">
- <div class="w-full p-1">
- <Show
- when={userFiles().length > 0}
- fallback={
- <div class="p-4 text-center text-sm">No files found.</div>
- }
- >
- <VList
- data={userFiles()}
- style={{ height: '320px', 'overflow-x': 'hidden' }}
- bufferSize={10 * 40}
- >
- {(item) => (
- <Dropdown.Item>
- <ItemOption file={item.file} type={item.type} />
- </Dropdown.Item>
- )}
- </VList>
- </Show>
- </div>
- </OldMenu>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/FloatingMenu.tsx b/apps/web/src/features/block-canvas/component/FloatingMenu.tsx
deleted file mode 100644
index d50fc6e2d9..0000000000
--- a/apps/web/src/features/block-canvas/component/FloatingMenu.tsx
+++ /dev/null
@@ -1,838 +0,0 @@
-import { useAlign } from '@block-canvas/signal/align';
-import { clamp } from '@block-canvas/util/math';
-import { vec2 } from '@block-canvas/util/vector2';
-import {
- type DropdownPreset,
- SlidableNumberInput,
- type SlidableNumberInputProps,
-} from '@core/component/SlidableNumberInput';
-import { themeColors, themeStyles } from '@core/component/Themes';
-import { isMobileWidth } from '@core/mobile/mobileWidth';
-import AlignBottom from '@phosphor-icons/core/regular/align-bottom.svg?component-solid';
-import AlignCenterHorizontal from '@phosphor-icons/core/regular/align-center-horizontal.svg?component-solid';
-import AlignCenterVertical from '@phosphor-icons/core/regular/align-center-vertical.svg?component-solid';
-import AlignLeft from '@phosphor-icons/core/regular/align-left.svg?component-solid';
-import AlignRight from '@phosphor-icons/core/regular/align-right.svg?component-solid';
-import AlignTop from '@phosphor-icons/core/regular/align-top.svg?component-solid';
-import Reverse from '@phosphor-icons/core/regular/arrows-horizontal.svg?component-solid';
-import CornersOut from '@phosphor-icons/core/regular/corners-out.svg?component-solid';
-import TextAa from '@phosphor-icons/core/regular/text-aa.svg?component-solid';
-import TrashSimple from '@phosphor-icons/core/regular/trash-simple.svg?component-solid';
-import { Button, cn, Tooltip } from '@ui';
-import type { JSX } from 'solid-js';
-import {
- batch,
- type Component,
- createMemo,
- For,
- onMount,
- Show,
- untrack,
-} from 'solid-js';
-import { unwrap } from 'solid-js/store';
-import { Dynamic } from 'solid-js/web';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { CanvasEntityStyle, NodeType } from '../model/CanvasModel';
-import { useCachedStyle } from '../signal/cachedStyle';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useSelection } from '../signal/selection';
-import { useToolManager } from '../signal/toolManager';
-import { useCanvasEdges, useCanvasNodes } from '../store/canvasData';
-import { allStyleProps, getTailwindColor } from '../util/style';
-import { handleDelete } from './CanvasController';
-import {
- ArrowCaret,
- ArrowCircle,
- ArrowCircleSmall,
- ArrowLine,
- ArrowTriangle,
- ConnectorBezier,
- ConnectorStepped,
- ConnectorStraight,
-} from './icons-custom/ArrowIcons';
-import { LineWeight } from './icons-custom/LineWeight';
-import { Swatch } from './Swatch';
-
-type CanvasEntity = NodeType | 'edge';
-
-function CanvasSlidableNumberInput(props: SlidableNumberInputProps) {
- const [, setActiveTextEditor] =
- useCanvasDocument().state.signals.activeTextEditor;
- return (
- <SlidableNumberInput {...props} onEditingChange={setActiveTextEditor} />
- );
-}
-
-type ColorOption = {
- base: string;
- fill: string;
- stroke: string;
-};
-
-function createColorOption(base: string, fillTint: number, strokeTint: number) {
- return {
- base,
- fill: `${base}-${fillTint}`,
- stroke: `${base}-${strokeTint}`,
- };
-}
-
-const colorOptions: ColorOption[] = [
- createColorOption('gray', 50, 700),
- createColorOption('neutral', 200, 400),
- createColorOption('red', 200, 600),
- createColorOption('orange', 200, 600),
- createColorOption('amber', 200, 600),
- createColorOption('green', 200, 600),
- createColorOption('blue', 200, 600),
-];
-
-const mobileColorOptions: ColorOption[] = [
- createColorOption('gray', 50, 700),
- createColorOption('neutral', 200, 400),
- createColorOption('red', 200, 600),
- createColorOption('amber', 200, 600),
- createColorOption('green', 200, 600),
- createColorOption('blue', 200, 600),
-];
-
-const ValidPropsByEntity: Partial<Record<CanvasEntity, Set<string>>> = {
- shape: new Set([
- 'fillColor',
- 'strokeColor',
- 'strokeWidth',
- 'cornerRadius',
- 'opacity',
- 'textSize',
- ]),
- pencil: new Set(['strokeColor', 'strokeWidth', 'opacity']),
- edge: new Set(['strokeColor', 'strokeWidth', 'opacity']),
- text: new Set(['textSize', 'strokeColor']),
- image: new Set(['strokeColor', 'strokeWidth', 'opacity', 'cornerRadius']),
- entitymention: new Set([]),
-};
-
-export function SwatchColorPicker(props: {
- fillColor: string | undefined;
- strokeColor: string | undefined;
- onClick: (colorOption: ColorOption) => void;
-}) {
- // Create a memo that determines the currently selected variant
- const selectedVariant = createMemo(() => {
- if (!props.fillColor || !props.strokeColor) return undefined;
- return props.fillColor;
- });
-
- // SCUFFED THEMING TODO: we need to handle canvas color selection? this checks if we are in a darkish or lightish theme but that is janky?
- return (
- <div
- class={cn('flex flex-wrap gap-1', isMobileWidth() ? 'w-20' : 'w-full')}
- >
- <For each={isMobileWidth() ? mobileColorOptions : colorOptions}>
- {(opt) => (
- <Swatch
- option={opt}
- isSelected={selectedVariant() === getTailwindColor(opt.fill)}
- onClick={props.onClick.bind(null, opt)}
- />
- )}
- </For>
- </div>
- );
-}
-
-function GroupLabel(props: { label: string }) {
- return (
- <div class="flex flex-row items-center mb-1">
- <div class="text-[0.67rem] opacity-75">{props.label}</div>
- </div>
- );
-}
-
-function Divider() {
- return (
- <Show when={!isMobileWidth()}>
- <div
- class="h-px w-full my-2 -mx-2 bg-edge"
- style={{ width: 'calc(100% + 1rem)' }}
- />
- </Show>
- );
-}
-
-function AlignmentOption(props: {
- alignment: number;
- icon: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
- onClick: (alignemnt: number) => void;
-}) {
- return (
- <div
- class="size-6 mx-1 flex justify-center items-center rounded-sm hover:bg-hover hover-transition-bg"
- onClick={() => {
- props.onClick(props.alignment);
- }}
- >
- <Dynamic
- component={props.icon}
- style={{
- 'overflow-clip-margin': 'content-box',
- }}
- width={20}
- height={20}
- />
- </div>
- );
-}
-
-function ReverseEdgeButton() {
- const { updateEdge, ...edges } = useCanvasEdges();
- const { selectedEdges } = useSelection();
-
- return (
- <Tooltip label="Reverse connection">
- <button
- class={cn(
- themeColors['base'],
- themeStyles['base'],
- 'size-6 flex border-0 rounded-md justify-center items-center'
- )}
- onClick={() => {
- edges.batchUpdate(
- () => {
- for (const edge of untrack(selectedEdges)) {
- const { from: oldFrom, to: oldTo } = unwrap(edge);
- updateEdge(edge.id, {
- to: oldFrom,
- from: oldTo,
- });
- }
- },
- { autosave: true }
- );
- }}
- >
- <div class="flex justify-start items-center">
- <Dynamic
- component={Reverse}
- style={{
- 'overflow-clip-margin': 'content-box',
- }}
- width={15}
- height={15}
- />
- </div>
- </button>
- </Tooltip>
- );
-}
-
-function MobileDeleteButton() {
- const toolManager = useToolManager();
- const selection = useSelection();
- const deleteSelection = handleDelete();
-
- let openMenu!: HTMLDivElement;
-
- onMount(() => {
- toolManager.ignoreMouseEvents(openMenu);
- });
-
- return (
- <Show when={selection.active() && isMobileWidth()}>
- <div class="max-h-12 flex p-2 bg-surface cursor-auto justify-center items-center rounded border border-edge shadow-md">
- <Button
- variant="ghost"
- size="icon-md"
- onClick={deleteSelection}
- class="text-failure"
- >
- <TrashSimple />
- </Button>
- </div>
- </Show>
- );
-}
-
-const strokeWidthPresets: DropdownPreset[] = [
- {
- value: '0',
- displayName: 'None',
- },
- {
- value: '1',
- displayName: 'Thin',
- },
- {
- value: '2',
- displayName: 'Regular',
- },
- {
- value: '4',
- displayName: 'Thick',
- },
- {
- value: '8',
- displayName: 'Extra thick',
- },
-];
-
-const cornerRadiusPresets: DropdownPreset[] = [
- {
- value: '0',
- displayName: 'None',
- },
- {
- value: '4',
- displayName: 'Extra Small',
- },
- {
- value: '8',
- displayName: 'Small',
- },
- {
- value: '16',
- displayName: 'Medium',
- },
- {
- value: '32',
- displayName: 'Larrge',
- },
- {
- value: '64',
- displayName: 'Extra Large',
- },
- {
- value: '100',
- displayName: 'Full',
- },
-];
-
-const textSizePresets: DropdownPreset[] = [
- {
- value: '12',
- displayName: 'Extra Small',
- },
- {
- value: '14',
- displayName: 'Small',
- },
- {
- value: '16',
- displayName: 'Base',
- },
- {
- value: '24',
- displayName: 'Large',
- },
- {
- value: '36',
- displayName: 'Extra Large',
- },
-];
-
-const arrowStylePresets: DropdownPreset[] = [
- {
- value: '0',
- displayName: 'Line',
- icon: ArrowLine,
- },
- {
- value: '1',
- displayName: 'Arrow',
- icon: ArrowCaret,
- },
- {
- value: '2',
- displayName: 'Arrow Filled',
- icon: ArrowTriangle,
- },
- {
- value: '3',
- displayName: 'Circle',
- icon: ArrowCircle,
- },
- {
- value: '4',
- displayName: 'Dot',
- icon: ArrowCircleSmall,
- },
-];
-
-const connectionStylePresets: DropdownPreset[] = [
- {
- value: '0',
- displayName: 'Straight',
- icon: ConnectorStraight,
- },
- {
- value: '1',
- displayName: 'Bent',
- icon: ConnectorStepped,
- },
- {
- value: '2',
- displayName: 'Curved',
- icon: ConnectorBezier,
- },
-];
-
-export function FloatingMenu() {
- const { selectedNodes, selectedEdges, extractSharedStyles, ...selection } =
- useSelection();
- const { updateNode, ...nodes } = useCanvasNodes();
- const { updateEdge, ...edges } = useCanvasEdges();
- const history = useCanvasHistory();
- const cachedStyle = useCachedStyle();
- const toolManager = useToolManager();
-
- let ref!: HTMLDivElement;
-
- onMount(() => {
- toolManager.ignoreMouseEvents(ref);
- });
-
- const sharedStyles = createMemo(() => {
- if (!selection.active())
- return new Map(Object.entries(cachedStyle.getStyle()));
-
- return extractSharedStyles();
- });
-
- const entityTypesInSelection = createMemo(() => {
- const types = new Set<CanvasEntity>();
-
- const activeTool = toolManager.activeTool();
- types.add(activeTool.toLowerCase() as CanvasEntity); // Convert to lowercase
-
- for (const node of selectedNodes()) {
- types.add(node.type);
- }
- if (selectedEdges().length > 0) types.add('edge');
- return types;
- });
-
- const validMenus = createMemo(() => {
- let menus = new Set(allStyleProps);
- for (const entity of entityTypesInSelection()) {
- if (entity in ValidPropsByEntity) {
- menus = menus.intersection(ValidPropsByEntity[entity]!);
- }
- }
- return menus;
- });
-
- function applyStyle(style: keyof CanvasEntityStyle, value: any) {
- batch(() => {
- nodes.batchUpdate(
- () => {
- for (const node of untrack(selectedNodes)) {
- const nodeStyle = { ...(unwrap(node).style ?? {}) };
- nodeStyle[style] = value;
- updateNode(node.id, { style: nodeStyle });
- }
- },
- { autosave: true }
- );
- edges.batchUpdate(
- () => {
- for (const edge of untrack(selectedEdges)) {
- const edgeStyle = { ...(unwrap(edge).style ?? {}) };
- edgeStyle[style] = value;
- updateEdge(edge.id, { style: edgeStyle });
- }
- },
- { autosave: true }
- );
- });
- }
-
- function applyStyleWithHistory(style: keyof CanvasEntityStyle, value: any) {
- cachedStyle.setProp(style, value);
- if (!selection.active()) return;
- history.open();
- applyStyle(style, value);
- history.close();
- }
-
- function applyUnfiedColor(colorOption: ColorOption) {
- const { stroke, fill } = colorOption;
- const strokeColor = getTailwindColor(stroke);
- const fillColor = getTailwindColor(fill);
- cachedStyle.setProp('strokeColor', strokeColor);
- cachedStyle.setProp('fillColor', fillColor);
- if (!selection.active()) return;
- history.open();
- batch(() => {
- if (fill) applyStyle('fillColor', fillColor);
- if (stroke) applyStyle('strokeColor', strokeColor);
- applyStyle('importedColor', false);
- });
- history.close();
- }
-
- //if the only thing in the menu is alignment
- const alignmentOnly = createMemo(() => {
- const nodes = selectedNodes();
- const edges = selectedEdges();
- const nodesLength = nodes.length;
- if (
- nodesLength > 1 &&
- nodes.some((node) => node.type === 'entitymention') &&
- edges.length < 1
- ) {
- return true;
- }
- return false;
- });
-
- const { align } = useAlign();
-
- return (
- <div
- class={cn(
- 'absolute flex flex-row top-4 z-5 cursor-auto',
- // Full-frame mobile/tablet: clear the floating split chrome at the top.
- 'touch:top-[calc(var(--mobile-content-inset-top,0)+0.5rem)]',
- !isMobileWidth() && 'right-4'
- )}
- >
- <div
- class={cn(
- 'flex bg-surface rounded-lg border border-edge shadow-lg',
- isMobileWidth() ? 'flex-row p-2 mr-2' : 'flex-col w-54 p-3',
- selectedNodes().length + selectedEdges().length <= 1 &&
- validMenus().size === 0 &&
- 'hidden'
- )}
- ref={ref}
- oncontextmenu={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- >
- <Show when={validMenus().has('strokeColor')}>
- <div
- class={cn(
- 'flex justify-center items-center',
- isMobileWidth() &&
- (validMenus().has('strokeWidth') ||
- validMenus().has('textSize') ||
- selectedNodes().length + selectedEdges().length > 1) &&
- 'mr-4'
- )}
- >
- <SwatchColorPicker
- onClick={(color) => applyUnfiedColor(color)}
- fillColor={sharedStyles().get('fillColor')}
- strokeColor={sharedStyles().get('strokeColor')}
- />
- </div>
- </Show>
-
- <div class="flex w-full grow flex-col">
- <Show
- when={
- !isMobileWidth() &&
- (validMenus().has('endStyle') || selectedEdges().length > 0)
- }
- >
- <Show when={validMenus().has('strokeColor')}>
- <Divider />
- </Show>
- <div class="flex flex-row h-10 justify-between items-center">
- <GroupLabel label="Line Styles" />
- <ReverseEdgeButton />
- </div>
- <div class="flex flex-row justify-between">
- <CanvasSlidableNumberInput
- icon={
- sharedStyles().get('fromEndStyle')
- ? arrowStylePresets[sharedStyles().get('fromEndStyle')]
- .icon!
- : arrowStylePresets[0].icon!
- }
- inputChanged={(newValue: string) => {
- const parsedValue = Number.parseInt(newValue);
- applyStyleWithHistory('fromEndStyle', parsedValue);
- }}
- currentValue={
- sharedStyles().get('fromEndStyle')
- ? arrowStylePresets[sharedStyles().get('fromEndStyle')]
- .value!
- : arrowStylePresets[0].value!
- }
- width="sm"
- presets={arrowStylePresets}
- showPresets={true}
- fullIcon={true}
- tooltip="Line start"
- />
- <CanvasSlidableNumberInput
- icon={
- sharedStyles().get('connectionStyle')
- ? connectionStylePresets[
- sharedStyles().get('connectionStyle')
- ].icon!
- : connectionStylePresets[0].icon!
- }
- inputChanged={(newValue: string) => {
- const parsedValue = Number.parseInt(newValue);
- applyStyleWithHistory('connectionStyle', parsedValue);
- }}
- currentValue={
- sharedStyles().get('connectionStyle')
- ? connectionStylePresets[
- sharedStyles().get('connectionStyle')
- ].value!
- : connectionStylePresets[0].value!
- }
- width="sm"
- presets={connectionStylePresets}
- showPresets={true}
- hideValue={true}
- fullIcon={true}
- tooltip="Connection type"
- />
- <CanvasSlidableNumberInput
- icon={
- sharedStyles().get('toEndStyle')
- ? arrowStylePresets[sharedStyles().get('toEndStyle')].icon!
- : arrowStylePresets[0].icon!
- }
- inputChanged={(newValue: string) => {
- const parsedValue = Number.parseInt(newValue);
- applyStyleWithHistory('toEndStyle', parsedValue);
- }}
- currentValue={
- sharedStyles().get('toEndStyle')
- ? arrowStylePresets[sharedStyles().get('toEndStyle')].value!
- : arrowStylePresets[0].value!
- }
- width="sm"
- presets={arrowStylePresets}
- showPresets={true}
- hideValue={true}
- fullIcon={true}
- flip={true}
- tooltip="Line end"
- />
- </div>
- </Show>
- <Show when={selectedNodes().length + selectedEdges().length > 1}>
- <Show when={!alignmentOnly()}>
- <Divider />
- </Show>
- <GroupLabel label="Align objects" />
- <div class="flex flex-wrap justify-center">
- <AlignmentOption
- alignment={0}
- icon={AlignLeft}
- onClick={(alignment) => {
- align(alignment, true);
- }}
- />
- <AlignmentOption
- alignment={1}
- icon={AlignCenterHorizontal}
- onClick={(alignment) => {
- align(alignment, true);
- }}
- />
- <AlignmentOption
- alignment={2}
- icon={AlignRight}
- onClick={(alignment) => {
- align(alignment, true);
- }}
- />
- <AlignmentOption
- alignment={3}
- icon={AlignTop}
- onClick={(alignment) => {
- align(alignment, true);
- }}
- />
- <AlignmentOption
- alignment={4}
- icon={AlignCenterVertical}
- onClick={(alignment) => {
- align(alignment, true);
- }}
- />
- <AlignmentOption
- alignment={5}
- icon={AlignBottom}
- onClick={(alignment) => {
- align(alignment, true);
- }}
- />
- </div>
- </Show>
- <Show
- when={
- validMenus().has('strokeWidth') ||
- validMenus().has('cornerRadius')
- }
- >
- <Divider />
- </Show>
- <div
- class={cn(
- 'flex',
- isMobileWidth() ? 'flex-row' : 'flex-col',
- isMobileWidth() &&
- selectedNodes().length + selectedEdges().length > 1 &&
- 'hidden'
- )}
- >
- <div class="flex flex-row">
- <Show when={validMenus().has('strokeWidth')}>
- <div class={cn(!isMobileWidth() && 'mr-3.5')}>
- <CanvasSlidableNumberInput
- label={'Line weight'}
- labelPosition="top"
- icon={LineWeight}
- inputChanged={(newValue: string) => {
- const parsedValue = Number.parseInt(newValue);
- if (Number.isNaN(parsedValue)) return;
- applyStyleWithHistory(
- 'strokeWidth',
- clamp(parsedValue, 0, 8)
- );
- }}
- onSlideStart={() => {
- if (!selection.active()) return;
- history.open();
- }}
- onSlidePreview={(newValue) => {
- if (!selection.active()) return;
- if (!newValue) return;
- applyStyle(
- 'strokeWidth',
- clamp(Number.parseInt(newValue), 0, 8)
- );
- }}
- onSlideEnd={(newValue) => {
- if (!selection.active()) return;
- if (!newValue) return;
- applyStyle(
- 'strokeWidth',
- clamp(Number.parseInt(newValue), 0, 8)
- );
- history.close();
- }}
- currentValue={sharedStyles().get('strokeWidth') ?? '-'}
- range={vec2(0, 8)}
- width={
- !isMobileWidth() && !validMenus().has('cornerRadius')
- ? 'lg'
- : 'sm'
- }
- presets={strokeWidthPresets}
- showPresets={true}
- isSlidable={true}
- />
- </div>
- </Show>
- <Show when={!isMobileWidth() && validMenus().has('cornerRadius')}>
- <CanvasSlidableNumberInput
- label={'Corner rounding'}
- labelPosition="top"
- icon={CornersOut}
- inputChanged={(newValue: string) => {
- const parsedValue = Number.parseInt(newValue);
- if (Number.isNaN(parsedValue)) return;
- applyStyleWithHistory(
- 'cornerRadius',
- clamp(parsedValue, 0, 100)
- );
- }}
- onSlideStart={() => {
- if (!selection.active()) return;
- history.open();
- }}
- onSlidePreview={(newValue) => {
- if (!selection.active()) return;
- if (!newValue) return;
- applyStyle(
- 'cornerRadius',
- clamp(Number.parseInt(newValue), 0, 100)
- );
- }}
- onSlideEnd={(newValue) => {
- if (!selection.active()) return;
- if (!newValue) return;
- applyStyle(
- 'cornerRadius',
- clamp(Number.parseInt(newValue), 0, 100)
- );
- history.close();
- }}
- currentValue={sharedStyles().get('cornerRadius') ?? '-'}
- range={vec2(0, 100)}
- width="sm"
- presets={cornerRadiusPresets}
- showPresets={true}
- isSlidable={true}
- />
- </Show>
- </div>
- <Show when={validMenus().has('textSize')}>
- <Divider />
- <div
- class={cn(
- isMobileWidth() &&
- (validMenus().has('strokeWidth') ||
- validMenus().has('cornerRadius')) &&
- 'ml-2'
- )}
- >
- <CanvasSlidableNumberInput
- label={'Font size'}
- labelPosition="top"
- icon={TextAa}
- onSlideStart={() => {
- if (!selection.active()) return;
- history.open();
- }}
- inputChanged={(newValue: string) => {
- const parsedValue = Number.parseInt(newValue);
- if (Number.isNaN(parsedValue)) return;
- applyStyleWithHistory(
- 'textSize',
- clamp(parsedValue, 5, 72)
- );
- }}
- onSlidePreview={(newValue) => {
- if (!selection.active()) return;
- if (!newValue) return;
- applyStyle(
- 'textSize',
- clamp(Number.parseInt(newValue), 5, 72)
- );
- }}
- onSlideEnd={(newValue) => {
- if (!selection.active()) return;
- if (!newValue) return;
- applyStyle(
- 'textSize',
- clamp(Number.parseInt(newValue), 5, 72)
- );
- history.close();
- }}
- currentValue={sharedStyles().get('textSize') ?? '-'}
- range={vec2(5, 72)}
- width={isMobileWidth() ? 'sm' : 'lg'}
- presets={textSizePresets}
- showPresets={true}
- isSlidable={true}
- />
- </div>
- </Show>
- </div>
- </div>
- </div>
- <MobileDeleteButton />
- </div>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/LayerContext.tsx b/apps/web/src/features/block-canvas/component/LayerContext.tsx
deleted file mode 100644
index 6cfe45e943..0000000000
--- a/apps/web/src/features/block-canvas/component/LayerContext.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import { createContext } from 'solid-js';
-
-export const LayerContext = createContext<
- () => {
- base: HTMLDivElement | undefined;
- selection: HTMLDivElement | undefined;
- lineSelection: HTMLDivElement | undefined;
- }
->(() => ({
- base: undefined,
- selection: undefined,
- lineSelection: undefined,
-}));
diff --git a/apps/web/src/features/block-canvas/component/MediaSelector.tsx b/apps/web/src/features/block-canvas/component/MediaSelector.tsx
deleted file mode 100644
index 2d17202572..0000000000
--- a/apps/web/src/features/block-canvas/component/MediaSelector.tsx
+++ /dev/null
@@ -1,221 +0,0 @@
-import { useCanvasFileDrop } from '@block-canvas/signal/fileDrop';
-import { useRenderState } from '@block-canvas/store/RenderState';
-import { vec2 } from '@block-canvas/util/vector2';
-import { EntityIcon } from '@core/component/EntityIcon';
-import { FileDropOverlay } from '@core/component/FileDropOverlay';
-import {
- blockAcceptsFileExtension,
- blockNameToFileExtensions,
- blockNameToMimeTypes,
-} from '@core/constant/allBlocks';
-import {
- ENABLE_CANVAS_HEIC,
- ENABLE_CANVAS_VIDEO,
-} from '@core/constant/featureFlags';
-import { fileDrop } from '@core/directive/fileDrop';
-import { fileSelector } from '@core/directive/fileSelector';
-import { HEIC_EXTENSIONS, HEIC_MIME_TYPES } from '@core/heic/constants';
-import UploadSimple from '@phosphor-icons/core/bold/upload-simple-bold.svg?component-solid';
-import Image from '@phosphor-icons/core/regular/image.svg?component-solid';
-//import { copiedFile } from "@core/state/clipboard";
-import { useHistoryQuery } from '@queries/history/history';
-import { Dropdown } from '@ui';
-import { createMemo, createSignal, Show } from 'solid-js';
-import { VList } from 'virtua/solid';
-import { Tools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import { useSelect } from '../operation/select';
-import { useToolManager } from '../signal/toolManager';
-
-false && fileSelector;
-false && fileDrop;
-
-type MediaType = 'image' | 'video';
-
-type MediaItem = {
- fileName: string;
- fileType: MediaType;
- id: string;
-};
-
-function ItemOption(props: { media: MediaItem }) {
- const [, setSelectedImage] = useCanvasDocument().state.signals.selectedImage;
- const toolManager = useToolManager();
- const select = useSelect();
-
- const selectItem = (e: MouseEvent | TouchEvent) => {
- e.stopPropagation();
- e.preventDefault();
- select.abort();
- setSelectedImage({
- type: props.media.fileType,
- id: props.media.id,
- });
- toolManager.setSelectedTool(Tools.Image);
- };
-
- return (
- <div
- class="w-72 flex flex-row rounded hover:bg-hover hover-transition-bg p-2 text-sm select-none items-center"
- onmousedown={selectItem}
- ontouchstart={selectItem}
- >
- <EntityIcon targetType={props.media.fileType} size="sm" />
- <div class="line-clamp-1 overflow-hidden text-ellipsis ml-2">
- {props.media.fileName}
- </div>
- </div>
- );
-}
-
-export function MediaSelector() {
- const mediaTypes: MediaType[] = ENABLE_CANVAS_VIDEO
- ? ['image', 'video']
- : ['image'];
- const historyQuery = useHistoryQuery();
- //const copiedFileID = copiedFile();
- const select = useSelect();
- const { handleFileDrop } = useCanvasFileDrop();
- const [isDragging, setIsDragging] =
- useCanvasDocument().state.signals.canvasDragging;
- const { viewBox } = useRenderState();
- const centerVec = createMemo(() => {
- return vec2(viewBox().x + viewBox().w / 2, viewBox().y + viewBox().h / 2);
- });
- const { focusCanvas } = useToolManager();
-
- const [imageSelectorOpen, setImageSelectorOpen] = createSignal(false);
-
- const imageExtensions = blockNameToFileExtensions.image;
- const imageMimeTypes = blockNameToMimeTypes.image;
- const videoExtensions = blockNameToFileExtensions.video;
- const videoMimeTypes = blockNameToMimeTypes.video;
-
- const canvasImageExtensions = ENABLE_CANVAS_HEIC
- ? [...imageExtensions, ...HEIC_EXTENSIONS]
- : imageExtensions;
- const canvasImageMimeTypes = ENABLE_CANVAS_HEIC
- ? [...imageMimeTypes, ...HEIC_MIME_TYPES]
- : imageMimeTypes;
-
- const acceptedMimeTypes = ENABLE_CANVAS_VIDEO
- ? [...canvasImageMimeTypes, ...videoMimeTypes]
- : canvasImageMimeTypes;
- const acceptedFileExtensions = ENABLE_CANVAS_VIDEO
- ? [...canvasImageExtensions, ...videoExtensions]
- : canvasImageExtensions;
-
- const userMediaFiles = createMemo(() => {
- const mediaFiles: MediaItem[] = [];
- for (const item of historyQuery.data ?? []) {
- for (const mediaType of mediaTypes) {
- if (
- item.type === 'document' &&
- item.fileType &&
- blockAcceptsFileExtension(mediaType, item.fileType)
- ) {
- mediaFiles.push({
- fileName: item.name,
- fileType: mediaType,
- id: item.id,
- });
- }
- }
- }
-
- return mediaFiles;
- });
-
- return (
- <Dropdown open={imageSelectorOpen()} onOpenChange={setImageSelectorOpen}>
- <Dropdown.Trigger
- variant="ghost"
- size="icon-sm"
- label="Media"
- tabIndex={-1}
- >
- <Image />
- </Dropdown.Trigger>
- <Dropdown.Content onCloseAutoFocus={focusCanvas}>
- <Dropdown.Group>
- <div
- use:fileDrop={{
- acceptedMimeTypes: acceptedMimeTypes,
- acceptedFileExtensions: acceptedFileExtensions,
- onDragStart: () => setIsDragging(true),
- onDragEnd: () => setIsDragging(false),
- onDrop: (files) => {
- handleFileDrop(files, centerVec());
- setImageSelectorOpen(false);
- },
- }}
- class="flex flex-col gap-1"
- >
- <Show when={isDragging()}>
- <FileDropOverlay valid={true}>
- Drop any file here to add it to your canvas
- </FileDropOverlay>
- </Show>
- <Dropdown.Item closeOnSelect={false}>
- <div
- class="w-72 flex flex-row select-none items-center gap-1"
- onmousedown={(e) => {
- e.stopPropagation();
- e.preventDefault();
- select.abort();
- }}
- ontouchstart={(e) => {
- e.stopPropagation();
- e.preventDefault();
- select.abort();
- }}
- >
- <div
- class="w-full hidden sm:flex p-2 mb-1 bg-edge hover:bg-accent/15 hover-transition-bg transition-colors items-center justify-center gap-2"
- use:fileSelector={{
- acceptedFileExtensions: acceptedFileExtensions,
- acceptedMimeTypes: acceptedMimeTypes,
- onSelect: (files: File[]) => {
- handleFileDrop(files, centerVec());
- setImageSelectorOpen(false);
- },
- }}
- >
- <UploadSimple class="size-3.5 shrink-0 text-accent" />
- <span class="text-sm font-medium text-accent">
- Upload File
- </span>
- </div>
- </div>
- </Dropdown.Item>
- <div class="w-full">
- <Show
- when={userMediaFiles().length > 0}
- fallback={
- <div class="p-4 text-sm text-center">No media found.</div>
- }
- >
- <VList
- data={userMediaFiles()}
- style={{ height: '256px' }}
- bufferSize={500}
- >
- {(media) => (
- <Dropdown.Item closeOnSelect={true} class="w-full">
- <ItemOption media={media} />
- </Dropdown.Item>
- )}
- </VList>
- </Show>
- {/* <Show when={copiedFile()}>
- <DropdownMenu.Item>
- <ItemOption image={{fileName:"Insert from clipboard", id:copiedFile()!}} />
- </DropdownMenu.Item>
- </Show> */}
- </div>
- </div>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/PanWidget.tsx b/apps/web/src/features/block-canvas/component/PanWidget.tsx
deleted file mode 100644
index 707dc15b92..0000000000
--- a/apps/web/src/features/block-canvas/component/PanWidget.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { Tooltip } from '@ui';
-import { onMount } from 'solid-js';
-import { useToolManager } from '../signal/toolManager';
-import { useRenderState } from '../store/RenderState';
-
-export function PanWidget() {
- let widgetRef!: HTMLDivElement;
- const toolManager = useToolManager();
- const { currentPosition, pan } = useRenderState();
-
- onMount(() => {
- toolManager.ignoreMouseEvents(widgetRef);
- });
-
- return (
- <div class="cursor-auto absolute bottom-4 right-4 flex flex-row items-center h-10">
- <div class="rounded-xl gap-1 p-2 min-w-24 text-center" ref={widgetRef}>
- <Tooltip placement="top" label="Reset view">
- <div
- class="text-ink-muted w-full select-none"
- on:mousedown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- pan(-currentPosition().x, -currentPosition().y);
- }}
- on:touchstart={(e) => {
- e.preventDefault();
- e.stopPropagation();
- pan(-currentPosition().x, -currentPosition().y);
- }}
- >
- {'(' +
- Math.round(-currentPosition().x) +
- ', ' +
- Math.round(currentPosition().y) +
- ')'}
- </div>
- </Tooltip>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/SelectionBox.tsx b/apps/web/src/features/block-canvas/component/SelectionBox.tsx
deleted file mode 100644
index 53ffa2ec70..0000000000
--- a/apps/web/src/features/block-canvas/component/SelectionBox.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { createMemo, Show } from 'solid-js';
-import type { Rectangle } from '../util/rectangle';
-
-export function SelectionBox(props: { rect?: Rectangle }) {
- // const currentScale = useRenderState().currentScale;
-
- const show = createMemo(() => {
- if (!props.rect) return false;
- return props.rect.width > 0 && props.rect.height > 0;
- });
-
- return (
- <Show when={show()}>
- <div class="absolute bg-edge" style={props.rect!.toCssRect()}></div>
- </Show>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/SelectionRenderer.tsx b/apps/web/src/features/block-canvas/component/SelectionRenderer.tsx
deleted file mode 100644
index d7769eefc0..0000000000
--- a/apps/web/src/features/block-canvas/component/SelectionRenderer.tsx
+++ /dev/null
@@ -1,236 +0,0 @@
-import { createCallback } from '@solid-primitives/rootless';
-import { createMemo, Show } from 'solid-js';
-import {
- type Corner,
- Corners,
- type Edge,
- Edges,
- HANDLE_SIZE,
- SELECTION_PADDING,
- Tools,
-} from '../constants';
-import { useMove } from '../operation/move';
-import { useRescale } from '../operation/rescale';
-import { useSelect } from '../operation/select';
-import { useSelection } from '../signal/selection';
-import { useToolManager } from '../signal/toolManager';
-import { useRenderState } from '../store/RenderState';
-import { type Rectangle, rect } from '../util/rectangle';
-import { vec2 } from '../util/vector2';
-
-function cornerToPosition(corner: Corner, size: number) {
- const halfSize = size / 2;
- switch (corner) {
- case Corners.TopLeft:
- return {
- top: -halfSize + 'px',
- left: -halfSize + 'px',
- };
- case Corners.TopRight:
- return {
- top: -halfSize + 'px',
- right: -halfSize + 'px',
- };
- case Corners.BottomRight:
- return {
- bottom: -halfSize + 'px',
- right: -halfSize + 'px',
- };
- case Corners.BottomLeft:
- return {
- bottom: -halfSize + 'px',
- left: -halfSize + 'px',
- };
- }
-}
-
-function cornerToCursor(corner: Corner) {
- const { activeTool } = useToolManager();
- if (activeTool() === Tools.Grab) return 'grab';
- switch (corner) {
- case Corners.TopLeft:
- return 'nwse-resize';
- case Corners.TopRight:
- return 'nesw-resize';
- case Corners.BottomRight:
- return 'nwse-resize';
- case Corners.BottomLeft:
- return 'nesw-resize';
- }
-}
-
-function CornerHandle(props: {
- corner: Corner;
- size: number;
- scaleFactor: number;
-}) {
- const safeSize = createMemo(() => {
- return Math.round(Math.max(props.size * props.scaleFactor, 2));
- });
- const position = createMemo(() => cornerToPosition(props.corner, safeSize()));
- const rescale = useRescale();
- const { setSelectedTool } = useToolManager();
- const move = useMove();
- const select = useSelect();
- return (
- <div
- class="absolute border-accent bg-surface"
- style={{
- cursor: cornerToCursor(props.corner),
- width: safeSize() + 'px',
- height: safeSize() + 'px',
- ...position(),
- 'border-width': 1 * props.scaleFactor + 'px',
- 'pointer-events': 'all',
- }}
- onPointerDown={createCallback((e: PointerEvent) => {
- move.abort();
- select.abort();
- setSelectedTool(Tools.Resize);
- rescale.start(e, props.corner);
- })}
- ></div>
- );
-}
-
-export function edgeToPosition(
- edge: Edge,
- size: number,
- scale: number,
- borderWidth: number
-) {
- const scaledSize = size * scale;
- const offset = size - scaledSize;
- switch (edge) {
- case Edges.Top:
- return {
- top: offset - (HANDLE_SIZE + borderWidth) + 'px',
- left: -borderWidth + 'px',
- width: '100%',
- height: scaledSize + 'px',
- };
- case Edges.Right:
- return {
- top: -borderWidth + 'px',
- right: offset - (HANDLE_SIZE - borderWidth) + 'px',
- width: scaledSize + 'px',
- height: '100%',
- };
- case Edges.Bottom:
- return {
- bottom: offset - (HANDLE_SIZE - borderWidth) + 'px',
- left: -borderWidth + 'px',
- width: '100%',
- height: scaledSize + 'px',
- };
- case Edges.Left:
- return {
- top: -borderWidth + 'px',
- left: offset - (HANDLE_SIZE + borderWidth) + 'px',
- width: scaledSize + 'px',
- height: '100%',
- };
- }
-}
-
-export function edgeToCursor(edge: Edge) {
- const { activeTool } = useToolManager();
- if (activeTool() === Tools.Grab) return 'grab';
-
- switch (edge) {
- case Edges.Top:
- return 'ns-resize';
- case Edges.Right:
- return 'ew-resize';
- case Edges.Bottom:
- return 'ns-resize';
- case Edges.Left:
- return 'ew-resize';
- }
-}
-
-function EdgeHandle(props: { edge: Edge; size: number; scaleFactor: number }) {
- const position = () =>
- edgeToPosition(props.edge, props.size, props.scaleFactor, 0);
- const { selectedTool, setSelectedTool } = useToolManager();
- const rescale = useRescale();
- const move = useMove();
- const select = useSelect();
-
- return (
- <div
- class="hover:bg-accent/20"
- style={{
- position: 'absolute',
- ...position(),
- cursor: edgeToCursor(props.edge),
- 'pointer-events': 'all',
- }}
- onPointerDown={createCallback((e: PointerEvent) => {
- if (selectedTool() === Tools.Select) {
- select.abort();
- move.abort();
- setSelectedTool(Tools.Resize);
- rescale.start(e, props.edge);
- }
- })}
- ></div>
- );
-}
-
-export function SelectionRenderer() {
- const { selectionBounds, selectedNodes, selectedEdges } = useSelection();
- const { currentScale } = useRenderState();
- const select = useSelect();
- const bounds = createMemo(() => selectionBounds());
- const show = createMemo(() => {
- const b = bounds();
- if (b === undefined) return false;
- if (b.width === 0 && b.height === 0) return false;
- if (selectedNodes().length === 0) {
- if (selectedEdges().length === 1) {
- return false;
- }
- }
- return (
- (selectedTool() === Tools.Select && !select.active()) ||
- selectedTool() === Tools.Resize ||
- selectedTool() === Tools.Move
- );
- });
-
- const { selectedTool } = useToolManager();
-
- const position = createMemo<Rectangle>(() => {
- return bounds() ?? rect(vec2(0, 0), vec2(0, 0));
- });
-
- const computedProps = createMemo(() => ({
- size: HANDLE_SIZE,
- scaleFactor: 1 / currentScale(),
- }));
-
- return (
- <Show when={show()}>
- <div
- class="absolute border-accent z-50 top-0 left-0"
- style={{
- width: position().width + 2 * SELECTION_PADDING + 'px',
- height: position().height + 2 * SELECTION_PADDING + 'px',
- transform: `translate(${position().x - SELECTION_PADDING}px, ${position().y - SELECTION_PADDING}px)`,
- 'border-width': 2 / currentScale() + 'px',
- 'pointer-events': 'none',
- }}
- >
- <EdgeHandle edge={Edges.Top} {...computedProps()} />
- <EdgeHandle edge={Edges.Right} {...computedProps()} />
- <EdgeHandle edge={Edges.Bottom} {...computedProps()} />
- <EdgeHandle edge={Edges.Left} {...computedProps()} />
- <CornerHandle corner={Corners.TopLeft} {...computedProps()} />
- <CornerHandle corner={Corners.TopRight} {...computedProps()} />
- <CornerHandle corner={Corners.BottomRight} {...computedProps()} />
- <CornerHandle corner={Corners.BottomLeft} {...computedProps()} />
- </div>
- </Show>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/Swatch.tsx b/apps/web/src/features/block-canvas/component/Swatch.tsx
deleted file mode 100644
index 9460e09851..0000000000
--- a/apps/web/src/features/block-canvas/component/Swatch.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { getTailwindColor } from '@block-canvas/util/style';
-import { cn } from '@ui';
-import { Show } from 'solid-js';
-
-type ColorOption = {
- base: string;
- fill: string;
- stroke: string;
-};
-
-const selectedStyling = 'bg-active ring-accent ring-2';
-
-export function Swatch(props: {
- option: ColorOption;
- isSelected: boolean;
- onClick: () => void;
-}) {
- const isTransparent = () => props.option.fill === 'transparent';
-
- const backgroundColor = () => {
- if (props.option.fill === 'transparent') return 'transparent';
- return getTailwindColor(props.option.fill);
- };
-
- const borderColor = () => {
- return getTailwindColor(props.option.stroke);
- };
-
- return (
- <div
- class={cn(
- 'size-6 flex justify-center items-center rounded-full hover:bg-hover hover-transition-bg hover:ring-2 hover:scale-115 transition-transform',
- props.isSelected ? selectedStyling : 'hover:ring-edge'
- )}
- classList={{
- 'z-user-highlight': props.isSelected,
- }}
- onClick={(e) => {
- e.stopPropagation();
- props.onClick();
- }}
- >
- <div
- class="rounded-full size-5 border-2"
- classList={{
- 'border-2! border-edge relative': props.option.fill === 'transparent',
- }}
- style={{
- 'background-color': backgroundColor(),
- 'border-color': borderColor(),
- }}
- >
- <Show when={isTransparent()}>
- <div class="absolute inset-0 flex items-center justify-center">
- <div class="w-full h-px bg-failure transform rotate-45" />
- </div>
- </Show>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/ToolBar.tsx b/apps/web/src/features/block-canvas/component/ToolBar.tsx
deleted file mode 100644
index 1b66138a4c..0000000000
--- a/apps/web/src/features/block-canvas/component/ToolBar.tsx
+++ /dev/null
@@ -1,300 +0,0 @@
-import {
- type EdgeConnectionStyle,
- EdgeConnectionStyles,
-} from '@block-canvas/model/CanvasModel';
-import { useCachedStyle } from '@block-canvas/signal/cachedStyle';
-import { useToolManager } from '@block-canvas/signal/toolManager';
-import { ScopedPortal } from '@core/component/ScopedPortal';
-import {
- ENABLE_CANVAS_FILES,
- ENABLE_CANVAS_IMAGES,
- ENABLE_CANVAS_TEXT,
-} from '@core/constant/featureFlags';
-import { registerHotkey } from '@core/hotkey/hotkeys';
-import { TOKENS } from '@core/hotkey/tokens';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import CaretDown from '@phosphor/caret-down.svg';
-import Cursor from '@phosphor/cursor.svg';
-import Hand from '@phosphor/hand.svg';
-import ZoomOut from '@phosphor/magnifying-glass-minus.svg';
-import ZoomIn from '@phosphor/magnifying-glass-plus.svg';
-import PencilSimple from '@phosphor/pencil-simple.svg';
-import Rectangle from '@phosphor/rectangle.svg';
-import Text from '@phosphor/text-t.svg';
-import { Button, ButtonGroup, Dropdown, Hotkey, Toolbar } from '@ui';
-import { createSignal, Show } from 'solid-js';
-import { Dynamic } from 'solid-js/web';
-import { Tools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import { FileSelector } from './FileSelector';
-import {
- ConnectorBezierArrows,
- ConnectorSteppedArrows,
- ConnectorStraightArrows,
-} from './icons-custom/ArrowIcons';
-import { MediaSelector } from './MediaSelector';
-
-const ConnectorTypeSubMenu = (props: {
- onSelect: (connectionStye: EdgeConnectionStyle) => void;
-}) => {
- const state = useCanvasDocument().state.signals;
- const [connectorTypeMenuTrigger, setConnectorTypeMenuTrigger] =
- state.connectorTypeMenuTrigger;
-
- return (
- <Dropdown
- placement="bottom"
- open={connectorTypeMenuTrigger()}
- onOpenChange={setConnectorTypeMenuTrigger}
- >
- <Dropdown.Trigger size="icon-sm" label="Connector options" tabIndex={-1}>
- <CaretDown class="size-3 text-ink-muted" />
- </Dropdown.Trigger>
- <Dropdown.Content>
- <Dropdown.Group>
- <Dropdown.Item
- onSelect={() => {
- props.onSelect('straight');
- }}
- >
- <ConnectorStraightArrows class="size-4 shrink-0" />
- <span class="flex-1 truncate">Connector</span>
- <Hotkey
- token={TOKENS.canvas.line.straight}
- class="text-ink-muted"
- showPlus
- />
- </Dropdown.Item>
- <Dropdown.Item
- onSelect={() => {
- props.onSelect('smooth');
- }}
- >
- <ConnectorBezierArrows class="size-4 shrink-0" />
- <span class="flex-1 truncate">Flow Connector</span>
- <Hotkey
- token={TOKENS.canvas.line.flow}
- class="text-ink-muted"
- showPlus
- />
- </Dropdown.Item>
- <Dropdown.Item
- onSelect={() => {
- props.onSelect('stepped');
- }}
- >
- <ConnectorSteppedArrows class="size-4 shrink-0" />
- <span class="flex-1 truncate">Bent Connector</span>
- <Hotkey
- token={TOKENS.canvas.line.bent}
- class="text-ink-muted"
- showPlus
- />
- </Dropdown.Item>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- );
-};
-
-export function ToolBar() {
- const canvas = useCanvasDocument();
- const canEdit = () => canvas.canEdit() && !canvas.isNested();
- const toolManager = useToolManager();
- const cachedStyle = useCachedStyle();
- const { activeTool } = toolManager;
- const [connectorTypeMenuTrigger, setConnectorTypeMenuTrigger] =
- canvas.state.signals.connectorTypeMenuTrigger;
- const scopeId = canvas.hotkeyScope;
-
- const [connectionStyle, setConnectionStyle] =
- createSignal<EdgeConnectionStyle>('straight');
-
- const onSelectConnectionStyle = (connectionStyle: EdgeConnectionStyle) => {
- setConnectionStyle(connectionStyle);
- cachedStyle.setProp(
- 'connectionStyle',
- EdgeConnectionStyles[connectionStyle]
- );
- toolManager.setSelectedTool(Tools.Line);
- };
-
- const connectorIcon = () => {
- switch (connectionStyle()) {
- case 'smooth':
- return ConnectorBezierArrows;
- case 'stepped':
- return ConnectorSteppedArrows;
- default:
- return ConnectorStraightArrows;
- }
- };
-
- registerHotkey({
- hotkey: 's',
- scopeId: scopeId(),
- condition: () => connectorTypeMenuTrigger(),
- description: 'Straight connector',
- keyDownHandler: () => {
- onSelectConnectionStyle('straight');
- setConnectorTypeMenuTrigger(false);
- return true;
- },
- hotkeyToken: TOKENS.canvas.line.straight,
- });
- registerHotkey({
- hotkey: 'f',
- scopeId: scopeId(),
- condition: () => connectorTypeMenuTrigger(),
- description: 'Flow connector',
- keyDownHandler: () => {
- onSelectConnectionStyle('smooth');
- setConnectorTypeMenuTrigger(false);
- return true;
- },
- hotkeyToken: TOKENS.canvas.line.flow,
- });
- registerHotkey({
- hotkey: 'b',
- scopeId: scopeId(),
- condition: () => connectorTypeMenuTrigger(),
- description: 'Bent connector',
- keyDownHandler: () => {
- onSelectConnectionStyle('stepped');
- setConnectorTypeMenuTrigger(false);
- return true;
- },
- hotkeyToken: TOKENS.canvas.line.bent,
- });
-
- return (
- <ScopedPortal scope={canvas.portalScope()}>
- {/* Full-frame mobile/tablet: rest above the floating bottom chrome. */}
- <Toolbar
- size="icon-sm"
- class="absolute left-1/2 bottom-2 touch:bottom-[calc(var(--mobile-content-inset-bottom,0)+0.5rem)] -translate-x-1/2"
- >
- <Toolbar.Group>
- <Toolbar.Button
- variant={activeTool() === Tools.Grab ? 'accent' : 'ghost'}
- label="Hand tool"
- hotkey={TOKENS.canvas.handTool}
- onClick={() => {
- toolManager.setSelectedTool(Tools.Grab);
- }}
- >
- <Hand />
- </Toolbar.Button>
-
- <Show when={!isTouchDevice()}>
- <Toolbar.Button
- variant={
- activeTool() === Tools.ZoomIn || activeTool() === Tools.ZoomOut
- ? 'accent'
- : 'ghost'
- }
- label="Zoom"
- hotkey={TOKENS.canvas.zoomInTool}
- /* scuffed: previously also showed a second row
- "Zoom out — hold ${IS_MAC ? 'option' : 'alt'}"
- but multi-row tooltips were dropped. */
- onClick={() => {
- toolManager.setSelectedTool(Tools.ZoomIn);
- }}
- >
- {activeTool() === Tools.ZoomOut ? <ZoomOut /> : <ZoomIn />}
- </Toolbar.Button>
- </Show>
-
- <Show when={canEdit()}>
- <Toolbar.Button
- variant={
- activeTool() === Tools.Select ||
- activeTool() === Tools.Resize ||
- activeTool() === Tools.Move
- ? 'accent'
- : 'ghost'
- }
- label="Move"
- hotkey={TOKENS.canvas.selectTool}
- onClick={() => {
- toolManager.setSelectedTool(Tools.Select);
- }}
- >
- <Cursor />
- </Toolbar.Button>
- </Show>
- </Toolbar.Group>
- <Show when={canEdit()}>
- <Toolbar.Divider />
- <Toolbar.Group>
- <Toolbar.Button
- variant={activeTool() === Tools.Shape ? 'accent' : 'ghost'}
- label="Rectangle"
- hotkey={TOKENS.canvas.shapeTool}
- onClick={() => {
- toolManager.setSelectedTool(Tools.Shape);
- }}
- >
- <Rectangle />
- </Toolbar.Button>
-
- <Toolbar.Button
- variant={activeTool() === Tools.Pencil ? 'accent' : 'ghost'}
- label="Pencil"
- hotkey={TOKENS.canvas.pencilTool}
- onClick={() => {
- toolManager.setSelectedTool(Tools.Pencil);
- }}
- >
- <PencilSimple />
- </Toolbar.Button>
-
- <ButtonGroup variant="outline" size="icon-sm">
- <Button
- variant={activeTool() === Tools.Line ? 'accent' : 'outline'}
- label="Connector"
- hotkey={TOKENS.canvas.lineTool}
- onClick={() => {
- toolManager.setSelectedTool(Tools.Line);
- }}
- >
- <Dynamic component={connectorIcon()} />
- </Button>
- <ButtonGroup.Divider />
- <ConnectorTypeSubMenu onSelect={onSelectConnectionStyle} />
- </ButtonGroup>
-
- <Show when={ENABLE_CANVAS_TEXT}>
- <Toolbar.Button
- variant={
- activeTool() === Tools.Text || activeTool() === Tools.Typing
- ? 'accent'
- : 'ghost'
- }
- label="Text"
- hotkey={TOKENS.canvas.textTool}
- onClick={() => {
- toolManager.setSelectedTool(Tools.Text);
- }}
- >
- <Text />
- </Toolbar.Button>
- </Show>
- </Toolbar.Group>
- </Show>
- <Show when={canEdit() && (ENABLE_CANVAS_IMAGES || ENABLE_CANVAS_FILES)}>
- <Toolbar.Divider />
- <Toolbar.Group>
- <Show when={ENABLE_CANVAS_IMAGES}>
- <MediaSelector />
- </Show>
- <Show when={ENABLE_CANVAS_FILES}>
- <FileSelector />
- </Show>
- </Toolbar.Group>
- </Show>
- </Toolbar>
- </ScopedPortal>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/TopBar.tsx b/apps/web/src/features/block-canvas/component/TopBar.tsx
index 3afcfd8c77..a47c6ff41d 100644
--- a/apps/web/src/features/block-canvas/component/TopBar.tsx
+++ b/apps/web/src/features/block-canvas/component/TopBar.tsx
@@ -33,21 +33,12 @@ import { downloadFile } from '@filesystem/download';
import IconShared from '@icon/share.svg';
import DownloadSimple from '@phosphor/download-simple.svg';
import { createCallback } from '@solid-primitives/rootless';
-import { onMount } from 'solid-js';
import { URL_PARAMS } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import { useToolManager } from '../signal/toolManager';
-import { useRenderState } from '../store/RenderState';
import type { CanvasDocumentChrome } from './CanvasDocument';
-export function TopBar(props: { next?: CanvasDocumentChrome } = {}) {
+export function TopBar(props: { state: CanvasDocumentChrome }) {
const analytics = useAnalytics();
- const toolManager = props.next ? undefined : useToolManager();
- const getLocation = props.next?.location ?? useRenderState().getLocation;
- const getCurrentSavedFile =
- props.next?.savedFile ??
- useCanvasDocument().state.signals.currentSavedFile[0];
const documentId = useBlockId();
const fileName = useBlockDocumentName('Unknown Filename');
const downloadName = useBlockDocumentDownloadName('Unknown Filename');
@@ -64,13 +55,8 @@ export function TopBar(props: { next?: CanvasDocumentChrome } = {}) {
}));
const copyEntityLink = useCopyLink();
- let ref!: HTMLDivElement;
- onMount(() => {
- toolManager?.ignoreMouseEvents(ref);
- });
-
const downloadDocument = createCallback(async () => {
- const file = getCurrentSavedFile() ?? canvasFile();
+ const file = props.state.savedFile() ?? canvasFile();
if (!file) return;
downloadFile(file, downloadName());
@@ -78,7 +64,7 @@ export function TopBar(props: { next?: CanvasDocumentChrome } = {}) {
});
const copyLink = () => {
- const location = getLocation();
+ const location = props.state.location();
const params = {
[URL_PARAMS.x]: location.x.toString(),
[URL_PARAMS.y]: location.y.toString(),
@@ -129,7 +115,7 @@ export function TopBar(props: { next?: CanvasDocumentChrome } = {}) {
];
return (
- <div ref={ref}>
+ <div>
<SplitHeaderLeft>
<BlockItemSplitLabel />
</SplitHeaderLeft>
diff --git a/apps/web/src/features/block-canvas/component/ZoomWidget.tsx b/apps/web/src/features/block-canvas/component/ZoomWidget.tsx
deleted file mode 100644
index 1530f5c2a7..0000000000
--- a/apps/web/src/features/block-canvas/component/ZoomWidget.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { ZOOM_TARGETS } from '@block-canvas/constants';
-import { isMobileWidth } from '@core/mobile/mobileWidth';
-import Minus from '@phosphor/minus.svg';
-import Plus from '@phosphor/plus.svg';
-import { Tooltip } from '@ui';
-import { onMount, Show } from 'solid-js';
-import { useToolManager } from '../signal/toolManager';
-import { useRenderState } from '../store/RenderState';
-
-const nextInList = (list: number[], current: number, larger = true) => {
- if (larger) {
- if (list.length === 0) return current;
- if (list[0] > current) {
- return list[0];
- }
- for (let i = 0; i < list.length; i++) {
- if (list[i] > current) {
- return list[i];
- }
- }
- }
- for (let i = list.length - 1; i >= 0; i--) {
- if (list[list.length - 1] < current) {
- return list[list.length - 1];
- }
- const val = list[i];
- if (val < current) {
- return val;
- }
- }
-};
-
-export function ZoomWidget() {
- let widgetRef!: HTMLDivElement;
- const { currentScale, animateTo } = useRenderState();
- const toolManager = useToolManager();
-
- const zoomIn = () => {
- const val = nextInList(ZOOM_TARGETS, currentScale(), true);
- animateTo({ scale: val }, 200, true);
- };
-
- const zoomOut = () => {
- const val = nextInList(ZOOM_TARGETS, currentScale(), false);
- animateTo({ scale: val }, 200, true);
- };
-
- const zoomPercent = () => {
- return Math.floor(currentScale() * 100);
- };
-
- const resetZoom = () => {
- animateTo({ scale: 1 }, 200, true);
- };
-
- onMount(() => {
- toolManager.ignoreMouseEvents(widgetRef);
- });
-
- return (
- <div
- class="cursor-auto absolute bottom-4 left-4 rounded-xl flex flex-row items-center gap-1 p-2 w-32 justify-between"
- ref={widgetRef}
- >
- <Show when={!isMobileWidth()}>
- <div
- on:click={zoomOut}
- class="hover:bg-hover hover-transition-bg rounded-lg w-1/4 h-6 flex items-center justify-center pointer-events-auto text-ink-muted"
- >
- <Minus class="size-4" />
- </div>
- </Show>
- <Tooltip placement="top" label="Reset zoom">
- <div
- class="text-ink-muted text-center w-12 h-6 select-none"
- on:click={resetZoom}
- >
- {zoomPercent()}%
- </div>
- </Tooltip>
- <Show when={!isMobileWidth()}>
- <div
- on:click={zoomIn}
- class="hover:bg-hover hover-bg-transition rounded-lg w-1/4 h-6 flex items-center justify-center pointer-events-auto text-ink-muted"
- >
- <Plus class="size-4" />
- </div>
- </Show>
- </div>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/edges/Arrows.tsx b/apps/web/src/features/block-canvas/component/edges/Arrows.tsx
deleted file mode 100644
index 952b28d5d3..0000000000
--- a/apps/web/src/features/block-canvas/component/edges/Arrows.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { EdgeEndStyles } from '@block-canvas/model/CanvasModel';
-import { Match, Switch } from 'solid-js';
-
-export type ArrowStyle = {
- stroke: string | undefined;
- 'stroke-width': string | number | undefined;
-};
-
-export interface ArrowProps {
- x: number;
- y: number;
- angle: number;
- style: ArrowStyle;
- arrowLength: number;
- onPointerDown?: (e: PointerEvent) => void;
-}
-
-export interface ArrowHeadProps {
- arrowStyle: number | undefined;
- x: number;
- y: number;
- angle: number;
- length: number;
- style: ArrowStyle;
- end: 'from' | 'to';
- onPointerDown?: (e: PointerEvent) => void;
-}
-
-export const ArrowLines = (props: ArrowProps) => {
- return (
- <>
- <line
- x1={props.x}
- y1={props.y}
- x2={props.x + props.arrowLength * Math.cos(props.angle - Math.PI / 4)}
- y2={props.y + props.arrowLength * Math.sin(props.angle - Math.PI / 4)}
- stroke={props.style.stroke}
- stroke-width={props.style['stroke-width']}
- stroke-linecap="round"
- stroke-linejoin="round"
- on:pointerdown={props.onPointerDown}
- />
- <line
- x1={props.x}
- y1={props.y}
- x2={props.x + props.arrowLength * Math.cos(props.angle + Math.PI / 4)}
- y2={props.y + props.arrowLength * Math.sin(props.angle + Math.PI / 4)}
- stroke={props.style.stroke}
- stroke-width={props.style['stroke-width']}
- stroke-linecap="round"
- stroke-linejoin="round"
- on:pointerdown={props.onPointerDown}
- />
- </>
- );
-};
-
-export const ArrowSolid = (props: ArrowProps) => {
- return (
- <polygon
- points={`${props.x},${props.y}
- ${props.x + props.arrowLength * Math.cos(props.angle - Math.PI / 6)},
- ${props.y + props.arrowLength * Math.sin(props.angle - Math.PI / 6)}
- ${props.x + props.arrowLength * Math.cos(props.angle + Math.PI / 6)},
- ${props.y + props.arrowLength * Math.sin(props.angle + Math.PI / 6)}`}
- fill={props.style.stroke}
- stroke-width={props.style['stroke-width']}
- stroke={props.style.stroke}
- on:pointerdown={props.onPointerDown}
- />
- );
-};
-
-export const ArrowCircle = (props: Omit<ArrowProps, 'angle'>) => {
- return (
- <circle
- cx={props.x}
- cy={props.y}
- r={props.arrowLength / 2}
- fill={props.style.stroke}
- on:pointerdown={props.onPointerDown}
- />
- );
-};
-
-export const ArrowCircleSmall = (props: Omit<ArrowProps, 'angle'>) => {
- return (
- <circle
- cx={props.x}
- cy={props.y}
- r={props.arrowLength / 4}
- fill={props.style.stroke}
- on:pointerdown={props.onPointerDown}
- />
- );
-};
-
-export const ArrowHead = (props: ArrowHeadProps) => {
- return (
- <Switch>
- <Match when={props.arrowStyle === EdgeEndStyles.Arrow}>
- <ArrowLines
- x={props.x}
- y={props.y}
- angle={props.angle}
- style={props.style}
- arrowLength={props.length}
- />
- </Match>
- <Match when={props.arrowStyle === EdgeEndStyles.ArrowFilled}>
- <ArrowSolid
- x={props.x}
- y={props.y}
- angle={props.angle}
- style={props.style}
- arrowLength={props.length}
- />
- </Match>
- <Match when={props.arrowStyle === EdgeEndStyles.Circle}>
- <ArrowCircle
- x={props.x}
- y={props.y}
- style={props.style}
- arrowLength={props.length}
- />
- </Match>
- <Match when={props.arrowStyle === EdgeEndStyles.CircleSmall}>
- <ArrowCircleSmall
- x={props.x}
- y={props.y}
- style={props.style}
- arrowLength={props.length}
- />
- </Match>
- </Switch>
- );
-};
diff --git a/apps/web/src/features/block-canvas/component/edges/Line.tsx b/apps/web/src/features/block-canvas/component/edges/Line.tsx
deleted file mode 100644
index 1211bf7321..0000000000
--- a/apps/web/src/features/block-canvas/component/edges/Line.tsx
+++ /dev/null
@@ -1,241 +0,0 @@
-import { edgeToRenderData } from '@block-canvas/util/connectors';
-import { createCallback } from '@solid-primitives/rootless';
-import {
- createMemo,
- createSignal,
- type JSX,
- onCleanup,
- onMount,
- useContext,
-} from 'solid-js';
-import { Portal } from 'solid-js/web';
-import {
- ARROW_SIZE,
- DRAG_THRESHOLD,
- type RenderMode,
- RenderModes,
- Tools,
-} from '../../constants';
-import type { CanvasEdge } from '../../model/CanvasModel';
-import { useConnect } from '../../operation/connect';
-import { useMove } from '../../operation/move';
-import { useSelect } from '../../operation/select';
-import { useSelection } from '../../signal/selection';
-import { useToolManager } from '../../signal/toolManager';
-import { useEdgeUtils } from '../../store/canvasData';
-import { useRenderState } from '../../store/RenderState';
-import { getTailwindColor } from '../../util/style';
-import { type Vector2, vec2 } from '../../util/vector2';
-import { LayerContext } from '../LayerContext';
-import { ArrowHead } from './Arrows';
-
-export function Line(props: { edge: CanvasEdge; mode: RenderMode }) {
- const layerContext = useContext(LayerContext);
- const { selectEdge, selectGroup, isSelected, deselectAll } = useSelection();
- const { activeTool, setSelectedTool } = useToolManager();
- const { currentScale } = useRenderState();
- const move = useMove();
- const select = useSelect();
- const connect = useConnect();
- const { getRawEndPoints } = useEdgeUtils();
-
- const [dragStartPos, setDragStartPos] = createSignal<Vector2>();
- const [dragActive, setDragActive] = createSignal(false);
-
- const pointerdown = createCallback((e: MouseEvent) => {
- if (activeTool() !== Tools.Select) return;
- setDragStartPos(vec2(e.pageX, e.pageY));
- setDragActive(false);
- e.stopPropagation();
- if (!e.shiftKey && !isSelected(props.edge.id)) {
- deselectAll();
- }
- select.abort();
- selectEdge(props.edge.id);
- if (props.edge.groupId) selectGroup(props.edge.groupId);
- });
-
- const pointermove = (e: PointerEvent) => {
- if (dragActive()) return;
- const pos = dragStartPos();
- if (pos === undefined) return;
- if (isSelected(props.edge.id) && dragStartPos() !== undefined) {
- if (pos.distance(vec2(e.pageX, e.pageY)) > DRAG_THRESHOLD) {
- select.abort();
- setSelectedTool(Tools.Move);
- move.start(e);
- setDragActive(true);
- }
- }
- };
-
- const pointerup = () => {
- setDragStartPos();
- setDragActive(false);
- };
-
- onMount(() => {
- document.addEventListener('pointermove', pointermove);
- document.addEventListener('pointerup', pointerup);
- });
-
- onCleanup(() => {
- document.removeEventListener('pointermove', pointermove);
- document.removeEventListener('pointerup', pointerup);
- });
-
- const endPoints = createMemo(() => getRawEndPoints(props.edge));
- const edgeRenderData = createMemo(() =>
- edgeToRenderData(props.edge, [endPoints().from, endPoints().to])
- );
-
- // While connection is active, we have to pass through pointer events
- // to the connection drop listeners on shapes.
- const pointerEvents = createMemo(() => {
- if (connect.active()) {
- return 'none';
- }
- return 'visiblePainted';
- });
-
- const lineStyle = createMemo(
- (): Partial<JSX.SvgSVGAttributes<SVGLineElement>> => {
- const fallbackColor = getTailwindColor('gray-700');
- const selected = props.mode === RenderModes.Selection;
- const strokeColor = selected
- ? getTailwindColor('sky-500')
- : (props.edge.style?.strokeColor ?? fallbackColor);
- const strokeWidth =
- props.mode === RenderModes.Selection
- ? 1 / currentScale()
- : (props.edge.style?.strokeWidth ?? 2);
- return {
- stroke: strokeColor,
- 'stroke-width': `${strokeWidth}px`,
- 'stroke-linecap': 'round',
- };
- }
- );
-
- const handleSize = createMemo(() => 12 / currentScale());
-
- // Calculate the angle of the base line
- const arrowLength = () => ARROW_SIZE;
- const arrowStyle = () => ({
- stroke: lineStyle().stroke,
- 'stroke-width': lineStyle()['stroke-width'],
- });
-
- const path = () => {
- return edgeRenderData().path;
- };
-
- return (
- <>
- <div class="absolute top-0 left-0 opacity-90 pointer-events-none">
- <svg
- width="10px"
- height="10px"
- class="overflow-visible"
- pointer-events="none"
- >
- {/* render a thick but transparent line for easier mouse selection */}
- <path
- d={path()}
- fill="none"
- stroke="transparent"
- stroke-width={20 / currentScale()}
- stroke-linecap={lineStyle()['stroke-linecap']}
- vector-effect="non-scaling-stroke"
- pointer-events={pointerEvents()}
- on:pointerdown={pointerdown}
- />
- <path
- d={path()}
- fill="none"
- stroke={lineStyle().stroke}
- stroke-width={lineStyle()['stroke-width']}
- stroke-linecap={lineStyle()['stroke-linecap']}
- vector-effect="non-scaling-stroke"
- pointer-events={pointerEvents()}
- on:pointerdown={pointerdown}
- />
- <ArrowHead
- x={edgeRenderData().fromPos.x}
- y={edgeRenderData().fromPos.y}
- angle={edgeRenderData().fromVec.angle()}
- length={arrowLength()}
- style={arrowStyle()}
- arrowStyle={props.edge.style?.fromEndStyle}
- end="from"
- onPointerDown={pointerdown}
- />
- <ArrowHead
- x={edgeRenderData().toPos.x}
- y={edgeRenderData().toPos.y}
- angle={edgeRenderData().toVec.angle()}
- length={arrowLength()}
- style={arrowStyle()}
- arrowStyle={props.edge.style?.toEndStyle}
- end="to"
- onPointerDown={pointerdown}
- />
- </svg>
- </div>
- <Portal mount={layerContext().lineSelection}>
- <div class="absolute top-0 left-0 pointer-events-none">
- <svg
- width="10px"
- height="10px"
- class="overflow-visible"
- pointer-events="none"
- visibility={isSelected(props.edge.id) ? 'visible' : 'hidden'}
- >
- <path
- d={path()}
- fill="none"
- stroke={getTailwindColor('sky-500')}
- stroke-width={`${1 / currentScale()}px`}
- stroke-linecap={lineStyle()['stroke-linecap']}
- vector-effect="non-scaling-stroke"
- />
- <circle
- cx={edgeRenderData().fromPos.x}
- cy={edgeRenderData().fromPos.y}
- r={handleSize() / 2}
- fill={getTailwindColor('gray-50')}
- stroke={getTailwindColor('sky-500')}
- stroke-width={`${1 / currentScale()}px`}
- pointer-events={pointerEvents()}
- onPointerDown={createCallback((e: PointerEvent) => {
- e.stopPropagation();
- move.abort();
- connect.abort();
- select.abort();
- setSelectedTool(Tools.Line);
- connect.start(e, { edge: props.edge, handle: 'from' });
- })}
- />
- <circle
- cx={edgeRenderData().toPos.x}
- cy={edgeRenderData().toPos.y}
- r={handleSize() / 2}
- fill={getTailwindColor('gray-50')}
- stroke={getTailwindColor('sky-500')}
- stroke-width={`${1 / currentScale()}px`}
- pointer-events={pointerEvents()}
- onPointerDown={createCallback((e: PointerEvent) => {
- e.stopPropagation();
- move.abort();
- connect.abort();
- select.abort();
- setSelectedTool(Tools.Line);
- connect.start(e, { edge: props.edge, handle: 'to' });
- })}
- />
- </svg>
- </div>
- </Portal>
- </>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/icons-custom/ArrowIcons.tsx b/apps/web/src/features/block-canvas/component/icons-custom/ArrowIcons.tsx
deleted file mode 100644
index bd52a7bb0c..0000000000
--- a/apps/web/src/features/block-canvas/component/icons-custom/ArrowIcons.tsx
+++ /dev/null
@@ -1,293 +0,0 @@
-import type { Component, JSX } from 'solid-js';
-
-export const ArrowLine: Component<JSX.SvgSVGAttributes<SVGSVGElement>> = (
- props
-) => {
- return (
- <svg width="64" height="64" viewBox="0 0 64 64" {...props}>
- <line
- x1="4"
- y1="32"
- x2="60"
- y2="32"
- stroke="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- </svg>
- );
-};
-
-export const ArrowCaret: Component<JSX.SvgSVGAttributes<SVGSVGElement>> = (
- props
-) => {
- // Arrowhead arms at 45 degrees, length ≈ 9.9 units from (4,32)
- return (
- <svg width="64" height="64" viewBox="0 0 64 64" {...props}>
- <line
- x1="4"
- y1="32"
- x2="13.9"
- y2="22.1"
- stroke="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- <line
- x1="4"
- y1="32"
- x2="13.9"
- y2="41.9"
- stroke="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- <line
- x1="4"
- y1="32"
- x2="60"
- y2="32"
- stroke="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- </svg>
- );
-};
-
-export const ArrowTriangle: Component<JSX.SvgSVGAttributes<SVGSVGElement>> = (
- props
-) => {
- // Triangle: (4,32), (13.9,22.1), (13.9,41.9)
- return (
- <svg width="64" height="64" viewBox="0 0 64 64" {...props}>
- <polygon
- points="4,32 13.9,22.1 13.9,41.9"
- fill="currentColor"
- stroke="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- <line
- x1="9.8"
- y1="32"
- x2="60"
- y2="32"
- stroke="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- </svg>
- );
-};
-
-export const ArrowCircle: Component<JSX.SvgSVGAttributes<SVGSVGElement>> = (
- props
-) => {
- // Filled circle at (14,32), r=10
- return (
- <svg width="64" height="64" viewBox="0 0 64 64" {...props}>
- <circle
- cx="14"
- cy="32"
- r="10"
- stroke="currentColor"
- fill="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- <line
- x1="24"
- y1="32"
- x2="60"
- y2="32"
- stroke="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- </svg>
- );
-};
-
-export const ArrowCircleSmall: Component<
- JSX.SvgSVGAttributes<SVGSVGElement>
-> = (props) => {
- // Filled smaller dot at (14,32), r=7
- return (
- <svg width="64" height="64" viewBox="0 0 64 64" {...props}>
- <circle
- cx="14"
- cy="32"
- r="7"
- stroke="currentColor"
- fill="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- <line
- x1="21"
- y1="32"
- x2="60"
- y2="32"
- stroke="currentColor"
- stroke-width="4"
- stroke-linecap="round"
- stroke-linejoin="round"
- />
- </svg>
- );
-};
-export const ConnectorStraight: Component<
- JSX.SvgSVGAttributes<SVGSVGElement>
-> = (props) => {
- return (
- <svg viewBox="0 0 256 256" {...props}>
- <path
- d="M24 232L232 24"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linecap="round"
- stroke-linejoin="round"
- fill="none"
- />
- </svg>
- );
-};
-
-export const ConnectorStraightArrows: Component<
- JSX.SvgSVGAttributes<SVGSVGElement>
-> = (props) => {
- return (
- <svg viewBox="0 0 256 256" {...props}>
- <path
- d="M188 24L232 24L232 68"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linecap="round"
- stroke-linejoin="round"
- fill="none"
- />
- <path
- d="M68 232L24 232L24 188"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linecap="round"
- stroke-linejoin="round"
- fill="none"
- />
- <path
- d="M24 232L232 24"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linecap="round"
- stroke-linejoin="round"
- fill="none"
- />
- </svg>
- );
-};
-
-export const ConnectorBezier: Component<JSX.SvgSVGAttributes<SVGSVGElement>> = (
- props
-) => {
- return (
- <svg viewBox="0 0 256 256" {...props}>
- <path
- d="M8 186C180 186 52 38 224 38"
- stroke="currentcolor"
- stroke-linecap="round"
- stroke-width="16"
- fill="none"
- />
- </svg>
- );
-};
-
-export const ConnectorBezierArrows: Component<
- JSX.SvgSVGAttributes<SVGSVGElement>
-> = (props) => {
- return (
- <svg viewBox="0 0 256 256" {...props}>
- <path
- d="M193.444 8L224.556 39.1127L193.444 70.2254"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linecap="round"
- stroke-linejoin="round"
- fill="none"
- />
- <path
- d="M38.5563 216L8 185.113L38 154"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linecap="round"
- stroke-linejoin="round"
- fill="none"
- />
- <path
- d="M8 186C180 186 52 38 224 38"
- stroke="currentcolor"
- stroke-linecap="round"
- stroke-width="16"
- fill="none"
- />
- </svg>
- );
-};
-
-export const ConnectorStepped: Component<
- JSX.SvgSVGAttributes<SVGSVGElement>
-> = (props) => {
- return (
- <svg viewBox="0 0 256 256" {...props}>
- <path
- d="M9 186H116V38H222"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linejoin="round"
- fill="none"
- />
- </svg>
- );
-};
-
-export const ConnectorSteppedArrows: Component<
- JSX.SvgSVGAttributes<SVGSVGElement>
-> = (props) => {
- return (
- <svg viewBox="0 0 256 256" {...props}>
- <path
- d="M193.444 8L224.556 38L193.444 70.2254"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linecap="round"
- stroke-linejoin="round"
- fill="none"
- />
- <path
- d="M38.5563 216L8 185.113L38 154"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linecap="round"
- stroke-linejoin="round"
- fill="none"
- />
- <path
- d="M9 186H116V38H222"
- stroke="currentcolor"
- stroke-width="16"
- stroke-linejoin="round"
- fill="none"
- />
- </svg>
- );
-};
diff --git a/apps/web/src/features/block-canvas/component/icons-custom/LineWeight.tsx b/apps/web/src/features/block-canvas/component/icons-custom/LineWeight.tsx
deleted file mode 100644
index 06ad987e13..0000000000
--- a/apps/web/src/features/block-canvas/component/icons-custom/LineWeight.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { Component, JSX } from 'solid-js';
-
-export const LineWeight: Component<JSX.SvgSVGAttributes<SVGSVGElement>> = (
- props
-) => {
- return (
- <svg width="64" height="64" viewBox="0 0 64 64" {...props}>
- <rect x="8" y="8" width="48" height="4" rx="2" stroke="none" />
- <rect x="8" y="20" width="48" height="8" rx="2" stroke="none" />
- <rect x="8" y="36" width="48" height="16" rx="2" stroke="none" />
- </svg>
- );
-};
diff --git a/apps/web/src/features/block-canvas/component/nodes/BaseCanvasRectangle.tsx b/apps/web/src/features/block-canvas/component/nodes/BaseCanvasRectangle.tsx
deleted file mode 100644
index f9681c6a0e..0000000000
--- a/apps/web/src/features/block-canvas/component/nodes/BaseCanvasRectangle.tsx
+++ /dev/null
@@ -1,266 +0,0 @@
-import { createCallback } from '@solid-primitives/rootless';
-import {
- type Accessor,
- createMemo,
- createSignal,
- type JSX,
- onCleanup,
- onMount,
- useContext,
-} from 'solid-js';
-import { Portal } from 'solid-js/web';
-import {
- DRAG_THRESHOLD,
- type Edge,
- Edges,
- HANDLE_SIZE,
- type RenderMode,
- Tools,
-} from '../../constants';
-import type { CanvasNode } from '../../model/CanvasModel';
-import { type ConnectOperator, useConnect } from '../../operation/connect';
-import { useMove } from '../../operation/move';
-import { useSelect } from '../../operation/select';
-import { useSelection } from '../../signal/selection';
-import { useToolManager } from '../../signal/toolManager';
-import { useRenderState } from '../../store/RenderState';
-import { Rect } from '../../util/rectangle';
-import { getBorderRadius, getTailwindColor } from '../../util/style';
-import { type Vector2, vec2 } from '../../util/vector2';
-import { LayerContext } from '../LayerContext';
-
-function edgeToPosition(edge: Edge, size: number): Partial<JSX.CSSProperties> {
- switch (edge) {
- case Edges.Top:
- return {
- top: -size / 2 + 'px',
- left: 0,
- width: '100%',
- height: size + 'px',
- };
- case Edges.Right:
- return {
- top: 0,
- right: -size / 2 + 'px',
- width: size + 'px',
- height: '100%',
- };
- case Edges.Bottom:
- return {
- bottom: -size / 2 + 'px',
- left: 0,
- width: '100%',
- height: size + 'px',
- };
- case Edges.Left:
- return {
- top: 0,
- left: -size / 2 + 'px',
- width: size + 'px',
- height: '100%',
- };
- }
-}
-
-function EdgeHandle(props: {
- id: string;
- edge: Edge;
- scale: Accessor<number>;
-}) {
- const position = () =>
- edgeToPosition(props.edge, (HANDLE_SIZE * 2) / props.scale());
- const { selectedTool } = useToolManager();
- const connect = useConnect() as ConnectOperator;
- const [hover, setHover] = createSignal(false);
-
- return (
- <div
- style={{
- position: 'absolute',
- ...position(),
- }}
- classList={{
- 'bg-ink-muted/60': hover(),
- }}
- onPointerDown={createCallback((e: PointerEvent) => {
- if (selectedTool() === Tools.Line) {
- e.preventDefault();
- e.stopPropagation();
- connect.reset();
- connect.start(e, { node: props.id, side: props.edge });
- }
- })}
- onPointerEnter={createCallback(() => {
- if (selectedTool() === Tools.Line) {
- setHover(true);
- connect.setDropTarget({ node: props.id, side: props.edge });
- }
- })}
- onPointerLeave={createCallback(() => {
- setHover(false);
- if (selectedTool() === Tools.Line) {
- connect.setDropTarget();
- }
- })}
- />
- );
-}
-
-interface BaseCanvasRectangleProps {
- node: CanvasNode;
- mode: RenderMode;
- children?: JSX.Element;
- onDragStart?: (e: PointerEvent) => void;
- onDragMove?: (e: PointerEvent) => void;
- onDragEnd?: () => void;
- showEdgeHandles?: boolean;
- clickable?: boolean;
-
- useSimpleSelectionBox?: boolean; //use a box with sharp corners and a fixed width
-}
-
-export function BaseCanvasRectangle(props: BaseCanvasRectangleProps) {
- const layerContext = useContext(LayerContext);
-
- const { selectNode, selectGroup, isSelected, deselectAll } = useSelection();
- const { currentScale, defferedScale } = useRenderState();
- const { activeTool, setSelectedTool, ignore } = useToolManager();
-
- const move = useMove();
- const select = useSelect();
-
- // Calculate normalized dimensions
- const rect = createMemo(() => {
- return Rect.fromCanvasNode(props.node).toCssRect();
- });
-
- const borderRadius = createMemo(() => ({
- 'border-radius': getBorderRadius(props.node),
- }));
-
- const isLineTool = createMemo(() => activeTool() === Tools.Line);
-
- const [dragStartPos, setDragStartPos] = createSignal<Vector2>();
- const [dragActive, setDragActive] = createSignal(false);
-
- const start = (e: PointerEvent) => {
- if (activeTool() !== Tools.Select) return;
- setDragStartPos(vec2(e.pageX, e.pageY));
- setDragActive(false);
-
- if (!e.shiftKey && !isSelected(props.node.id)) {
- deselectAll();
- }
- selectNode(props.node.id);
- if (props.node.groupId) selectGroup(props.node.groupId);
- select.abort();
- props.onDragStart?.(e);
- };
-
- const drag = (e: PointerEvent) => {
- if (dragActive()) return;
- const pos = dragStartPos();
- if (pos === undefined) return;
- if (isSelected(props.node.id) && dragStartPos() !== undefined) {
- if (pos.distance(vec2(e.pageX, e.pageY)) > DRAG_THRESHOLD) {
- select.abort();
- setSelectedTool(Tools.Move);
- move.start(e);
- setDragActive(true);
- props.onDragMove?.(e);
- }
- }
- };
-
- const end = () => {
- setDragStartPos();
- setDragActive(false);
- props.onDragEnd?.();
- };
-
- onMount(() => {
- document.addEventListener('pointermove', drag);
- document.addEventListener('pointerup', end);
- });
-
- onCleanup(() => {
- document.removeEventListener('pointermove', drag);
- document.removeEventListener('pointerup', end);
- });
-
- const selectionStyle = createMemo((): Partial<JSX.CSSProperties> => {
- if (props.useSimpleSelectionBox === false) {
- const shapeStrokeWidth = props.node.style?.strokeWidth ?? 2;
- const outlineWidth = 1 / currentScale();
- const outlineOffset = -shapeStrokeWidth / 2 - outlineWidth;
- return {
- 'border-radius': `${getBorderRadius(props.node)}`,
- outline: `${outlineWidth}px solid ${getTailwindColor('sky-500')}`,
- 'outline-offset': `${outlineOffset}px`,
- visibility: isSelected(props.node.id) ? 'visible' : 'hidden',
- };
- } else {
- return {
- 'border-radius': `0px`,
- outline: `${1 / currentScale()}px solid ${getTailwindColor('sky-500')}`,
- 'outline-offset': `-1px`, //i think
- visibility: isSelected(props.node.id) ? 'visible' : 'hidden',
- };
- }
- });
-
- return (
- <>
- <div
- class="absolute top-0 left-0 box-border"
- style={{ ...rect(), ...borderRadius() }}
- onPointerDown={(e) => {
- if (props.clickable) {
- if (e.button !== 0 || ignore(e)) return;
- e.stopPropagation();
- start(e);
- }
- }}
- >
- <div class="h-full pointer-events-none">{props.children}</div>
- </div>
-
- <Portal mount={layerContext().selection}>
- <div
- class="absolute pointer-events-none top-0 left-0 opacity-90 outline-accent outline-1"
- style={{
- // TODO
- ...rect(),
- ...selectionStyle(), // So here *everything* takes the selection style, even text boxes
- }}
- />
- </Portal>
-
- <div
- class="absolute top-0 left-0 border-transparent opacity-40 z-user-highlight"
- style={{
- ...rect(),
- ...borderRadius(),
- 'pointer-events': isLineTool() ? 'auto' : 'none',
- }}
- >
- <EdgeHandle id={props.node.id} edge={Edges.Top} scale={defferedScale} />
- <EdgeHandle
- id={props.node.id}
- edge={Edges.Right}
- scale={defferedScale}
- />
- <EdgeHandle
- id={props.node.id}
- edge={Edges.Bottom}
- scale={defferedScale}
- />
- <EdgeHandle
- id={props.node.id}
- edge={Edges.Left}
- scale={defferedScale}
- />
- </div>
- </>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/nodes/DSSMedia.tsx b/apps/web/src/features/block-canvas/component/nodes/DSSMedia.tsx
deleted file mode 100644
index cb21e6593f..0000000000
--- a/apps/web/src/features/block-canvas/component/nodes/DSSMedia.tsx
+++ /dev/null
@@ -1,410 +0,0 @@
-import { clamp } from '@block-canvas/util/math';
-import { LoadErrors } from '@core/block';
-import { CircleSpinner } from '@core/component/CircleSpinner';
-import { staticFileIdEndpoint } from '@core/constant/servers';
-import PauseIcon from '@phosphor/pause.svg';
-import PlayIcon from '@phosphor/play.svg';
-import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
-import LockKey from '@phosphor-icons/core/regular/lock-key.svg?component-solid';
-import Question from '@phosphor-icons/core/regular/question.svg?component-solid';
-import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
-import { fetchBinary } from '@service-storage/util/fetchBinary';
-import {
- createEffect,
- createMemo,
- createReaction,
- createSignal,
- type JSX,
- Match,
- Show,
- Switch,
-} from 'solid-js';
-import {
- type RenderMode,
- RenderModes,
- TOOLTIP_FONTSIZE,
-} from '../../constants';
-import type { ImageNode, VideoNode } from '../../model/CanvasModel';
-import { useCanvasNodes } from '../../store/canvasData';
-import { useRenderState } from '../../store/RenderState';
-import { getBorderRadius } from '../../util/style';
-import { BaseCanvasRectangle } from './BaseCanvasRectangle';
-
-type MediaNode = ImageNode | VideoNode;
-
-function ErrorMessage(props: {
- node: MediaNode;
- error: 'UNAUTHORIZED' | 'MISSING' | 'INVALID' | 'LOADING' | undefined;
- size: { width: number; height: number };
-}) {
- const { currentScale } = useRenderState();
- const iconSize = 24;
- const tooSmall = createMemo(
- () =>
- props.size.width * currentScale() < 150 ||
- props.size.height * currentScale() < 150
- );
- const bottomMargin = !tooSmall() ? 8 : 0;
- const textColor = 'text-ink';
- const visibilityScreen =
- 'w-full h-full bg-surface/50 flex flex-col items-center justify-center';
-
- return (
- <div
- class="flex flex-col size-full text-center bg-surface/40 rounded border border-dashed border-edge items-center justify-center"
- style={{
- 'border-radius': getBorderRadius(props.node),
- 'font-size': TOOLTIP_FONTSIZE / currentScale() + 'px',
- 'background-size':
- 15 / currentScale() + 'px ' + 15 / currentScale() + 'px',
- 'background-blend-mode': 'lighten',
- 'background-image':
- props.error === 'LOADING'
- ? 'none'
- : 'linear-gradient(-45deg, transparent 10%, var(--color-gray-100) 10%, var(--color-gray-100) 20%, transparent 10%, transparent 60%, var(--color-gray-100) 60%, var(--color-gray-100) 70%, transparent 70%, transparent)',
- }}
- >
- <Switch>
- <Match when={props.error === 'UNAUTHORIZED'}>
- <div class={visibilityScreen}>
- <LockKey
- width={iconSize / currentScale() + 'px'}
- class="fill-ink bg-surface rounded-full"
- style={{
- 'margin-bottom': bottomMargin / currentScale() + 'px',
- }}
- />
- {!tooSmall() ? (
- <div class={textColor}>
- Unauthorized: <br />
- Invalid permissions
- </div>
- ) : null}
- </div>
- </Match>
- <Match when={props.error === 'MISSING'}>
- <div class={visibilityScreen}>
- <Question
- width={iconSize / currentScale() + 'px'}
- class="fill-ink bg-surface rounded-full"
- style={{
- 'margin-bottom': bottomMargin / currentScale() + 'px',
- }}
- />
- {!tooSmall() ? (
- <div class={textColor}>Error: Missing image</div>
- ) : null}
- </div>
- </Match>
- <Match when={props.error === 'INVALID'}>
- <div class={visibilityScreen}>
- <Question
- width={iconSize / currentScale() + 'px'}
- class="fill-ink bg-surface rounded-full"
- style={{
- 'margin-bottom': bottomMargin / currentScale() + 'px',
- }}
- />
- {!tooSmall() ? (
- <div class={textColor}>Error: Invalid image</div>
- ) : null}
- </div>
- </Match>
- <Match when={props.error === 'LOADING'}>
- <CircleSpinner />
- </Match>
- </Switch>
- </div>
- );
-}
-
-export function DSSMedia(props: { node: MediaNode; mode: RenderMode }) {
- const imageFlip = createMemo((): Partial<JSX.CSSProperties> => {
- return {
- transform: `scaleX(${props.node.flipX ? '-1' : '1'}) scaleY(${props.node.flipY ? '-1' : '1'})`,
- };
- });
-
- const [url, setUrl] = createSignal('');
- const [error, setError] = createSignal<
- 'UNAUTHORIZED' | 'MISSING' | 'INVALID' | 'LOADING' | undefined
- >('LOADING');
- const [originalSize, setOriginalSize] = createSignal<{
- width: number;
- height: number;
- }>();
- const { updateNode } = useCanvasNodes();
- const { currentSize, currentScale } = useRenderState();
- const [videoIsPlaying, setVideoIsPlaying] = createSignal(false);
- const [, setShowVideoControls] = createSignal(false);
- const [hoveringOverVideo, setHoveringOverVideo] = createSignal(false);
-
- let videoRef: HTMLVideoElement | undefined;
-
- const handleVideoRewind = () => {
- if (props.node.type !== 'video' || !videoRef) {
- return;
- }
-
- videoRef.currentTime = 0;
- };
-
- // Handle video click for play/pause
- const handleVideoClick = () => {
- if (props.node.type !== 'video' || !videoRef) {
- return;
- }
-
- if (videoRef.paused) {
- setVideoIsPlaying(() => true);
- videoRef.play().catch((error: Error) => {
- setVideoIsPlaying(() => false);
- console.error('Failed to play video:', error);
- });
- } else {
- setVideoIsPlaying(() => false);
- videoRef.pause();
- }
- };
-
- createEffect(async () => {
- if (props.node.status === 'dss' || !props.node.status) {
- const res = await fetchBinaryDocumentData(props.node.uuid);
-
- if (
- (res.isErr() &&
- res.error.some((error) => error.code === 'UNAUTHORIZED')) ||
- (res.isErr() && res.error.some((error) => error.code === 'HTTP_ERROR'))
- ) {
- setError();
- setError('UNAUTHORIZED');
- return LoadErrors.UNAUTHORIZED;
- }
- if (res.isErr()) {
- setError();
- setError('MISSING');
- return LoadErrors.MISSING;
- }
-
- const documentResult = res.value;
-
- const { blobUrl } = documentResult;
-
- const blobResult = await fetchBinary(blobUrl, 'blob');
-
- if (blobResult.isErr()) {
- return LoadErrors.MISSING;
- }
-
- const url = URL.createObjectURL(blobResult.value);
- setUrl(url);
- setError();
-
- if (props.node.type === 'image') {
- const img = new Image();
- img.src = url;
- img.onload = () => {
- setOriginalSize({ width: img.width, height: img.height });
- };
- } else if (props.node.type === 'video') {
- const video = document.createElement('video');
- video.src = url;
- video.oncanplay = () => {
- setOriginalSize({
- width: video.videoWidth,
- height: video.videoHeight,
- });
- };
- }
- } else if (props.node.status === 'static') {
- // Get from sfs
- const imageUrl = () => {
- return staticFileIdEndpoint(props.node.uuid);
- };
- setUrl(imageUrl());
- const img = new Image();
- img.src = props.node.uuid;
- img.onload = () => {
- setOriginalSize({ width: img.width, height: img.height });
- };
-
- setError();
- } else if (props.node.status === 'loading') {
- // temporarily load from blob
- setUrl(props.node.uuid);
- const img = new Image();
- img.src = props.node.uuid;
- img.onload = () => {
- setOriginalSize({ width: img.width, height: img.height });
- };
- setError();
- }
- });
-
- const updateSize = createReaction(() => {
- const canvasWidth = currentSize().x / 2 / currentScale();
- const canvasHeight = currentSize().y / 2 / currentScale();
-
- if (props.mode === RenderModes.Preview) return;
- if (props.node.width !== 0 && props.node.height !== 0) return;
- else if (!originalSize()) return;
- else {
- const width = originalSize()!.width;
- const height = originalSize()!.height;
- if (width < canvasWidth && height < canvasHeight) {
- return updateNode(props.node.id, {
- width,
- height,
- x: props.node.x - width / 2,
- y: props.node.y - height / 2,
- flipX: false,
- flipY: false,
- });
- } else {
- const widthRatio = width / canvasWidth;
- const heightRatio = height / canvasHeight;
- if (widthRatio <= heightRatio) {
- updateNode(props.node.id, {
- width: canvasWidth,
- height: height / widthRatio,
- x: props.node.x - canvasWidth / 2,
- y: props.node.y - height / widthRatio / 2,
- flipX: false,
- flipY: false,
- });
- } else if (heightRatio < widthRatio) {
- updateNode(props.node.id, {
- width: width / heightRatio,
- height: canvasHeight,
- x: props.node.x - width / heightRatio / 2,
- y: props.node.y - canvasHeight / 2,
- flipX: false,
- flipY: false,
- });
- }
- }
- }
- });
- updateSize(() => originalSize());
-
- const size = () => ({
- width: clamp(40 / currentScale(), 4, 100) + 'px',
- height: clamp(40 / currentScale(), 4, 100) + 'px',
- padding: 10 / currentScale() + 'px',
- });
- const renderMedia = () => {
- if (props.node.type === 'image') {
- return (
- <img
- src={url()}
- style={{
- ...imageFlip(),
- width: props.node.width + 'px',
- height: props.node.height + 'px',
- }}
- alt={''}
- />
- );
- } else if (props.node.type === 'video') {
- const controlIcon = videoIsPlaying() ? (
- <PauseIcon class="size-full" />
- ) : (
- <PlayIcon class="size-full" />
- );
- return (
- <div
- class="relative size-full pointer-events-auto"
- style={{
- width: props.node.width + 'px',
- height: props.node.height + 'px',
- }}
- onMouseEnter={() => {
- setHoveringOverVideo(() => true);
- }}
- onMouseLeave={() => {
- setHoveringOverVideo(() => false);
- }}
- >
- {
- // TODO: pull out as renderPlayControls()
- (hoveringOverVideo() || !videoIsPlaying()) && (
- <div class="absolute top-1/2 left-1/2 -translate-1/2 z-10 flex pointer-events-auto cursor-auto">
- <div
- onPointerDown={handleVideoRewind}
- class="text-surface bg-edge rounded-full flex items-center justify-center"
- style={{
- 'margin-right': 10 / currentScale() + 'px',
- ...size(),
- }}
- >
- <ArrowCounterClockwise class="size-full" style={{}} />
- </div>
- <div
- onPointerDown={handleVideoClick}
- class="text-surface bg-edge rounded-full flex items-center justify-center"
- style={size()}
- >
- {controlIcon}
- </div>
- </div>
- )
- }
-
- <video
- ref={videoRef}
- style={{
- width: '100%',
- height: '100%',
- 'object-fit': 'fill',
- ...imageFlip(),
- }}
- src={url()}
- controls={false}
- onplay={() => {
- setShowVideoControls(() => true);
- }}
- onpause={() => {
- setShowVideoControls(() => false);
- }}
- loop
- />
- </div>
- );
- }
- };
-
- return (
- <BaseCanvasRectangle
- node={props.node}
- mode={props.mode}
- clickable={true}
- useSimpleSelectionBox={false}
- >
- <div
- class="size-full overflow-hidden"
- style={{
- 'border-radius': getBorderRadius(props.node),
- 'border-color':
- props.node.style?.fillColor === 'transparent'
- ? 'transparent'
- : (props.node.style?.strokeColor ?? 'transparent'),
- 'border-width': `${props.node.style?.strokeWidth ?? 2}px`,
- 'border-style': 'solid',
- }}
- >
- <Show
- when={!error()}
- fallback={
- <ErrorMessage
- error={error()}
- node={props.node}
- size={{ width: props.node.width, height: props.node.height }}
- />
- }
- >
- {renderMedia()}
- </Show>
- </div>
- </BaseCanvasRectangle>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/nodes/EntityMention.tsx b/apps/web/src/features/block-canvas/component/nodes/EntityMention.tsx
deleted file mode 100644
index c5d9147b3b..0000000000
--- a/apps/web/src/features/block-canvas/component/nodes/EntityMention.tsx
+++ /dev/null
@@ -1,260 +0,0 @@
-import { useToolManager } from '@block-canvas/signal/toolManager';
-import { useRenderState } from '@block-canvas/store/RenderState';
-import { useSplitLayout } from '@components/app/split-layout/layout';
-import type { BlockName } from '@core/block';
-import { CircleSpinner } from '@core/component/CircleSpinner';
-import { PopupPreview } from '@core/component/DocumentPreview';
-import { EntityIcon, getPreviewItemIconType } from '@core/component/EntityIcon';
-import { HoverCard } from '@core/component/HoverCard';
-import { itemToBlockName } from '@core/constant/allBlocks';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { matches } from '@core/util/match';
-import LockKey from '@phosphor-icons/core/regular/lock-key.svg';
-import Question from '@phosphor-icons/core/regular/question.svg';
-import { type PreviewItemNoAccess, useItemPreview } from '@queries/preview';
-import {
- createEffect,
- createMemo,
- createSignal,
- Match,
- Show,
- Switch,
-} from 'solid-js';
-import { DRAG_THRESHOLD, type RenderMode, Tools } from '../../constants';
-import { useCanvasDocument } from '../../context/canvas-document-context';
-import type { EntityMentionNode } from '../../model/CanvasModel';
-import { fileWidth } from '../../operation/file';
-import { type Vector2, vec2 } from '../../util/vector2';
-import { BaseCanvasRectangle } from './BaseCanvasRectangle';
-
-function ErrorMessage(props: {
- node: EntityMentionNode;
- error: 'UNAUTHORIZED' | 'MISSING' | 'INVALID' | 'LOADING' | undefined;
-}) {
- const { currentScale } = useRenderState();
- return (
- <div
- class="size-full bg-surface/40 rounded border border-dashed border-edge"
- style={{
- 'font-size': 12 * (props.node.width / fileWidth) + 'px',
- 'background-size':
- 15 / currentScale() + 'px ' + 15 / currentScale() + 'px',
- 'background-blend-mode': 'lighten',
- 'background-image':
- props.error === 'LOADING'
- ? 'none'
- : 'linear-gradient(-45deg, transparent 10%, var(--color-gray-100) 10%, var(--color-gray-100) 20%, transparent 10%, transparent 60%, var(--color-gray-100) 60%, var(--color-gray-100) 70%, transparent 70%, transparent)',
- }}
- >
- <Switch>
- <Match when={props.error === 'UNAUTHORIZED'}>
- <div class="size-full flex flex-row items-center">
- <LockKey
- width={18 * (props.node.width / fileWidth) + 'px'}
- class="mx-1 fill-failure bg-surface rounded-full"
- />
- Unauthorized: Invalid file permissions
- </div>
- </Match>
- <Match when={props.error === 'MISSING'}>
- <div class="size-full flex flex-row items-center px-2">
- <Question
- width={18 * (props.node.width / fileWidth) + 'px'}
- class="mx-1 fill-ink-extra-muted bg-surface rounded-full"
- />
- Error: Missing file
- </div>
- </Match>
- <Match when={props.error === 'INVALID'}>
- <div class="size-full flex flex-row items-center px-2">
- <Question
- width={18 * (props.node.width / fileWidth) + 'px'}
- class="mx-1 fill-ink-extra-muted bg-surface rounded-full"
- />
- Error: Invalid file
- </div>
- </Match>
- <Match when={props.error === 'LOADING'}>
- <div class="size-full flex items-center justify-center">
- <CircleSpinner />
- </div>
- </Match>
- </Switch>
- </div>
- );
-}
-
-export function File(props: { node: EntityMentionNode; mode: RenderMode }) {
- const [fileRef, setFileRef] = createSignal<HTMLDivElement>();
-
- const [error, setError] = createSignal<
- 'UNAUTHORIZED' | 'MISSING' | 'INVALID' | 'LOADING' | undefined
- >('LOADING');
-
- const blockId = useCanvasDocument().documentId();
-
- const { openWithSplit } = useSplitLayout();
-
- const [selfMouseDownPosition, setSelfMouseDownPosition] =
- createSignal<Vector2>();
-
- const [item] = useItemPreview(() => ({
- id: props.node.file,
- type: props.node.entityType,
- }));
-
- createEffect(() => {
- const currentItem = item();
- if (currentItem.loading) {
- setError('LOADING');
- return;
- }
- if ((currentItem as PreviewItemNoAccess).access === 'no_access') {
- setError('UNAUTHORIZED');
- return;
- }
- if (currentItem.access === 'does_not_exist') {
- setError('MISSING');
- return;
- }
- if (currentItem.access === 'access') {
- setError();
- }
- });
-
- const iconType = createMemo(() => {
- return getPreviewItemIconType(item());
- });
-
- const fileName = createMemo(() => {
- const currentItem = item();
- if (
- !currentItem ||
- currentItem.loading ||
- currentItem.access !== 'access'
- ) {
- return '';
- }
- return currentItem.name;
- });
-
- const blockName = createMemo(() => {
- const currentItem = item();
- if (
- !currentItem ||
- currentItem.loading ||
- currentItem.access !== 'access'
- ) {
- return undefined;
- }
- return itemToBlockName(currentItem);
- });
-
- const { selectedTool, mouseIsDown, activeTool } = useToolManager();
-
- const hoverDisabled = createMemo(
- () => isTouchDevice() || mouseIsDown() || selectedTool() === Tools.Line
- );
-
- return (
- <Show when={blockName()}>
- {(name) => (
- <HoverCard
- anchorRef={fileRef()}
- trigger={
- <div
- class="document-mention internal-link"
- on:pointerdown={(e) => {
- setSelfMouseDownPosition(vec2(e.pageX, e.pageY));
- }}
- on:click={(e) => {
- if (
- activeTool() !== Tools.Select &&
- activeTool() !== Tools.Grab
- ) {
- return;
- }
- const pos = selfMouseDownPosition();
- if (
- pos &&
- pos.distance(vec2(e.pageX, e.pageY)) > DRAG_THRESHOLD
- ) {
- return;
- }
- e.stopPropagation();
- if (
- matches(item(), (i) => !i.loading && i.access === 'access')
- ) {
- openWithSplit(
- {
- type: blockName() as BlockName,
- id: props.node.file,
- },
- { activate: true, preferNewSplit: e.shiftKey }
- );
- }
- }}
- >
- <BaseCanvasRectangle
- node={props.node}
- mode={props.mode}
- clickable={true}
- useSimpleSelectionBox={true}
- >
- <Show
- when={!error()}
- fallback={<ErrorMessage error={error()} node={props.node} />}
- >
- <div
- ref={setFileRef}
- class="size-full bg-surface rounded-lg shadow-md flex items-center"
- >
- <div class="flex flex-row p-2 truncate">
- <div
- class="font-semibold text-sm"
- style={{
- 'font-size':
- 12 * (props.node.width / fileWidth) + 'px',
- }}
- >
- <div class="flex flex-row items-center">
- <div
- style={{
- 'margin-left':
- 2 * (props.node.width / fileWidth) + 'px',
- 'margin-right':
- 2 * (props.node.width / fileWidth) + 'px',
- width: 18 * (props.node.width / fileWidth) + 'px',
- height:
- 18 * (props.node.width / fileWidth) + 'px',
- }}
- >
- <EntityIcon targetType={iconType()} size={'fill'} />
- </div>
- {fileName()}
- </div>
- </div>
- </div>
- </div>
- </Show>
- </BaseCanvasRectangle>
- </div>
- }
- content={
- <PopupPreview
- mouseEnter={() => {}}
- mouseLeave={() => {}}
- documentInfo={{
- id: props.node.file,
- type: name() as BlockName,
- params: {},
- isOpenable: blockId !== props.node.file,
- }}
- />
- }
- disabled={hoverDisabled()}
- />
- )}
- </Show>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/nodes/Pencil.tsx b/apps/web/src/features/block-canvas/component/nodes/Pencil.tsx
deleted file mode 100644
index 21587846d0..0000000000
--- a/apps/web/src/features/block-canvas/component/nodes/Pencil.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-import {
- createMemo,
- createSignal,
- type JSX,
- onCleanup,
- onMount,
- useContext,
-} from 'solid-js';
-import { Portal } from 'solid-js/web';
-import {
- DRAG_THRESHOLD,
- type RenderMode,
- RenderModes,
- Tools,
-} from '../../constants';
-import type { PencilNode } from '../../model/CanvasModel';
-import { useMove } from '../../operation/move';
-import { useSelect } from '../../operation/select';
-import { useSelection } from '../../signal/selection';
-import { useToolManager } from '../../signal/toolManager';
-import { useRenderState } from '../../store/RenderState';
-import { getTailwindColor } from '../../util/style';
-import { type Vector2, vec2 } from '../../util/vector2';
-import { LayerContext } from '../LayerContext';
-
-export function Pencil(props: { node: PencilNode; mode: RenderMode }) {
- const layerContext = useContext(LayerContext);
- const { selectNode, isSelected, deselectAll } = useSelection();
- const { setSelectedTool, activeTool } = useToolManager();
- const move = useMove();
- const select = useSelect();
- const { currentScale } = useRenderState();
-
- const [dragStartPos, setDragStartPos] = createSignal<Vector2>();
- const [dragActive, setDragActive] = createSignal(false);
-
- const pointerdown = (e: PointerEvent) => {
- if (activeTool() !== Tools.Select) return;
- setDragStartPos(vec2(e.pageX, e.pageY));
- setDragActive(false);
- e.stopPropagation();
-
- if (!e.shiftKey && !isSelected(props.node.id)) {
- deselectAll();
- }
- select.abort();
- selectNode(props.node.id);
- };
-
- const pointermove = (e: PointerEvent) => {
- if (dragActive()) return;
- const pos = dragStartPos();
- if (pos === undefined) return;
- if (isSelected(props.node.id) && dragStartPos() !== undefined) {
- if (pos.distance(vec2(e.pageX, e.pageY)) > DRAG_THRESHOLD) {
- select.abort();
- setSelectedTool(Tools.Move);
- move.start(e);
- setDragActive(true);
- }
- }
- };
-
- const pointerup = () => {
- setDragStartPos();
- setDragActive(false);
- };
-
- onMount(() => {
- document.addEventListener('pointermove', pointermove);
- document.addEventListener('pointerup', pointerup);
- });
-
- onCleanup(() => {
- document.removeEventListener('pointermove', pointermove);
- document.removeEventListener('pointerup', pointerup);
- });
-
- const x = createMemo(() => props.node.x ?? 0);
- const y = createMemo(() => props.node.y ?? 0);
- const wScale = createMemo(() => props.node.wScale ?? 1);
- const hScale = createMemo(() => props.node.hScale ?? 1);
-
- const pathStyle = createMemo(
- (): Partial<JSX.SvgSVGAttributes<SVGPathElement>> => {
- const fallbackColor = getTailwindColor('gray-700');
- const strokeColor = props.node.style?.strokeColor ?? fallbackColor;
-
- const strokeWidth =
- props.mode === RenderModes.Selection
- ? 1 / currentScale()
- : (props.node.style?.strokeWidth ?? 2);
-
- return {
- stroke: strokeColor,
- 'stroke-width': `${strokeWidth}px`,
- };
- }
- );
- const selectedPathStyle = createMemo(
- (): Partial<JSX.SvgSVGAttributes<SVGPathElement>> => {
- const strokeColor =
- props.mode === RenderModes.Preview
- ? 'transparent'
- : getTailwindColor('sky-500');
- const strokeWidth = 1 / currentScale();
- return {
- stroke: strokeColor,
- 'stroke-width': `${strokeWidth}px`,
- };
- }
- );
-
- const path = createMemo(() => {
- const points = props.node.coords;
- if (!points?.length) return '';
-
- // Start with move command
- let d = `M ${points[0].join(' ')}`;
-
- // For n points, we can make n-1 curves
- for (let i = 1; i < points.length - 1; i++) {
- const [x0, y0] = points[i];
- const [x1, y1] = points[i + 1];
- d += ` Q ${x0} ${y0}, ${(x0 + x1) / 2} ${(y0 + y1) / 2}`;
- }
-
- // Draw the final segment if we have more than one point
- if (points.length > 1) {
- const lastPoint = points[points.length - 1];
- d += ` L ${lastPoint.join(' ')}`;
- }
-
- return d;
- });
-
- return (
- <>
- <div class="absolute top-0 left-0" onPointerDown={pointerdown}>
- <svg width="10px" height="10px" class="overflow-visible">
- <g
- transform={`translate(${x()} ${y()}) scale(${wScale()} ${hScale()})`}
- >
- {/* render a thick but transparent line for easier mouse selection */}
- <path
- d={path()}
- stroke-width={20 / currentScale()}
- stroke={'transparent'}
- stroke-linecap="round"
- stroke-linejoin="round"
- vector-effect="non-scaling-stroke"
- fill="none"
- />
- {/* Main visible Path */}
- <path
- d={path()}
- stroke-width={pathStyle()['stroke-width']}
- stroke={pathStyle()['stroke']}
- stroke-linecap="round"
- stroke-linejoin="round"
- vector-effect="non-scaling-stroke"
- fill="none"
- />
- </g>
- </svg>
- </div>
- <Portal mount={layerContext().selection}>
- <div class="absolute top-0 left-0">
- <svg width="10px" height="10px" class="overflow-visible">
- <g
- transform={`translate(${x()} ${y()}) scale(${wScale()} ${hScale()})`}
- >
- <path
- d={path()}
- stroke-width={selectedPathStyle()['stroke-width']}
- stroke={selectedPathStyle()['stroke']}
- stroke-linecap="round"
- stroke-linejoin="round"
- vector-effect="non-scaling-stroke"
- fill="none"
- visibility={isSelected(props.node.id) ? 'visible' : 'hidden'}
- />
- </g>
- </svg>
- </div>
- </Portal>
- </>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/nodes/Shape.tsx b/apps/web/src/features/block-canvas/component/nodes/Shape.tsx
deleted file mode 100644
index a0e8d84b39..0000000000
--- a/apps/web/src/features/block-canvas/component/nodes/Shape.tsx
+++ /dev/null
@@ -1,228 +0,0 @@
-import { useToolManager } from '@block-canvas/signal/toolManager';
-import { useUpdateNode } from '@block-canvas/store/canvasData';
-import {
- createEffect,
- createMemo,
- createSignal,
- type JSX,
- Match,
- onCleanup,
- onMount,
- type Setter,
- Show,
- Switch,
-} from 'solid-js';
-import { type RenderMode, RenderModes } from '../../constants';
-import { useCanvasDocument } from '../../context/canvas-document-context';
-import type { ShapeNode, ShapeType } from '../../model/CanvasModel';
-import type { Color } from '../../util/color';
-import { getBorderRadius, getTailwindColor, opacity } from '../../util/style';
-import { BaseCanvasRectangle } from './BaseCanvasRectangle';
-
-const selectEnd = (target: HTMLElement) => {
- const range = document.createRange();
- const selection = window.getSelection();
- range.setStart(target, target.childNodes.length);
- range.collapse(true);
- selection?.removeAllRanges();
- selection?.addRange(range);
-};
-
-function Label(props: {
- node: ShapeNode;
- setRef: Setter<HTMLSpanElement | undefined>;
- onFocus?: (value: string) => void;
- onBlur?: (value: string) => void;
-}) {
- const canEdit = useCanvasDocument().canEdit;
- const toolManager = useToolManager();
- let labelRef!: HTMLSpanElement;
- const [hasFocus, setHasFocus] = createSignal(false);
-
- const labelStyle = createMemo((): Partial<JSX.CSSProperties> => {
- const color = props.node.style?.strokeColor ?? getTailwindColor('gray-700');
- return {
- color: color,
- 'font-size': `${props.node.style?.textSize ?? 12}px`,
- 'caret-color': color,
- };
- });
-
- createEffect(() => {
- if (!hasFocus() && labelRef.textContent !== props.node.label) {
- labelRef.textContent = props.node.label || '';
- }
- });
-
- onMount(() => {
- props.setRef(labelRef);
- toolManager.ignoreMouseEvents(labelRef);
- });
-
- onCleanup(() => {
- toolManager.removeIgnoreMouseEvents(labelRef);
- });
-
- const handleFocus = () => {
- props.onFocus?.(labelRef.textContent || '');
- toolManager.setActiveTextEditor(true);
- setHasFocus(true);
- };
- const handleBlur = () => {
- props.onBlur?.(labelRef.textContent || '');
- getSelection()?.empty();
- labelRef.textContent = '';
- toolManager.setActiveTextEditor(false);
- setHasFocus(false);
- };
-
- const handleKeyDown = (e: KeyboardEvent) => {
- e.stopPropagation();
- if (e.key === 'Enter') {
- e.preventDefault();
- labelRef.blur();
- } else if (e.key === 'Escape') {
- e.preventDefault();
- labelRef.blur();
- }
- };
-
- return (
- <div
- class="absolute top-0 left-0 size-full flex items-center justify-center overflow-clip"
- classList={{
- 'select-none': !hasFocus(),
- 'pointer-events-auto': hasFocus(),
- }}
- >
- <span
- ref={labelRef}
- class="text-center font-semibold break-all min-w-0 max-w-[calc(100%-2rem)]"
- style={labelStyle()}
- contentEditable={canEdit()}
- on:focus={handleFocus}
- on:blur={handleBlur}
- on:keydown={handleKeyDown}
- ></span>
- </div>
- );
-}
-
-function RectanglePrimitive(props: { style: Partial<JSX.CSSProperties> }) {
- return <div style={props.style} />;
-}
-
-function EllipsePrimitive(props: { style: any; node: ShapeNode }) {
- return (
- <svg width={props.node.width} height={props.node.height}>
- <ellipse style={props.style} />
- </svg>
- );
-}
-
-function RenderPrimitive(props: {
- shapeType: ShapeType;
- shapeStyle: Partial<JSX.CSSProperties>;
- node: ShapeNode;
-}) {
- return (
- <Switch>
- <Match when={props.shapeType === 'rectangle'}>
- <RectanglePrimitive style={props.shapeStyle} />
- </Match>
- <Match when={props.shapeType === 'ellipse'}>
- <EllipsePrimitive style={props.shapeStyle} node={props.node} />
- </Match>
- </Switch>
- );
-}
-
-export function Shape(props: { node: ShapeNode; mode: RenderMode }) {
- const updateNode = useUpdateNode();
- const [labelRef, setLabelRef] = createSignal<HTMLSpanElement>();
- const [labelHasFocus, setLabelHasFocus] = createSignal(false);
-
- const strokeWidth = props.node.style?.strokeWidth || 0;
- const borderRadiusWidthPct = (strokeWidth / props.node.width) * 100;
- const borderRadiusHeightPct = (strokeWidth / props.node.height) * 100;
-
- const shapeStyle = createMemo((): any => {
- const fillHex = props.node.style?.fillColor ?? getTailwindColor('gray-200');
- const fillHexWithOpacity = opacity(
- fillHex as Color,
- props.mode === RenderModes.Preview ? 20 : 80
- );
- let borderHex =
- props.node.style?.strokeColor ?? getTailwindColor('gray-700');
-
- return {
- fill: fillHexWithOpacity,
- stroke: borderHex,
- 'stroke-width': props.node.style?.strokeWidth,
- 'background-color': fillHexWithOpacity,
- 'border-color': borderHex,
- 'border-width': `${props.node.style?.strokeWidth ?? 2}px`,
- 'border-style': 'solid',
- 'border-radius': `${getBorderRadius(props.node)}`,
- 'box-sizing': 'border-box',
- width: '100%',
- height: '100%',
- cx: '50%',
- cy: '50%',
- rx: `${50 - borderRadiusWidthPct}%`,
- ry: `${50 - borderRadiusHeightPct}%`,
- };
- });
-
- const handleDblClick = (e: MouseEvent) => {
- e.stopPropagation();
- if (!props.node.label) {
- updateNode(props.node.id, {
- label: '',
- });
- }
- const ref = labelRef();
- if (ref) {
- ref.focus();
- selectEnd(ref);
- }
- };
-
- return (
- <BaseCanvasRectangle
- node={props.node}
- mode={props.mode}
- clickable={!labelHasFocus()}
- useSimpleSelectionBox={false}
- >
- <div
- class="size-full"
- classList={{
- 'pointer-events-auto': !labelHasFocus(),
- }}
- on:dblclick={handleDblClick}
- >
- <RenderPrimitive
- shapeType={props.node.shape}
- shapeStyle={shapeStyle()}
- node={props.node}
- />
- </div>
- <Show when={props.node.label !== undefined}>
- <Label
- node={props.node}
- setRef={setLabelRef}
- onFocus={() => {
- setLabelHasFocus(true);
- }}
- onBlur={(str) => {
- updateNode(props.node.id, {
- label: str,
- });
- setLabelHasFocus(false);
- }}
- />
- </Show>
- </BaseCanvasRectangle>
- );
-}
diff --git a/apps/web/src/features/block-canvas/component/nodes/TextBox.tsx b/apps/web/src/features/block-canvas/component/nodes/TextBox.tsx
deleted file mode 100644
index ce86bab7c2..0000000000
--- a/apps/web/src/features/block-canvas/component/nodes/TextBox.tsx
+++ /dev/null
@@ -1,425 +0,0 @@
-import { type Vector2, vec2 } from '@block-canvas/util/vector2';
-import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';
-import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
-import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';
-import { NodeAccessoryRenderer } from '@core/component/LexicalMarkdown/component/core/NodeAccessoryRenderer';
-import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';
-import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu';
-import { SnippetsMenu } from '@core/component/LexicalMarkdown/component/menu/SnippetsMenu';
-import { LexicalWrapperContext } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
-import {
- DefaultShortcuts,
- keyboardShortcutsPlugin,
-} from '@core/component/LexicalMarkdown/plugins';
-import clickOutside from '@core/directive/clickOutside';
-import {
- $getRoot,
- $setSelection,
- COMMAND_PRIORITY_LOW,
- KEY_ESCAPE_COMMAND,
- type LexicalEditor,
-} from 'lexical';
-import {
- type Accessor,
- batch,
- createEffect,
- createMemo,
- createSignal,
- type JSX,
- onCleanup,
- onMount,
- type Setter,
- Show,
- untrack,
-} from 'solid-js';
-import {
- DRAG_THRESHOLD,
- type RenderMode,
- RenderModes,
- type Tool,
- Tools,
-} from '../../constants';
-import { useCanvasDocument } from '../../context/canvas-document-context';
-import type { TextNode } from '../../model/CanvasModel';
-import { useCanvasHistory } from '../../signal/canvasHistory';
-import { useSelection } from '../../signal/selection';
-import { useToolManager } from '../../signal/toolManager';
-import { useCanvasNodes } from '../../store/canvasData';
-import { useTextNodeEditors } from '../../store/textNodeEditors';
-import { getTailwindColor } from '../../util/style';
-import { BaseCanvasRectangle } from './BaseCanvasRectangle';
-
-false && clickOutside;
-
-function TextBoxEditor(props: {
- node: TextNode;
- editable: Accessor<boolean>;
- setter: Setter<LexicalEditor | undefined>;
- onFocus?: () => void;
- onBlur?: () => void;
- onTextChange?: (value: string) => void;
- onHeightChange?: (height: number) => void;
- onWidthChange?: (width: number) => void;
- focusOnMount?: boolean;
- blockId?: string;
-}) {
- const { registerEditor, unregisterEditor } = useTextNodeEditors();
- const canvas = useCanvasDocument();
- const canEdit = canvas.canEdit;
- const useBlockBoundary = () => canvas.portalScope() === 'block';
- let mountRef!: HTMLDivElement;
-
- const toolManager = useToolManager();
-
- const config = buildConfig('markdown')
- .withAppLinkResolver(useMacroMentionLinkResolver())
- .namespace('canvas-text-box')
- .withHistory({ timeGap: 400 })
- .withEmojis()
- .withMentions({ sourceDocumentId: props.blockId })
- .withCode()
- .use((editor) => {
- return editor.registerCommand(
- KEY_ESCAPE_COMMAND,
- () => {
- editor.getRootElement()?.blur();
- return true;
- },
- COMMAND_PRIORITY_LOW
- );
- })
- .use(
- keyboardShortcutsPlugin({
- shortcuts: DefaultShortcuts,
- })
- );
-
- const handle = config.buildHandle();
- const { lexical: editor, plugins } = handle;
- const state = handle._internal;
- props.setter(editor);
-
- createEffect(() => state.setIsInteractable(canEdit() ?? false));
-
- const resizeObserver = new ResizeObserver((entries) => {
- const height = entries[0].borderBoxSize[0].blockSize;
- const width = entries[0].borderBoxSize[0].inlineSize;
- props.onHeightChange && props.onHeightChange(height);
- props.onWidthChange && props.onWidthChange(width);
- });
-
- onMount(() => {
- resizeObserver.observe(mountRef, { box: 'border-box' });
- editor.setRootElement(mountRef);
- if (props.focusOnMount) {
- setTimeout(() => editor.focus());
- }
- // Register the editor for this text node
- registerEditor(props.node.id, editor);
- });
-
- const text = () => props.node.text;
-
- // TODO: trim text?
- if (text() && text() !== '') {
- handle.controls.setMarkdown(text());
- } else {
- handle.controls.clear();
- }
-
- onCleanup(() => {
- // Unregister the editor before cleanup
- unregisterEditor(props.node.id);
- editor.setRootElement(null);
- resizeObserver.disconnect();
- state.cleanupLexical();
- });
-
- const textwrapStyles = () => {
- return {
- 'white-space': props.node.followTextWidth ? 'pre' : 'pre-wrap',
- width: props.node.followTextWidth ? 'max-content' : '100%',
- };
- };
-
- plugins.useReactive(
- () => props.focusOnMount,
- () => {
- if (props.focusOnMount) {
- return (editor) => {
- return editor.registerRootListener((root) => {
- if (root === null) return;
- Object.assign(root.style, textwrapStyles());
- });
- };
- }
- }
- );
-
- createEffect(() => {
- const val = state.markdownState();
- if (props.editable()) {
- props.onTextChange?.(val);
- }
- });
-
- createEffect(() => {
- const val = text();
- if (val && val !== untrack(state.markdownState)) {
- handle.controls.setMarkdown(val);
- }
- });
-
- onMount(() => {
- // Lexical sets user-select in its mount so we have to set it again.
- mountRef.style.userSelect = props.editable() ? 'text' : 'none';
- });
-
- return (
- <LexicalWrapperContext.Provider value={state.lexicalWrapper}>
- <div
- class="w-full absolute m-0 top-0 left-0"
- classList={{
- 'bg-edge': props.editable(),
- }}
- style={{
- ...textwrapStyles(),
- 'pointer-events': props.editable() ? 'auto' : 'none',
- 'user-select': props.editable() ? 'text' : 'none',
- }}
- ref={mountRef}
- onfocus={() => {
- props.onFocus?.();
- }}
- onblur={() => {
- editor.update(() => $setSelection(null));
- props.onBlur?.();
- }}
- onmousedown={(e) => {
- e.stopPropagation();
- toolManager.setSelectedTool(Tools.Typing);
- }}
- ontouchstart={(e) => {
- e.stopPropagation();
- toolManager.setSelectedTool(Tools.Typing);
- }}
- onkeydown={() => {
- toolManager.setSelectedTool(Tools.Typing);
- }}
- contentEditable={props.editable()}
- />
- <MentionsMenu
- editor={editor}
- menu={state.mentionsMenuOps!}
- useBlockBoundary={useBlockBoundary()}
- portalScope={canvas.portalScope()}
- />
- <EmojiMenu
- editor={editor}
- menu={state.emojisMenuOps!}
- useBlockBoundary={useBlockBoundary()}
- portalScope={canvas.portalScope()}
- />
- <Show when={state.snippetsMenuOps}>
- {(menu) => (
- <SnippetsMenu
- editor={editor}
- menu={menu()}
- useBlockBoundary={useBlockBoundary()}
- portalScope={canvas.portalScope()}
- sourceDocumentId={props.blockId}
- />
- )}
- </Show>
- <DecoratorRenderer editor={editor} />
- <NodeAccessoryRenderer editor={editor} store={state.accessoryStore!} />
- </LexicalWrapperContext.Provider>
- );
-}
-
-export function TextBox(props: { node: TextNode; mode: RenderMode }) {
- const canvas = useCanvasDocument();
- const canEdit = canvas.canEdit;
- const activeTool = useToolManager().activeTool;
- const history = useCanvasHistory();
- const selection = useSelection();
- const nodes = useCanvasNodes();
- const toolManager = useToolManager();
- const blockId = canvas.documentId();
-
- const style = createMemo((): Partial<JSX.CSSProperties> => {
- return {
- color: props.node.style?.strokeColor ?? getTailwindColor('gray-700'),
- 'font-size': `${props.node.style?.textSize ?? 24}px`,
- };
- });
-
- const [editor, setEditor] = createSignal<LexicalEditor>();
-
- let focusOnMount = props.node.id === nodes.lastCreated();
-
- const [editable, setEditable] = createSignal(focusOnMount);
-
- const [selfMouseDownPosition, setSelfMouseDownPosition] =
- createSignal<Vector2 | null>(null);
-
- /* let touchTimer: Timer | null = null;
-
- const touchStart = (e: TouchEvent) => {
- if (touchTimer == null) {
- touchTimer = setTimeout(() => {
- touchTimer = null;
- }, 500);
- } else {
- if (!userCanEdit()) return;
- e.preventDefault();
- e.stopPropagation();
-
- if (activeTool() !== Tools.Select && activeTool() !== Tools.Text) return;
-
- toolManager.abortAll();
-
- setEditable(true);
-
- editor()?.update(() => {
- const root = $getRoot();
- root.selectEnd();
- });
-
- clearTimeout(touchTimer);
- touchTimer = null;
- }
- }; */
-
- const doubleClick = (e: MouseEvent) => {
- if (!canEdit()) return;
- e.stopPropagation();
-
- if (activeTool() !== Tools.Select && activeTool() !== Tools.Text) return;
-
- toolManager.abortAll();
-
- setEditable(true);
-
- editor()?.update(() => {
- const root = $getRoot();
- root.selectEnd();
- });
- };
-
- const onClick = (e: MouseEvent | TouchEvent) => {
- const pos = selfMouseDownPosition();
- const upPos =
- e instanceof MouseEvent
- ? vec2(e.pageX, e.pageY)
- : vec2(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
-
- if (pos && pos.distance(upPos) > DRAG_THRESHOLD) {
- return;
- }
- if (!canEdit()) return;
- if (activeTool() !== Tools.Text) return;
- e.stopPropagation();
- toolManager.abortAll();
- setEditable(true);
- };
-
- const [_lastSelectedTool, setLastSelectedTool] = createSignal<Tool>(
- Tools.Select
- );
-
- const showClickBlocker = createMemo(() => {
- if (toolManager.isDragging()) return true;
- const pos = selfMouseDownPosition();
- if (!pos) return false;
- if (toolManager.mousePosition().distance(pos) > DRAG_THRESHOLD) {
- return true;
- }
- });
-
- return (
- <BaseCanvasRectangle
- node={props.node}
- mode={props.mode}
- showEdgeHandles={false}
- clickable={!editable()}
- useSimpleSelectionBox={true}
- >
- <Show when={props.mode === RenderModes.Basic}>
- <div
- class="size-full absolute top-0 left-0 bg-transparent"
- style={{
- 'pointer-events': 'auto',
- 'user-select': 'none',
- ...style(),
- overflow: 'hidden',
- }}
- on:pointerdown={(e) => {
- setSelfMouseDownPosition(vec2(e.pageX, e.pageY));
- }}
- on:dblclick={doubleClick}
- on:click={onClick}
- //on:touchstart={touchStart}
- on:touchend={onClick}
- on:pointerup={() => {
- setSelfMouseDownPosition(null);
- }}
- >
- <TextBoxEditor
- node={props.node}
- editable={editable}
- setter={setEditor}
- blockId={blockId}
- onFocus={() => {
- setLastSelectedTool(toolManager.selectedTool());
- toolManager.setSelectedTool(Tools.Typing);
- toolManager.setActiveTextEditor(true);
- selection.deselectAll();
- selection.selectNode(props.node.id);
- history.open();
- }}
- onBlur={() => {
- toolManager.setSelectedTool(Tools.Select);
- toolManager.setActiveTextEditor(false);
- setEditable(false);
- batch(() => {
- if (props.node.followTextWidth) {
- nodes.updateNode(props.node.id, { followTextWidth: false });
- }
- if (props.node.text === `\n \n`) {
- // Empty case. See LexicalMarkdown/transformers.ts.
- selection.deselectNode(props.node.id);
- nodes.delete(props.node.id);
- }
- });
- history.close();
- nodes.save();
- nodes.setLastCreated();
- }}
- onTextChange={(val) =>
- nodes.updateNode(props.node.id, { text: val })
- }
- focusOnMount={focusOnMount}
- onHeightChange={(height: number) => {
- nodes.updateNode(props.node.id, { height: height });
- }}
- onWidthChange={(width: number) => {
- if (props.node.followTextWidth) {
- nodes.updateNode(props.node.id, {
- width: Math.min(width + 2, 3000),
- });
- }
- }}
- />
- {/* click blocker */}
- <div
- class="size-full absolute top-0 left-0 invisible"
- classList={{
- visible: showClickBlocker(),
- }}
- />
- </div>
- </Show>
- </BaseCanvasRectangle>
- );
-}
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/arrange-controls.tsx b/apps/web/src/features/block-canvas/components/arrange-controls.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/arrange-controls.tsx
rename to apps/web/src/features/block-canvas/components/arrange-controls.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/connector-inspector.tsx b/apps/web/src/features/block-canvas/components/connector-inspector.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/connector-inspector.tsx
rename to apps/web/src/features/block-canvas/components/connector-inspector.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/connector-style-icon.tsx b/apps/web/src/features/block-canvas/components/connector-style-icon.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/connector-style-icon.tsx
rename to apps/web/src/features/block-canvas/components/connector-style-icon.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/embed-view.ts b/apps/web/src/features/block-canvas/components/embed-view.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/embed-view.ts
rename to apps/web/src/features/block-canvas/components/embed-view.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/eraser-trail.tsx b/apps/web/src/features/block-canvas/components/eraser-trail.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/eraser-trail.tsx
rename to apps/web/src/features/block-canvas/components/eraser-trail.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-color-field.tsx b/apps/web/src/features/block-canvas/components/inspector-color-field.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/inspector-color-field.tsx
rename to apps/web/src/features/block-canvas/components/inspector-color-field.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-control-frame.ts b/apps/web/src/features/block-canvas/components/inspector-control-frame.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/inspector-control-frame.ts
rename to apps/web/src/features/block-canvas/components/inspector-control-frame.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-field.tsx b/apps/web/src/features/block-canvas/components/inspector-field.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/inspector-field.tsx
rename to apps/web/src/features/block-canvas/components/inspector-field.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-number-field.tsx b/apps/web/src/features/block-canvas/components/inspector-number-field.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/inspector-number-field.tsx
rename to apps/web/src/features/block-canvas/components/inspector-number-field.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-section.tsx b/apps/web/src/features/block-canvas/components/inspector-section.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/inspector-section.tsx
rename to apps/web/src/features/block-canvas/components/inspector-section.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-select.tsx b/apps/web/src/features/block-canvas/components/inspector-select.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/inspector-select.tsx
rename to apps/web/src/features/block-canvas/components/inspector-select.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/selection-layout-inspector.tsx b/apps/web/src/features/block-canvas/components/selection-layout-inspector.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/selection-layout-inspector.tsx
rename to apps/web/src/features/block-canvas/components/selection-layout-inspector.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/style-inspector.tsx b/apps/web/src/features/block-canvas/components/style-inspector.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/style-inspector.tsx
rename to apps/web/src/features/block-canvas/components/style-inspector.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/components/text-inspector.tsx b/apps/web/src/features/block-canvas/components/text-inspector.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/components/text-inspector.tsx
rename to apps/web/src/features/block-canvas/components/text-inspector.tsx
diff --git a/apps/web/src/features/block-canvas/constants.ts b/apps/web/src/features/block-canvas/constants.ts
index 2b91c57594..2695878091 100644
--- a/apps/web/src/features/block-canvas/constants.ts
+++ b/apps/web/src/features/block-canvas/constants.ts
@@ -1,102 +1,3 @@
-export const OPERATION_LOGGING = false;
-
-// Padding between nodes and their selection handles
-export const SELECTION_PADDING = 0;
-
-// The size of the handles that appear when a Node is selected.
-export const HANDLE_SIZE = 8;
-
-// The number of screen space pixels the use has to move the mouse before
-// a click type event becomes a drag gesture like move.
-export const DRAG_THRESHOLD = 3;
-
-export const TOOLTIP_FONTSIZE = 14;
-
-// Zoom bounds for the canvas.
-export const MAX_ZOOM = 8;
-export const MIN_ZOOM = 0.05;
-
-// The maximum allowable flick speed when us touch to pan
-export const MAX_PAN_FLICK_SPEED = 300;
-
-// The pre-selected zoom level when interacting with +/- zoom buttons.
-export const ZOOM_TARGETS = [
- 0.05, 0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 5, 6, 8,
-];
-
-export const ARROW_SIZE = 12;
-export const ARROW_OFFSET = 36;
-
-// Export types for UI and rectangle calculations to use.
-export const ReorderOperations = {
- Forward: 'Forward',
- Backward: 'Backward',
- BringToFront: 'BringToFront',
- SendToBack: 'SendToBack',
-} as const;
-
-export type ReorderOperation =
- (typeof ReorderOperations)[keyof typeof ReorderOperations];
-
-export const Corners = {
- TopLeft: 'TopLeft',
- TopRight: 'TopRight',
- BottomRight: 'BottomRight',
- BottomLeft: 'BottomLeft',
-} as const;
-
-export type Corner = (typeof Corners)[keyof typeof Corners];
-
-export const Edges = {
- Top: 'top',
- Right: 'right',
- Bottom: 'bottom',
- Left: 'left',
-} as const;
-
-export type Edge = (typeof Edges)[keyof typeof Edges];
-
-export type Anchor = Corner | Edge;
-
-export const Directions = {
- Up: 'Up',
- Down: 'Down',
- Left: 'Left',
- Right: 'Right',
-} as const;
-
-export type Direction = (typeof Directions)[keyof typeof Directions];
-
-export const RenderModes = {
- Basic: 'Basic',
- Preview: 'Preview',
- Selection: 'Selection',
-} as const;
-
-export type RenderMode = (typeof RenderModes)[keyof typeof RenderModes];
-
-export const Tools = {
- Select: 'Select',
- SelectBox: 'SelectBox',
- Resize: 'Resize',
- Move: 'Move',
- Grab: 'Grab',
- ZoomIn: 'ZoomIn',
- ZoomOut: 'ZoomOut',
- Shape: 'Shape',
- Image: 'Image',
- File: 'File',
- Pencil: 'Pencil',
- Text: 'Text',
- Line: 'Line',
- Typing: 'Typing',
- // TODO: Comment
- // TODO: Crop
-} as const;
-
-export type Tool = (typeof Tools)[keyof typeof Tools];
-export const ViewOnlyTools: Tool[] = [Tools.Grab, Tools.ZoomIn, Tools.ZoomOut];
-
export const URL_PARAMS = {
x: 'canvas_x',
y: 'canvas_y',
diff --git a/apps/web/src/features/block-canvas/canvas-next/context/canvas-ancestry.ts b/apps/web/src/features/block-canvas/context/canvas-ancestry.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/context/canvas-ancestry.ts
rename to apps/web/src/features/block-canvas/context/canvas-ancestry.ts
diff --git a/apps/web/src/features/block-canvas/context/canvas-document-context.tsx b/apps/web/src/features/block-canvas/context/canvas-document-context.tsx
deleted file mode 100644
index bd9d7d295f..0000000000
--- a/apps/web/src/features/block-canvas/context/canvas-document-context.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import type { PortalScope } from '@core/component/ScopedPortal';
-import type { Accessor, FlowComponent, Owner } from 'solid-js';
-import { createContext, getOwner, useContext } from 'solid-js';
-import {
- type CanvasDocumentState,
- createCanvasDocumentState,
-} from './canvas-document-state';
-
-export type CanvasView = {
- x: number;
- y: number;
- scale: number;
-};
-
-export type CanvasDocumentContextValue = {
- documentId: Accessor<string>;
- canEdit: Accessor<boolean>;
- isNested: Accessor<boolean>;
- hotkeyScope: Accessor<string>;
- portalScope: Accessor<PortalScope>;
- onLocationChange: Accessor<((location: CanvasView) => void) | undefined>;
- state: CanvasDocumentState;
- instanceOwner?: Owner;
-};
-
-export type CanvasDocumentProviderProps = {
- documentId: string;
- canEdit: boolean;
- isNested?: boolean;
- hotkeyScope: string;
- portalScope?: PortalScope;
- onLocationChange?: (location: CanvasView) => void;
-};
-
-const CanvasDocumentContext = createContext<CanvasDocumentContextValue>();
-
-const CanvasDocumentOwner: FlowComponent = (props) => {
- const context = useContext(CanvasDocumentContext);
- if (!context) throw new Error('CanvasDocumentOwner requires its provider');
- context.instanceOwner = getOwner() ?? undefined;
- return props.children;
-};
-
-export const CanvasDocumentProvider: FlowComponent<
- CanvasDocumentProviderProps
-> = (props) => {
- const context: CanvasDocumentContextValue = {
- documentId: () => props.documentId,
- canEdit: () => props.canEdit,
- isNested: () => props.isNested ?? false,
- hotkeyScope: () => props.hotkeyScope,
- portalScope: () => props.portalScope ?? 'split',
- onLocationChange: () => props.onLocationChange,
- state: createCanvasDocumentState(),
- };
-
- return (
- <CanvasDocumentContext.Provider value={context}>
- <CanvasDocumentOwner>{props.children}</CanvasDocumentOwner>
- </CanvasDocumentContext.Provider>
- );
-};
-
-export function useCanvasDocument(): CanvasDocumentContextValue {
- const context = useContext(CanvasDocumentContext);
- if (!context) {
- throw new Error(
- 'useCanvasDocument must be used within a CanvasDocumentProvider'
- );
- }
- return context;
-}
diff --git a/apps/web/src/features/block-canvas/context/canvas-document-state.ts b/apps/web/src/features/block-canvas/context/canvas-document-state.ts
deleted file mode 100644
index 8d35349a83..0000000000
--- a/apps/web/src/features/block-canvas/context/canvas-document-state.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { type Tool, Tools } from '@block-canvas/constants';
-import {
- type CanvasEdge,
- type CanvasEntityStyle,
- type CanvasGroup,
- type CanvasId,
- type CanvasNode,
- EdgeConnectionStyles,
-} from '@block-canvas/model/CanvasModel';
-import type { ItemType } from '@service-storage/client';
-import type { LexicalEditor } from 'lexical';
-import { createSignal } from 'solid-js';
-import { createStore } from 'solid-js/store';
-import type { ConnectOperation } from '../operation/connect';
-import type { FileOperation } from '../operation/file';
-import type { ImageOperation } from '../operation/image';
-import type { MoveOperation } from '../operation/move';
-import type { Operator } from '../operation/operation';
-import type { PencilOperation } from '../operation/pencil';
-import type { RescaleOperation } from '../operation/rescale';
-import type { SelectOperation } from '../operation/select';
-import type { ShapeOperation } from '../operation/shape';
-import type { TextOperation } from '../operation/text';
-import type { Snapshot } from '../signal/canvasHistory';
-import type { RenderState } from '../store/RenderState';
-import type { Rectangle } from '../util/rectangle';
-import { getTailwindColor } from '../util/style';
-import type { Vector2 } from '../util/vector2';
-
-export type CanvasAnimationState = {
- startX: number;
- startY: number;
- startScale: number;
- targetX: number;
- targetY: number;
- targetScale: number;
- startTime: number;
- duration: number;
- isAnimating: boolean;
-};
-
-export type CanvasContextMenuState = {
- open: boolean;
- x: number;
- y: number;
- ref?: HTMLDivElement;
- mousePos?: { x: number; y: number };
-};
-
-const defaultStyle = (): CanvasEntityStyle => ({
- fillColor: getTailwindColor('neutral-100'),
- strokeColor: getTailwindColor('neutral-700'),
- strokeWidth: 2,
- cornerRadius: 0,
- opacity: 1,
- textSize: 16,
- connectionStyle: EdgeConnectionStyles.straight,
-});
-
-export function createCanvasDocumentState() {
- return {
- stores: {
- nodes: createStore<Record<CanvasId, CanvasNode>>({}),
- edges: createStore<Record<CanvasId, CanvasEdge>>({}),
- groups: createStore<Record<CanvasId, CanvasGroup>>({}),
- render: createStore<RenderState>({
- x: 0,
- y: 0,
- scale: 1,
- containerRect: undefined,
- }),
- animation: createStore<CanvasAnimationState>({
- startX: 0,
- startY: 0,
- startScale: 1,
- targetX: 0,
- targetY: 0,
- targetScale: 1,
- startTime: 0,
- duration: 0,
- isAnimating: false,
- }),
- cachedStyle: createStore<CanvasEntityStyle>(defaultStyle()),
- contextMenu: createStore<CanvasContextMenuState>({
- open: false,
- x: 0,
- y: 0,
- }),
- textNodeEditors: createStore<Record<string, LexicalEditor>>({}),
- },
- signals: {
- selectedNodeIds: createSignal<Set<string>>(new Set()),
- selectedEdgeIds: createSignal<Set<string>>(new Set()),
- selectedGroupIds: createSignal<Set<string>>(new Set()),
- selectionBox: createSignal<Rectangle>(),
- lastSelectedNodeIds: createSignal<Set<string>>(new Set()),
- lastSelectedEdgeIds: createSignal<Set<string>>(new Set()),
- history: createSignal<Snapshot[]>([]),
- currentHistory: createSignal<Snapshot>(),
- currentHistoryIndex: createSignal(-1),
- highestOrder: createSignal(0),
- lastCreatedNodeId: createSignal<CanvasId>(),
- pendingUpdates: createSignal(false),
- currentSavedFile: createSignal<Blob | null>(null),
- selectedTool: createSignal<Tool>(Tools.Grab),
- handlersByTool: createSignal<Map<Tool, Operator[]>>(new Map()),
- mouseDownPosition: createSignal<Vector2>(),
- mousePosition: createSignal<Vector2>(),
- lastMousePosition: createSignal<Vector2>(),
- rawMouseDownPosition: createSignal<Vector2>(),
- activeTextEditor: createSignal(false),
- middleMousePressed: createSignal<boolean>(),
- canvasDragging: createSignal(false),
- connectorTypeMenuTrigger: createSignal(false),
- currentConnectOperation: createSignal<ConnectOperation>(),
- currentShapeOperation: createSignal<ShapeOperation>(),
- currentRescaleOperation: createSignal<RescaleOperation>(),
- currentPencilOperation: createSignal<PencilOperation>(),
- currentTextOperation: createSignal<TextOperation>(),
- currentMoveOperation: createSignal<MoveOperation>(),
- selectedImage: createSignal<{
- type: 'image' | 'video';
- id: string;
- }>(),
- currentImageOperation: createSignal<ImageOperation>(),
- currentSelectOperation: createSignal<SelectOperation>(),
- selectedFile: createSignal<{
- type?: ItemType;
- id?: string;
- }>({}),
- currentFileOperation: createSignal<FileOperation>(),
- },
- instances: new Map<symbol, unknown>(),
- };
-}
-
-export type CanvasDocumentState = ReturnType<typeof createCanvasDocumentState>;
diff --git a/apps/web/src/features/block-canvas/canvas-next/context/document-source.ts b/apps/web/src/features/block-canvas/context/document-source.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/context/document-source.ts
rename to apps/web/src/features/block-canvas/context/document-source.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/assets.ts b/apps/web/src/features/block-canvas/core/assets.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/assets.ts
rename to apps/web/src/features/block-canvas/core/assets.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/defaults.ts b/apps/web/src/features/block-canvas/core/defaults.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/defaults.ts
rename to apps/web/src/features/block-canvas/core/defaults.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/document-display.ts b/apps/web/src/features/block-canvas/core/document-display.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/document-display.ts
rename to apps/web/src/features/block-canvas/core/document-display.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/document-format.ts b/apps/web/src/features/block-canvas/core/document-format.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/document-format.ts
rename to apps/web/src/features/block-canvas/core/document-format.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/eraser.test.ts b/apps/web/src/features/block-canvas/core/eraser.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/eraser.test.ts
rename to apps/web/src/features/block-canvas/core/eraser.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/eraser.ts b/apps/web/src/features/block-canvas/core/eraser.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/eraser.ts
rename to apps/web/src/features/block-canvas/core/eraser.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/excalidraw.test.ts b/apps/web/src/features/block-canvas/core/excalidraw.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/excalidraw.test.ts
rename to apps/web/src/features/block-canvas/core/excalidraw.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/excalidraw.ts b/apps/web/src/features/block-canvas/core/excalidraw.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/excalidraw.ts
rename to apps/web/src/features/block-canvas/core/excalidraw.ts
diff --git a/apps/web/src/features/block-canvas/model/CanvasModel.ts b/apps/web/src/features/block-canvas/core/legacy-format.ts
similarity index 50%
rename from apps/web/src/features/block-canvas/model/CanvasModel.ts
rename to apps/web/src/features/block-canvas/core/legacy-format.ts
index 90a48c303f..18659f04be 100644
--- a/apps/web/src/features/block-canvas/model/CanvasModel.ts
+++ b/apps/web/src/features/block-canvas/core/legacy-format.ts
@@ -1,29 +1,9 @@
-import { ENABLE_CANVAS_VIDEO } from '@core/constant/featureFlags';
+// Persisted version 1 schema, retained only for file format migration.
import { z } from 'zod';
-
-// For now we are just using strings as node ids.
-// But it's nice to habe a names type for clode clarity
-export type CanvasId = string;
-
-// TODO: The fact that edge style are defined but not used is causing
-// a lot of the ai-gen parse fails. Move a to loose number. This is a
-// hack until we either migrate to Loro or a Zod schema v2.
-const looseNumber = z
- .any()
- .optional()
- .transform((v) => {
- if (typeof v === 'number') return v;
- if (typeof v === 'string' && EDGE_END_STYLES.includes(v as any))
- return EDGE_END_STYLES.indexOf(v as any);
- if (typeof v === 'string' && EDGE_CONNECTION_STYLES.includes(v as any))
- return EDGE_CONNECTION_STYLES.indexOf(v as any);
- const parsedNumber = Number(v);
- if (Number.isNaN(parsedNumber)) return 0;
- return parsedNumber;
- });
+import { isRecord } from './document-format';
// Node Types
-export const NODE_TYPES = [
+const NODE_TYPES = [
'text',
'entitymention',
'link',
@@ -32,62 +12,46 @@ export const NODE_TYPES = [
'image',
'video',
] as const;
-export const NodeTypeSchema = z.enum(NODE_TYPES);
-export type NodeType = (typeof NODE_TYPES)[number];
// Sides for edges
-export const EDGE_SIDES = ['top', 'right', 'bottom', 'left'] as const;
-export const EdgeSideSchema = z.enum(EDGE_SIDES);
-export type EdgeSideType = (typeof EDGE_SIDES)[number];
-export const EdgeSides = {
- Top: 0,
- Right: 1,
- Bottom: 2,
- Left: 3,
-};
+const EDGE_SIDES = ['top', 'right', 'bottom', 'left'] as const;
// Edge endpoint styles
-const EDGE_END_STYLES = [
+const EDGE_END_STYLES: readonly string[] = [
'none',
'arrow',
'arrow-filled',
'circle',
'circle-small',
] as const;
-export const EdgeEndStyleSchema = z.enum(EDGE_END_STYLES);
-export type EdgeEndStyle = (typeof EDGE_END_STYLES)[number];
-export const EdgeEndStyles = {
- None: 0,
- Arrow: 1,
- ArrowFilled: 2,
- Circle: 3,
- CircleSmall: 4,
-} as const;
-export const EDGE_CONNECTION_STYLES = [
+const EDGE_CONNECTION_STYLES: readonly string[] = [
'straight',
'stepped',
'smooth',
] as const;
-export const EdgeConnectionStyleSchema = z.enum(EDGE_CONNECTION_STYLES);
-export type EdgeConnectionStyle = (typeof EDGE_CONNECTION_STYLES)[number];
-export const EdgeConnectionStyles = {
- straight: 0,
- stepped: 1,
- smooth: 2,
-} as const;
const SHAPES = ['rectangle', 'ellipse'] as const;
-export const ShapeSchema = z.enum(SHAPES);
-export type ShapeType = (typeof SHAPES)[number];
const IMAGE_STATUS = ['dss', 'static', 'loading'] as const;
-export const ImageStatusSchema = z.enum(IMAGE_STATUS);
-export type ImageSourcesType = (typeof IMAGE_STATUS)[number];
const VIDEO_STATUS = ['dss', 'static', 'loading'] as const;
-export const VideoStatusSchema = z.enum(VIDEO_STATUS);
-export type VideoSourcesType = (typeof VIDEO_STATUS)[number];
+
+// Historical files use both numeric enum values and string style names.
+const looseNumber = z
+ .unknown()
+ .optional()
+ .transform((value) => {
+ if (typeof value === 'number') return value;
+ if (typeof value === 'string') {
+ const end = EDGE_END_STYLES.indexOf(value);
+ if (end !== -1) return end;
+ const connection = EDGE_CONNECTION_STYLES.indexOf(value);
+ if (connection !== -1) return connection;
+ }
+ const parsed = Number(value);
+ return Number.isNaN(parsed) ? 0 : parsed;
+ });
const hex = z
.string()
@@ -98,7 +62,7 @@ const hexColorSchema = z.literal('transparent').or(hex);
/**
* The bucket of styles that nodes and edges can apply.
*/
-export const StyleSchema = z.object({
+const StyleSchema = z.object({
fillColor: hexColorSchema.optional(),
strokeColor: hexColorSchema.optional(),
strokeWidth: z.number().optional(),
@@ -111,10 +75,8 @@ export const StyleSchema = z.object({
importedColor: z.boolean().optional(),
});
-export type CanvasEntityStyle = z.infer<typeof StyleSchema>;
-
// Generic node schema with common attributes
-export const BaseNodeSchema = z.object({
+const BaseNodeSchema = z.object({
id: z.string(),
groupId: z.string().optional(),
type: z.enum(NODE_TYPES),
@@ -133,17 +95,17 @@ export const BaseNodeSchema = z.object({
// followTextWidth is a flag is set to true the very first time we are typing
// into a text node. Once the node loses focus, the pending width is done
// and text box wraps at the width of the node.
-export const TextNodeSchema = BaseNodeSchema.extend({
+const TextNodeSchema = BaseNodeSchema.extend({
type: z.literal('text'),
text: z.string(),
followTextWidth: z.boolean().optional(),
});
// Entity mention node schema with backward compatibility
-export const EntityMentionSchema = z.preprocess(
- (data: any) => {
+const EntityMentionSchema = z.preprocess(
+ (data) => {
// migrate old schema to new schema
- if (data && typeof data === 'object') {
+ if (isRecord(data)) {
if (data.type === 'file') {
data.type = 'entitymention';
}
@@ -182,17 +144,17 @@ export const EntityMentionSchema = z.preprocess(
);
// Link node schema
-export const LinkNodeSchema = BaseNodeSchema.extend({
+const LinkNodeSchema = BaseNodeSchema.extend({
type: z.literal('link'),
url: z.string().url(),
});
-export const ShapeNodeSchema = BaseNodeSchema.extend({
+const ShapeNodeSchema = BaseNodeSchema.extend({
type: z.literal('shape'),
shape: z.enum(SHAPES).default('rectangle'),
});
-export const ImageNodeSchema = BaseNodeSchema.extend({
+const ImageNodeSchema = BaseNodeSchema.extend({
type: z.literal('image'),
status: z.enum(IMAGE_STATUS).optional().default('dss'),
uuid: z.string(),
@@ -200,7 +162,7 @@ export const ImageNodeSchema = BaseNodeSchema.extend({
flipY: z.boolean().default(false),
});
-export const VideoNodeSchema = BaseNodeSchema.extend({
+const VideoNodeSchema = BaseNodeSchema.extend({
type: z.literal('video'),
status: z.enum(VIDEO_STATUS).optional().default('dss'),
uuid: z.string(),
@@ -208,7 +170,7 @@ export const VideoNodeSchema = BaseNodeSchema.extend({
flipY: z.boolean().default(false),
});
-export const PencilNodeSchema = BaseNodeSchema.extend({
+const PencilNodeSchema = BaseNodeSchema.extend({
type: z.literal('pencil'),
coords: z.tuple([z.number(), z.number()]).array(),
wScale: z.number().default(1),
@@ -216,7 +178,7 @@ export const PencilNodeSchema = BaseNodeSchema.extend({
});
// Union of all node types
-export const NodeSchema = z.union([
+const NodeSchema = z.union([
TextNodeSchema,
EntityMentionSchema,
LinkNodeSchema,
@@ -231,20 +193,17 @@ const ConnectedEnd = z.object({
node: z.string(),
side: z.enum(EDGE_SIDES),
});
-export type ConnectedEnd = z.infer<typeof ConnectedEnd>;
const FreeEnd = z.object({
type: z.literal('free'),
x: z.number(),
y: z.number(),
});
-export type FreeEnd = z.infer<typeof FreeEnd>;
const EdgeEnd = z.union([ConnectedEnd, FreeEnd]);
-export type EdgeEnd = z.infer<typeof EdgeEnd>;
// Edge schema
-export const EdgeSchema = z.object({
+const EdgeSchema = z.object({
id: z.string(),
groupId: z.string().optional(),
from: EdgeEnd,
@@ -256,7 +215,7 @@ export const EdgeSchema = z.object({
});
// Group schema
-export const GroupSchema = z.object({
+const GroupSchema = z.object({
id: z.string(),
childNodes: z.array(z.string()).optional(),
childEdges: z.array(z.string()).optional(),
@@ -271,64 +230,6 @@ export const CanvasSchema = z.object({
groups: z.array(GroupSchema).optional(),
});
-// Inferred Schemas Types
-export type BaseNode = z.infer<typeof BaseNodeSchema>;
-export type TextNode = z.infer<typeof TextNodeSchema>;
-export type EntityMentionNode = z.infer<typeof EntityMentionSchema>;
-export type LinkNode = z.infer<typeof LinkNodeSchema>;
-export type ShapeNode = z.infer<typeof ShapeNodeSchema>;
-export type ImageNode = z.infer<typeof ImageNodeSchema>;
-export type VideoNode = z.infer<typeof VideoNodeSchema>;
-export type PencilNode = z.infer<typeof PencilNodeSchema>;
-export type CanvasNode =
- | BaseNode
- | TextNode
- | EntityMentionNode
- | LinkNode
- | ShapeNode
- | ImageNode
- | VideoNode
- | PencilNode;
-export type CanvasEdge = z.infer<typeof EdgeSchema>;
-export type CanvasGroup = z.infer<typeof GroupSchema>;
export type Canvas = z.infer<typeof CanvasSchema>;
-
-export type CanvasEntity = CanvasNode | CanvasEdge | CanvasGroup;
-
-export const isCanvasNode = (entity: CanvasEntity): entity is CanvasNode => {
- return 'type' in entity;
-};
-
-export const isCanvasEdge = (entity: CanvasEntity): entity is CanvasEdge => {
- return 'to' in entity;
-};
-
-export const isTextNode = (node: CanvasNode): node is TextNode => {
- return node.type === 'text';
-};
-
-export const isEntityMentionNode = (
- node: CanvasNode
-): node is EntityMentionNode => {
- return node.type === 'entitymention';
-};
-
-export const isLinkNode = (node: CanvasNode): node is LinkNode => {
- return node.type === 'link';
-};
-
-export const isShapeNode = (node: CanvasNode): node is ShapeNode => {
- return node.type === 'shape';
-};
-
-export const isImageNode = (node: CanvasNode): node is ImageNode => {
- return node.type === 'image';
-};
-
-export const isVideoNode = (node: CanvasNode): node is VideoNode => {
- return ENABLE_CANVAS_VIDEO && node.type === 'video';
-};
-
-export const isPencilNode = (node: CanvasNode): node is PencilNode => {
- return node.type === 'pencil';
-};
+export type CanvasEntityStyle = z.infer<typeof StyleSchema>;
+export type EdgeEnd = z.infer<typeof EdgeEnd>;
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/load-document.ts b/apps/web/src/features/block-canvas/core/load-document.ts
similarity index 55%
rename from apps/web/src/features/block-canvas/canvas-next/core/load-document.ts
rename to apps/web/src/features/block-canvas/core/load-document.ts
index cd0e33b390..c6f9e368a6 100644
--- a/apps/web/src/features/block-canvas/canvas-next/core/load-document.ts
+++ b/apps/web/src/features/block-canvas/core/load-document.ts
@@ -6,31 +6,18 @@ import {
import { type LegacyTextCodec, migrateLegacyCanvas } from './migrate-legacy';
export type CanvasLoadResult =
- | { kind: 'legacy' }
| { kind: 'next'; file: CanvasFile }
- | { kind: 'error'; message: string; canOpenLegacy: boolean };
+ | { kind: 'error'; message: string };
export function loadCanvasFile(
value: unknown,
- enabled: boolean,
text: LegacyTextCodec
): CanvasLoadResult {
- let version: 1 | 2 | undefined;
try {
- version = canvasVersion(value);
- if (!enabled)
- return version === 1
- ? { kind: 'legacy' }
- : {
- kind: 'error',
- message:
- 'This canvas requires Canvas Next. Enable Canvas Next to open it.',
- canOpenLegacy: false,
- };
return {
kind: 'next',
file:
- version === 2
+ canvasVersion(value) === 2
? readCanvasFile(value)
: migrateLegacyCanvas(value, text),
};
@@ -38,7 +25,6 @@ export function loadCanvasFile(
return {
kind: 'error',
message: error instanceof Error ? error.message : 'Could not open canvas',
- canOpenLegacy: version === 1,
};
}
}
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.test.ts b/apps/web/src/features/block-canvas/core/migrate-legacy.test.ts
similarity index 87%
rename from apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.test.ts
rename to apps/web/src/features/block-canvas/core/migrate-legacy.test.ts
index 191e347278..dfcb586ba7 100644
--- a/apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.test.ts
+++ b/apps/web/src/features/block-canvas/core/migrate-legacy.test.ts
@@ -9,7 +9,6 @@ import { loadCanvasFile } from './load-document';
import { migrateLegacyCanvas } from './migrate-legacy';
import { plainRichText } from './text-codec';
-vi.mock('@core/constant/featureFlags', () => ({ ENABLE_CANVAS_VIDEO: true }));
const shape = (id = 'box', extra = {}) => ({
id,
type: 'shape',
@@ -237,30 +236,38 @@ describe('versioned canvas migration', () => {
});
const updated = { ...file, document: editor.document };
const text = vi.fn();
- expect(
- loadCanvasFile(JSON.parse(JSON.stringify(updated)), true, text)
- ).toEqual({ kind: 'next', file: updated });
+ expect(loadCanvasFile(JSON.parse(JSON.stringify(updated)), text)).toEqual({
+ kind: 'next',
+ file: updated,
+ });
expect(text).not.toHaveBeenCalled();
editor.dispose();
});
it.each([undefined, 1])(
- 'opens legacy version %s unchanged with the flag off',
+ 'opens legacy version %s in the current editor without changing the source',
(version) => {
- const text = vi.fn();
- expect(
- loadCanvasFile({ version, nodes: [shape()] }, false, text)
- ).toEqual({ kind: 'legacy' });
- expect(text).not.toHaveBeenCalled();
+ const source = {
+ version,
+ nodes: [shape('text', { type: 'text', text: '**Hello**' })],
+ };
+ const original = structuredClone(source);
+ const text = vi.fn(plainRichText);
+ const result = loadCanvasFile(source, text);
+ expect(result).toMatchObject({
+ kind: 'next',
+ file: { version: 2, legacy: { source: original } },
+ });
+ expect(text).toHaveBeenCalledWith('**Hello**');
+ expect(source).toEqual(original);
}
);
it.each([2, 3, '2', null])(
- 'protects version %s from the legacy editor',
+ 'rejects invalid or unsupported version %s',
(version) => {
- expect(loadCanvasFile({ version }, false, plainRichText)).toMatchObject({
+ expect(loadCanvasFile({ version }, plainRichText)).toMatchObject({
kind: 'error',
- canOpenLegacy: false,
});
}
);
@@ -279,19 +286,20 @@ describe('versioned canvas migration', () => {
],
},
])(
- 'offers the original legacy editor instead of discarding unsupported records (%j)',
+ 'rejects unsupported records without changing the source (%j)',
(source) => {
- expect(loadCanvasFile(source, true, plainRichText)).toMatchObject({
+ const original = structuredClone(source);
+ expect(loadCanvasFile(source, plainRichText)).toMatchObject({
kind: 'error',
- canOpenLegacy: true,
});
+ expect(source).toEqual(original);
}
);
it('rejects malformed v2 files without a legacy fallback', () => {
expect(
- loadCanvasFile({ version: 2, document: {} }, true, plainRichText)
- ).toMatchObject({ kind: 'error', canOpenLegacy: false });
+ loadCanvasFile({ version: 2, document: {} }, plainRichText)
+ ).toMatchObject({ kind: 'error' });
});
it('handles empty canvases and root-id collisions', () => {
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.ts b/apps/web/src/features/block-canvas/core/migrate-legacy.ts
similarity index 96%
rename from apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.ts
rename to apps/web/src/features/block-canvas/core/migrate-legacy.ts
index 4c196391de..73a1bc79ad 100644
--- a/apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.ts
+++ b/apps/web/src/features/block-canvas/core/migrate-legacy.ts
@@ -8,13 +8,13 @@ import {
translation,
} from '@macro-inc/graphics';
import { match } from 'ts-pattern';
+import { CANVAS_VERSION, type CanvasFile, isRecord } from './document-format';
import {
type Canvas,
type CanvasEntityStyle,
CanvasSchema,
type EdgeEnd,
-} from '../../model/CanvasModel';
-import { CANVAS_VERSION, type CanvasFile, isRecord } from './document-format';
+} from './legacy-format';
import {
plainRichText,
validCanvasText,
@@ -177,7 +177,7 @@ function migrateNode(
};
})
.with({ type: 'link' }, (): never => {
- throw new Error(`Link ${node.id} requires the legacy editor`);
+ throw new Error(`Link ${node.id} cannot be migrated yet`);
})
.exhaustive();
}
@@ -265,7 +265,7 @@ function legacyLayout(canvas: Canvas) {
const root = parent ?? item.id;
if (root !== previous) {
if (rootOrder.includes(root))
- throw new Error('Interleaved group layers require the legacy editor');
+ throw new Error('Interleaved group layers cannot be migrated yet');
rootOrder.push(root);
previous = root;
}
@@ -330,7 +330,7 @@ function migrateEdges(
const routes = ['straight', 'stepped', 'smooth'] as const;
for (const edge of edges) {
if (edge.label)
- throw new Error(`Connector label ${edge.id} requires the legacy editor`);
+ throw new Error(`Connector label ${edge.id} cannot be migrated yet`);
const startHead = heads[edge.style?.fromEndStyle ?? 0],
endHead = heads[edge.style?.toEndStyle ?? 0],
route = routes[edge.style?.connectionStyle ?? 0];
@@ -355,7 +355,7 @@ function migrateEdges(
}
/** One-way migration at the application boundary. Never mutate the source or
- * discard an unsupported record. Callers keep the legacy editor available on error. */
+ * discard an unsupported record. Callers report migration errors without writing data. */
export function migrateLegacyCanvas(
source: unknown,
text: LegacyTextCodec
@@ -396,7 +396,7 @@ export function migrateLegacyCanvas(
]),
});
if (!validCanvasTextDocument(document))
- throw new Error('Canvas text requires the legacy editor');
+ throw new Error('Canvas text cannot be migrated yet');
return {
version: CANVAS_VERSION,
document,
diff --git a/apps/web/src/features/block-canvas/util/parse.ts b/apps/web/src/features/block-canvas/core/parse.ts
similarity index 83%
rename from apps/web/src/features/block-canvas/util/parse.ts
rename to apps/web/src/features/block-canvas/core/parse.ts
index d6a7c6b25c..e755bfd1fe 100644
--- a/apps/web/src/features/block-canvas/util/parse.ts
+++ b/apps/web/src/features/block-canvas/core/parse.ts
@@ -5,8 +5,8 @@
*/
export function createNumericParser<T extends Record<string, number>>(
mappings: Record<keyof T, string[]>
-): (params: Record<string, any>) => T | null {
- return (params: Record<string, any>) => {
+): (params: Record<string, unknown>) => T | null {
+ return (params: Record<string, unknown>) => {
const result = {} as T;
let hasValidProperty = false;
for (const [outputKey, inputKeys] of Object.entries(mappings)) {
@@ -16,7 +16,7 @@ export function createNumericParser<T extends Record<string, number>>(
const parsedValue = Number(value);
if (!isNaN(parsedValue)) {
- (result as any)[outputKey] = parsedValue;
+ (result as Record<string, number>)[outputKey] = parsedValue;
hasValidProperty = true;
break;
}
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/seed-scene.ts b/apps/web/src/features/block-canvas/core/seed-scene.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/seed-scene.ts
rename to apps/web/src/features/block-canvas/core/seed-scene.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/selection-layout.test.ts b/apps/web/src/features/block-canvas/core/selection-layout.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/selection-layout.test.ts
rename to apps/web/src/features/block-canvas/core/selection-layout.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/selection-layout.ts b/apps/web/src/features/block-canvas/core/selection-layout.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/selection-layout.ts
rename to apps/web/src/features/block-canvas/core/selection-layout.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/snapping.ts b/apps/web/src/features/block-canvas/core/snapping.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/snapping.ts
rename to apps/web/src/features/block-canvas/core/snapping.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/text-codec.test.ts b/apps/web/src/features/block-canvas/core/text-codec.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/text-codec.test.ts
rename to apps/web/src/features/block-canvas/core/text-codec.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/core/text-codec.ts b/apps/web/src/features/block-canvas/core/text-codec.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/core/text-codec.ts
rename to apps/web/src/features/block-canvas/core/text-codec.ts
diff --git a/apps/web/src/features/block-canvas/core/view.ts b/apps/web/src/features/block-canvas/core/view.ts
new file mode 100644
index 0000000000..dd574c25df
--- /dev/null
+++ b/apps/web/src/features/block-canvas/core/view.ts
@@ -0,0 +1,5 @@
+export type CanvasView = {
+ x: number;
+ y: number;
+ scale: number;
+};
diff --git a/apps/web/src/features/block-canvas/definition.ts b/apps/web/src/features/block-canvas/definition.ts
index 924809c33c..07a78cb6ed 100644
--- a/apps/web/src/features/block-canvas/definition.ts
+++ b/apps/web/src/features/block-canvas/definition.ts
@@ -10,8 +10,7 @@ import { fetchBinary } from '@service-storage/util/fetchBinary';
import { makeFileFromBlob } from '@service-storage/util/makeFileFromBlob';
import { err, ok } from 'neverthrow';
import { lazy } from 'solid-js';
-import type { CanvasFile } from './canvas-next/core/document-format';
-import type { Canvas } from './model/CanvasModel';
+import type { CanvasFile } from './core/document-format';
export const definition = defineBlock({
name: 'canvas',
@@ -74,5 +73,5 @@ export const definition = defineBlock({
export type CanvasData = ExtractLoadType<(typeof definition)['load']>;
export type CanvasSpec = {
- exportCanvas: () => Promise<Canvas | CanvasFile>;
+ exportCanvas: () => Promise<CanvasFile>;
};
diff --git a/apps/web/src/features/block-canvas/canvas-next/hotkeys.ts b/apps/web/src/features/block-canvas/hotkeys.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/hotkeys.ts
rename to apps/web/src/features/block-canvas/hotkeys.ts
diff --git a/apps/web/src/features/block-canvas/operation/connect.ts b/apps/web/src/features/block-canvas/operation/connect.ts
deleted file mode 100644
index 536003664f..0000000000
--- a/apps/web/src/features/block-canvas/operation/connect.ts
+++ /dev/null
@@ -1,297 +0,0 @@
-import { useToolManager } from '@block-canvas/signal/toolManager';
-import {
- degreesToRadians,
- radiansToDegrees,
- snapTo,
-} from '@block-canvas/util/math';
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { unwrap } from 'solid-js/store';
-import type { Edge } from '../constants';
-import { OPERATION_LOGGING, Tools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type {
- CanvasEdge,
- CanvasId,
- ConnectedEnd,
- FreeEnd,
-} from '../model/CanvasModel';
-import { useCachedStyle } from '../signal/cachedStyle';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useSelection } from '../signal/selection';
-import { useCanvasEdges, useEdgeUtils } from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { sharedInstance } from '../util/sharedInstance';
-import { type Vector2, vec2 } from '../util/vector2';
-import type { Operation } from './operation';
-
-function _log(message: string) {
- if (!OPERATION_LOGGING || !DEV_MODE_ENV) return;
- console.log(`%c[Connect] ${message}`, 'color: teal');
-}
-
-export type NodeConnectionInfo = {
- node: CanvasId;
- side: Edge;
-};
-
-export type LineEditInfo = {
- edge: CanvasEdge;
- handle: 'from' | 'to';
-};
-
-/**
- * Represents a connection operation between nodes in a canvas.
- * The connect operation is fairly tricky.
- * @extends {Operation}
- * @property {string} type - Must be 'connect' to identify this operation type
- * @property {NodeConnectionInfo | Vector2} start - Starting point of the connection, either a node connection or coordinates
- * @property {Vector2} currentMousePos - Current position of the mouse during the operation
- * @property {CanvasEdge} edge - The edge being created or modified. Will be a previe edge if edge is being created or a "regular" edge if
- * the edges if being edited from existing.
- * @property {NodeConnectionInfo | Vector2} end - Ending point of the connection, either a node connection or coordinates
- * @property {'from' | 'to'} handle - Specifies which end of the connection is being manipulated. When you edito an existing edge,
- * you can grab it by either the from or the to side, so we track which one is being manipulated.
- * @property {NodeConnectionInfo} [dropTarget] - Optional target node information when hovering over a valid connection point, like
- * the edge of a shape
- * @property {true} [editExisting] - Optional flag indicating if this is modifying an existing connection
- */
-export type ConnectOperation = Operation & {
- type: 'connect';
- start: NodeConnectionInfo | Vector2;
- currentMousePos: Vector2;
- edge: CanvasEdge;
- end: NodeConnectionInfo | Vector2;
- handle: 'from' | 'to';
- dropTarget?: NodeConnectionInfo;
- editExisting?: true;
-};
-
-function freeEnd(x: number, y: number): FreeEnd {
- return {
- type: 'free',
- x,
- y,
- };
-}
-
-function connectedEnd(id: string, side: Edge): ConnectedEnd {
- return {
- type: 'connected',
- node: id,
- side: side,
- };
-}
-
-export type ConnectOperator = ReturnType<typeof useConnect>;
-
-export const useConnect = sharedInstance(() => {
- const [currentConnectOperation, setCurrentConnectOperation] =
- useCanvasDocument().state.signals.currentConnectOperation;
- const edges = useCanvasEdges();
- const { selectEdge, deselectAll } = useSelection();
- const { clientToCanvas } = useRenderState();
- const history = useCanvasHistory();
- const cachedStyle = useCachedStyle();
- const highestOrder = useCanvasDocument().state.signals.highestOrder[0];
- const { setSelectedTool } = useToolManager();
- const edgeUtils = useEdgeUtils();
-
- const snap = (edge: CanvasEdge, handle: 'from' | 'to', mousePos: Vector2) => {
- const endpoints = edgeUtils.getRawEndPoints(edge);
- const other = handle === 'from' ? 'to' : 'from';
- const otherEnd = endpoints[other];
- const delta = mousePos.subtract(otherEnd);
- let angle = snapTo(radiansToDegrees(Math.atan2(delta.y, delta.x)), 45);
- const newDelta = vec2(
- Math.cos(degreesToRadians(angle)) * delta.mag(),
- Math.sin(degreesToRadians(angle)) * delta.mag()
- );
- const newEnd = otherEnd.add(newDelta);
- return newEnd;
- };
-
- function applyMousePos(mousePos: Vector2, opts: { shiftKey?: boolean }) {
- const op = currentConnectOperation();
- if (!op) return;
- op.currentMousePos = mousePos;
-
- if (!opts.shiftKey) {
- edges.updateEdge(op.edge.id, {
- [op.handle]: freeEnd(mousePos.x, mousePos.y),
- });
- return;
- }
- const newEnd = snap(op.edge, op.handle, mousePos);
-
- edges.updateEdge(op.edge.id, {
- [op.handle]: freeEnd(newEnd.x, newEnd.y),
- });
- }
-
- return {
- reset() {
- setCurrentConnectOperation();
- edges.clearPreview();
- },
-
- start(e: PointerEvent, target?: NodeConnectionInfo | LineEditInfo) {
- _log('start');
- const current = currentConnectOperation();
- if (current) setCurrentConnectOperation();
- const mousePos = clientToCanvas({ clientX: e.pageX, clientY: e.pageY });
- history.open();
-
- // No target means a doubly free edge.
- if (target === undefined) {
- const edge = edges.createEdge(
- {
- from: freeEnd(mousePos.x, mousePos.y),
- to: freeEnd(mousePos.x, mousePos.y),
- style: cachedStyle.getStyle(),
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { preview: true }
- );
-
- setCurrentConnectOperation({
- type: 'connect',
- currentMousePos: mousePos,
- timeStamp: Date.now(),
- edge,
- start: vec2(mousePos.x, mousePos.y),
- end: vec2(mousePos.x, mousePos.y),
- handle: 'to',
- });
-
- return;
- }
-
- // We are starting a line from the egde of a node.
- if ('node' in target) {
- const t = target as NodeConnectionInfo;
- const edge = edges.createEdge(
- {
- from: connectedEnd(t.node, t.side),
- to: freeEnd(mousePos.x, mousePos.y),
- style: cachedStyle.getStyle(),
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { preview: true }
- );
-
- setCurrentConnectOperation({
- type: 'connect',
- timeStamp: Date.now(),
- currentMousePos: mousePos,
- edge,
- start: t,
- end: vec2(mousePos.x, mousePos.y),
- handle: 'to',
- });
- }
-
- // We grabbed a handle and are updateing and exisiting line
- if ('handle' in target) {
- const t = target as LineEditInfo;
- const edge = edges.get(t.edge.id);
- if (!edge) return;
- setCurrentConnectOperation({
- type: 'connect',
- timeStamp: Date.now(),
- currentMousePos: mousePos,
- edge,
- start:
- edge.from.type === 'free'
- ? vec2(edge.from.x, edge.from.y)
- : connectedEnd(edge.from.node, edge.from.side),
- end:
- edge.to.type === 'free'
- ? vec2(edge.to.x, edge.to.y)
- : connectedEnd(edge.to.node, edge.to.side),
- handle: t.handle,
- editExisting: true,
- });
- }
- },
-
- commit(e: PointerEvent) {
- const op = currentConnectOperation();
- if (!op) return;
- _log('commit');
-
- const mousePos = clientToCanvas(e);
-
- let edge: CanvasEdge;
-
- let newEnd = vec2(mousePos.x, mousePos.y);
- if (e.shiftKey) {
- newEnd = snap(op.edge, op.handle, mousePos);
- }
-
- if (op.editExisting) {
- edge = op.edge;
- } else {
- // convert the preview edge to a real edge.
- edge = edges.createEdge(
- {
- id: op.edge.id,
- style: { ...(unwrap(op.edge.style) || {}) },
- from: { ...unwrap(op.edge.from) },
- to: freeEnd(newEnd.x, newEnd.y),
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { autosave: true }
- );
- }
-
- // apply the drop target.
- if (op.dropTarget) {
- edges.updateEdge(edge.id, {
- [op.handle]: connectedEnd(op.dropTarget.node, op.dropTarget.side),
- });
- }
-
- setCurrentConnectOperation();
- edges.clearPreview();
-
- deselectAll();
- selectEdge(edge.id);
- history.close();
-
- setSelectedTool(Tools.Select);
- },
-
- abort() {
- const op = currentConnectOperation();
- if (!op) return;
- _log('abort');
- setCurrentConnectOperation();
- edges.clearPreview();
- },
-
- preview(e: PointerEvent) {
- const op = currentConnectOperation();
- if (!op) return;
- _log('preview');
- const mousePos = clientToCanvas(e);
- applyMousePos(mousePos, { shiftKey: e.shiftKey });
- },
-
- active() {
- const op = currentConnectOperation();
- return !!op;
- },
-
- setDropTarget(info?: NodeConnectionInfo) {
- const op = currentConnectOperation();
- if (!op) return;
- setCurrentConnectOperation({
- ...op,
- dropTarget: info,
- });
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/operation/file.ts b/apps/web/src/features/block-canvas/operation/file.ts
deleted file mode 100644
index 3c60471403..0000000000
--- a/apps/web/src/features/block-canvas/operation/file.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { trackMention } from '@core/signal/mention';
-import { copiedItem } from '@core/state/clipboard';
-import { unwrap } from 'solid-js/store';
-import { OPERATION_LOGGING, Tools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { EntityMentionNode } from '../model/CanvasModel';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useToolManager } from '../signal/toolManager';
-import { useCanvasNodes } from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { sharedInstance } from '../util/sharedInstance';
-import type { Vector2 } from '../util/vector2';
-import type { Operation, Operator } from './operation';
-
-export const fileWidth = 250;
-export const fileHeight = 50;
-
-function _log(message: string) {
- if (!OPERATION_LOGGING || !DEV_MODE_ENV) return;
- console.log(`%c[File] ${message}`, 'color: peru');
-}
-
-export type FileOperation = Operation & {
- type: 'file';
- initialMousePos: Vector2;
- node: EntityMentionNode;
-};
-
-export const useFile = sharedInstance((): Operator => {
- const canvas = useCanvasDocument();
- const state = canvas.state.signals;
- const { pageToCanvas } = useRenderState();
- const { createNode, updateNode, ...nodes } = useCanvasNodes();
- const [currentFileOperation, setCurrentFileOperation] =
- state.currentFileOperation;
- const { setSelectedTool } = useToolManager();
- const history = useCanvasHistory();
- const [highestOrder] = state.highestOrder;
- const blockId = canvas.documentId();
-
- const [selectedFile, setSelectedFile] = state.selectedFile;
-
- function _applyMousePos(mousePos: Vector2) {
- const op = currentFileOperation();
- if (!op) return;
- updateNode(
- op.node.id,
- {
- x: mousePos.x - fileWidth / 2,
- y: mousePos.y - fileHeight / 2,
- width: fileWidth,
- height: fileHeight,
- },
- { preview: true }
- );
- }
-
- return {
- reset() {
- _log('reset');
- setCurrentFileOperation();
- nodes.clearPreview();
- },
-
- start(e: PointerEvent) {
- _log('start');
- history.open();
- const mousePos = pageToCanvas(e);
- let { id, type } = selectedFile();
- if (!id) {
- if (copiedItem()) {
- id = copiedItem()!.id;
- type = copiedItem()!.type;
- } else {
- console.warn('No source File found');
- return;
- }
- }
- const node = createNode(
- {
- type: 'entitymention',
- file: id,
- entityType: type as
- | 'document'
- | 'chat'
- | 'project'
- | 'channel'
- | 'email',
- x: mousePos.x - fileWidth / 2,
- y: mousePos.y - fileHeight / 2,
- width: fileWidth,
- height: fileHeight,
- edges: [],
- style: { strokeColor: 'transparent' },
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { preview: true }
- ) as EntityMentionNode;
-
- setCurrentFileOperation({
- type: 'file',
- timeStamp: Date.now(),
- initialMousePos: mousePos,
- node,
- });
- },
-
- async commit(e: PointerEvent) {
- const op = currentFileOperation();
- if (!op) return;
- _log('commit');
- history.close();
- const mousePos = pageToCanvas(e);
- _applyMousePos(mousePos);
- const { id: _, ...newNode } = structuredClone(unwrap(op.node));
-
- // Track document mention and store the UUID
- let mentionUuid: string | undefined;
- if (blockId && op.node.file && op.node.entityType === 'document') {
- mentionUuid = await trackMention(blockId, 'document', op.node.file);
- }
-
- createNode({ ...newNode, mentionUuid }, { autosave: true });
-
- setCurrentFileOperation();
- nodes.clearPreview();
-
- setSelectedTool(Tools.Select);
- setSelectedFile({
- type: undefined,
- id: undefined,
- });
- },
-
- abort() {
- _log('abort');
- setCurrentFileOperation();
- nodes.clearPreview();
- },
-
- preview(e: PointerEvent) {
- if (!currentFileOperation()) return;
- _log('preview');
- const mousePos = pageToCanvas(e);
- _applyMousePos(mousePos);
- },
-
- active() {
- const op = currentFileOperation();
- return !!op;
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/operation/image.ts b/apps/web/src/features/block-canvas/operation/image.ts
deleted file mode 100644
index fef83254d3..0000000000
--- a/apps/web/src/features/block-canvas/operation/image.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { copiedItem } from '@core/state/clipboard';
-import { unwrap } from 'solid-js/store';
-import { OPERATION_LOGGING, Tools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { ImageNode, VideoNode } from '../model/CanvasModel';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useToolManager } from '../signal/toolManager';
-import { useCanvasNodes } from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { sharedInstance } from '../util/sharedInstance';
-import type { Vector2 } from '../util/vector2';
-import type { Operation, Operator } from './operation';
-
-const minSize = 1;
-
-function _log(message: string) {
- if (!OPERATION_LOGGING || !DEV_MODE_ENV) return;
- console.log(`%c[Image] ${message}`, 'color: peru');
-}
-
-export type ImageOperation = Operation & {
- type: 'image';
- initialMousePos: Vector2;
- node: ImageNode | VideoNode;
-};
-
-export const useImage = sharedInstance((): Operator => {
- const state = useCanvasDocument().state.signals;
- const { pageToCanvas } = useRenderState();
- const { createNode, updateNode, ...nodes } = useCanvasNodes();
- const [currentImageOperation, setCurrentImageOperation] =
- useCanvasDocument().state.signals.currentImageOperation;
- const { setSelectedTool } = useToolManager();
- const history = useCanvasHistory();
- const [highestOrder] = state.highestOrder;
-
- const [selectedImage, setSelectedImage] = state.selectedImage;
-
- function _applyMousePos(mousePos: Vector2) {
- const op = currentImageOperation();
- if (!op) return;
- const calculatedWidth = mousePos.x - op.initialMousePos.x;
- const calculatedHeight = mousePos.y - op.initialMousePos.y;
- updateNode(
- op.node.id,
- {
- x: Math.min(mousePos.x, op.initialMousePos.x),
- y: Math.min(mousePos.y, op.initialMousePos.y),
- width: calculatedWidth === 0 ? -1 : Math.abs(calculatedWidth),
- height: calculatedHeight === 0 ? -1 : Math.abs(calculatedHeight),
- flipX: mousePos.x < op.initialMousePos.x,
- flipY: mousePos.y < op.initialMousePos.y,
- },
- { preview: true }
- );
- }
-
- return {
- reset() {
- _log('reset');
- setCurrentImageOperation();
- nodes.clearPreview();
- },
-
- start(e: PointerEvent) {
- _log('start');
- history.open();
- const mousePos = pageToCanvas(e);
- let idToCreate = selectedImage()?.id;
- if (!idToCreate) {
- if (copiedItem()) {
- idToCreate = copiedItem()!.id;
- } else {
- console.warn('No source image found');
- return;
- }
- }
-
- const node = createNode(
- {
- type: selectedImage()?.type ?? 'image',
- uuid: idToCreate,
- x: mousePos.x,
- y: mousePos.y,
- width: -1,
- height: -1,
- edges: [],
- style: { strokeColor: 'transparent', strokeWidth: 0 },
- flipX: false,
- flipY: false,
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { preview: true }
- ) as ImageNode;
-
- setCurrentImageOperation({
- type: 'image',
- timeStamp: Date.now(),
- initialMousePos: mousePos,
- node,
- });
- },
-
- commit(e: PointerEvent) {
- const op = currentImageOperation();
- if (!op) return;
- _log('commit');
- history.close();
- const mousePos = pageToCanvas(e);
- _applyMousePos(mousePos);
- const { id: _, ...newNode } = structuredClone(unwrap(op.node));
-
- if (newNode.width <= minSize || newNode.height <= minSize) {
- newNode.width = 0;
- newNode.height = 0;
- }
-
- createNode(newNode, { autosave: true });
-
- setCurrentImageOperation();
- nodes.clearPreview();
-
- setSelectedTool(Tools.Select);
- setSelectedImage();
- },
-
- abort() {
- _log('abort');
- setCurrentImageOperation();
- // deselectAll();
- nodes.clearPreview();
- },
-
- preview(e: PointerEvent) {
- if (!currentImageOperation()) return;
- _log('preview');
- const mousePos = pageToCanvas(e);
- _applyMousePos(mousePos);
- },
-
- active() {
- const op = currentImageOperation();
- return !!op;
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/operation/move.ts b/apps/web/src/features/block-canvas/operation/move.ts
deleted file mode 100644
index 9b2e9edf7a..0000000000
--- a/apps/web/src/features/block-canvas/operation/move.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { batch, untrack } from 'solid-js';
-import { OPERATION_LOGGING, Tools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useSelection } from '../signal/selection';
-import { useToolManager } from '../signal/toolManager';
-import { useCanvasEdges, useCanvasNodes } from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { sharedInstance } from '../util/sharedInstance';
-import { type Vector2, vec2 } from '../util/vector2';
-import type { Operation, Operator } from './operation';
-
-function _log(message: string) {
- if (!OPERATION_LOGGING || !DEV_MODE_ENV) return;
- console.log(`%c[Move] ${message}`, 'color: violet');
-}
-
-export type MoveOperation = Operation & {
- type: 'move';
- initialMousePos: Vector2;
- nodePositions: Record<string, Vector2>;
- edgePositions: Record<string, { from?: Vector2; to?: Vector2 }>;
-};
-
-export const useMove = sharedInstance((): Operator => {
- const [currentMoveOperation, setCurrentMoveOperation] =
- useCanvasDocument().state.signals.currentMoveOperation;
- const { selectedNodes, selectedEdges } = useSelection();
- const { pageToCanvas } = useRenderState();
- const { updateNode, ...nodes } = useCanvasNodes();
- const { updateEdge, ...edges } = useCanvasEdges();
- const { setSelectedTool } = useToolManager();
- const history = useCanvasHistory();
-
- function applyMousePos(
- mousePos: Vector2,
- opts?: { autosave?: boolean; shiftKey?: boolean }
- ) {
- const op = currentMoveOperation();
- if (!op) return;
-
- let delta = mousePos.subtract(op.initialMousePos);
-
- if (opts?.shiftKey) {
- if (Math.abs(delta.x) > Math.abs(delta.y)) {
- delta.y = 0;
- } else if (Math.abs(delta.y) > Math.abs(delta.x)) {
- delta.x = 0;
- }
- }
-
- batch(() => {
- nodes.batchUpdate(() => {
- for (const [nodeId, nodePos] of Object.entries(op.nodePositions)) {
- updateNode(nodeId, {
- x: nodePos.x + delta.x,
- y: nodePos.y + delta.y,
- });
- }
- }, opts);
-
- edges.batchUpdate(() => {
- for (const [edgeId, edgePos] of Object.entries(op.edgePositions)) {
- const original = edges.get(edgeId);
- updateEdge(edgeId, {
- from: edgePos.from
- ? {
- type: 'free',
- x: edgePos.from.x + delta.x,
- y: edgePos.from.y + delta.y,
- }
- : original.from,
- to: edgePos.to
- ? {
- type: 'free',
- x: edgePos.to.x + delta.x,
- y: edgePos.to.y + delta.y,
- }
- : original.to,
- });
- }
- }, opts);
- });
- }
-
- return {
- reset() {
- _log('reset');
- setCurrentMoveOperation();
- },
-
- start(e: PointerEvent) {
- _log('start');
- if (
- untrack(selectedNodes).length === 0 &&
- untrack(selectedEdges).length === 0
- ) {
- return;
- }
- history.open();
- const nodePositions: Record<string, Vector2> = {};
- const edgePositions: Record<string, { from?: Vector2; to?: Vector2 }> =
- {};
-
- for (const node of untrack(selectedNodes)) {
- nodePositions[node.id] = vec2(node.x, node.y);
- }
- for (const edge of untrack(selectedEdges)) {
- edgePositions[edge.id] = {
- from:
- edge.from.type === 'free'
- ? vec2(edge.from.x, edge.from.y)
- : undefined,
- to: edge.to.type === 'free' ? vec2(edge.to.x, edge.to.y) : undefined,
- };
- }
-
- setCurrentMoveOperation({
- type: 'move',
- timeStamp: Date.now(),
- initialMousePos: pageToCanvas(e),
- nodePositions,
- edgePositions,
- });
- },
-
- commit(e: PointerEvent) {
- if (!currentMoveOperation()) return;
- _log('commit');
- const mousePos = pageToCanvas(e);
-
- applyMousePos(mousePos, {
- autosave: true,
- shiftKey: e.shiftKey,
- });
-
- setCurrentMoveOperation();
- history.close();
- setSelectedTool(Tools.Select);
- },
-
- abort() {
- const op = currentMoveOperation();
- if (!op) return;
- _log('abort');
- applyMousePos(op.initialMousePos, { autosave: true });
- setCurrentMoveOperation();
- },
-
- preview(e: PointerEvent) {
- if (!currentMoveOperation()) return;
- _log('preview');
- const mousePos = pageToCanvas(e);
- applyMousePos(mousePos, { shiftKey: e.shiftKey });
- },
-
- active() {
- const op = currentMoveOperation();
- return !!op;
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/operation/operation.ts b/apps/web/src/features/block-canvas/operation/operation.ts
deleted file mode 100644
index e8676dd40e..0000000000
--- a/apps/web/src/features/block-canvas/operation/operation.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-export type Operation = {
- type: string;
- timeStamp: DOMHighResTimeStamp;
-};
-
-export type Operator = {
- start: (e: PointerEvent, ...args: any[]) => void;
- preview: (e: PointerEvent, ...args: any[]) => void;
- commit: (e: PointerEvent, ...args: any[]) => void;
- abort: () => void;
- reset: () => void;
- active: () => boolean;
-};
-
-export function operatorFromPartial(partial: Partial<Operator>): Operator {
- return {
- start: () => {},
- preview: () => {},
- commit: () => {},
- abort: () => {},
- reset: () => {},
- active: () => false,
- ...partial,
- };
-}
diff --git a/apps/web/src/features/block-canvas/operation/pencil.ts b/apps/web/src/features/block-canvas/operation/pencil.ts
deleted file mode 100644
index 17005d1982..0000000000
--- a/apps/web/src/features/block-canvas/operation/pencil.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { unwrap } from 'solid-js/store';
-import { OPERATION_LOGGING } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { PencilNode } from '../model/CanvasModel';
-import { useCachedStyle } from '../signal/cachedStyle';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useSelection } from '../signal/selection';
-import { useCanvasNodes } from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { sharedInstance } from '../util/sharedInstance';
-import { simplify } from '../util/simplify';
-import { type Vector2, vec2 } from '../util/vector2';
-import type { Operation, Operator } from './operation';
-
-type Coords = Vector2[];
-
-function _log(message: string) {
- if (!OPERATION_LOGGING || !DEV_MODE_ENV) return;
- console.log(`%c[Pencil] ${message}`, 'color: green');
-}
-
-export type PencilOperation = Operation & {
- type: 'pencil';
- node: PencilNode;
- coords: Coords;
-};
-
-function cleanUpLine(coords: Coords): [number, number][] {
- const simplified = simplify(coords, 0.25, false);
- return simplified.map(({ x, y }) => [x, y]);
-}
-
-export const usePencil = sharedInstance((): Operator => {
- const { pageToCanvas } = useRenderState();
- const { deselectNode } = useSelection();
- const { createNode, updateNode, ...nodes } = useCanvasNodes();
- const history = useCanvasHistory();
- const cachedStyle = useCachedStyle();
- const [currentPencilOperation, setCurrentPencilOperation] =
- useCanvasDocument().state.signals.currentPencilOperation;
- const highestOrder = useCanvasDocument().state.signals.highestOrder[0];
-
- function _calculateDimensions(coords: [number, number][]) {
- let minX = Infinity;
- let maxX = -Infinity;
- let minY = Infinity;
- let maxY = -Infinity;
- for (const [x, y] of coords) {
- minX = Math.min(minX, x);
- maxX = Math.max(maxX, x);
- minY = Math.min(minY, y);
- maxY = Math.max(maxY, y);
- }
- return {
- x: minX,
- y: minY,
- width: maxX - minX,
- height: maxY - minY,
- };
- }
-
- //claude slop
- function _updateCoords(mousePos: Vector2) {
- const op = currentPencilOperation();
- if (!op) return;
-
- const newCoords = [...op.coords, vec2(mousePos.x, mousePos.y)];
- // Don't simplify during preview, just use raw coords
- const dimensions = _calculateDimensions(
- newCoords.map(({ x, y }) => [x, y])
- );
-
- updateNode(op.node.id, {
- coords: newCoords.map(({ x, y }) => [x, y]), // Use raw coords
- width: dimensions.width,
- height: dimensions.height,
- });
-
- op.coords = newCoords;
- }
-
- return {
- reset() {
- _log('reset');
- setCurrentPencilOperation();
- nodes.clearPreview();
- },
-
- start(e: PointerEvent) {
- _log('start');
- history.open();
- const mousePos = pageToCanvas(e);
- const initialCoords = [vec2(mousePos.x, mousePos.y)];
-
- const node = createNode(
- {
- type: 'pencil',
- x: 0,
- y: 0,
- width: 0,
- height: 0,
- edges: [],
- coords: initialCoords,
- style: cachedStyle.getStyle(),
- wScale: 1,
- hScale: 1,
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { preview: true, selectOnCreate: false }
- ) as PencilNode;
-
- setCurrentPencilOperation({
- type: 'pencil',
- timeStamp: Date.now(),
- node,
- coords: initialCoords,
- });
- },
-
- commit(e: PointerEvent) {
- const op = currentPencilOperation();
- if (!op) return;
- _log('commit');
-
- const mousePos = pageToCanvas(e);
- let finalCoords = [...op.coords, vec2(mousePos.x, mousePos.y)];
- const line = cleanUpLine(finalCoords);
- const dimensions = _calculateDimensions(line);
-
- const finalLine = line.map(([x, y]) => [
- x - dimensions.x,
- y - dimensions.y,
- ]) as [number, number][];
-
- const { id: _, ...newNode } = JSON.parse(JSON.stringify(unwrap(op.node)));
- createNode(
- {
- ...newNode,
- coords: finalLine,
- ...dimensions,
- },
- { autosave: true }
- );
-
- setCurrentPencilOperation();
- nodes.clearPreview();
- history.close();
- },
-
- abort() {
- const op = currentPencilOperation();
- if (!op) return;
- _log('abort');
- setCurrentPencilOperation();
- deselectNode(op.node.id);
- nodes.clearPreview();
- },
-
- preview(e: PointerEvent) {
- if (!currentPencilOperation()) return;
- _log('preview');
- const mousePos = pageToCanvas(e);
- _updateCoords(mousePos);
- },
-
- active() {
- const op = currentPencilOperation();
- return !!op;
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/operation/rescale.ts b/apps/web/src/features/block-canvas/operation/rescale.ts
deleted file mode 100644
index 1d63bf4290..0000000000
--- a/apps/web/src/features/block-canvas/operation/rescale.ts
+++ /dev/null
@@ -1,340 +0,0 @@
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { pressedKeys } from '@core/hotkey/state';
-import { batch, untrack } from 'solid-js';
-import { type Anchor, OPERATION_LOGGING, Tools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import {
- type CanvasEdge,
- type CanvasId,
- type CanvasNode,
- type EntityMentionNode,
- type ImageNode,
- isEntityMentionNode,
- isImageNode,
- isPencilNode,
- isShapeNode,
- isTextNode,
- isVideoNode,
- type PencilNode,
- type ShapeNode,
- type TextNode,
- type VideoNode,
-} from '../model/CanvasModel';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useSelection } from '../signal/selection';
-import { useToolManager } from '../signal/toolManager';
-import {
- useCanvasEdges,
- useCanvasNodes,
- useSaveCanvasData,
-} from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { Rect, type Rectangle } from '../util/rectangle';
-import { sharedInstance } from '../util/sharedInstance';
-import { Vec2, type Vector2, vec2 } from '../util/vector2';
-import { fileHeight, fileWidth } from './file';
-import type { Operator } from './operation';
-
-function _log(message: string) {
- if (!OPERATION_LOGGING || !DEV_MODE_ENV) return;
- console.log(`%c[Rescale] ${message}`, 'color: orangered');
-}
-
-export type RescaleOperation = {
- initialBoundingRect: Rectangle;
- initialMousePos: Vector2;
- innerNodeRatioRects: Record<CanvasId, Rectangle>;
- innerEdgeRatioVects: Record<string, { from?: Vector2; to?: Vector2 }>;
- anchor: Anchor;
- initialFlip: Record<CanvasId, Vector2>;
- proportionalDefault: boolean;
-};
-
-type CoordTuple = [number, number];
-
-type RescaleNodeFunction<T extends CanvasNode> = (
- nodes: ReturnType<typeof useCanvasNodes>,
- node: T,
- innerRect: Rectangle,
- normalized?: boolean,
- flip?: Vector2
-) => void;
-
-const rescalePencil: RescaleNodeFunction<PencilNode> = (
- nodes,
- node,
- innerRect,
- normalized
-) => {
- if (normalized) {
- const newCoords = node.coords.map((coord: CoordTuple) => [
- coord[0] * (innerRect.w / node.width) +
- (innerRect.w < 0 ? -innerRect.w : 0),
- coord[1] * (innerRect.h / node.height) +
- (innerRect.h < 0 ? -innerRect.h : 0),
- ]) as CoordTuple[];
- nodes.updateNode(node.id, {
- x: Math.min(innerRect.x, innerRect.x + innerRect.w),
- y: Math.min(innerRect.y, innerRect.y + innerRect.h),
- wScale: 1,
- hScale: 1,
- width: Math.abs(innerRect.w),
- height: Math.abs(innerRect.h),
- coords: newCoords,
- });
- return;
- }
- nodes.updateNode(node.id, {
- x: innerRect.x,
- y: innerRect.y,
- wScale: innerRect.w / node.width,
- hScale: innerRect.h / node.height,
- });
-};
-
-const rescaleShape: RescaleNodeFunction<ShapeNode> = (
- nodes,
- node,
- innerRect
-) => {
- nodes.updateNode(node.id, {
- x: Math.min(innerRect.x, innerRect.x + innerRect.w),
- y: Math.min(innerRect.y, innerRect.y + innerRect.h),
- width: Math.abs(innerRect.w),
- height: Math.abs(innerRect.h),
- });
-};
-
-const rescaleFile: RescaleNodeFunction<EntityMentionNode> = (
- nodes,
- node,
- innerRect
-) => {
- const ratio = fileWidth / fileHeight;
- const largerWidth = Math.abs(innerRect.w) / Math.abs(innerRect.h) > ratio;
- nodes.updateNode(node.id, {
- x: Math.min(innerRect.x, innerRect.x + innerRect.w),
- y: Math.min(innerRect.y, innerRect.y + innerRect.h),
- width: largerWidth ? Math.abs(innerRect.w) : ratio * Math.abs(innerRect.h),
- height: !largerWidth
- ? Math.abs(innerRect.h)
- : Math.abs(innerRect.w) / ratio,
- });
-};
-
-const rescaleMediaNode: RescaleNodeFunction<ImageNode | VideoNode> = (
- nodes,
- node,
- innerRect,
- _normalized,
- initialFlip
-) => {
- let flipX = false;
- let flipY = false;
- if (initialFlip !== undefined) {
- flipX = initialFlip.x * Math.sign(innerRect.w) < 0;
- flipY = initialFlip.y * Math.sign(innerRect.h) < 0;
- }
- nodes.updateNode(node.id, {
- x: Math.min(innerRect.x, innerRect.x + innerRect.w),
- y: Math.min(innerRect.y, innerRect.y + innerRect.h),
- width: Math.abs(innerRect.w),
- height: Math.abs(innerRect.h),
- flipX: flipX,
- flipY: flipY,
- });
-};
-
-// Do not upddate the height of the text node. The is a resize observer on the
-// componnent that will handle setting rect height based on the text wrapping.
-const rescaleText: RescaleNodeFunction<TextNode> = (nodes, node, innerRect) => {
- nodes.updateNode(node.id, {
- x: Math.min(innerRect.x, innerRect.x + innerRect.w),
- y: Math.min(innerRect.y, innerRect.y + innerRect.h),
- });
-
- // If node does not have pending width, then we can rescale it.
- if (node.followTextWidth) return;
-
- nodes.updateNode(node.id, {
- width: Math.max(Math.abs(innerRect.w), 50),
- });
-};
-
-const rescaleEdge = (
- edges: ReturnType<typeof useCanvasEdges>,
- edge: CanvasEdge,
- innerRect: Rectangle,
- innerVects: { from?: Vector2; to?: Vector2 }
-) => {
- if (innerVects.from !== undefined) {
- const v = Vec2.applyRatioVect(innerVects.from, innerRect);
- edges.updateEdge(edge.id, {
- from: {
- type: 'free',
- x: v.x,
- y: v.y,
- },
- });
- }
- if (innerVects.to !== undefined) {
- const v = Vec2.applyRatioVect(innerVects.to, innerRect);
- edges.updateEdge(edge.id, {
- to: {
- type: 'free',
- x: v.x,
- y: v.y,
- },
- });
- }
-};
-
-export const useRescale = sharedInstance((): Operator => {
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
- const { selectedNodes, selectedEdges, selectionBounds } = useSelection();
- const { pageToCanvas } = useRenderState();
- const { setSelectedTool } = useToolManager();
- const history = useCanvasHistory();
- const [currentRescaleOperation, setCurrentRescaleOperation] =
- useCanvasDocument().state.signals.currentRescaleOperation;
- const saveCanvasData = useSaveCanvasData();
-
- function applyMousePos(mousePos: Vector2, normalize?: boolean) {
- const op = currentRescaleOperation();
- if (!op) return;
-
- const proportional = op.proportionalDefault !== pressedKeys().has('shift');
-
- const centered = pressedKeys().has('opt');
-
- const scaledOuterRect = Rect.rescaleFromAnchorToPoint(
- op.initialBoundingRect,
- op.anchor,
- mousePos,
- proportional,
- centered
- );
-
- batch(() => {
- for (const [nodeId, ratio] of Object.entries(op.innerNodeRatioRects)) {
- const newInnerRect = Rect.applyRatioRectangle(ratio, scaledOuterRect);
- const node = nodes.get(nodeId);
- if (isPencilNode(node)) {
- rescalePencil(nodes, node, newInnerRect, normalize);
- } else if (isShapeNode(node)) {
- rescaleShape(nodes, node, newInnerRect);
- } else if (isImageNode(node)) {
- const flip = op.initialFlip[node.id];
- rescaleMediaNode(nodes, node, newInnerRect, undefined, flip);
- } else if (isTextNode(node)) {
- rescaleText(nodes, node, newInnerRect);
- } else if (isEntityMentionNode(node)) {
- rescaleFile(nodes, node, newInnerRect);
- } else if (isVideoNode(node)) {
- const flip = op.initialFlip[node.id];
- rescaleMediaNode(nodes, node, newInnerRect, undefined, flip);
- }
- }
- for (const [edgeId, ratio] of Object.entries(op.innerEdgeRatioVects)) {
- const edge = edges.get(edgeId);
- rescaleEdge(edges, edge, scaledOuterRect, ratio);
- }
- });
- }
-
- return {
- reset() {
- _log('reset');
- setCurrentRescaleOperation();
- setSelectedTool(Tools.Select);
- },
-
- active() {
- const op = currentRescaleOperation();
- return !!op;
- },
-
- start(e: PointerEvent, anchor: Anchor) {
- _log('start');
- const initialBoundingRect = untrack(selectionBounds)?.clone();
- if (!initialBoundingRect) return;
-
- if (
- untrack(selectedNodes).length === 0 &&
- untrack(selectedEdges).length === 0
- )
- return;
-
- history.open();
-
- const innerNodeRatioRects: Record<string, Rectangle> = {};
- const innerEdgeRatioVects: Record<
- string,
- { from: Vector2 | undefined; to: Vector2 | undefined }
- > = {};
- const initialFlip: Record<string, Vector2> = {};
-
- for (const node of untrack(selectedNodes)) {
- const nodeRect = Rect.fromCanvasNode(node);
- innerNodeRatioRects[node.id] = Rect.calculateRatioRectangle(
- nodeRect,
- initialBoundingRect
- );
- if (isImageNode(node)) {
- initialFlip[node.id] = vec2(node.flipX ? -1 : 1, node.flipY ? -1 : 1);
- }
- }
-
- for (const edge of untrack(selectedEdges)) {
- innerEdgeRatioVects[edge.id] = Vec2.calculateRatioVect(
- edge,
- initialBoundingRect
- );
- }
-
- const mediaOnly = selectedNodes().every(
- (node) => isImageNode(node) || isVideoNode(node)
- );
-
- setCurrentRescaleOperation({
- type: 'rescale',
- timeStamp: Date.now(),
- initialMousePos: pageToCanvas(e),
- initialBoundingRect,
- innerNodeRatioRects,
- innerEdgeRatioVects,
- anchor,
- initialFlip,
- proportionalDefault: mediaOnly,
- });
- },
-
- commit(e: PointerEvent) {
- const op = currentRescaleOperation();
- if (!op) return;
- _log('commit');
- history.close();
- const mousePos = pageToCanvas(e);
- applyMousePos(mousePos, true);
- setCurrentRescaleOperation();
- setSelectedTool(Tools.Select);
- saveCanvasData();
- },
-
- preview(e: PointerEvent) {
- if (!currentRescaleOperation()) return;
- _log('preview');
- const mousePos = pageToCanvas(e);
- applyMousePos(mousePos);
- },
-
- abort() {
- _log('abort');
- const op = currentRescaleOperation();
- if (!op) return;
- applyMousePos(op.initialMousePos);
- setCurrentRescaleOperation();
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/operation/select.ts b/apps/web/src/features/block-canvas/operation/select.ts
deleted file mode 100644
index bef73bfa96..0000000000
--- a/apps/web/src/features/block-canvas/operation/select.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { edgeToCollisionData } from '@block-canvas/util/connectors';
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { OPERATION_LOGGING } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { CanvasId, PencilNode } from '../model/CanvasModel';
-import { useSelection } from '../signal/selection';
-import { useToolManager } from '../signal/toolManager';
-import {
- useCanvasEdges,
- useCanvasGroups,
- useCanvasNodes,
- useEdgeUtils,
-} from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { Rect } from '../util/rectangle';
-import { sharedInstance } from '../util/sharedInstance';
-import type { Vector2 } from '../util/vector2';
-import type { Operation, Operator } from './operation';
-
-function _log(message: string) {
- if (!OPERATION_LOGGING || !DEV_MODE_ENV) return;
- console.log(`%c[Select] ${message}`, 'color: deeppink');
-}
-
-export type SelectOperation = Operation & {
- type: 'select';
- initialMousePos: Vector2;
- initialSelectedNodes: CanvasId[];
- initialSelectedEdges: CanvasId[];
-};
-
-export const useSelect = sharedInstance((): Operator => {
- const { pageToCanvas } = useRenderState();
- const { setSelectionBox, forceSetSelection } = useSelection();
- const [currentOperation, setCurrentOperation] =
- useCanvasDocument().state.signals.currentSelectOperation;
- const nodes = useCanvasNodes();
- const egdes = useCanvasEdges();
- const groups = useCanvasGroups();
- const { getRawEndPoints: getEdgeEndPoints } = useEdgeUtils();
- const toolManager = useToolManager();
- const selection = useSelection();
-
- function applyMousePos(mousePos: Vector2, opts?: { shiftKey?: boolean }) {
- const op = currentOperation();
- if (!op) return;
- const rect = Rect.fromPoints(op.initialMousePos, mousePos);
- if (rect.width < 1 || rect.height < 1) return;
- setSelectionBox(rect);
-
- const containedGroupIds = new Set<string>();
-
- const containedNodeIds = nodes.visible().reduce((acc: string[], node) => {
- const nodeRect = Rect.fromCanvasNode(node);
- if (
- node.type === 'shape' ||
- node.type === 'image' ||
- node.type === 'video' ||
- node.type === 'text' ||
- node.type === 'entitymention'
- ) {
- if (rect.intersects(nodeRect)) {
- acc.push(node.id);
- if (node.groupId) {
- containedGroupIds.add(node.groupId);
- const group = groups.get(node.groupId);
- group.childNodes?.forEach((n) => acc.push(n));
- }
- }
- } else if (node.type === 'pencil') {
- if (Rect.checkPencilIntersection(node as PencilNode, rect)) {
- acc.push(node.id);
- if (node.groupId) {
- containedGroupIds.add(node.groupId);
- const group = groups.get(node.groupId);
- group.childNodes?.forEach((n) => acc.push(n));
- }
- }
- }
- return acc;
- }, []);
-
- const containedEdgeIds = egdes.visible().reduce((acc: string[], edge) => {
- const endPoints = getEdgeEndPoints(edge);
- const sel = () => {
- acc.push(edge.id);
- if (edge.groupId) {
- containedGroupIds.add(edge.groupId);
- const group = groups.get(edge.groupId);
- group.childEdges?.forEach((e) => acc.push(e));
- }
- };
- if (
- rect.containsPoint(endPoints.from) ||
- rect.containsPoint(endPoints.to)
- ) {
- sel();
- }
- const points = edgeToCollisionData(edge, [endPoints.from, endPoints.to]);
- for (let i = 1; i < points.length; i++) {
- const current = points[i];
- const previous = points[i - 1];
- if (rect.containsPoint(current)) {
- sel();
- break;
- }
- if (Rect.intersectLineSegment(rect, previous, current).length > 0) {
- sel();
- break;
- }
- }
- return acc;
- }, []);
-
- if (opts?.shiftKey) {
- containedNodeIds.push(...op.initialSelectedNodes);
- containedEdgeIds.push(...op.initialSelectedEdges);
- }
-
- forceSetSelection(
- containedNodeIds,
- containedEdgeIds,
- Array.from(containedGroupIds)
- );
- }
-
- return {
- reset() {
- _log('reset');
- setCurrentOperation();
- setSelectionBox();
- },
-
- start(e: PointerEvent) {
- _log('start');
- setCurrentOperation({
- type: 'select',
- timeStamp: Date.now(),
- initialMousePos: pageToCanvas(e),
- initialSelectedNodes: [...selection.getStashed().nodes],
- initialSelectedEdges: [...selection.getStashed().edges],
- });
- },
-
- commit(_e: PointerEvent) {
- _log('commit');
- setCurrentOperation();
- setSelectionBox();
- },
-
- abort() {
- _log('abort');
- setCurrentOperation();
- setSelectionBox();
- },
-
- preview(e: PointerEvent) {
- if (!currentOperation()) return;
- applyMousePos(pageToCanvas(e), {
- shiftKey: e.shiftKey,
- });
- _log('preview');
- },
-
- // TODO (seamus) : This is not ideal aesthetically. Active() should always return true if there
- // is an active operation. But see the logic inside of the selectionRenderer - we swtich from
- // showing the selectionRenderer with proper handdles to showing the box select box when the
- // box is bigger than some arbitrary size.
- active() {
- const op = currentOperation();
- if (op === undefined) return false;
- const pos = pageToCanvas({
- pageX: toolManager.mousePosition().x,
- pageY: toolManager.mousePosition().y,
- });
- return (op && op.initialMousePos.distance(pos) > 5) ?? false;
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/operation/shape.ts b/apps/web/src/features/block-canvas/operation/shape.ts
deleted file mode 100644
index f95f4e000c..0000000000
--- a/apps/web/src/features/block-canvas/operation/shape.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { unwrap } from 'solid-js/store';
-import { OPERATION_LOGGING, Tools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { ShapeNode } from '../model/CanvasModel';
-import { useCachedStyle } from '../signal/cachedStyle';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useSelection } from '../signal/selection';
-import { useToolManager } from '../signal/toolManager';
-import { useCanvasNodes } from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { sharedInstance } from '../util/sharedInstance';
-import type { Vector2 } from '../util/vector2';
-import type { Operation, Operator } from './operation';
-
-const minSize = 10;
-
-function _log(message: string) {
- if (!OPERATION_LOGGING || !DEV_MODE_ENV) return;
- console.log(`%c[Shape] ${message}`, 'color: goldenrod');
-}
-
-export type ShapeOperation = Operation & {
- type: 'shape';
- initialMousePos: Vector2;
- node: ShapeNode;
-};
-
-export const useShape = sharedInstance((): Operator => {
- const { pageToCanvas } = useRenderState();
- const { createNode, updateNode, ...nodes } = useCanvasNodes();
- const { deselectAll, deselectNode } = useSelection();
- const [currentShapeOperation, setCurrentShapeOperation] =
- useCanvasDocument().state.signals.currentShapeOperation;
- const history = useCanvasHistory();
- const cachedStyle = useCachedStyle();
- const { setSelectedTool } = useToolManager();
- const highestOrder = useCanvasDocument().state.signals.highestOrder[0];
-
- function _applyMousePos(mousePos: Vector2, normalize?: boolean) {
- const op = currentShapeOperation();
- if (!op) return;
- if (normalize) {
- const calculatedWidth = mousePos.x - op.initialMousePos.x;
- const calculatedHeight = mousePos.y - op.initialMousePos.y;
- updateNode(
- op.node.id,
- {
- x: Math.min(op.node.x, op.node.x + calculatedWidth),
- y: Math.min(op.node.y, op.node.y + calculatedHeight),
- width: Math.abs(calculatedWidth),
- height: Math.abs(calculatedHeight),
- },
- { preview: true }
- );
- } else {
- updateNode(
- op.node.id,
- {
- width: mousePos.x - op.initialMousePos.x,
- height: mousePos.y - op.initialMousePos.y,
- },
- { preview: true }
- );
- }
- }
-
- return {
- reset() {
- _log('reset');
- setCurrentShapeOperation();
- nodes.clearPreview();
- },
-
- start(e: PointerEvent) {
- _log('start');
- history.open();
- const mousePos = pageToCanvas(e);
- const node = createNode(
- {
- type: 'shape',
- shape: 'rectangle',
- x: mousePos.x,
- y: mousePos.y,
- width: 0,
- height: 0,
- edges: [],
- style: cachedStyle.getStyle(),
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { preview: true }
- ) as ShapeNode;
-
- setCurrentShapeOperation({
- type: 'shape',
- timeStamp: Date.now(),
- initialMousePos: mousePos,
- node,
- });
- },
-
- commit(e: PointerEvent) {
- const op = currentShapeOperation();
- if (!op) return;
- _log('commit');
- const mousePos = pageToCanvas(e);
- _applyMousePos(mousePos, true);
- const { id, ...newNode } = structuredClone(unwrap(op.node));
-
- if (newNode.width < minSize || newNode.height < minSize) {
- nodes.delete(id);
- setCurrentShapeOperation();
- nodes.clearPreview();
- deselectAll();
- return;
- }
-
- createNode(newNode, { autosave: true });
-
- setCurrentShapeOperation();
- nodes.clearPreview();
-
- history.close();
-
- setSelectedTool(Tools.Select);
- },
-
- abort() {
- const op = currentShapeOperation();
- if (!op) return;
- _log('abort');
- setCurrentShapeOperation();
- deselectNode(op.node.id);
- nodes.clearPreview();
- },
-
- preview(e: PointerEvent) {
- if (!currentShapeOperation()) return;
- _log('preview');
- const mousePos = pageToCanvas(e);
- _applyMousePos(mousePos);
- },
-
- active() {
- const op = currentShapeOperation();
- return !!op;
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/operation/text.ts b/apps/web/src/features/block-canvas/operation/text.ts
deleted file mode 100644
index e82145608b..0000000000
--- a/apps/web/src/features/block-canvas/operation/text.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { batch } from 'solid-js';
-import { unwrap } from 'solid-js/store';
-import { OPERATION_LOGGING } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { TextNode } from '../model/CanvasModel';
-import { useCachedStyle } from '../signal/cachedStyle';
-import { useCanvasHistory } from '../signal/canvasHistory';
-import { useSelection } from '../signal/selection';
-import { useCanvasNodes } from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { sharedInstance } from '../util/sharedInstance';
-import type { Vector2 } from '../util/vector2';
-import type { Operation, Operator } from './operation';
-
-function _log(message: string) {
- if (!OPERATION_LOGGING || !DEV_MODE_ENV) return;
- console.log(`%c[Text] ${message}`, 'color: peru');
-}
-
-export type TextOperation = Operation & {
- type: 'text';
- initialMousePos: Vector2;
- node: TextNode;
-};
-
-export const useText = sharedInstance((): Operator => {
- const { pageToCanvas } = useRenderState();
- const { createNode, updateNode, ...nodes } = useCanvasNodes();
- const { deselectNode } = useSelection();
- const [currentTextOperation, setCurrentTextOperation] =
- useCanvasDocument().state.signals.currentTextOperation;
- const history = useCanvasHistory();
- const cachedStyle = useCachedStyle();
- const highestOrder = useCanvasDocument().state.signals.highestOrder[0];
-
- function _applyMousePos(mousePos: Vector2, normalize?: boolean) {
- const op = currentTextOperation();
- if (!op) return;
- if (normalize) {
- const calculatedWidth = mousePos.x - op.initialMousePos.x;
- const calculatedHeight = mousePos.y - op.initialMousePos.y;
- updateNode(
- op.node.id,
- {
- x: Math.min(op.node.x, op.node.x + calculatedWidth),
- y: Math.min(op.node.y, op.node.y + calculatedHeight),
- width: Math.abs(calculatedWidth),
- },
- { preview: true }
- );
- } else {
- updateNode(
- op.node.id,
- {
- width: mousePos.x - op.initialMousePos.x,
- },
- { preview: true }
- );
- }
- }
-
- return {
- reset() {
- _log('reset');
- setCurrentTextOperation();
- nodes.clearPreview();
- },
-
- start(e: PointerEvent) {
- _log('start');
- history.open();
- const mousePos = pageToCanvas(e);
- const fontSize = cachedStyle.getStyle().fontSize ?? 24;
-
- const node = createNode(
- {
- type: 'text',
- x: mousePos.x,
- y: mousePos.y,
- width: 0,
- height: 2.25 * fontSize,
- edges: [],
- style: cachedStyle.getStyle(),
- text: '',
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- {
- preview: true,
- }
- ) as TextNode;
-
- setCurrentTextOperation({
- type: 'text',
- timeStamp: Date.now(),
- initialMousePos: mousePos,
- node,
- });
- },
-
- commit(e: PointerEvent) {
- const op = currentTextOperation();
- if (!op) return;
- _log('commit');
- const mousePos = pageToCanvas(e);
- _applyMousePos(mousePos, true);
- const { id: _, ...newNode } = structuredClone(unwrap(op.node));
-
- // If the drag was small, then make follow text node.
- if (newNode.width < 10) {
- newNode.followTextWidth = true;
- }
-
- batch(() => {
- const { id: newId } = createNode(newNode, { autosave: true });
- setCurrentTextOperation();
- nodes.clearPreview();
- history.close();
- nodes.setLastCreated(newId);
- });
- },
-
- abort() {
- const op = currentTextOperation();
- if (!op) return;
- _log('abort');
- setCurrentTextOperation();
- deselectNode(op.node.id);
- nodes.clearPreview();
- },
-
- preview(e: PointerEvent) {
- if (!currentTextOperation()) return;
- _log('preview');
- const mousePos = pageToCanvas(e);
- _applyMousePos(mousePos);
- },
-
- active() {
- const op = currentTextOperation();
- return !!op;
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/asset-drop.ts b/apps/web/src/features/block-canvas/primitives/asset-drop.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/asset-drop.ts
rename to apps/web/src/features/block-canvas/primitives/asset-drop.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.test.ts b/apps/web/src/features/block-canvas/primitives/create-asset-state.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.test.ts
rename to apps/web/src/features/block-canvas/primitives/create-asset-state.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.ts b/apps/web/src/features/block-canvas/primitives/create-asset-state.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.ts
rename to apps/web/src/features/block-canvas/primitives/create-asset-state.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.test.ts b/apps/web/src/features/block-canvas/primitives/create-canvas-snapping.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.test.ts
rename to apps/web/src/features/block-canvas/primitives/create-canvas-snapping.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.ts b/apps/web/src/features/block-canvas/primitives/create-canvas-snapping.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.ts
rename to apps/web/src/features/block-canvas/primitives/create-canvas-snapping.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.test.ts b/apps/web/src/features/block-canvas/primitives/create-canvas-state.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.test.ts
rename to apps/web/src/features/block-canvas/primitives/create-canvas-state.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.ts b/apps/web/src/features/block-canvas/primitives/create-canvas-state.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.ts
rename to apps/web/src/features/block-canvas/primitives/create-canvas-state.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-connector-state.ts b/apps/web/src/features/block-canvas/primitives/create-connector-state.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-connector-state.ts
rename to apps/web/src/features/block-canvas/primitives/create-connector-state.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.test.ts b/apps/web/src/features/block-canvas/primitives/create-document-persistence.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.test.ts
rename to apps/web/src/features/block-canvas/primitives/create-document-persistence.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.ts b/apps/web/src/features/block-canvas/primitives/create-document-persistence.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.ts
rename to apps/web/src/features/block-canvas/primitives/create-document-persistence.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-embed-state.ts b/apps/web/src/features/block-canvas/primitives/create-embed-state.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-embed-state.ts
rename to apps/web/src/features/block-canvas/primitives/create-embed-state.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.test.ts b/apps/web/src/features/block-canvas/primitives/create-eraser-state.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.test.ts
rename to apps/web/src/features/block-canvas/primitives/create-eraser-state.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.ts b/apps/web/src/features/block-canvas/primitives/create-eraser-state.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.ts
rename to apps/web/src/features/block-canvas/primitives/create-eraser-state.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.test.ts b/apps/web/src/features/block-canvas/primitives/create-inspector-preview.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.test.ts
rename to apps/web/src/features/block-canvas/primitives/create-inspector-preview.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.ts b/apps/web/src/features/block-canvas/primitives/create-inspector-preview.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.ts
rename to apps/web/src/features/block-canvas/primitives/create-inspector-preview.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-text-state.ts b/apps/web/src/features/block-canvas/primitives/create-text-state.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/create-text-state.ts
rename to apps/web/src/features/block-canvas/primitives/create-text-state.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.test.ts b/apps/web/src/features/block-canvas/primitives/read-swatch-color.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.test.ts
rename to apps/web/src/features/block-canvas/primitives/read-swatch-color.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.ts b/apps/web/src/features/block-canvas/primitives/read-swatch-color.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.ts
rename to apps/web/src/features/block-canvas/primitives/read-swatch-color.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/text-input.test.ts b/apps/web/src/features/block-canvas/primitives/text-input.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/text-input.test.ts
rename to apps/web/src/features/block-canvas/primitives/text-input.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/text-input.ts b/apps/web/src/features/block-canvas/primitives/text-input.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/text-input.ts
rename to apps/web/src/features/block-canvas/primitives/text-input.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.test.ts b/apps/web/src/features/block-canvas/primitives/text-lexical.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.test.ts
rename to apps/web/src/features/block-canvas/primitives/text-lexical.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.ts b/apps/web/src/features/block-canvas/primitives/text-lexical.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.ts
rename to apps/web/src/features/block-canvas/primitives/text-lexical.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/queries/assets.ts b/apps/web/src/features/block-canvas/queries/assets.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/queries/assets.ts
rename to apps/web/src/features/block-canvas/queries/assets.ts
diff --git a/apps/web/src/features/block-canvas/queries/canvas-document.test.ts b/apps/web/src/features/block-canvas/queries/canvas-document.test.ts
index ae2b0db031..520d07dc77 100644
--- a/apps/web/src/features/block-canvas/queries/canvas-document.test.ts
+++ b/apps/web/src/features/block-canvas/queries/canvas-document.test.ts
@@ -29,24 +29,6 @@ describe('canvas document queries', () => {
});
});
- it('serializes canvas data for storage', async () => {
- storageMocks.simpleSave.mockResolvedValue(ok({}));
- const canvas = {
- nodes: [],
- edges: [],
- groups: [],
- };
-
- const result = await saveCanvasDocument('canvas-1', canvas);
-
- expect(result.saved).toBe(true);
- expect(storageMocks.simpleSave).toHaveBeenCalledWith({
- documentId: 'canvas-1',
- file: result.file,
- });
- expect(await readBlob(result.file)).toBe(JSON.stringify(canvas));
- });
-
it('stores version 2 through the same JSON endpoint and MIME type', async () => {
storageMocks.simpleSave.mockResolvedValue(ok({}));
const editor = createGraphicsEditor();
diff --git a/apps/web/src/features/block-canvas/queries/canvas-document.ts b/apps/web/src/features/block-canvas/queries/canvas-document.ts
index 0400d6d868..d39d215556 100644
--- a/apps/web/src/features/block-canvas/queries/canvas-document.ts
+++ b/apps/web/src/features/block-canvas/queries/canvas-document.ts
@@ -1,6 +1,5 @@
import { storageServiceClient } from '@service-storage/client';
-import type { CanvasFile } from '../canvas-next/core/document-format';
-import type { Canvas } from '../model/CanvasModel';
+import type { CanvasFile } from '../core/document-format';
export type CanvasViewLocation = {
x?: number;
@@ -32,7 +31,7 @@ export async function fetchCanvasViewLocation(
export async function saveCanvasDocument(
documentId: string,
- canvas: Canvas | CanvasFile
+ canvas: CanvasFile
): Promise<{ file: Blob; saved: boolean }> {
const buffer = new TextEncoder().encode(JSON.stringify(canvas));
const file = new Blob([buffer], {
diff --git a/apps/web/src/features/block-canvas/canvas-next/queries/document.test.ts b/apps/web/src/features/block-canvas/queries/document.test.ts
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/queries/document.test.ts
rename to apps/web/src/features/block-canvas/queries/document.test.ts
diff --git a/apps/web/src/features/block-canvas/canvas-next/queries/document.ts b/apps/web/src/features/block-canvas/queries/document.ts
similarity index 89%
rename from apps/web/src/features/block-canvas/canvas-next/queries/document.ts
rename to apps/web/src/features/block-canvas/queries/document.ts
index 447600e0c5..1d8fb2ab1a 100644
--- a/apps/web/src/features/block-canvas/canvas-next/queries/document.ts
+++ b/apps/web/src/features/block-canvas/queries/document.ts
@@ -1,6 +1,6 @@
-import { saveCanvasDocument } from '../../queries/canvas-document';
import type { CanvasDocumentSource } from '../context/document-source';
import { readCanvasFile } from '../core/document-format';
+import { saveCanvasDocument } from './canvas-document';
export function canvasDocumentSource(
documentId: string,
diff --git a/apps/web/src/features/block-canvas/signal/align.ts b/apps/web/src/features/block-canvas/signal/align.ts
deleted file mode 100644
index d6574f605e..0000000000
--- a/apps/web/src/features/block-canvas/signal/align.ts
+++ /dev/null
@@ -1,430 +0,0 @@
-import { sharedInstance } from '@block-canvas/util/sharedInstance';
-import { type Vector2, vec2 } from '@block-canvas/util/vector2';
-import { batch } from 'solid-js';
-import {
- useBoundingBox,
- useCanvasEdges,
- useCanvasNodes,
-} from '../store/canvasData';
-import { useCanvasHistory } from './canvasHistory';
-import { useSelection } from './selection';
-
-export const useAlign = sharedInstance(() => {
- const history = useCanvasHistory();
- const selection = useSelection();
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
- const boundingBox = useBoundingBox();
-
- return {
- align(alignment: number, autosave?: boolean) {
- history.open();
- const bounds = selection.selectionBounds();
-
- if (!bounds) return;
-
- const boundsXStart = bounds.x;
- const boundsXMid = bounds.x + bounds.w / 2;
- const boundsXEnd = bounds.x + bounds.w;
- const boundsYStart = bounds.y;
- const boundsYMid = bounds.y + bounds.h / 2;
- const boundsYEnd = bounds.y + bounds.h;
-
- const groupsPos = new Map<
- string,
- { x: number; y: number; width: number; height: number }
- >();
- const groupsToMove = new Map<string, Vector2>();
-
- selection.selectedGroups().forEach((group) => {
- const groupId = group.id;
- let groupPos = groupsPos.get(groupId);
- if (!groupPos) {
- const groupBounds = boundingBox(
- group.childNodes?.map((n) => nodes.get(n)) ?? [],
- group.childEdges?.map((e) => edges.get(e)) ?? []
- );
- groupPos = {
- x: groupBounds.x,
- y: groupBounds.y,
- width: groupBounds.w,
- height: groupBounds.h,
- };
- groupsPos.set(groupId, groupPos);
- }
- if (!groupsToMove.get(groupId)) {
- switch (alignment) {
- case 0:
- groupsToMove.set(groupId, vec2(groupPos.x - boundsXStart, 0));
- break;
- case 1:
- groupsToMove.set(
- groupId,
- vec2(groupPos.x - (boundsXMid - groupPos.width / 2), 0)
- );
- break;
- case 2:
- groupsToMove.set(
- groupId,
- vec2(groupPos.x - (boundsXEnd - groupPos.width), 0)
- );
- break;
- case 3:
- groupsToMove.set(groupId, vec2(0, groupPos.y - boundsYStart));
- break;
- case 4:
- groupsToMove.set(
- groupId,
- vec2(0, groupPos.y - (boundsYMid - groupPos.height / 2))
- );
- break;
- case 5:
- groupsToMove.set(
- groupId,
- vec2(0, groupPos.y - (boundsYEnd - groupPos.height))
- );
- break;
- }
- }
- });
-
- batch(() => {
- nodes.batchUpdate(
- () => {
- selection.selectedNodeIds().forEach((nodeId) => {
- const original = nodes.get(nodeId);
- const groupId = original.groupId;
- if (groupId) {
- let group = groupsPos.get(groupId);
- if (group) {
- let groupShift = groupsToMove.get(groupId);
- nodes.updateNode(nodeId, {
- x: original.x - groupShift!.x,
- y: original.y - groupShift!.y,
- });
- return;
- }
- } else {
- switch (alignment) {
- case 0:
- nodes.updateNode(nodeId, { x: boundsXStart });
- break;
- case 1:
- nodes.updateNode(nodeId, {
- x: boundsXMid - original.width / 2,
- });
- break;
- case 2:
- nodes.updateNode(nodeId, {
- x: boundsXEnd - original.width,
- });
- break;
- case 3:
- nodes.updateNode(nodeId, { y: boundsYStart });
- break;
- case 4:
- nodes.updateNode(nodeId, {
- y: boundsYMid - original.height / 2,
- });
- break;
- case 5:
- nodes.updateNode(nodeId, {
- y: boundsYEnd - original.height,
- });
- break;
- }
- }
- });
- },
- { autosave }
- );
-
- edges.batchUpdate(
- () => {
- selection.selectedEdgeIds().forEach((edgeId) => {
- const original = edges.get(edgeId);
- const groupId = original.groupId;
- if (groupId) {
- let groupShift = groupsToMove.get(groupId);
- edges.updateEdge(edgeId, {
- from:
- original.from.type === 'free'
- ? {
- type: 'free',
- x: original.from.x - groupShift!.x,
- y: original.from.y - groupShift!.y,
- }
- : original.from,
- to:
- original.to.type === 'free'
- ? {
- type: 'free',
- x: original.to.x - groupShift!.x,
- y: original.to.y - groupShift!.y,
- }
- : original.to,
- });
- } else {
- switch (alignment) {
- case 0:
- if (
- original.from.type === 'free' &&
- original.to.type === 'free'
- ) {
- const xShift =
- original.from.x < original.to.x
- ? original.from.x - boundsXStart
- : original.to.x - boundsXStart;
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: original.from.x - xShift,
- y: original.from.y,
- },
- to: {
- type: 'free',
- x: original.to.x - xShift,
- y: original.to.y,
- },
- });
- } else if (original.from.type === 'free') {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: boundsXStart,
- y: original.from.y,
- },
- });
- } else if (original.to.type === 'free') {
- edges.updateEdge(edgeId, {
- to: {
- type: 'free',
- x: boundsXStart,
- y: original.to.y,
- },
- });
- }
- break;
- case 1:
- if (
- original.from.type === 'free' &&
- original.to.type === 'free'
- ) {
- const xMidpoint = (original.to.x - original.from.x) / 2; // midpoint between ends
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: boundsXMid - xMidpoint,
- y: original.from.y,
- },
- to: {
- type: 'free',
- x: boundsXMid + xMidpoint,
- y: original.to.y,
- },
- });
- } else if (original.from.type === 'free') {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: boundsXMid,
- y: original.from.y,
- },
- });
- } else if (original.to.type === 'free') {
- edges.updateEdge(edgeId, {
- to: {
- type: 'free',
- x: boundsXMid,
- y: original.to.y,
- },
- });
- }
- break;
- case 2:
- if (
- original.from.type === 'free' &&
- original.to.type === 'free'
- ) {
- if (original.from.x > original.to.x) {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: boundsXEnd,
- y: original.from.y,
- },
- to: {
- type: 'free',
- x: boundsXEnd - (original.from.x - original.to.x),
- y: original.to.y,
- },
- });
- } else {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: boundsXEnd - (original.to.x - original.from.x),
- y: original.from.y,
- },
- to: {
- type: 'free',
- x: boundsXEnd,
- y: original.to.y,
- },
- });
- }
- } else if (original.from.type === 'free') {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: boundsXEnd,
- y: original.from.y,
- },
- });
- } else if (original.to.type === 'free') {
- edges.updateEdge(edgeId, {
- to: {
- type: 'free',
- x: boundsXEnd,
- y: original.to.y,
- },
- });
- }
- break;
- case 3:
- if (
- original.from.type === 'free' &&
- original.to.type === 'free'
- ) {
- const yShift =
- original.from.y < original.to.y
- ? original.from.y - boundsYStart
- : original.to.y - boundsYStart;
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: original.from.x,
- y: original.from.y - yShift,
- },
- to: {
- type: 'free',
- x: original.to.x,
- y: original.to.y - yShift,
- },
- });
- } else if (original.from.type === 'free') {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: original.from.x,
- y: boundsYStart,
- },
- });
- } else if (original.to.type === 'free') {
- edges.updateEdge(edgeId, {
- to: {
- type: 'free',
- x: original.to.x,
- y: boundsYStart,
- },
- });
- }
- break;
- case 4:
- if (
- original.from.type === 'free' &&
- original.to.type === 'free'
- ) {
- const yMidpoint = (original.to.y - original.from.y) / 2;
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: original.from.x,
- y: boundsYMid - yMidpoint,
- },
- to: {
- type: 'free',
- x: original.to.x,
- y: boundsYMid + yMidpoint,
- },
- });
- } else if (original.from.type === 'free') {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: original.from.x,
- y: boundsYMid,
- },
- });
- } else if (original.to.type === 'free') {
- edges.updateEdge(edgeId, {
- to: {
- type: 'free',
- x: original.to.x,
- y: boundsYMid,
- },
- });
- }
- break;
- case 5:
- if (
- original.from.type === 'free' &&
- original.to.type === 'free'
- ) {
- if (original.from.y > original.to.y) {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: original.from.x,
- y: boundsYEnd,
- },
- to: {
- type: 'free',
- x: original.to.x,
- y: boundsYEnd - (original.from.y - original.to.y),
- },
- });
- } else {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: original.from.x,
- y: boundsYEnd - (original.from.y - original.to.y),
- },
- to: {
- type: 'free',
- x: original.to.x,
- y: boundsYEnd,
- },
- });
- }
- } else if (original.from.type === 'free') {
- edges.updateEdge(edgeId, {
- from: {
- type: 'free',
- x: original.from.x,
- y: boundsYEnd,
- },
- });
- } else if (original.to.type === 'free') {
- edges.updateEdge(edgeId, {
- to: {
- type: 'free',
- x: original.to.x,
- y: boundsYEnd,
- },
- });
- }
- break;
- }
- }
- });
- },
- { autosave }
- );
-
- history.close();
- });
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/signal/cachedStyle.ts b/apps/web/src/features/block-canvas/signal/cachedStyle.ts
deleted file mode 100644
index a2681950bc..0000000000
--- a/apps/web/src/features/block-canvas/signal/cachedStyle.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { createMemo } from 'solid-js';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { CanvasEntityStyle } from '../model/CanvasModel';
-
-export function useCachedStyle() {
- const [style, setStyle] = useCanvasDocument().state.stores.cachedStyle;
- return {
- getStyle: createMemo(() => JSON.parse(JSON.stringify(style))),
- setProp: (prop: keyof CanvasEntityStyle, value: any) => {
- setStyle(prop, value);
- },
- };
-}
diff --git a/apps/web/src/features/block-canvas/signal/canvasHistory.ts b/apps/web/src/features/block-canvas/signal/canvasHistory.ts
deleted file mode 100644
index ede5da5ba7..0000000000
--- a/apps/web/src/features/block-canvas/signal/canvasHistory.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { sharedInstance } from '@block-canvas/util/sharedInstance';
-import { batch, untrack } from 'solid-js';
-import { reconcile, unwrap } from 'solid-js/store';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { CanvasEdge, CanvasId, CanvasNode } from '../model/CanvasModel';
-import {
- renderQueue,
- useCanvasEdges,
- useCanvasNodes,
-} from '../store/canvasData';
-import type { Renderable } from '../util/renderQueue';
-import { useSelection } from './selection';
-
-export type Snapshot = {
- renderQueue: Renderable[];
- allNodes: Record<CanvasId, CanvasNode>;
- allEdges: Record<string, CanvasEdge>;
- selectedNodeIds: CanvasId[];
- selectedEdgeIds: string[];
- selectedGroupIds: string[];
-};
-
-const MAX_HISTORY_LENGTH = 40;
-
-export const useCanvasHistory = sharedInstance(createHistory);
-
-function createHistory() {
- const canvasState = useCanvasDocument().state;
- const state = canvasState.signals;
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
- const selection = useSelection();
- const [history, setHistory] = state.history;
- const [current, setCurrent] = state.currentHistory;
- const [currentIndex, setCurrentIndex] = state.currentHistoryIndex;
- const [allNodes, setNodeStore] = canvasState.stores.nodes;
- const [allEdges, setEdgeStore] = canvasState.stores.edges;
- const queue = renderQueue();
-
- function createSnapshot(): Snapshot {
- return {
- renderQueue: JSON.parse(JSON.stringify(untrack(queue.list))),
- allNodes: JSON.parse(JSON.stringify(unwrap(allNodes))),
- allEdges: JSON.parse(JSON.stringify(unwrap(allEdges))),
- selectedNodeIds: [...selection.selectedNodeIds()],
- selectedEdgeIds: [...selection.selectedEdgeIds()],
- selectedGroupIds: [...selection.selectedGroupIds()],
- };
- }
-
- function applySnapshot(snapshot: Snapshot) {
- batch(() => {
- queue.forceSet(snapshot.renderQueue);
- setNodeStore(reconcile(snapshot.allNodes));
- setEdgeStore(reconcile(snapshot.allEdges));
- selection.forceSetSelection(
- snapshot.selectedNodeIds,
- snapshot.selectedEdgeIds,
- snapshot.selectedGroupIds
- );
- });
- }
-
- function addToHistory(snapshot: Snapshot, setIndex = true) {
- const nextIndex = currentIndex() + 1;
-
- // kill the future.
- const newHistory = history().slice(0, nextIndex);
- newHistory.push(snapshot);
-
- if (newHistory.length > MAX_HISTORY_LENGTH) {
- newHistory.shift();
- }
-
- setHistory(newHistory);
- if (setIndex) setCurrentIndex(Math.min(nextIndex, newHistory.length - 1));
- }
-
- return {
- open: () => {
- setCurrent(createSnapshot());
- },
-
- close: () => {
- const currentSnapshot = current();
- if (!currentSnapshot) return;
- addToHistory(currentSnapshot);
- setCurrent(undefined);
- },
-
- undo: () => {
- // push current state to history at stack top - for the first redo
- if (currentIndex() === history().length - 1) {
- addToHistory(createSnapshot());
- }
-
- if (currentIndex() === 0) {
- // toast.failure('Nothing to undo');
- return;
- }
-
- // now jump one back
- setCurrentIndex(currentIndex() - 1);
- const previousSnapshot = history()[currentIndex()];
- if (!previousSnapshot) {
- return;
- }
- applySnapshot(previousSnapshot);
- nodes.save();
- edges.save();
- },
-
- redo: () => {
- const snapshot = history()[currentIndex() + 1];
- if (!snapshot) return;
-
- // Create a snapshot of the current state before applying the redo
- const currentSnapshot = createSnapshot();
- addToHistory(currentSnapshot, false); // Add without changing the index
-
- applySnapshot(snapshot);
- setCurrentIndex(currentIndex() + 1);
- },
-
- clearHistory: () => {
- setHistory([]);
- setCurrentIndex(-1);
- setCurrent(undefined);
- },
-
- getCurrentIndex: () => currentIndex(),
- getHistoryLength: () => history().length,
- };
-}
diff --git a/apps/web/src/features/block-canvas/signal/clipboard.ts b/apps/web/src/features/block-canvas/signal/clipboard.ts
deleted file mode 100644
index a3a52f65e6..0000000000
--- a/apps/web/src/features/block-canvas/signal/clipboard.ts
+++ /dev/null
@@ -1,451 +0,0 @@
-import { sharedInstance } from '@block-canvas/util/sharedInstance';
-import { getTextNodeHeight } from '@block-canvas/util/style';
-import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';
-import { jsonToXML } from '@core/component/LexicalMarkdown/citationsUtils';
-import { resolvePastedMacroAppUrl } from '@core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin';
-import { blockNameToFileExtensions } from '@core/constant/allBlocks';
-import { CANVAS_SVG_IMPORT } from '@core/constant/featureFlags';
-import { nanoid } from 'nanoid';
-import { batch } from 'solid-js';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import {
- type Canvas,
- type CanvasEdge,
- type CanvasNode,
- CanvasSchema,
-} from '../model/CanvasModel';
-import {
- useBoundingBox,
- useCanvasEdges,
- useCanvasGroups,
- useCanvasNodes,
-} from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { Rect } from '../util/rectangle';
-import { type Vector2, vec2 } from '../util/vector2';
-import { useCachedStyle } from './cachedStyle';
-import { useCanvasHistory } from './canvasHistory';
-import { useCanvasFileDrop } from './fileDrop';
-import { useSelection } from './selection';
-import { useToolManager } from './toolManager';
-
-export const useClipboard = sharedInstance(() => {
- const {
- selectedNodeIds,
- selectedEdgeIds,
- active,
- forceSetSelection,
- deselectAll,
- } = useSelection();
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
- const groups = useCanvasGroups();
- const highestOrder = useCanvasDocument().state.signals.highestOrder[0];
- const history = useCanvasHistory();
- const { staticImageUpload, parseSVGStringToNodes } = useCanvasFileDrop();
- const boundingBox = useBoundingBox();
- const { activeTextEditor } = useToolManager();
- const resolveAppLink = useMacroMentionLinkResolver();
-
- const cachedStyle = useCachedStyle();
- const style = cachedStyle.getStyle;
-
- const { currentPosition, currentScale, viewBox } = useRenderState();
-
- const checkForMacroUrl = (text: string): string => {
- const parsedMacroAppUrl = resolvePastedMacroAppUrl(text, resolveAppLink);
- if (!parsedMacroAppUrl?.id || !parsedMacroAppUrl.block) {
- return text;
- }
-
- return jsonToXML('m-document-mention', {
- documentId: parsedMacroAppUrl.id,
- blockName: parsedMacroAppUrl.block,
- documentName: '',
- blockParams: parsedMacroAppUrl.params,
- });
- };
-
- const pasteCanvas = (copiedText: string, position?: Vector2) => {
- if (activeTextEditor()) return;
-
- const json = JSON.parse(copiedText);
- const canvasData = CanvasSchema.parse(json);
- const pastedNodes = (canvasData.nodes ?? []) as CanvasNode[];
- const pastedEdges = (canvasData.edges ?? []) as CanvasEdge[];
- const groupMap = new Map();
-
- // todo: throw or return if not valid parse;
- if (pastedNodes.length === 0 && pastedEdges.length === 0) return;
-
- const freeEdges = pastedEdges.filter(
- (edge) => edge.from.type === 'free' || edge.to.type === 'free'
- );
- const originalBounds = boundingBox(pastedNodes, freeEdges);
- const pasteCenter = position ?? originalBounds.center;
- let offset = vec2(10, 10);
-
- if (!viewBox().containsPoint(pasteCenter)) {
- offset = currentPosition()
- .multiply(-1 / currentScale())
- .subtract(pasteCenter);
- }
-
- const updatedIds = new Map<string, string>();
-
- if (position) {
- const freeEdges = pastedEdges.filter(
- (edge) => edge.from.type === 'free' || edge.to.type === 'free'
- );
- const bounds = boundingBox(pastedNodes, freeEdges);
- const widthOffset = position.x - bounds.x - bounds.width / 2;
- const heightOffset = position.y - bounds.y - bounds.height / 2;
-
- pastedNodes.forEach((node) => {
- const newId = nanoid(8);
- node.x += widthOffset;
- node.y += heightOffset;
- updatedIds.set(node.id, newId);
- node.id = newId;
- if (node.groupId) {
- if (groupMap.has(node.groupId)) {
- node.groupId = groupMap.get(node.groupId);
- groups.addNode(node.groupId!, newId);
- } else {
- const newGroupId = nanoid(8);
- groupMap.set(node.groupId, newGroupId);
- node.groupId = newGroupId;
- groups.createGroup(
- newGroupId,
- highestOrder() + 1,
- node.layer,
- [newId],
- []
- );
- }
- }
- });
- pastedEdges.forEach((edge) => {
- const newId = nanoid(8);
- updatedIds.set(edge.id, newId);
- edge.id = newId;
- if (edge.from.type === 'free') {
- edge.from.x += widthOffset;
- edge.from.y += heightOffset;
- } else if (edge.from.type === 'connected') {
- edge.from.node = updatedIds.get(edge.from.node) ?? edge.from.node;
- }
- if (edge.to.type === 'free') {
- edge.to.x += widthOffset;
- edge.to.y += heightOffset;
- } else if (edge.to.type === 'connected') {
- edge.to.node = updatedIds.get(edge.to.node) ?? edge.to.node;
- }
- if (edge.groupId) {
- if (groupMap.has(edge.groupId)) {
- edge.groupId = groupMap.get(edge.groupId);
- groups.addNode(edge.groupId!, newId);
- } else {
- const newGroupId = nanoid(8);
- groupMap.set(edge.groupId, newGroupId);
- edge.groupId = newGroupId;
- groups.createGroup(
- newGroupId,
- highestOrder() + 1,
- edge.layer,
- [],
- [newId]
- );
- }
- }
- });
- } else {
- pastedNodes.forEach((node) => {
- const newId = nanoid(8);
- node.x += offset.x;
- node.y += offset.y;
- updatedIds.set(node.id, newId);
- node.id = newId;
- if (node.groupId) {
- if (groupMap.has(node.groupId)) {
- node.groupId = groupMap.get(node.groupId);
- groups.addNode(node.groupId!, newId);
- } else {
- const newGroupId = nanoid(8);
- groupMap.set(node.groupId, newGroupId);
- node.groupId = newGroupId;
- groups.createGroup(
- newGroupId,
- highestOrder() + 1,
- node.layer,
- [newId],
- []
- );
- }
- }
- });
- pastedEdges.forEach((edge) => {
- const newId = nanoid(8);
- updatedIds.set(edge.id, newId);
- edge.id = newId;
- if (edge.from.type === 'free') {
- edge.from.x += offset.x;
- edge.from.y += offset.y;
- } else if (edge.from.type === 'connected') {
- edge.from.node = updatedIds.get(edge.from.node) ?? edge.from.node;
- }
- if (edge.to.type === 'free') {
- edge.to.x += offset.x;
- edge.to.y += offset.y;
- } else if (edge.to.type === 'connected') {
- edge.to.node = updatedIds.get(edge.to.node) ?? edge.to.node;
- }
- if (edge.groupId) {
- if (groupMap.has(edge.groupId)) {
- edge.groupId = groupMap.get(edge.groupId);
- groups.addNode(edge.groupId!, newId);
- } else {
- const newGroupId = nanoid(8);
- groupMap.set(edge.groupId, newGroupId);
- edge.groupId = newGroupId;
- groups.createGroup(
- newGroupId,
- highestOrder() + 1,
- edge.layer,
- [],
- [newId]
- );
- }
- }
- });
- }
- for (const node of pastedNodes) {
- node.edges = node.edges.map((edgeId) => {
- if (updatedIds.has(edgeId)) {
- return updatedIds.get(edgeId)!;
- }
- return edgeId;
- });
- }
-
- const pastedGroupIds = new Set<string>();
-
- batch(() => {
- nodes.batchUpdate(
- () => {
- for (const node of pastedNodes) {
- nodes.createNode(node);
- if (node.groupId) pastedGroupIds.add(node.groupId);
- }
- },
- { autosave: true }
- );
- edges.batchUpdate(
- () => {
- for (const edge of pastedEdges) {
- edges.createEdge(edge);
- if (edge.groupId) pastedGroupIds.add(edge.groupId);
- }
- },
- { autosave: true }
- );
- });
-
- const pastedNodeIds = pastedNodes.map((node) => node.id);
- const pastedEdgeIds = pastedEdges.map((edge) => edge.id);
-
- forceSetSelection(pastedNodeIds, pastedEdgeIds, Array.from(pastedGroupIds));
- };
-
- const handleStandardPaste = async (position?: Vector2) => {
- const clipboardData = await navigator.clipboard.read();
- const item = clipboardData[0];
- if (!item) return;
- const centerPoint = currentPosition().multiply(-1 / currentScale());
-
- history.open();
- deselectAll();
-
- if (item.types.includes('text/plain')) {
- let copiedText = await navigator.clipboard.readText();
- try {
- // Paste Canvas
- if (copiedText.startsWith('<svg ') && copiedText.endsWith('</svg>')) {
- if (CANVAS_SVG_IMPORT) {
- parseSVGStringToNodes(copiedText, centerPoint);
- } else {
- const blob = new Blob([copiedText], { type: 'image/svg+xml' });
- staticImageUpload(blob, centerPoint);
- }
- } else {
- pasteCanvas(copiedText, position);
- }
- } catch {
- // Paste text box
- const id = nanoid(8);
- const height = getTextNodeHeight(style().fontSize);
- const centerPoint = currentPosition().multiply(-1 / currentScale());
- nodes.setLastCreated(id);
- nodes.createNode(
- {
- id,
- type: 'text',
- x: centerPoint.x,
- y: centerPoint.y,
- width: 0,
- height,
- edges: [],
- style: style(),
- text: checkForMacroUrl(copiedText),
- followTextWidth: true,
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { autosave: true }
- );
- }
- history.close();
- return;
- }
-
- for (const imageType of blockNameToFileExtensions.image) {
- const mime = `image/${imageType}`;
- if (item.types.includes(mime)) {
- const blob = await item.getType(mime);
- staticImageUpload(blob, centerPoint);
- history.close();
- return;
- }
- }
- };
-
- // Some older applications may write image data to the clipboard in a way that is not
- // compatible with the newer clipboard API. This has to be a synchronous call and the above
- // paste method is cleaner as an async - hence the annoying branching.
- const handleLegacyImagePaste = (e: ClipboardEvent): boolean => {
- if (!e.clipboardData) return false;
- const items = e.clipboardData.items;
- for (const item of items) {
- if (
- blockNameToFileExtensions.image.includes(
- item.type.replace('image/', '')
- )
- ) {
- const blob = item.getAsFile();
- if (blob) {
- const centerPoint = currentPosition().multiply(-1 / currentScale());
- history.open();
- deselectAll();
- staticImageUpload(blob, centerPoint);
- history.close();
- return true;
- }
- }
- }
- return false;
- };
-
- return {
- copySelection(cut?: boolean) {
- if (!active()) return;
-
- let canvasNodes: CanvasNode[] = [];
- selectedNodeIds().forEach((id) => {
- const node = nodes.get(id);
- if (node) canvasNodes.push(node);
- });
-
- let canvasEdges: CanvasEdge[] = [];
- selectedEdgeIds().forEach((id) => {
- const edge = edges.get(id);
- if (edge) canvasEdges.push(edge);
- });
-
- canvasEdges = JSON.parse(JSON.stringify(canvasEdges));
- canvasNodes = JSON.parse(JSON.stringify(canvasNodes));
-
- const updatedIds = new Map<string, string>();
-
- for (const node of canvasNodes) {
- const newId = nanoid(8);
- updatedIds.set(node.id, newId);
- node.id = newId;
- }
-
- for (const edge of canvasEdges) {
- const newId = nanoid(8);
- updatedIds.set(edge.id, newId);
- edge.id = newId;
-
- if (edge.from.type === 'connected') {
- if (updatedIds.has(edge.from.node)) {
- edge.from.node = updatedIds.get(edge.from.node)!;
- } else {
- const oldNode = nodes.get(edge.from.node);
- // todo : what if there is no node? - shouldn't happen but .....
- const pos = Rect.centerPointOfEdge(oldNode, edge.from.side);
- edge.from = {
- type: 'free',
- x: pos.x,
- y: pos.y,
- };
- }
- }
-
- if (edge.to.type === 'connected') {
- if (updatedIds.has(edge.to.node)) {
- edge.to.node = updatedIds.get(edge.to.node)!;
- } else {
- const oldNode = nodes.get(edge.to.node);
- // todo : what if there is no node? - shouldn't happen but .....
- const pos = Rect.centerPointOfEdge(oldNode, edge.to.side);
- edge.to = {
- type: 'free',
- x: pos.x,
- y: pos.y,
- };
- }
- }
- }
-
- for (const node of canvasNodes) {
- node.edges = node.edges.map((edgeId) => {
- if (updatedIds.has(edgeId)) {
- return updatedIds.get(edgeId)!;
- }
- return edgeId;
- });
- }
-
- navigator.clipboard.writeText(
- JSON.stringify({ nodes: canvasNodes, edges: canvasEdges } as Canvas)
- );
-
- if (cut) {
- nodes.batchUpdate(
- () => {
- selectedNodeIds().forEach((id) => {
- nodes.delete(id);
- });
- },
- { autosave: true }
- );
- edges.batchUpdate(
- () => {
- selectedEdgeIds().forEach((id) => {
- edges.delete(id);
- });
- },
- { autosave: true }
- );
- }
- },
-
- handlePaste(opts: { position?: Vector2; event?: ClipboardEvent }) {
- if (opts?.event?.clipboardData instanceof DataTransfer) {
- if (handleLegacyImagePaste(opts.event)) return;
- }
- handleStandardPaste(opts.position);
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/signal/fileDrop.ts b/apps/web/src/features/block-canvas/signal/fileDrop.ts
deleted file mode 100644
index b45fd7a12a..0000000000
--- a/apps/web/src/features/block-canvas/signal/fileDrop.ts
+++ /dev/null
@@ -1,273 +0,0 @@
-import { analytics } from '@app/lib/analytics';
-import { Tools } from '@block-canvas/constants';
-import type {
- CanvasEntityStyle,
- ShapeType,
-} from '@block-canvas/model/CanvasModel';
-import { useCanvasNodes } from '@block-canvas/store/canvasData';
-import { useRenderState } from '@block-canvas/store/RenderState';
-import {
- parseScale,
- parseTranslate,
- svgEntityStyles,
-} from '@block-canvas/util/svg';
-import { type Vector2, vec2 } from '@block-canvas/util/vector2';
-import { toast } from '@core/component/Toast/Toast';
-import { CANVAS_SVG_IMPORT } from '@core/constant/featureFlags';
-import { uploadFile } from '@core/util/upload';
-import { nanoid } from 'nanoid';
-import { createSignal } from 'solid-js';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import { getTextNodeHeight } from '../util/style';
-import { useCachedStyle } from './cachedStyle';
-import { useCanvasHistory } from './canvasHistory';
-import { useToolManager } from './toolManager';
-
-export const useCanvasFileDrop = () => {
- const [fileDropPos, setFileDropPos] = createSignal(vec2(0, 0));
- const { clientToCanvas } = useRenderState();
- const nodes = useCanvasNodes();
- const { setSelectedTool } = useToolManager();
- const highestOrder = useCanvasDocument().state.signals.highestOrder[0];
- const history = useCanvasHistory();
-
- const cachedStyle = useCachedStyle();
- const style = cachedStyle.getStyle;
- const height = getTextNodeHeight(style().fontSize);
-
- const createTextNode = (
- text: string,
- position: Vector2,
- styleOverrides: Partial<CanvasEntityStyle>
- ) => {
- history.open();
- const id = nanoid(8);
- nodes.setLastCreated(id);
- nodes.createNode(
- {
- id,
- type: 'text',
- x: position.x,
- y: position.y,
- width: 0,
- height,
- edges: [],
- style: {
- ...style(),
- ...styleOverrides,
- importedColor: true,
- },
- text,
- followTextWidth: true,
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { autosave: true }
- );
- history.close();
- };
-
- const createShapeNode = (
- position: Vector2,
- width: number,
- height: number,
- styleOverrides: Partial<CanvasEntityStyle>,
- shapeType: ShapeType
- ) => {
- history.open();
- const id = nanoid(8);
- nodes.setLastCreated(id);
- nodes.createNode(
- {
- id,
- type: 'shape',
- x: position.x,
- y: position.y,
- width,
- height,
- edges: [],
- style: {
- ...style(),
- ...styleOverrides,
- importedColor: true,
- },
- layer: 0,
- sortOrder: highestOrder() + 1,
- shape: shapeType,
- },
- { autosave: true }
- );
- history.close();
- };
-
- const parseSVGStringToNodes = (svg: string, position: Vector2) => {
- const parser = new DOMParser();
- const svgDoc = parser.parseFromString(svg, 'image/svg+xml');
- parseSVGDocToNodes(svgDoc, {}, position);
- };
-
- const parseSVGDocToNodes = (
- svg: Document | Element,
- styleContext: Partial<CanvasEntityStyle>,
- offset: Vector2 = vec2(0, 0),
- scale: number = 1.0,
- width: number = 0,
- height: number = 0
- ) => {
- for (const child of svg.children) {
- const el = child as Element;
- let elOffset = offset.clone();
- let elScale = scale;
- const newStyleContext = { ...styleContext };
-
- const transform = el.getAttribute('transform');
- if (transform) {
- elOffset = elOffset.add(parseTranslate(transform).multiply(scale));
- elScale *= parseScale(transform);
- }
-
- for (const styleEntry of svgEntityStyles) {
- let val: any = el.getAttribute(styleEntry.svgAttribute);
- if (val) {
- if (val && styleEntry.type === 'number') {
- val = parseInt(val);
- if (styleEntry.applyScale) {
- val *= elScale;
- }
- }
- newStyleContext[styleEntry.styleProperty] = val;
- }
- }
-
- const x = parseInt(el.getAttribute('x') || '0');
- const y = parseInt(el.getAttribute('y') || '0');
- elOffset = elOffset.add(vec2(x, y).multiply(scale));
-
- const newWidth = el.getAttribute('width');
- const newHeight = el.getAttribute('height');
- if (newWidth) {
- width = newWidth.includes('%')
- ? width * parseInt(newWidth) * 0.01
- : parseInt(newWidth);
- }
- if (newHeight) {
- height = newHeight.includes('%')
- ? height * parseInt(newHeight) * 0.01
- : parseInt(newHeight);
- }
-
- if (el.tagName === 'text') {
- createTextNode(el.textContent || '', elOffset, {
- ...newStyleContext,
- strokeColor: newStyleContext.fillColor,
- });
- }
-
- if (el.tagName === 'rect') {
- createShapeNode(elOffset, width, height, newStyleContext, 'rectangle');
- }
-
- if (el.tagName === 'ellipse') {
- const rx = parseInt(el.getAttribute('rx') || '0');
- const ry = parseInt(el.getAttribute('ry') || '0');
- const cx = parseInt(el.getAttribute('cx') || '0');
- const cy = parseInt(el.getAttribute('cy') || '0');
- elOffset = elOffset.add(vec2(cx, cy));
- if (rx && ry) {
- elOffset = elOffset.subtract(vec2(rx, ry));
- createShapeNode(elOffset, rx * 2, ry * 2, newStyleContext, 'ellipse');
- }
- }
- parseSVGDocToNodes(
- el,
- { ...newStyleContext },
- elOffset,
- elScale,
- width,
- height
- );
- }
- };
-
- const staticImageUpload = async (blob: File | Blob, position: Vector2) => {
- const url = URL.createObjectURL(blob);
- const loadingNode = nodes.createNode({
- type: 'image',
- status: 'loading',
- uuid: url,
- x: position.x,
- y: position.y,
- width: 0,
- height: 0,
- edges: [],
- style: { strokeColor: 'transparent' },
- flipX: false,
- flipY: false,
- layer: 0,
- sortOrder: highestOrder() + 1,
- });
- setSelectedTool(Tools.Select);
-
- try {
- const file =
- blob instanceof File
- ? blob
- : new File([blob], 'pastedCanvasImage', { type: blob.type });
-
- const result = await uploadFile(file, 'static', {
- hideProgressIndicator: true,
- });
-
- if (!result.failed) {
- nodes.updateNode(
- loadingNode.id,
- {
- status: 'static',
- uuid: result.id,
- },
- { autosave: true }
- );
- } else {
- throw result.error;
- }
- } catch (_error) {
- analytics.track('upload_error', {
- type: 'canvas_image',
- destination: 'static',
- });
- toast.failure('Failed to upload image');
- nodes.delete(loadingNode.id, { autosave: true });
- }
- };
-
- return {
- handleMouseUp: (x: number, y: number) => {
- setFileDropPos(clientToCanvas({ clientX: x, clientY: y }));
- },
- handleFileDrop: async (files: File[], pos?: Vector2) => {
- const file = files[0];
- if (!file) {
- toast.failure('Invalid file');
- return;
- }
- const position = vec2(
- pos ? pos.x : fileDropPos().x,
- pos ? pos.y : fileDropPos().y
- );
- if (CANVAS_SVG_IMPORT && file.type === 'image/svg+xml') {
- const reader = new FileReader();
- reader.onloadend = (readerEvent) => {
- if (readerEvent.target?.result) {
- const svgString = readerEvent.target.result.toString();
- parseSVGStringToNodes(svgString, position);
- }
- };
- reader.readAsText(file);
- return;
- }
- staticImageUpload(file, position);
- },
- staticImageUpload,
- parseSVGStringToNodes,
- };
-};
diff --git a/apps/web/src/features/block-canvas/signal/nudge.ts b/apps/web/src/features/block-canvas/signal/nudge.ts
deleted file mode 100644
index 02fe13c2a9..0000000000
--- a/apps/web/src/features/block-canvas/signal/nudge.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { sharedInstance } from '@block-canvas/util/sharedInstance';
-import { batch } from 'solid-js';
-import { useCanvasEdges, useCanvasNodes } from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { vec2 } from '../util/vector2';
-import { useCanvasHistory } from './canvasHistory';
-import { useSelection } from './selection';
-
-export const useNudge = sharedInstance(() => {
- const baseNudgeDistance = 5;
- const { currentScale } = useRenderState();
- const history = useCanvasHistory();
- const selection = useSelection();
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
-
- return {
- nudge(direction: string, shift: boolean, autosave: boolean) {
- const nudgeDistance =
- (shift ? baseNudgeDistance * 10 : baseNudgeDistance) / currentScale();
-
- const modifier = vec2(
- direction === 'right'
- ? nudgeDistance
- : direction === 'left'
- ? -nudgeDistance
- : 0,
- direction === 'down'
- ? nudgeDistance
- : direction === 'up'
- ? -nudgeDistance
- : 0
- );
-
- history.open();
-
- batch(() => {
- nodes.batchUpdate(
- () => {
- selection.selectedNodeIds().forEach((nodeId) => {
- const original = nodes.get(nodeId);
- nodes.updateNode(nodeId, {
- x: original.x + modifier.x,
- y: original.y + modifier.y,
- });
- });
- },
- { autosave }
- );
-
- edges.batchUpdate(
- () => {
- selection.selectedEdgeIds().forEach((edgeId) => {
- const original = edges.get(edgeId);
- edges.updateEdge(edgeId, {
- from:
- original.from.type === 'free'
- ? {
- type: 'free',
- x: original.from.x + modifier.x,
- y: original.from.y + modifier.y,
- }
- : original.from,
- to:
- original.to.type === 'free'
- ? {
- type: 'free',
- x: original.to.x + modifier.x,
- y: original.to.y + modifier.y,
- }
- : original.to,
- });
- });
- },
- { autosave }
- );
-
- history.close();
- });
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/signal/reorder.ts b/apps/web/src/features/block-canvas/signal/reorder.ts
deleted file mode 100644
index 718b22dcc7..0000000000
--- a/apps/web/src/features/block-canvas/signal/reorder.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { batch } from 'solid-js';
-import { type ReorderOperation, ReorderOperations } from '../constants';
-import {
- renderQueue,
- useCanvasEdges,
- useCanvasGroups,
- useCanvasNodes,
-} from '../store/canvasData';
-import { useCanvasHistory } from './canvasHistory';
-import { useSelection } from './selection';
-
-export function useReorder() {
- const history = useCanvasHistory();
- const selection = useSelection();
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
- const groups = useCanvasGroups();
- const rq = renderQueue();
-
- return {
- reorder(op: ReorderOperation, autosave: boolean) {
- history.open();
-
- batch(() => {
- rq.normalize();
- const len = rq.length();
- let sortOffset = 0;
- if (op === ReorderOperations.BringToFront) {
- sortOffset = len + 1;
- } else if (op === ReorderOperations.SendToBack) {
- sortOffset = -len - 1;
- } else if (op === ReorderOperations.Forward) {
- sortOffset = 1.5;
- } else if (op === ReorderOperations.Backward) {
- sortOffset = -1.5;
- }
-
- const selectedGroups = new Set<string>();
-
- nodes.batchUpdate(
- () => {
- selection.selectedNodes().forEach((node) => {
- if (node.groupId) {
- selectedGroups.add(node.groupId);
- return;
- }
- nodes.updateNode(node.id, {
- sortOrder: nodes.get(node.id).sortOrder + sortOffset,
- });
- });
- },
- { autosave }
- );
-
- edges.batchUpdate(
- () => {
- selection.selectedEdges().forEach((edge) => {
- if (edge.groupId) {
- selectedGroups.add(edge.groupId);
- return;
- }
- if (
- edge.from.type === 'connected' ||
- edge.to.type === 'connected'
- ) {
- return;
- }
- edges.updateEdge(edge.id, {
- sortOrder: edges.get(edge.id).sortOrder + sortOffset,
- });
- });
- },
- { autosave }
- );
-
- groups.batchUpdate(
- () => {
- selectedGroups.forEach((groupId) => {
- groups.update(groupId, {
- sortOrder: groups.get(groupId).sortOrder + sortOffset,
- });
- });
- },
- { autosave }
- );
-
- rq.normalize();
- history.close();
- });
- },
- };
-}
diff --git a/apps/web/src/features/block-canvas/signal/selection.ts b/apps/web/src/features/block-canvas/signal/selection.ts
deleted file mode 100644
index bbae25bf7f..0000000000
--- a/apps/web/src/features/block-canvas/signal/selection.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-import { renderQueue, useBoundingBox } from '@block-canvas/store/canvasData';
-import {
- useGetEdge,
- useGetGroup,
- useGetNode,
-} from '@block-canvas/store/getNodeEdge';
-import { createMemo, untrack } from 'solid-js';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import {
- type CanvasEdge,
- type CanvasEntityStyle,
- type CanvasGroup,
- type CanvasNode,
- StyleSchema,
-} from '../model/CanvasModel';
-import type { Rectangle } from '../util/rectangle';
-import { sharedInstance } from '../util/sharedInstance';
-
-export type Selection = ReturnType<typeof createSelection>;
-
-export const useSelection = sharedInstance<Selection>(createSelection);
-
-function createSelection() {
- const state = useCanvasDocument().state.signals;
- const [selectedNodeIds, setSelectedNodeIds] = state.selectedNodeIds;
- const [selectedEdgeIds, setSelectedEdgeIds] = state.selectedEdgeIds;
- const [selectedGroupIds, setSelectedGroupIds] = state.selectedGroupIds;
- const [lastSelectedNodeIds, setLastSelectedNodeIds] =
- state.lastSelectedNodeIds;
- const [lastSelectedEdgeIds, setLastSelectedEdgeIds] =
- state.lastSelectedEdgeIds;
- const [boxSelection, setBoxSelection] = state.selectionBox;
- const getNode = useGetNode();
- const getEdge = useGetEdge();
- const getGroup = useGetGroup();
- const boundingBox = useBoundingBox();
-
- const rq = renderQueue();
-
- const selectedNodes = createMemo(() => {
- const nodes = Array.from(selectedNodeIds().values()).map((id) =>
- getNode(id)
- );
- return nodes.filter((node) => node !== undefined) as CanvasNode[];
- });
-
- const selectedEdges = createMemo(() => {
- const edges = Array.from(selectedEdgeIds().values()).map((id) =>
- getEdge(id)
- );
- return edges.filter((edge) => edge !== undefined) as CanvasEdge[];
- });
-
- const selectedGroups = createMemo(() => {
- const groups = Array.from(selectedGroupIds().values()).map((id) =>
- getGroup(id)
- );
- return groups.filter((group) => group !== undefined) as CanvasGroup[];
- });
-
- return {
- selectAll() {
- setSelectedNodeIds(new Set(rq.nodes().map((node) => node.id)));
- setSelectedEdgeIds(new Set(rq.edges().map((edge) => edge.id)));
- setSelectedGroupIds(new Set(rq.groups().map((group) => group.id)));
- },
-
- deselectAll() {
- setSelectedNodeIds(new Set() as Set<string>);
- setSelectedEdgeIds(new Set() as Set<string>);
- setSelectedGroupIds(new Set() as Set<string>);
- },
-
- selectNode(id: string | { id: string }) {
- const keys = [...selectedNodeIds().keys()];
- const _id = typeof id === 'string' ? id : id.id;
- const groupId = getNode(_id).groupId;
- const group = groupId ? getGroup(groupId) : undefined;
- const childNodes = group && group.childNodes ? group.childNodes : [];
- setSelectedNodeIds(new Set([...keys, _id, ...childNodes]));
- const childEdges = group ? group.childEdges : undefined;
- if (childEdges)
- setSelectedEdgeIds(
- new Set([...selectedEdgeIds().keys(), ...childEdges])
- );
- },
- deselectNode(id: string | { id: string }) {
- const keys = [...selectedNodeIds().keys()];
- const _id = typeof id === 'string' ? id : id.id;
- setSelectedNodeIds(new Set([...keys].filter((i) => i !== _id)));
- },
- selectEdge(id: string | { id: string }) {
- const keys = [...selectedEdgeIds().keys()];
- const _id = typeof id === 'string' ? id : id.id;
- const groupId = getEdge(_id).groupId;
- const group = groupId ? getGroup(groupId) : undefined;
- const childEdges = group && group.childEdges ? group.childEdges : [];
- setSelectedEdgeIds(new Set([...keys, _id, ...childEdges]));
- const childNodes = group ? group.childNodes : undefined;
- if (childNodes)
- setSelectedNodeIds(
- new Set([...selectedNodeIds().keys(), ...childNodes])
- );
- },
- deselectEdge(id: string | { id: string }) {
- const keys = [...selectedEdgeIds().keys()];
- const _id = typeof id === 'string' ? id : id.id;
- setSelectedEdgeIds(new Set([...keys].filter((i) => i !== _id)));
- },
- selectGroup(id: string) {
- const keys = [...selectedGroupIds().keys()];
- setSelectedGroupIds(new Set([...keys, id]));
- },
-
- isSelected(id: string | { id: string }) {
- if (typeof id === 'string')
- return selectedNodeIds().has(id) || selectedEdgeIds().has(id);
- return selectedNodeIds().has(id.id) || selectedEdgeIds().has(id.id);
- },
- selectionBounds: createMemo(() => {
- if (selectedNodes().length === 0 && selectedEdges().length === 0) return;
- return boundingBox(selectedNodes(), selectedEdges());
- }),
- active: createMemo(
- () => selectedNodeIds().size > 0 || selectedEdgeIds().size > 0
- ),
- selectionBox: createMemo(() => boxSelection()),
- setSelectionBox(rect?: Rectangle) {
- setBoxSelection(rect);
- },
-
- extractSharedStyles(): Map<keyof CanvasEntityStyle, any> {
- const sharedStyles = new Map<keyof CanvasEntityStyle, any>();
-
- [...selectedNodes(), ...selectedEdges()].forEach((element: any) => {
- Object.keys(StyleSchema.shape).forEach((_prop) => {
- const prop = _prop as keyof CanvasEntityStyle;
- if (element.style && prop in element.style) {
- const styleValue = element.style[prop];
-
- if (!sharedStyles.has(prop)) {
- sharedStyles.set(prop, styleValue);
- } else if (sharedStyles.get(prop) !== styleValue) {
- sharedStyles.set(prop, undefined);
- }
- }
- });
- });
-
- return sharedStyles;
- },
-
- forceSetSelection(
- NodeIds: string[],
- EdgeIds: string[],
- GroupIds: string[]
- ) {
- setSelectedNodeIds(new Set(NodeIds));
- setSelectedEdgeIds(new Set(EdgeIds));
- setSelectedGroupIds(new Set(GroupIds));
- },
-
- stash() {
- setLastSelectedNodeIds(new Set([...untrack(selectedNodeIds)]));
- setLastSelectedEdgeIds(new Set([...untrack(selectedEdgeIds)]));
- },
-
- getStashed: createMemo(() => {
- return {
- nodes: lastSelectedNodeIds(),
- edges: lastSelectedEdgeIds(),
- };
- }),
-
- selectedNodeIds,
- selectedEdgeIds,
- selectedGroupIds,
- selectedNodes,
- selectedEdges,
- selectedGroups,
- };
-}
diff --git a/apps/web/src/features/block-canvas/signal/toolManager.ts b/apps/web/src/features/block-canvas/signal/toolManager.ts
deleted file mode 100644
index cbaaa94973..0000000000
--- a/apps/web/src/features/block-canvas/signal/toolManager.ts
+++ /dev/null
@@ -1,396 +0,0 @@
-import { clamp, lerp, remap } from '@block-canvas/util/math';
-import { getTextNodeHeight } from '@block-canvas/util/style';
-import { IS_MAC } from '@core/constant/isMac';
-import { pressedKeys } from '@core/hotkey/state';
-import { isEditableInput } from '@core/util/isEditableInput';
-import { createCallback } from '@solid-primitives/rootless';
-import { nanoid } from 'nanoid';
-import { createMemo, createSignal } from 'solid-js';
-import { DRAG_THRESHOLD, type Tool, Tools, ViewOnlyTools } from '../constants';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import type { Operator } from '../operation/operation';
-import { useCanvasNodes } from '../store/canvasData';
-import { useRenderState } from '../store/RenderState';
-import { sharedInstance } from '../util/sharedInstance';
-import { type Vector2, vec2 } from '../util/vector2';
-import { useCachedStyle } from './cachedStyle';
-import { useCanvasHistory } from './canvasHistory';
-import { useSelection } from './selection';
-
-export type DispatchMouseArgs = {
- tool: Tool;
- action: 'start' | 'preview' | 'commit';
- e: PointerEvent;
- args: any[];
-};
-
-export const useToolManager = sharedInstance<ToolManager>(createToolManager);
-
-function createToolManager() {
- const canvas = useCanvasDocument();
- const { canEdit, isNested } = canvas;
- const state = canvas.state.signals;
- const [selectedTool, setTool] = state.selectedTool;
- const [mouseDownPos, setMouseDownPos] = state.mouseDownPosition;
- const [handlersByTool, setHandlersByTool] = state.handlersByTool;
- const [middleMousePressed, setMiddleMousePressed] = state.middleMousePressed;
- const [mousePosition, setMousePosition] = state.mousePosition;
- const [lastMousePosition, setLastMousePosition] = state.lastMousePosition;
- const [rawMouseDownPos, setRawMouseDownPos] = state.rawMouseDownPosition;
- const [isDragging, setIsDragging] = createSignal(false);
- const [activeTextEditor, setActiveTextEditor] = state.activeTextEditor;
- const [_previousTouch, setPreviousTouch] = createSignal<Vector2>();
-
- const { clientToCanvas, zoom, pan } = useRenderState();
- const selection = useSelection();
- const history = useCanvasHistory();
- const [highestOrder] = state.highestOrder;
-
- const ignoreTargets: HTMLElement[] = [];
-
- const nodes = useCanvasNodes();
- const cachedStyle = useCachedStyle();
- const style = cachedStyle.getStyle;
-
- setMousePosition(vec2(0, 0));
- setLastMousePosition(vec2(0, 0));
-
- let containerRef: HTMLElement | undefined;
-
- let mouseMovedInDoubleClick = false;
-
- const canUseTool = createCallback((tool: Tool) => {
- return canEdit() || ViewOnlyTools.indexOf(tool) > -1;
- });
-
- const activeTool = createMemo(() => {
- const tool = selectedTool();
- if (middleMousePressed()) {
- return Tools.Grab;
- }
-
- if (activeTextEditor()) return Tools.Typing;
-
- // Any override that is not grab or zoom should be checked for canUseTool(Tool.ToolName)
- return tool ?? Tools.Grab;
- });
-
- function ignore(e: PointerEvent | MouseEvent) {
- const shouldIgnore = ignoreTargets.some((el) =>
- el?.contains(e.target as Node)
- );
- return shouldIgnore;
- }
-
- // @ts-ignore waiting to ship touch events until they feel more stable
- function _touchStart(e: TouchEvent) {
- if (e.touches.length !== 1) return;
- setPreviousTouch(
- vec2(e.changedTouches[0].clientX, e.changedTouches[0].clientY)
- );
- }
-
- // @ts-ignore waiting to ship touch events until they feel more stable
- function _touchMove(e: TouchEvent) {
- if (e.changedTouches.length !== 1) {
- setPreviousTouch();
- return;
- }
- const currentPos = vec2(
- e.changedTouches[0].clientX,
- e.changedTouches[0].clientY
- );
- setPreviousTouch(currentPos);
- }
-
- const [contextMenu] = canvas.state.stores.contextMenu;
-
- function pointerDown(e: PointerEvent) {
- if (e.pointerType === 'mouse') {
- if (e.button === 1) setMiddleMousePressed(true);
- if (
- (e.button !== 0 ||
- (IS_MAC && pressedKeys().has('ctrl') && pressedKeys().size === 1) ||
- contextMenu.open) &&
- e.button !== 1
- )
- return;
- }
-
- if (ignore(e)) return;
- setMousePosition(vec2(e.pageX, e.pageY));
- setRawMouseDownPos(vec2(e.pageX, e.pageY));
- const tool = activeTool();
-
- if (e.target === containerRef && tool !== Tools.Grab) {
- selection.stash();
- selection.deselectAll();
- }
-
- const handlers = handlersByTool().get(tool);
- if (!handlers) return;
- if (!mouseDownPos()) {
- for (const handler of handlers) {
- handler.start(e);
- }
- } else {
- for (const handler of handlers) {
- handler.abort();
- }
- }
-
- setMouseDownPos(vec2(e.pageX, e.pageY));
- mouseMovedInDoubleClick = false;
- }
-
- function pointerMove(e: PointerEvent) {
- setMousePosition(vec2(e.pageX, e.pageY));
- if (rawMouseDownPos()) {
- if (mousePosition()!.distance(rawMouseDownPos()!) > DRAG_THRESHOLD) {
- mouseMovedInDoubleClick = true;
- setIsDragging(true);
- }
- }
- const tool = activeTool();
- const handlers = handlersByTool().get(tool) ?? [];
- for (const handler of handlers) {
- handler.preview(e);
- }
- setLastMousePosition(vec2(e.pageX, e.pageY));
- }
-
- function pointerUp(e: PointerEvent) {
- setMousePosition(vec2(e.pageX, e.pageY));
- setMouseDownPos();
- setRawMouseDownPos();
- setIsDragging(false);
-
- const tool = activeTool();
- const handlers = handlersByTool().get(tool);
- if (!handlers) return;
- for (const handler of handlers) {
- if (ignore(e)) {
- handler.abort();
- } else {
- handler.commit(e);
- }
- }
-
- if (e.pointerType === 'mouse') {
- if (e.button === 1) setMiddleMousePressed(false);
- }
- setPreviousTouch();
- }
-
- function _pointerEnter() {
- if (activeTextEditor()) return;
- const activeElement = document.activeElement;
-
- if (activeElement === null || !(activeElement instanceof HTMLElement)) {
- containerRef?.focus();
- return;
- }
-
- // Editable inputs take take precedence over the canvas.
- if (isEditableInput(activeElement)) {
- return;
- }
- containerRef?.focus();
- }
-
- function dblClick(e: MouseEvent) {
- if (ignore(e)) return;
- if (mouseMovedInDoubleClick) {
- mouseMovedInDoubleClick = false;
- return;
- }
- const tool = activeTool();
- const mousePos = clientToCanvas(e);
- if (tool === Tools.Select) {
- setTool(Tools.Text);
- const id = nanoid(8);
- const height = getTextNodeHeight(style().fontSize);
- nodes.setLastCreated(id);
- history.open();
- nodes.createNode(
- {
- id,
- type: 'text',
- x: mousePos.x - height / 8,
- y: mousePos.y - height / 2,
- width: 0,
- height,
- edges: [],
- style: style(),
- text: '',
- followTextWidth: true,
- layer: 0,
- sortOrder: highestOrder() + 1,
- },
- { autosave: true }
- );
- history.close();
- }
- }
-
- function createScrollCurve(params: {
- deltaRange: Vector2;
- velocityRange: Vector2;
- }) {
- let lastEventTime = Date.now();
- let lastDelta = 0;
- let lastSpeed = 0;
- const { deltaRange, velocityRange } = params;
-
- return (inputDelta: number, scale: number) => {
- const now = Date.now();
- const deltaTime = Math.max(1, now - lastEventTime) / 1000;
-
- let speed = clamp(
- Math.abs(inputDelta - lastDelta) / deltaTime,
- velocityRange.x,
- velocityRange.y
- );
-
- const clampedDelta = clamp(
- Math.abs(inputDelta),
- deltaRange.x,
- deltaRange.y
- );
- const normalizedDelta = remap(
- clampedDelta,
- deltaRange.x,
- deltaRange.y,
- 0,
- 1
- );
- const curvedDelta = Math.pow(normalizedDelta, 0.3);
- const deltaFactor = remap(curvedDelta, 0, 1, deltaRange.x, deltaRange.y);
- const speedFactor = lerp(speed, lastSpeed, 0.1);
- const output = deltaFactor * speedFactor * scale * Math.sign(inputDelta);
-
- lastEventTime = now;
- lastDelta = inputDelta;
- lastSpeed = speed;
-
- return output;
- };
- }
-
- const scaleScroll = createScrollCurve({
- deltaRange: vec2(0, 100),
- velocityRange: vec2(0, 3),
- });
-
- function scroll(e: WheelEvent) {
- if (ignore(e)) return;
- e.preventDefault();
- e.stopPropagation();
- if (e.ctrlKey) {
- const s = scaleScroll(e.deltaY, -0.0005);
- zoom(s, e, true);
- } else {
- pan(-e.deltaX, -e.deltaY, true);
- }
- }
-
- return {
- selectedTool,
- setSelectedTool(tool: Tool) {
- if (activeTextEditor()) {
- if (tool !== Tools.Typing) containerRef?.focus();
- }
- if (canUseTool(tool)) {
- setTool(tool);
- }
- },
- mouseDownPos,
-
- activeTool,
-
- isDragging,
-
- registerMouseTool(tool: Tool, operator: Operator) {
- let cloned = handlersByTool();
- let handlers = cloned.get(tool);
- if (handlers) {
- handlers.push(operator);
- } else {
- handlers = [operator];
- }
- cloned.set(tool, handlers);
- setHandlersByTool(cloned);
- },
-
- mount(ref: HTMLElement) {
- containerRef = ref;
- containerRef.addEventListener('pointerdown', pointerDown);
- document.addEventListener('pointermove', pointerMove);
- document.addEventListener('pointerup', pointerUp);
- // NOTE (seamus) In the new split designs, this is absurdly distracting
- // containerRef.addEventListener('pointerenter', pointerEnter);
- containerRef.addEventListener('dblclick', dblClick);
-
- if (!isNested()) {
- containerRef.addEventListener('wheel', scroll, { passive: false });
- }
- },
-
- cleanup() {
- containerRef?.removeEventListener('pointerdown', pointerDown);
- document.removeEventListener('pointermove', pointerMove);
- document.removeEventListener('pointerup', pointerUp);
- // NOTE (seamus) In the new split designs, this is absurdly distracting
- // containerRef?.removeEventListener('pointerenter', pointerEnter);
- containerRef?.removeEventListener('dblclick', dblClick);
-
- if (!isNested()) {
- containerRef?.removeEventListener('wheel', scroll);
- }
- },
-
- dispatch(
- tool: Tool,
- action: keyof Operator,
- e: PointerEvent,
- ...args: any[]
- ) {
- const handlers = handlersByTool().get(tool);
- if (!handlers) return;
- for (const handler of handlers) {
- handler[action](e, ...args);
- }
- },
-
- abortAll() {
- const handlers = handlersByTool();
- for (const [, operators] of handlers) {
- for (const operator of operators) {
- operator.abort();
- }
- }
- },
-
- ignoreMouseEvents(el: HTMLElement) {
- ignoreTargets.push(el);
- },
- removeIgnoreMouseEvents(el: HTMLElement) {
- ignoreTargets.splice(ignoreTargets.indexOf(el));
- },
- ignore,
-
- setActiveTextEditor,
- activeTextEditor,
- mousePosition: () => mousePosition() ?? vec2(0, 0),
- lastMousePosition: () => lastMousePosition() ?? vec2(0, 0),
- safeMouseDelta: () => vec2(1, 1),
- mouseIsDown: () => !!mouseDownPos(),
- focusCanvas: () => {
- setTimeout(() => {
- containerRef?.focus();
- }, 0);
- },
- };
-}
-
-export type ToolManager = ReturnType<typeof createToolManager>;
diff --git a/apps/web/src/features/block-canvas/store/RenderState.ts b/apps/web/src/features/block-canvas/store/RenderState.ts
deleted file mode 100644
index 0998e29b37..0000000000
--- a/apps/web/src/features/block-canvas/store/RenderState.ts
+++ /dev/null
@@ -1,299 +0,0 @@
-import { MAX_ZOOM, MIN_ZOOM } from '@block-canvas/constants';
-import { sharedInstance } from '@block-canvas/util/sharedInstance';
-import { createCallback } from '@solid-primitives/rootless';
-import { debounce } from '@solid-primitives/scheduled';
-import { createEffect, createSignal } from 'solid-js';
-import { unwrap } from 'solid-js/store';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import { saveCanvasViewLocation } from '../queries/canvas-document';
-import { clamp, easeInOutCubic } from '../util/math';
-import { Rect } from '../util/rectangle';
-import { vec2 } from '../util/vector2';
-
-export type RenderState = {
- x: number;
- y: number;
- scale: number;
- containerRect: DOMRect | undefined;
-};
-
-export const defaultRenderState = (): RenderState => ({
- x: 0,
- y: 0,
- scale: 1,
- containerRect: undefined,
-});
-
-/**
- * Modify and read the canvas's render state from its document-scoped context
- * (usually the top level of a component or a createCallback called from the top
- * level of a component).
- */
-export const useRenderState = sharedInstance(() => {
- const canvas = useCanvasDocument();
- const [state, setState] = canvas.state.stores.render;
- const [animation, setAnimation] = canvas.state.stores.animation;
- const { documentId, isNested } = canvas;
-
- createEffect(() => {
- if (!animation.isAnimating) return;
-
- const animate = () => {
- const now = performance.now();
- const elapsed = now - animation.startTime;
- const progress = Math.min(elapsed / animation.duration, 1);
- const t = easeInOutCubic(progress);
- const x = animation.startX + (animation.targetX - animation.startX) * t;
- const y = animation.startY + (animation.targetY - animation.startY) * t;
- const scale =
- animation.startScale +
- (animation.targetScale - animation.startScale) * t;
-
- setState({ x, y, scale });
-
- if (progress < 1) {
- requestAnimationFrame(animate);
- } else {
- setAnimation('isAnimating', false);
- }
- };
-
- requestAnimationFrame(animate);
- });
-
- const debouncedSaveState = debounce(() => {
- if (isNested()) return;
- void saveCanvasViewLocation(documentId(), unwrap(state));
- }, 500);
-
- const [defferedScale, setDeferredScale] = createSignal(state.scale);
- const debouncedSetDeferredScale = debounce(setDeferredScale, 20);
- createEffect(() => {
- debouncedSetDeferredScale(state.scale);
- });
-
- return {
- /**
- * Convert a clientX and clientY to a canvasX and canvasY. This
- * reads the current renderer sate and container rect with a non-reactive
- * unwrap.
- */
- clientToCanvas: createCallback(
- ({ clientX, clientY }: { clientX: number; clientY: number }) => {
- const { x, y, scale, containerRect } = unwrap(state);
- if (!containerRect) return vec2(clientX, clientY);
- return vec2(
- (clientX - containerRect.left - containerRect.width / 2 - x) / scale,
- (clientY - containerRect.top - containerRect.height / 2 - y) / scale
- );
- }
- ),
-
- pageToCanvas: createCallback(
- ({ pageX, pageY }: { pageX: number; pageY: number }) => {
- const { x, y, scale, containerRect } = unwrap(state);
- if (!containerRect) return vec2(pageX, pageY);
- return vec2(
- (pageX - containerRect.left - containerRect.width / 2 - x) / scale,
- (pageY - containerRect.top - containerRect.height / 2 - y) / scale
- );
- }
- ),
-
- /**
- * Zoom the canvas.
- * @param intensity - The amount to zoom. 0.1 is a 10% zoom.
- * @param direction - 'in' | 'out'
- * @param withMouse - If the zoom should be focused on the cursor position
- * pass an object with a clientX and clientY (i.e. a mouseEvent).
- */
- zoom: createCallback(
- (
- amount: number,
- withMouse?: { clientX: number; clientY: number },
- savePos?: boolean
- ) => {
- if (isNaN(amount)) return;
- setAnimation('isAnimating', false);
- const { scale, x, y, containerRect } = unwrap(state);
- if (!containerRect) return;
- if (
- (scale === MIN_ZOOM && amount < 0) ||
- (scale === MAX_ZOOM && amount > 0)
- ) {
- return;
- }
- const delta = 1 + amount;
- const rect = containerRect;
-
- // Zoom towards mouseEvent or container center if undefined.
- let { clientX, clientY } = withMouse ?? {
- clientX: rect.left + rect.width / 2,
- clientY: rect.top + rect.height / 2,
- };
-
- const mouseX = clientX - rect.left - rect.width / 2;
- const mouseY = clientY - rect.top - rect.height / 2;
-
- const canvasPointX = (mouseX - x) / scale;
- const canvasPointY = (mouseY - y) / scale;
- const newScale = clamp(scale * delta, MIN_ZOOM, MAX_ZOOM);
-
- setState({
- x: mouseX - canvasPointX * newScale,
- y: mouseY - canvasPointY * newScale,
- scale: newScale,
- });
-
- if (savePos) debouncedSaveState();
- }
- ),
-
- zoomTo: createCallback((scale: number, savePos?: boolean) => {
- if (isNaN(scale)) return;
- const { x, y, containerRect } = unwrap(state);
- if (!containerRect) return;
- if (scale <= MIN_ZOOM || scale >= MAX_ZOOM) {
- return;
- } else {
- setState({
- x,
- y,
- scale,
- });
- }
-
- if (savePos) debouncedSaveState();
- }),
-
- /**
- * Pan the cannvas with a movementX and movementY.
- * @param movementX - The amount to pan in the x direction.
- * @param movementY - The amount to pan in the y direction.
- */
- pan: createCallback(
- (movementX: number, movementY: number, savePos?: boolean) => {
- if (isNaN(movementX) || isNaN(movementY)) return;
- const { x, y } = unwrap(state);
- setState({
- x: x + movementX,
- y: y + movementY,
- });
-
- if (savePos) debouncedSaveState();
- }
- ),
-
- /**
- * Reset the canvas to the default state.
- */
- reset: createCallback(() => {
- setState(structuredClone(defaultRenderState));
- }),
-
- currentScale: () => {
- return state.scale;
- },
-
- defferedScale,
-
- currentPosition: () => {
- const x = state.x;
- const y = state.y;
- const vec = vec2(x, y);
- return vec;
- },
-
- currentSize: () => {
- return vec2(
- state.containerRect?.width ?? 0,
- state.containerRect?.height ?? 0
- );
- },
-
- setDomRect: (rect: DOMRect | undefined) => {
- setState({ containerRect: rect });
- },
-
- /**
- * Get the current viewBox of the canvas.
- * This is the canvas-space rectangle of the currently visible area of the canvas.
- */
- viewBox: () => {
- const s = state.scale;
- const w = state.containerRect?.width ?? 0;
- const h = state.containerRect?.height ?? 0;
-
- return Rect.fromParams({
- x: (-state.x - w / 2) / s,
- y: (-state.y - h / 2) / s,
- w: w / s,
- h: h / s,
- });
- },
-
- /**
- * Animate to a new view state. You can pass in optional targets for x, t, and scale.
- * If you pass in a target for scale, it will be clamped to the min and max zoom levels.
- * If you pass only scale, it will zoom toward the center of the canvas.
- */
- animateTo: createCallback(
- (
- target: { x?: number; y?: number; scale?: number },
- duration: number = 500,
- savePos?: boolean
- ) => {
- const { x, y, scale, containerRect } = unwrap(state);
- if (!containerRect) return;
-
- let targetX = x;
- let targetY = y;
-
- const targetScale =
- target.scale !== undefined
- ? clamp(target.scale, MIN_ZOOM, MAX_ZOOM)
- : scale;
-
- if (
- target.x === undefined &&
- target.y === undefined &&
- target.scale !== undefined
- ) {
- const canvasX = -x / scale;
- const canvasY = -y / scale;
- targetX = -canvasX * targetScale;
- targetY = -canvasY * targetScale;
- } else {
- if (target.x !== undefined) {
- targetX = target.x * targetScale;
- }
- if (target.y !== undefined) {
- targetY = target.y * targetScale;
- }
- }
- setAnimation({
- startX: x,
- startY: y,
- startScale: scale,
- targetX,
- targetY,
- targetScale,
- startTime: performance.now(),
- duration,
- isAnimating: true,
- });
- if (savePos) debouncedSaveState();
- }
- ),
-
- getCanvasRef: () => {},
-
- getLocation: () => {
- const s = state.scale;
- const x = state.x;
- const y = state.y;
-
- return { x: Math.round(x), y: Math.round(y), s: Math.round(s * 100) };
- },
- };
-});
diff --git a/apps/web/src/features/block-canvas/store/canvasData.ts b/apps/web/src/features/block-canvas/store/canvasData.ts
deleted file mode 100644
index ad8a4117aa..0000000000
--- a/apps/web/src/features/block-canvas/store/canvasData.ts
+++ /dev/null
@@ -1,866 +0,0 @@
-import {
- edgeToCollisionData,
- getEdgeEndVectors,
-} from '@block-canvas/util/connectors';
-import { filterMapAsync } from '@core/util/list';
-
-import { createCallback } from '@solid-primitives/rootless';
-import { debounce } from '@solid-primitives/scheduled';
-import { nanoid } from 'nanoid';
-import { batch, createMemo } from 'solid-js';
-import { useCanvasDocument } from '../context/canvas-document-context';
-import {
- type Canvas,
- type CanvasEdge,
- type CanvasEntity,
- type CanvasGroup,
- type CanvasId,
- type CanvasNode,
- EdgeSchema,
- GroupSchema,
- NodeSchema,
- type PencilNode,
-} from '../model/CanvasModel';
-import { saveCanvasDocument } from '../queries/canvas-document';
-import { useSelection } from '../signal/selection';
-import { untrackMentionsInTextNode } from '../util/mentions';
-import { Rect, type Rectangle } from '../util/rectangle';
-import { createRenderQueue } from '../util/renderQueue';
-import { sharedInstance } from '../util/sharedInstance';
-import { type Vector2, vec2 } from '../util/vector2';
-import { useGetEdge, useGetGroup, useGetNode } from './getNodeEdge';
-
-export const renderQueue = sharedInstance(() => {
- const state = useCanvasDocument().state;
- return createRenderQueue(
- state.stores.nodes,
- state.stores.edges,
- state.stores.groups,
- state.signals.highestOrder[1]
- );
-});
-
-export const previewRenderQueue = sharedInstance(() => {
- const state = useCanvasDocument().state;
- return createRenderQueue(
- state.stores.nodes,
- state.stores.edges,
- state.stores.groups,
- state.signals.highestOrder[1]
- );
-});
-
-export const debugRenderQueue = sharedInstance(() => {
- const state = useCanvasDocument().state;
- return createRenderQueue(
- state.stores.nodes,
- state.stores.edges,
- state.stores.groups,
- state.signals.highestOrder[1]
- );
-});
-
-// TODO (seamus) : This pending updates thing is a stop gap until the save logic
-// is refined and integrated into undo/redo system.
-// Since it's a temp. solution, I've left it as a shared signal between nodes and edges -Ness
-
-export interface OperationOptions {
- autosave?: boolean;
- preview?: boolean;
- debug?: boolean;
- initialize?: boolean;
-}
-
-export const useSetAllNodes = sharedInstance(() => {
- const [, setStore] = useCanvasDocument().state.stores.nodes;
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
- const rq = renderQueue();
-
- return createCallback((nodes: CanvasNode[], opts?: OperationOptions) => {
- setStore(Object.fromEntries(nodes.map((node) => [node.id, node])));
- batch(() => {
- for (const node of nodes) {
- rq.addNode(node.id);
- }
- });
- if (!opts?.initialize) setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- });
-});
-
-export const useDeleteNode = sharedInstance(() => {
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
- const getNode = useGetNode();
- const getEdge = useGetEdge();
- const disconnectEdge = useEdgeUtils().disconnectEdge;
- const rq = renderQueue();
- const blockId = useCanvasDocument().documentId();
- const untrackMentionsInTextNode_ = createCallback(untrackMentionsInTextNode);
-
- return createCallback(async (id: CanvasId, opts?: OperationOptions) => {
- const node = getNode(id);
- if (!node) return;
-
- // Handle mention cleanup before deletion
- if (blockId) {
- untrackMentionsInTextNode_(node, blockId, id);
- }
-
- node.edges.forEach((edgeId) => {
- const edge = getEdge(edgeId);
- if (!edge) return;
- disconnectEdge(edge, id);
- });
-
- rq.remove(id);
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- });
-});
-
-export const useCreateNode = sharedInstance(() => {
- const [nodes, setStore] = useCanvasDocument().state.stores.nodes;
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
- const { selectNode, deselectAll } = useSelection();
- const rq = renderQueue();
- const prq = previewRenderQueue();
- const drq = debugRenderQueue();
-
- return createCallback(
- (
- newNode: CanvasNode | Omit<CanvasNode, 'id'>,
- opts?: OperationOptions & { selectOnCreate?: boolean }
- ) => {
- let id = nanoid(8);
- if ('id' in newNode) id = newNode.id;
- let tryCount = 0;
- while (id in nodes) {
- id += tryCount;
- }
- setStore(id, { ...newNode, id: id });
- if (opts?.preview) {
- prq.addNode(id);
- } else if (opts?.debug) {
- drq.addNode(id);
- } else {
- rq.addNode(id);
- }
-
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
-
- deselectAll();
- if (opts?.selectOnCreate === false) {
- selectNode(id);
- }
- return nodes[id];
- }
- );
-});
-
-export const useUpdateNode = sharedInstance(() => {
- const [store, setStore] = useCanvasDocument().state.stores.nodes;
- const saveCanvasData = useSaveCanvasData();
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
-
- return createCallback(
- (id: CanvasId, updates: Partial<CanvasNode>, opts?: OperationOptions) => {
- if (!store[id]) return;
- const current = store[id];
-
- // only when at least one field actually changes.
- for (const [key, next] of Object.entries(updates) as [
- keyof CanvasNode,
- CanvasNode[keyof CanvasNode],
- ][]) {
- if (next !== current[key]) {
- setStore(id, { ...current, ...updates });
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- return;
- }
- }
- }
- );
-});
-
-export const useCanvasNodes = sharedInstance(() => {
- const [pending, setPending] =
- useCanvasDocument().state.signals.pendingUpdates;
- const [lastCreated, setLastCreated] =
- useCanvasDocument().state.signals.lastCreatedNodeId;
- const saveCanvasData = useSaveCanvasData();
- const getNode = useGetNode();
- const rq = renderQueue();
- const prq = previewRenderQueue();
- return {
- get: getNode,
- initialize: useSetAllNodes(),
- delete: useDeleteNode(),
- createNode: useCreateNode(),
- updateNode: useUpdateNode(),
- lastCreated,
- batchUpdate: (fn: () => void, opts?: OperationOptions) => {
- batch(fn);
- if (opts?.autosave && pending()) {
- saveCanvasData();
- }
- },
- setLastCreated,
- save: useSaveCanvasData(),
- unsaved: () => pending(),
- clearPreview: () => prq.clear(),
- visible: createMemo(() => {
- return rq.nodes().map((renderable) => getNode(renderable.id));
- }),
- setVisible: (ids: CanvasId[], opts?: OperationOptions) => {
- rq.clear();
- for (const id of ids) {
- rq.addNode(id);
- }
- setPending(true);
- if (opts?.autosave) saveCanvasData();
- },
- };
-});
-
-export const useSetAllEdges = sharedInstance(() => {
- const [, setStore] = useCanvasDocument().state.stores.edges;
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
- const rq = renderQueue();
-
- return createCallback((edges: CanvasEdge[], opts?: OperationOptions) => {
- setStore(Object.fromEntries(edges.map((edge) => [edge.id, edge])));
- batch(() => {
- for (const edge of edges) {
- rq.addEdge(edge.id);
- }
- });
- if (!opts?.initialize) setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- });
-});
-
-export const useDeleteEdge = sharedInstance(() => {
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
- const getEdge = useGetEdge();
- const getNode = useGetNode();
- const updateNode = useUpdateNode();
- const rq = renderQueue();
-
- return createCallback((id: CanvasId, opts?: OperationOptions) => {
- const edge = getEdge(id);
- if (!edge) return;
- if (edge.from.type === 'connected') {
- const fromNode = getNode(edge.from.node);
- if (fromNode) {
- updateNode(fromNode.id, {
- edges: fromNode.edges.filter((e) => e !== id),
- });
- }
- }
- if (edge.to.type === 'connected') {
- const toNode = getNode(edge.to.node);
- if (toNode) {
- updateNode(toNode.id, {
- edges: toNode.edges.filter((e) => e !== id),
- });
- }
- }
-
- rq.remove(id);
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- });
-});
-
-export const useCreateEdge = sharedInstance(() => {
- const [, setStore] = useCanvasDocument().state.stores.edges;
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
- const getNode = useGetNode();
- const updateNode = useUpdateNode();
- const rq = renderQueue();
- const prq = previewRenderQueue();
- const drq = debugRenderQueue();
-
- return createCallback(
- (
- newEdge: CanvasEdge | Omit<CanvasEdge, 'id'>,
- opts?: OperationOptions & { selectOnCreate?: boolean }
- ) => {
- const id = 'id' in newEdge ? newEdge.id : nanoid(8);
- setStore(id, { ...newEdge, id });
-
- if (opts?.preview) {
- prq.addEdge(id);
- } else if (opts?.debug) {
- drq.addEdge(id);
- } else {
- rq.addEdge(id);
- }
- setPendingUpdates(true);
-
- if (opts?.autosave) saveCanvasData();
-
- if (newEdge.from.type === 'connected') {
- const oldEdges = getNode(newEdge.from.node)?.edges;
- updateNode(newEdge.from.node, {
- edges: [...oldEdges, id],
- });
- }
- if (newEdge.to.type === 'connected') {
- const oldEdges = getNode(newEdge.to.node)?.edges;
- updateNode(newEdge.to.node, {
- edges: [...oldEdges, id],
- });
- }
-
- return { id, ...newEdge };
- }
- );
-});
-
-export const useUpdateEdge = sharedInstance(() => {
- const [store, setStore] = useCanvasDocument().state.stores.edges;
- const saveCanvasData = useSaveCanvasData();
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const getEdge = useGetEdge();
- const getNode = useGetNode();
- const updateNode = useUpdateNode();
-
- return createCallback(
- (id: CanvasId, updates: Partial<CanvasEdge>, opts?: OperationOptions) => {
- if (!store[id]) return;
-
- const edge = getEdge(id);
- if (!edge) return;
- if (updates.from?.type === 'free' && edge.from.type === 'connected') {
- const fromNode = getNode(edge.from.node);
- if (fromNode) {
- updateNode(fromNode.id, {
- edges: fromNode.edges.filter((e) => e !== id),
- });
- }
- }
- if (updates.to?.type === 'free' && edge.to.type === 'connected') {
- const toNode = getNode(edge.to.node);
- if (toNode) {
- updateNode(toNode.id, {
- edges: toNode.edges.filter((e) => e !== id),
- });
- }
- }
- if (updates.from?.type === 'connected' && edge.from.type === 'free') {
- const fromNode = getNode(updates.from.node);
- if (fromNode) {
- updateNode(fromNode.id, {
- edges: [...fromNode.edges, id],
- });
- }
- }
- if (updates.to?.type === 'connected' && edge.to.type === 'free') {
- const toNode = getNode(updates.to.node);
- if (toNode) {
- updateNode(toNode.id, {
- edges: [...toNode.edges, id],
- });
- }
- }
-
- setStore(id, { ...store[id], ...updates });
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- }
- );
-});
-
-export const useCanvasEdges = sharedInstance(() => {
- const [pending, setPending] =
- useCanvasDocument().state.signals.pendingUpdates;
- const getEdge = useGetEdge();
- const saveCanvasData = useSaveCanvasData();
- const rq = renderQueue();
- const prq = previewRenderQueue();
- return {
- get: getEdge,
- initialize: useSetAllEdges(),
- delete: useDeleteEdge(),
- createEdge: useCreateEdge(),
- updateEdge: useUpdateEdge(),
- batchUpdate: (fn: () => void, opts?: OperationOptions) => {
- batch(fn);
- if (opts?.autosave && pending()) {
- saveCanvasData();
- }
- },
- save: useSaveCanvasData(),
- unsaved: () => pending(),
- clearPreview: () => prq.clear(),
- visible: createMemo(() => {
- return rq.edges().map((renderable) => getEdge(renderable.id));
- }),
- setVisible: (ids: CanvasId[], opts?: OperationOptions) => {
- rq.clear();
- for (const id of ids) {
- rq.addEdge(id);
- }
- setPending(true);
- if (opts?.autosave) saveCanvasData();
- },
- };
-});
-
-export type EdgeEndPoints = {
- from: Vector2;
- to: Vector2;
-};
-
-export const useEdgeUtils = sharedInstance(() => {
- const getNode = useGetNode();
- const updateEdge = useUpdateEdge();
-
- const getRawEndPoints = (edge: CanvasEdge): EdgeEndPoints => {
- const { from, to } = edge;
- const val: EdgeEndPoints = { from: vec2(0, 0), to: vec2(0, 0) };
-
- if (from.type === 'free') {
- val.from = vec2(from.x, from.y);
- } else if (from.type === 'connected') {
- const { node: nodeId, side } = from;
- const nodeData = getNode(nodeId);
- if (nodeData) {
- const pos = Rect.centerPointOfEdge(nodeData, side);
- val.from = vec2(pos.x, pos.y);
- } else {
- val.from = vec2(0, 0);
- }
- }
-
- if (to.type === 'free') {
- val.to = vec2(to.x, to.y);
- } else if (to.type === 'connected') {
- const { node: nodeId, side } = to;
- const nodeData = getNode(nodeId);
- if (nodeData) {
- const pos = Rect.centerPointOfEdge(nodeData, side);
- val.to = vec2(pos.x, pos.y);
- } else {
- val.to = vec2(0, 0);
- }
- }
- return val;
- };
-
- return {
- getRawEndPoints,
- getEdgeEndVectors(edge: CanvasEdge) {
- const { from, to } = getRawEndPoints(edge);
- return getEdgeEndVectors(edge, [from, to]);
- },
- disconnectEdge(edge: CanvasEdge, nodeId: CanvasId) {
- const { from, to } = edge;
- if (from.type === 'connected' && from.node === nodeId) {
- const { node: nodeId, side } = from;
- const nodeData = getNode(nodeId);
- if (nodeData) {
- const pos = Rect.centerPointOfEdge(nodeData, side);
- updateEdge(edge.id, {
- from: {
- type: 'free',
- x: pos.x,
- y: pos.y,
- },
- });
- }
- }
- if (to.type === 'connected' && to.node === nodeId) {
- const { node: nodeId, side } = to;
- const nodeData = getNode(nodeId);
- if (nodeData) {
- const pos = Rect.centerPointOfEdge(nodeData, side);
- updateEdge(edge.id, {
- to: {
- type: 'free',
- x: pos.x,
- y: pos.y,
- },
- });
- }
- }
- },
- };
-});
-
-export const useBoundingBox = sharedInstance(() => {
- const { getRawEndPoints } = useEdgeUtils();
- return (rectangles: Array<Rectangle | CanvasNode>, edges: CanvasEdge[]) => {
- const min = vec2(Infinity, Infinity);
- const max = vec2(-Infinity, -Infinity);
- for (const rect of rectangles) {
- let xVal = rect.x;
- let yVal = rect.y;
- let width = rect.width;
- let height = rect.height;
-
- // apply the manual scale from pencil node
- if ('wScale' in rect) {
- width *= (rect as PencilNode).wScale;
- }
- if ('hScale' in rect) {
- height *= (rect as PencilNode).hScale;
- }
-
- min.x = Math.min(min.x, xVal, xVal + width);
- min.y = Math.min(min.y, yVal, yVal + height);
- max.x = Math.max(max.x, xVal, xVal + width);
- max.y = Math.max(max.y, yVal, yVal + height);
- }
- for (const edge of edges) {
- const endPoints = getRawEndPoints(edge);
- const points = edgeToCollisionData(edge, [endPoints.from, endPoints.to]);
- for (const point of points) {
- min.x = Math.min(min.x, point.x);
- min.y = Math.min(min.y, point.y);
- max.x = Math.max(max.x, point.x);
- max.y = Math.max(max.y, point.y);
- }
- }
- return Rect.fromPoints(min, max);
- };
-});
-
-export const useSetAllGroups = sharedInstance(() => {
- const [, setStore] = useCanvasDocument().state.stores.groups;
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
-
- return createCallback((groups: CanvasGroup[], opts?: OperationOptions) => {
- setStore(Object.fromEntries(groups.map((group) => [group.id, group])));
- if (!opts?.initialize) setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- });
-});
-
-export const useDeleteGroup = sharedInstance(() => {
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
- const getNode = useGetNode();
- const getEdge = useGetEdge();
- const getGroup = useGetGroup();
- const updateNode = useUpdateNode();
- const updateEdge = useUpdateEdge();
- const { selectedNodeIds, selectedEdgeIds } = useSelection();
-
- return createCallback((opts?: OperationOptions) => {
- const groupIds = new Set<string | undefined>();
- selectedNodeIds().forEach((nodeId: string) => {
- const node = getNode(nodeId);
- const groupId = node?.groupId;
- if (node && groupId) {
- groupIds.add(groupId);
- updateNode(nodeId, {
- groupId: undefined,
- sortOrder: getGroup(groupId).sortOrder + node.sortOrder / 1000,
- });
- }
- });
- selectedEdgeIds().forEach((edgeId: string) => {
- const edge = getEdge(edgeId);
- const groupId = edge?.groupId;
- if (edge && groupId) {
- groupIds.add(getEdge(edgeId)?.groupId);
- updateEdge(edgeId, {
- groupId: undefined,
- sortOrder: getGroup(groupId).sortOrder + edge.sortOrder / 1000,
- });
- }
- });
-
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- });
-});
-
-export const useCreateGroup = sharedInstance(() => {
- const [groups, setStore] = useCanvasDocument().state.stores.groups;
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
- const { selectedNodeIds, selectedEdgeIds, selectedNodes } = useSelection();
- const updateNode = useUpdateNode();
- const updateEdge = useUpdateEdge();
- const rq = renderQueue();
-
- return createCallback(
- (
- existingId?: string,
- existingSortOrder?: number,
- existingLayer?: number,
- existingChildNodes?: string[],
- existingChildEdges?: string[],
- opts?: OperationOptions
- ) => {
- const id = existingId ?? nanoid(8);
-
- const sortOrder =
- existingSortOrder ??
- Math.max(...selectedNodes().map((n: CanvasNode) => n.sortOrder)) + 0.5;
- const layer =
- existingLayer ??
- Math.max(...selectedNodes().map((n: CanvasNode) => n.layer));
- setStore(id, {
- id,
- childNodes: existingChildNodes ?? Array.from(selectedNodeIds()),
- childEdges: existingChildEdges ?? Array.from(selectedEdgeIds()),
- sortOrder,
- layer,
- });
-
- selectedNodeIds().forEach((nodeId: string) => {
- updateNode(nodeId, { groupId: id });
- });
- selectedEdgeIds().forEach((edgeId: string) => {
- updateEdge(edgeId, { groupId: id });
- });
-
- // Normalize to maintain stacking order/avoid same sortOrder on copy
- rq.normalize();
-
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
-
- return groups[id];
- }
- );
-});
-
-export const useUpdateGroup = sharedInstance(() => {
- const [store, setStore] = useCanvasDocument().state.stores.groups;
- const saveCanvasData = useSaveCanvasData();
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
-
- return createCallback(
- (id: CanvasId, updates: Partial<CanvasGroup>, opts?: OperationOptions) => {
- if (!store[id]) return;
- setStore(id, { ...store[id], ...updates });
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- }
- );
-});
-
-export const useAddNodeToGroup = sharedInstance(() => {
- const [store, setStore] = useCanvasDocument().state.stores.groups;
- const saveCanvasData = useSaveCanvasData();
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
-
- return createCallback(
- (id: CanvasId, nodeId: string, opts?: OperationOptions) => {
- if (!store[id]) return;
- const existingChildren = store[id].childNodes ?? [];
- setStore(id, { ...store[id], childNodes: [...existingChildren, nodeId] });
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- }
- );
-});
-
-export const useAddEdgeToGroup = sharedInstance(() => {
- const [store, setStore] = useCanvasDocument().state.stores.groups;
- const saveCanvasData = useSaveCanvasData();
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
-
- return createCallback(
- (id: CanvasId, edgeId: string, opts?: OperationOptions) => {
- if (!store[id]) return;
- const existingChildren = store[id].childEdges ?? [];
- setStore(id, { ...store[id], childEdges: [...existingChildren, edgeId] });
- setPendingUpdates(true);
- if (opts?.autosave) saveCanvasData();
- }
- );
-});
-
-export const useCanvasGroups = sharedInstance(() => {
- const [pending, setPending] =
- useCanvasDocument().state.signals.pendingUpdates;
- const saveCanvasData = useSaveCanvasData();
- const getGroup = useGetGroup();
- const rq = renderQueue();
- const prq = previewRenderQueue();
- return {
- get: getGroup,
- initialize: useSetAllGroups(),
- delete: useDeleteGroup(),
- createGroup: useCreateGroup(),
- update: useUpdateGroup(),
- addNode: useAddNodeToGroup(),
- addEdge: useAddEdgeToGroup(),
- batchUpdate: (fn: () => void, opts?: OperationOptions) => {
- batch(fn);
- if (opts?.autosave && pending()) {
- saveCanvasData();
- }
- },
- save: useSaveCanvasData(),
- unsaved: () => pending(),
- clearPreview: () => prq.clear(),
- visible: createMemo(() => {
- return rq.nodes().map((renderable) => getGroup(renderable.id));
- }),
- setVisible: (ids: CanvasId[], opts?: OperationOptions) => {
- rq.clear();
- for (const id of ids) {
- rq.addGroup(id);
- }
- setPending(true);
- if (opts?.autosave) saveCanvasData();
- },
- };
-});
-
-export const useLoadCanvasData = sharedInstance(() => {
- const nodes = useCanvasNodes();
- const edges = useCanvasEdges();
- const groups = useCanvasGroups();
- const setHighestOrder = useCanvasDocument().state.signals.highestOrder[1];
- const assertLayerAndSortOrder = (entity: CanvasEntity) => {
- if (entity.layer === undefined) entity.layer = 0;
- if (entity.sortOrder === undefined) entity.sortOrder = 0;
- };
- return async (json: Canvas, shouldApply: () => boolean = () => true) => {
- let highestSortOrder = 0;
-
- const nodeMap = await filterMapAsync<any, CanvasNode>(
- json.nodes || [],
- async (node) => {
- if ((await NodeSchema.safeParseAsync(node)).success) {
- const n = node as CanvasNode;
- if (n.sortOrder > highestSortOrder) highestSortOrder = n.sortOrder;
- assertLayerAndSortOrder(n);
- return n;
- } else {
- try {
- NodeSchema.parse(node);
- } catch (e) {
- console.error('error parsing node', e);
- }
- }
- }
- );
- if (!shouldApply()) return false;
-
- const edgeMap = await filterMapAsync<any, CanvasEdge>(
- json.edges || [],
- async (edge) => {
- if ((await EdgeSchema.safeParseAsync(edge)).success) {
- const e = edge as CanvasEdge;
- if (e.sortOrder > highestSortOrder) highestSortOrder = e.sortOrder;
- assertLayerAndSortOrder(e);
- return e;
- }
- }
- );
- if (!shouldApply()) return false;
-
- const groupMap = await filterMapAsync<any, CanvasGroup>(
- json.groups || [],
- async (group) => {
- if ((await GroupSchema.safeParseAsync(group)).success) {
- const g = group as CanvasGroup;
- if (g.sortOrder > highestSortOrder) highestSortOrder = g.sortOrder;
- assertLayerAndSortOrder(g);
- return g;
- }
- }
- );
- if (!shouldApply()) return false;
-
- nodes.initialize(nodeMap, { initialize: true });
- edges.initialize(edgeMap, { initialize: true });
- groups.initialize(groupMap, { initialize: true });
- setHighestOrder(highestSortOrder);
- return true;
- };
-});
-
-export const useExportCanvasData = sharedInstance(() => {
- const getNode = useGetNode();
- const getEdge = useGetEdge();
- const [canvasGroups] = useCanvasDocument().state.stores.groups;
- const rq = renderQueue();
- return (): Canvas => {
- const nodes: CanvasNode[] = [];
- const edges: CanvasEdge[] = [];
- const groups: CanvasGroup[] = [];
-
- const groupIds = new Set<string>();
-
- for (const renderable of rq.sorted()) {
- if (renderable.type === 'node') {
- const node = getNode(renderable.id);
- if (node && (!('status' in node) || node.status !== 'loading'))
- if (node.groupId) groupIds.add(node.groupId);
- nodes.push(node);
- }
- if (renderable.type === 'edge') {
- const edge = getEdge(renderable.id);
- if (edge.groupId) groupIds.add(edge.groupId);
- if (edge) edges.push(edge);
- }
- }
- for (const group of Object.values(canvasGroups)) {
- if (groupIds.has(group.id)) groups.push(group);
- }
- return { nodes, edges, groups } as Canvas;
- };
-});
-
-// Immediate save function (not debounced)
-export const useSaveCanvasDataImmediate = sharedInstance(() => {
- const exportCanvasData = useExportCanvasData();
- const [, setPendingUpdates] =
- useCanvasDocument().state.signals.pendingUpdates;
- const setCurrentSavedFile =
- useCanvasDocument().state.signals.currentSavedFile[1];
- const documentId = useCanvasDocument().documentId();
-
- return createCallback(async () => {
- const canvas = exportCanvasData();
- const { file, saved } = await saveCanvasDocument(documentId, canvas);
- if (!saved) {
- console.error('error on canvas save');
- return false;
- }
-
- setCurrentSavedFile(() => file);
-
- setPendingUpdates(false);
- return true;
- });
-});
-
-// Save document-level canvas data to DSS (debounced).
-export const useSaveCanvasData = sharedInstance(() => {
- const saveImmediate = useSaveCanvasDataImmediate();
- return debounce(saveImmediate, 1500);
-});
diff --git a/apps/web/src/features/block-canvas/store/getNodeEdge.ts b/apps/web/src/features/block-canvas/store/getNodeEdge.ts
deleted file mode 100644
index 726331027e..0000000000
--- a/apps/web/src/features/block-canvas/store/getNodeEdge.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import type { CanvasId } from '@block-canvas/model/CanvasModel';
-import { sharedInstance } from '@block-canvas/util/sharedInstance';
-import { createCallback } from '@solid-primitives/rootless';
-import { useCanvasDocument } from '../context/canvas-document-context';
-
-export const useGetEdge = sharedInstance(() => {
- const [store] = useCanvasDocument().state.stores.edges;
- return createCallback((id: CanvasId) => store[id]);
-});
-
-export const useGetNode = sharedInstance(() => {
- const [store] = useCanvasDocument().state.stores.nodes;
- return createCallback((id: CanvasId) => store[id]);
-});
-
-export const useGetGroup = sharedInstance(() => {
- const [store] = useCanvasDocument().state.stores.groups;
- return createCallback((id: CanvasId) => store[id]);
-});
diff --git a/apps/web/src/features/block-canvas/store/textNodeEditors.ts b/apps/web/src/features/block-canvas/store/textNodeEditors.ts
deleted file mode 100644
index cbab74062a..0000000000
--- a/apps/web/src/features/block-canvas/store/textNodeEditors.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import type { LexicalEditor } from 'lexical';
-import { useCanvasDocument } from '../context/canvas-document-context';
-
-export function useTextNodeEditors() {
- const [textNodeEditors, setTextNodeEditors] =
- useCanvasDocument().state.stores.textNodeEditors;
-
- return {
- getEditor: (nodeId: string) => textNodeEditors[nodeId],
- registerEditor: (nodeId: string, editor: LexicalEditor) => {
- setTextNodeEditors(nodeId, editor);
- },
- unregisterEditor: (nodeId: string) => {
- delete textNodeEditors[nodeId];
- setTextNodeEditors(textNodeEditors);
- },
- };
-}
diff --git a/apps/web/src/features/block-canvas/util/color.ts b/apps/web/src/features/block-canvas/util/color.ts
deleted file mode 100644
index 15483f79b9..0000000000
--- a/apps/web/src/features/block-canvas/util/color.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-export type Hex = `#${string}`;
-export type Color = Hex | 'transparent';
-
-export type RGB = {
- r: number;
- g: number;
- b: number;
-};
-
-export type HSL = {
- h: number;
- s: number;
- l: number;
-};
-
-export function hexToRgb(hex: Hex): RGB {
- let c = hex.replace('#', '');
- if (c.length === 3) {
- c = c
- .split('')
- .map((char) => char + char)
- .join('');
- } else if (c.length === 8) {
- c = c.substring(0, 6);
- } else if (c.length !== 6) {
- return { r: 0, g: 0, b: 0 };
- }
- return {
- r: parseInt(c.substring(0, 2), 16),
- g: parseInt(c.substring(2, 4), 16),
- b: parseInt(c.substring(4, 6), 16),
- };
-}
-
-export function hslToRgb(hsl: HSL): RGB {
- let { h, s, l } = hsl;
- h = (h + 360) % 360;
- s = Math.max(Math.min(s / 100, 1), 0);
- l = Math.max(Math.min(l / 100, 1), 0);
-
- // Chroma.
- const c = (1 - Math.abs(2 * l - 1)) * s;
-
- // Piecewise hue.
- const h1 = h / 60;
-
- // Using the temporary value (x), map r, g, and b at a particular chroma.
- const x = c * (1 - Math.abs((h1 % 2) - 1));
- let r, g, b;
-
- if (h1 < 1) {
- r = c;
- g = x;
- b = 0;
- } else if (h1 < 2) {
- r = x;
- g = c;
- b = 0;
- } else if (h1 < 3) {
- r = 0;
- g = c;
- b = x;
- } else if (h1 < 4) {
- r = 0;
- g = x;
- b = c;
- } else if (h1 < 5) {
- r = x;
- g = 0;
- b = c;
- } else {
- r = c;
- g = 0;
- b = x;
- }
-
- // Apply the lightness
- const m = l - c / 2;
- r = Math.floor((r + m) * 255);
- g = Math.floor((g + m) * 255);
- b = Math.floor((b + m) * 255);
- return { r, g, b };
-}
-
-export function rgbToHsl(rgb: RGB) {
- let { r, g, b } = rgb;
- // Validate rgb.
- r = Math.min(Math.max(r / 255, 0), 1);
- g = Math.min(Math.max(g / 255, 0), 1);
- b = Math.min(Math.max(b / 255, 0), 1);
-
- // Min and max components let us calculate chroma.
- const xMax = Math.max(r, g, b);
- const xMin = Math.min(r, g, b);
-
- // Value.
- const v = xMax;
-
- // Chroma.
- const c = xMax - xMin;
-
- // Lightness.
- const l = (xMax + xMin) / 2;
-
- let h = 0;
- if (c === 0) {
- h = 0;
- } else if (v === r) {
- h = 60 * (0 + (g - b) / c);
- } else if (v === g) {
- h = 60 * (2 + (b - r) / c);
- } else if (v === b) {
- h = 60 * (4 + (r - g) / c);
- }
-
- let s = 0;
- if (l > 0 && l < 1) {
- s = (v - l) / Math.min(l, 1 - l);
- }
- return {
- h: Math.round(h),
- s: Math.round(s * 100),
- l: Math.round(l * 100),
- };
-}
-
-export function rgbToHex(rgb: RGB): Hex {
- const { r, g, b } = rgb;
- const toHex = (c: number): string => {
- const hex = c.toString(16);
- return hex.length === 1 ? '0' + hex : hex;
- };
- return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
-}
diff --git a/apps/web/src/features/block-canvas/util/connectors.ts b/apps/web/src/features/block-canvas/util/connectors.ts
deleted file mode 100644
index f2ef55cfdb..0000000000
--- a/apps/web/src/features/block-canvas/util/connectors.ts
+++ /dev/null
@@ -1,360 +0,0 @@
-import { ARROW_OFFSET } from '@block-canvas/constants';
-import type { EdgeSideType } from '@block-canvas/model/CanvasModel';
-import {
- type CanvasEdge,
- EDGE_CONNECTION_STYLES,
-} from '@block-canvas/model/CanvasModel';
-import { rayRayIntersection } from './intersect';
-import { clamp, cubicBezierPoint } from './math';
-import { PathBuilder } from './svg';
-import { Vec2, type Vector2, vec2 } from './vector2';
-
-export type SvgPath = string;
-
-export type EdgeRenderData = {
- fromPos: Vector2;
- fromVec: Vector2;
- toPos: Vector2;
- toVec: Vector2;
- path: SvgPath;
-};
-
-type ConnectorPoint = {
- pos: Vector2;
- outgoingVector: Vector2;
-};
-
-const pathBuilder = new PathBuilder();
-
-const egdeDirectionLookup: Record<EdgeSideType, Vector2> = {
- top: vec2(0, -1),
- right: vec2(1, 0),
- bottom: vec2(0, 1),
- left: vec2(-1, 0),
-};
-
-/**
- * Calculates the midpoint between two vectors.
- * @param a - First vector
- * @param b - Second vector
- * @returns A new vector at the midpoint
- */
-function midpoint(a: Vector2, b: Vector2): Vector2 {
- return Vec2.lerp(a, b, 0.5);
-}
-
-/**
- * True if a vector is primarily horizontal.
- * @param v - Vector to check
- * @returns True if the vector's x component is larger than its y component
- */
-function isHorizontal(v: Vector2) {
- return Math.abs(v.x) > Math.abs(v.y) + 1e-6;
-}
-
-/**
- * Generates points for a rectilinear path between two positions with given directions.
- * @param a - Start position
- * @param b - End position
- * @param aDir - Direction vector at start position
- * @param bDir - Direction vector at end position
- * @param padding - Distance to extend from endpoints along their directions
- * @returns Array of points defining the rectilinear path
- */
-function getRectilinearPoints(
- a: Vector2,
- b: Vector2,
- aDir: Vector2,
- bDir: Vector2,
- padding: number
-) {
- const aNext = a.add(aDir.multiply(padding));
- const bNext = b.add(bDir.multiply(padding));
- const dot = aDir.dot(bDir);
- const horizontal = isHorizontal(aDir);
-
- // Perpendicular.
- if (dot === 0) {
- // Case 1: perpendicular with a correctly signed intersection position.
- const intersect = rayRayIntersection(a, aDir, b, bDir);
- if (intersect) {
- return [a.clone(), intersect, b.clone()];
- }
-
- // Case 2: perpendicular with a midpoint.
- const elbow = horizontal ? vec2(aNext.x, bNext.y) : vec2(bNext.x, aNext.y);
-
- return [a.clone(), aNext, elbow, bNext, b.clone()];
- }
-
- const delta = bNext.subtract(aNext);
- const aligned = horizontal
- ? Math.sign(aDir.x) === Math.sign(delta.x)
- : Math.sign(aDir.y) === Math.sign(delta.y);
-
- // Parallel opposite.
- if (dot === -1) {
- if (aligned) {
- const m = midpoint(a, b);
- const mA = horizontal ? vec2(m.x, a.y) : vec2(a.x, m.y);
- const mB = horizontal ? vec2(m.x, b.y) : vec2(b.x, m.y);
- return [a.clone(), mA, mB, b.clone()];
- }
-
- const m = midpoint(aNext, bNext);
- const mA = horizontal ? vec2(aNext.x, m.y) : vec2(m.x, aNext.y);
- const mB = horizontal ? vec2(bNext.x, m.y) : vec2(m.x, bNext.y);
- return [a.clone(), aNext, mA, mB, bNext, b.clone()];
- }
-
- // Parallel aligned.
- if (dot === 1) {
- if (aligned) {
- const elbow = horizontal ? vec2(bNext.x, a.y) : vec2(a.x, bNext.y);
- return [a.clone(), elbow, bNext, b.clone()];
- }
- const elbow = horizontal ? vec2(aNext.x, bNext.y) : vec2(bNext.x, aNext.y);
- return [a.clone(), aNext, elbow, bNext, b.clone()];
- }
-
- console.error('Stepped Connector - Unexpected dot value', dot);
- return [a.clone(), aNext, bNext, b.clone()];
-}
-
-/**
- * Filters points that are too close to each other based on a distance threshold.
- * @param points - Array of Vector2 points to filter
- * @param threshold - Minimum distance between points
- * @returns Filtered array with redundant points removed
- */
-function mergeByDistance(points: Vector2[], threshold: number = 1): Vector2[] {
- if (points.length < 2) return points;
- let prev = points[0];
- const merged = [prev];
- let t = threshold * threshold;
- for (let i = 1; i < points.length; i++) {
- const current = points[i];
- const distance = prev.distanceSq(current);
- if (distance > t) {
- merged.push(current);
- prev = current;
- } else {
- }
- }
- return merged;
-}
-
-/**
- * Creates a straight line SVG path between two connector points.
- * @param from - Starting connector point with position and direction
- * @param to - Ending connector point with position and direction
- * @returns SVG path string for a straight line
- */
-const linePath = (from: ConnectorPoint, to: ConnectorPoint): SvgPath => {
- pathBuilder.moveTo(from.pos.x, from.pos.y);
- pathBuilder.lineTo(to.pos.x, to.pos.y);
- return pathBuilder.flush();
-};
-
-/**
- * Creates a stepped (rectilinear) SVG path between two connector points with rounded corners.
- * @param from - Starting connector point with position and direction
- * @param to - Ending connector point with position and direction
- * @param cornerRadius - Radius for rounded corners in the path
- * @returns SVG path string for a stepped line with rounded corners
- */
-const steppedPath = (
- from: ConnectorPoint,
- to: ConnectorPoint,
- cornerRadius: number
-): SvgPath => {
- pathBuilder.moveTo(from.pos.x, from.pos.y);
- let points = mergeByDistance(
- getRectilinearPoints(
- from.pos,
- to.pos,
- from.outgoingVector,
- to.outgoingVector,
- ARROW_OFFSET
- ),
- 5
- );
- pathBuilder.roundedPolyline(points, cornerRadius);
- return pathBuilder.flush();
-};
-
-/**
- * Creates a smooth bezier curve SVG path between two connector points.
- * @param from - Starting connector point with position and direction
- * @param to - Ending connector point with position and direction
- * @returns SVG path string for a cubic bezier curve
- */
-const bezierPath = (from: ConnectorPoint, to: ConnectorPoint): SvgPath => {
- pathBuilder.moveTo(from.pos.x, from.pos.y);
- const distance = from.pos.distance(to.pos);
- const str = clamp(distance / 2, 1, 200);
- const cp1 = from.pos.add(from.outgoingVector.multiply(str));
- const cp2 = to.pos.add(to.outgoingVector.multiply(str));
- pathBuilder.cubicBezierTo(cp1.x, cp1.y, cp2.x, cp2.y, to.pos.x, to.pos.y);
- return pathBuilder.flush();
-};
-
-const segmentedBezier = (
- from: ConnectorPoint,
- to: ConnectorPoint,
- resolution: number
-) => {
- const distance = from.pos.distance(to.pos);
- const str = clamp(distance / 2, 1, 200);
- const cp1 = from.pos.add(from.outgoingVector.multiply(str));
- const cp2 = to.pos.add(to.outgoingVector.multiply(str));
- const points: Vector2[] = [];
- for (let i = 0; i <= resolution; i++) {
- const t = i / resolution;
- const p = cubicBezierPoint(from.pos, cp1, cp2, to.pos, t);
- points.push(p);
- }
- return points;
-};
-
-/**
- * Calculates directional vectors for the start and end points of an edge
- * based on its connection style and endpoint properties.
- * @param edge - The canvas edge to calculate vectors for
- * @param rawEndPoints - Tuple containing computed start and end positions of the edge
- * @returns A tuple containing normalized directional vectors for both endpoints
- */
-export function getEdgeEndVectors(
- edge: CanvasEdge,
- rawEndPoints: [Vector2, Vector2]
-): [Vector2, Vector2] {
- const connectionStyle =
- EDGE_CONNECTION_STYLES[edge.style?.connectionStyle ?? 0];
- const [fromPos, toPos] = rawEndPoints;
- const dir = toPos.subtract(fromPos).normalize();
- const iDir = dir.multiply(-1);
-
- switch (connectionStyle) {
- case 'stepped':
- case 'smooth':
- const { from, to } = edge;
- const horizontal = isHorizontal(dir);
- const sign = horizontal ? Math.sign(dir.x) : Math.sign(dir.y);
-
- let fromDir = vec2(0, 0);
- let toDir = vec2(0, 0);
- if (from.type === 'connected') {
- fromDir.setFrom(egdeDirectionLookup[from.side]);
- } else {
- if (horizontal) {
- fromDir.setTo(sign, 0);
- } else {
- fromDir.setTo(0, sign);
- }
- }
-
- if (to.type === 'connected') {
- toDir.setFrom(egdeDirectionLookup[to.side]);
- } else {
- if (horizontal) {
- toDir.setTo(-sign, 0);
- } else {
- toDir.setTo(0, -sign);
- }
- }
-
- return [fromDir, toDir];
-
- default:
- return [dir.clone(), iDir.clone()];
- }
-}
-
-/**
- * Converts a canvas edge into render data including positions, vectors and SVG path.
- * Handles different connection styles (straight, stepped, smooth).
- *
- * @param edge - The canvas edge to convert
- * @param rawEndPoints - Array containing start and end positions of the edge
- * @returns Edge render data with positions, vectors and SVG path
- */
-export function edgeToRenderData(
- edge: CanvasEdge,
- rawEndPoints: [Vector2, Vector2]
-): EdgeRenderData {
- const [fromPos, toPos] = rawEndPoints;
- const [fromVec, toVec] = getEdgeEndVectors(edge, rawEndPoints);
- const connectionStyle =
- EDGE_CONNECTION_STYLES[edge.style?.connectionStyle ?? 0];
-
- let path: SvgPath;
- switch (connectionStyle) {
- case 'stepped':
- path = steppedPath(
- { pos: fromPos, outgoingVector: fromVec },
- {
- pos: toPos,
- outgoingVector: toVec.clone(),
- },
- 10
- );
- break;
-
- case 'smooth':
- path = bezierPath(
- { pos: fromPos, outgoingVector: fromVec },
- {
- pos: toPos,
- outgoingVector: toVec.clone(),
- }
- );
- break;
-
- default:
- path = linePath(
- { pos: fromPos, outgoingVector: fromVec },
- {
- pos: toPos,
- outgoingVector: toVec.clone(),
- }
- );
- break;
- }
-
- return {
- fromPos,
- fromVec,
- toPos,
- toVec,
- path,
- };
-}
-
-export function edgeToCollisionData(
- edge: CanvasEdge,
- rawEndPoints: [Vector2, Vector2]
-): Vector2[] {
- const [fromPos, toPos] = rawEndPoints;
- const [fromVec, toVec] = getEdgeEndVectors(edge, rawEndPoints);
- const connectionStyle =
- EDGE_CONNECTION_STYLES[edge.style?.connectionStyle ?? 0];
-
- switch (connectionStyle) {
- case 'stepped':
- return getRectilinearPoints(fromPos, toPos, fromVec, toVec, ARROW_OFFSET);
- case 'smooth':
- return segmentedBezier(
- {
- pos: fromPos,
- outgoingVector: fromVec,
- },
- {
- pos: toPos,
- outgoingVector: toVec,
- },
- 10
- );
- default:
- return [fromPos, toPos];
- }
-}
diff --git a/apps/web/src/features/block-canvas/util/intersect.ts b/apps/web/src/features/block-canvas/util/intersect.ts
deleted file mode 100644
index 3c74a585c4..0000000000
--- a/apps/web/src/features/block-canvas/util/intersect.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { type Vector2, vec2 } from './vector2';
-
-export function rayRayIntersection(
- a: Vector2,
- aDir: Vector2,
- b: Vector2,
- bDir: Vector2
-): Vector2 | null {
- const det = aDir.x * bDir.y - aDir.y * bDir.x;
- if (Math.abs(det) < 1e-8) {
- return null;
- }
- const ba = b.subtract(a);
- const t = (ba.x * bDir.y - ba.y * bDir.x) / det;
- const u = (ba.x * aDir.y - ba.y * aDir.x) / det;
- if (t >= 0 && u >= 0) {
- return a.add(aDir.multiply(t));
- }
- return null;
-}
-
-export function lineSegmentIntersection(
- s1: Vector2,
- e1: Vector2,
- s2: Vector2,
- e2: Vector2
-): Vector2 | null {
- const denominator =
- (e2.y - s2.y) * (e1.x - s1.x) - (e2.x - s2.x) * (e1.y - s1.y);
-
- if (denominator === 0) return null; // Parallel lines
-
- const ua =
- ((e2.x - s2.x) * (s1.y - s2.y) - (e2.y - s2.y) * (s1.x - s2.x)) /
- denominator;
-
- const ub =
- ((e1.x - s1.x) * (s1.y - s2.y) - (e1.y - s1.y) * (s1.x - s2.x)) /
- denominator;
-
- if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {
- return vec2(s1.x + ua * (e1.x - s1.x), s1.y + ua * (e1.y - s1.y));
- }
-
- return null;
-}
diff --git a/apps/web/src/features/block-canvas/util/math.ts b/apps/web/src/features/block-canvas/util/math.ts
deleted file mode 100644
index d09a127eb9..0000000000
--- a/apps/web/src/features/block-canvas/util/math.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { type Vector2, vec2 } from './vector2';
-
-const { max, min } = Math;
-
-export function clamp(x: number, mn: number, mx: number) {
- return max(min(mx, x), mn);
-}
-
-export function lerp(a: number, b: number, t: number) {
- return a * (1 - t) + b * t;
-}
-
-export function easeInOutCubic(t: number) {
- let r = clamp(t, 0, 1);
- return r < 0.5 ? 4 * r * r * r : 1 - Math.pow(-2 * r + 2, 3) / 2;
-}
-
-export function remap(
- x: number,
- inMin: number,
- inMax: number,
- outMin: number,
- outMax: number
-) {
- return ((x - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
-}
-
-export const degreesToRadians = (deg: number) => deg * (Math.PI / 180);
-
-export const radiansToDegrees = (rad: number) => rad * (180 / Math.PI);
-
-export const snapTo = (x: number, step: number) => {
- if (step === 0) return x;
- return Math.round(x / step) * step;
-};
-
-export function cubicBezierPoint(
- p0: Vector2,
- p1: Vector2,
- p2: Vector2,
- p3: Vector2,
- t: number
-) {
- // B(t) = (1-t)³P₀ + 3(1-t)²tP₁ + 3(1-t)t²P₂ + t³P₃
- const oneMinusT = 1 - t;
- const oneMinusTSquared = oneMinusT * oneMinusT;
- const oneMinusTCubed = oneMinusTSquared * oneMinusT;
- const tSquared = t * t;
- const tCubed = tSquared * t;
- const x =
- oneMinusTCubed * p0.x +
- 3 * oneMinusTSquared * t * p1.x +
- 3 * oneMinusT * tSquared * p2.x +
- tCubed * p3.x;
- const y =
- oneMinusTCubed * p0.y +
- 3 * oneMinusTSquared * t * p1.y +
- 3 * oneMinusT * tSquared * p2.y +
- tCubed * p3.y;
- return vec2(x, y);
-}
diff --git a/apps/web/src/features/block-canvas/util/mentions.ts b/apps/web/src/features/block-canvas/util/mentions.ts
deleted file mode 100644
index 13f2890f1e..0000000000
--- a/apps/web/src/features/block-canvas/util/mentions.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import {
- type CanvasNode,
- isEntityMentionNode,
-} from '@block-canvas/model/CanvasModel';
-import { useTextNodeEditors } from '@block-canvas/store/textNodeEditors';
-import { untrackMention } from '@core/signal/mention';
-import {
- $isDocumentMentionNode,
- type DocumentMentionNode,
-} from '@macro-inc/lexical-core/nodes/DocumentMentionNode';
-import { $getRoot, $isElementNode, type LexicalEditor } from 'lexical';
-
-export interface MentionInfo {
- mentionUuid: string;
- documentId: string;
-}
-
-/**
- * Extracts all document mentions from a Lexical editor
- */
-function extractMentionsFromEditor(editor: LexicalEditor): MentionInfo[] {
- const mentions: MentionInfo[] = [];
-
- editor.getEditorState().read(() => {
- const root = $getRoot();
- const collectMentions = (node: any) => {
- if ($isDocumentMentionNode(node)) {
- const mentionNode = node as DocumentMentionNode;
- const mentionUuid = mentionNode.getMentionUuid();
- const documentId = mentionNode.getDocumentId();
- if (mentionUuid && documentId) {
- mentions.push({ mentionUuid, documentId });
- }
- }
- if ($isElementNode(node)) {
- node.getChildren().forEach(collectMentions);
- }
- };
-
- root.getChildren().forEach(collectMentions);
- });
-
- return mentions;
-}
-
-export async function untrackMentionsInTextNode(
- node: CanvasNode,
- blockId: string,
- nodeId: string
-) {
- const getTextNodeEditor = useTextNodeEditors().getEditor;
- if (isEntityMentionNode(node) && node.entityType === 'document') {
- if (node.mentionUuid) {
- await untrackMention(blockId, node.mentionUuid);
- }
- }
-
- // For text nodes, we need to extract and untrack all mentions
- if (node.type === 'text') {
- const editor = getTextNodeEditor(nodeId);
- if (editor) {
- const mentions = extractMentionsFromEditor(editor);
- await Promise.all(
- mentions.map(({ mentionUuid }) => untrackMention(blockId, mentionUuid))
- );
- }
- }
-}
diff --git a/apps/web/src/features/block-canvas/util/rectangle.ts b/apps/web/src/features/block-canvas/util/rectangle.ts
deleted file mode 100644
index 190e35455f..0000000000
--- a/apps/web/src/features/block-canvas/util/rectangle.ts
+++ /dev/null
@@ -1,503 +0,0 @@
-import type { JSX } from 'solid-js';
-import { type Anchor, Corners, type Edge, Edges } from '../constants';
-import type { CanvasNode, PencilNode } from '../model/CanvasModel';
-import { lineSegmentIntersection } from './intersect';
-import { type Vector2, vec2 } from './vector2';
-
-/**
- * A Rectangle - the building block of the geometric logic for canvas nodes.
- */
-export type Rectangle = {
- position: Vector2;
- size: Vector2;
-
- x: number;
- y: number;
- w: number;
- h: number;
- width: number;
- height: number;
-
- left: number;
- right: number;
- top: number;
- bottom: number;
- center: Vector2;
-
- // Methods
- containsPoint(point: Vector2): boolean;
- containsRect(rect: Rectangle): boolean;
- intersects(other: Rectangle): boolean;
- intersection(other: Rectangle): Rectangle | null;
- union(other: Rectangle): Rectangle;
- expand(amount: number | Vector2): Rectangle;
- scale(factor: number | Vector2): Rectangle;
- translate(offset: Vector2): Rectangle;
- clone(): Rectangle;
- equals(other: Rectangle): boolean;
- toCssRect(): Partial<JSX.CSSProperties>;
- alignToTarget(
- target: Rectangle,
- opts: { x?: 'left' | 'center' | 'right'; y: 'top' | 'center' | 'bottom' }
- ): Rectangle;
-};
-
-const rectangleMethods = {
- containsPoint(this: Rectangle, point: Vector2): boolean {
- return (
- point.x >= this.position.x &&
- point.x <= this.position.x + this.size.x &&
- point.y >= this.position.y &&
- point.y <= this.position.y + this.size.y
- );
- },
-
- containsRect(this: Rectangle, other: Rectangle): boolean {
- return (
- other.position.x >= this.position.x &&
- other.position.x + other.size.x <= this.position.x + this.size.x &&
- other.position.y >= this.position.y &&
- other.position.y + other.size.y <= this.position.y + this.size.y
- );
- },
-
- intersects(this: Rectangle, other: Rectangle): boolean {
- return !(
- other.position.x > this.position.x + this.size.x ||
- other.position.x + other.size.x < this.position.x ||
- other.position.y > this.position.y + this.size.y ||
- other.position.y + other.size.y < this.position.y
- );
- },
-
- intersection(this: Rectangle, other: Rectangle): Rectangle | null {
- const x1 = Math.max(this.position.x, other.position.x);
- const y1 = Math.max(this.position.y, other.position.y);
- const x2 = Math.min(
- this.position.x + this.size.x,
- other.position.x + other.size.x
- );
- const y2 = Math.min(
- this.position.y + this.size.y,
- other.position.y + other.size.y
- );
-
- if (x1 >= x2 || y1 >= y2) return null;
-
- return rect(vec2(x1, y1), vec2(x2 - x1, y2 - y1));
- },
-
- union(this: Rectangle, other: Rectangle): Rectangle {
- const x1 = Math.min(this.position.x, other.position.x);
- const y1 = Math.min(this.position.y, other.position.y);
- const x2 = Math.max(
- this.position.x + this.size.x,
- other.position.x + other.size.x
- );
- const y2 = Math.max(
- this.position.y + this.size.y,
- other.position.y + other.size.y
- );
-
- return rect(vec2(x1, y1), vec2(x2 - x1, y2 - y1));
- },
-
- expand(this: Rectangle, amount: number | Vector2): Rectangle {
- const expansion =
- typeof amount === 'number' ? vec2(amount, amount) : amount;
- return rect(
- this.position.subtract(expansion.multiply(0.5)),
- this.size.add(expansion)
- );
- },
-
- scale(this: Rectangle, factor: number | Vector2): Rectangle {
- const scaleFactor =
- typeof factor === 'number' ? vec2(factor, factor) : factor;
- return rect(this.position, this.size.multiply(scaleFactor));
- },
-
- translate(this: Rectangle, offset: Vector2): Rectangle {
- return rect(this.position.add(offset), this.size);
- },
-
- clone(this: Rectangle): Rectangle {
- return rect(this.position.clone(), this.size.clone());
- },
-
- equals(this: Rectangle, other: Rectangle): boolean {
- return this.position.equals(other.position) && this.size.equals(other.size);
- },
-
- toString(this: Rectangle): string {
- return `rect(${this.position.toString()}, ${this.size.toString()})`;
- },
-
- toCssRect(this: Rectangle): Partial<JSX.CSSProperties> {
- const x = this.size.x > 0 ? this.position.x : this.position.x + this.size.x;
- const y = this.size.y > 0 ? this.position.y : this.position.y + this.size.y;
- return {
- transform: `translate(${x}px, ${y}px)`,
- width: `${Math.abs(this.size.x)}px`,
- height: `${Math.abs(this.size.y)}px`,
- };
- },
-
- alignToTarget(
- this: Rectangle,
- target: Rectangle,
- opts: { x?: 'left' | 'center' | 'right'; y: 'top' | 'center' | 'bottom' }
- ): Rectangle {
- let x = this.x;
- let y = this.y;
-
- switch (opts.x) {
- case 'left':
- x = target.x;
- break;
- case 'center':
- x = target.x + target.w / 2 - this.w / 2;
- break;
- case 'right':
- x = target.x + (target.w - this.w);
- break;
- }
- switch (opts.y) {
- case 'top':
- y = target.y;
- break;
- case 'center':
- y = target.y + target.h / 2 - this.h / 2;
- break;
- case 'bottom':
- y = target.y + (target.h - this.h);
- break;
- }
- return Rect.fromParams({ x, y, w: this.w, h: this.h });
- },
-};
-
-const rectangleHandler: ProxyHandler<Rectangle> = {
- get(target, prop) {
- if (prop === 'x') return target.position.x;
- if (prop === 'y') return target.position.y;
- if (prop === 'w') return target.size.x;
- if (prop === 'h') return target.size.y;
- if (prop === 'width') return target.size.x;
- if (prop === 'height') return target.size.y;
- if (prop === 'left') return target.position.x;
- if (prop === 'right') return target.position.x + target.size.x;
- if (prop === 'top') return target.position.y;
- if (prop === 'bottom') return target.position.y + target.size.y;
- if (prop === 'center')
- return vec2(
- target.position.x + target.size.x / 2,
- target.position.y + target.size.y / 2
- );
- if (prop in rectangleMethods)
- return rectangleMethods[prop as keyof typeof rectangleMethods];
- return target[prop as keyof Rectangle];
- },
-};
-
-/**
- * Creates a new Rectangle instance.
- * @param position The position vector of the rectangle's top-left corner.
- * @param size The size vector of the rectangle (width and height).
- * @returns A new Rectangle instance.
- */
-export function rect(position: Vector2, size: Vector2): Rectangle {
- return new Proxy({ position, size } as Rectangle, rectangleHandler);
-}
-
-// Helper constants and functions
-export const Rect = {
- fromPoints(point1: Vector2, point2: Vector2): Rectangle {
- const minX = Math.min(point1.x, point2.x);
- const minY = Math.min(point1.y, point2.y);
- const maxX = Math.max(point1.x, point2.x);
- const maxY = Math.max(point1.y, point2.y);
-
- return rect(vec2(minX, minY), vec2(maxX - minX, maxY - minY));
- },
-
- fromCenter(center: Vector2, size: Vector2): Rectangle {
- const halfSize = size.multiply(0.5);
- return rect(center.subtract(halfSize), size);
- },
-
- boundingRect(rectangles: Rectangle[] | CanvasNode[]): Rectangle {
- const min = vec2(Infinity, Infinity);
- const max = vec2(-Infinity, -Infinity);
- for (const rect of rectangles) {
- let xVal = rect.x;
- let yVal = rect.y;
- let width = rect.width;
- let height = rect.height;
- // apply the manual scale from pencil node
- if ('wScale' in rect) {
- width *= (rect as PencilNode).wScale;
- }
- if ('hScale' in rect) {
- height *= (rect as PencilNode).hScale;
- }
-
- min.x = Math.min(min.x, xVal, xVal + width);
- min.y = Math.min(min.y, yVal, yVal + height);
- max.x = Math.max(max.x, xVal, xVal + width);
- max.y = Math.max(max.y, yVal, yVal + height);
- }
- return Rect.fromPoints(min, max);
- },
-
- fromParams(
- params:
- | { x: number; y: number; w: number; h: number }
- | { x: number; y: number; width: number; height: number }
- ): Rectangle {
- if ('w' in params) {
- return rect(vec2(params.x, params.y), vec2(params.w, params.h));
- }
- return rect(vec2(params.x, params.y), vec2(params.width, params.height));
- },
-
- fromCanvasNode(node: CanvasNode): Rectangle {
- if ('coords' in node)
- return rect(
- vec2(node.x, node.y),
- vec2(node.width * node.wScale, node.height * node.hScale)
- );
- return rect(vec2(node.x, node.y), vec2(node.width, node.height));
- },
-
- /**
- * Caluclate a new rectangle from a user scale operation as defined by an Anchor type and
- * a canvas-space pointer position.
- * @param rect The rectangle to scale.
- * @param anchor The anchor point of the scale operation.
- * @param point The position of the mouse pointer in canvas space.
- * @returns A new rectangle with the new scale.
- */
- rescaleFromAnchorToPoint(
- rect: Rectangle,
- anchor: Anchor,
- point: Vector2,
- proportional?: boolean,
- centered?: boolean
- ): Rectangle {
- let { x, y, w, h } = rect;
-
- switch (anchor) {
- case Edges.Top:
- h = rect.h + rect.y - point.y;
- break;
- case Edges.Right:
- w = point.x - rect.x;
- break;
- case Edges.Bottom:
- h = point.y - rect.y;
- break;
- case Edges.Left:
- w = rect.w + rect.x - point.x;
- break;
- case Corners.TopLeft:
- w = rect.w + rect.x - point.x;
- h = rect.h + rect.y - point.y;
- break;
- case Corners.TopRight:
- h = rect.h + rect.y - point.y;
- w = point.x - rect.x;
- break;
- case Corners.BottomRight:
- w = point.x - rect.x;
- h = point.y - rect.y;
- break;
- case Corners.BottomLeft:
- w = rect.w + rect.x - point.x;
- h = point.y - rect.y;
- break;
- }
-
- let wRatio = w / rect.w;
- let hRatio = h / rect.h;
-
- // Enforce ratio if rescale is proportional
- if (proportional && (wRatio !== 1 || hRatio !== 1)) {
- // Use the smaller of the two ratios
- if (wRatio === 1 || (hRatio !== 1 && wRatio > hRatio)) {
- wRatio = hRatio;
- w = rect.w * hRatio;
- } else if (hRatio === 1 || (wRatio !== 1 && hRatio > wRatio)) {
- hRatio = wRatio;
- h = rect.h * wRatio;
- }
- }
- // Double scaling if centered, so edge/corner stays under cursor
- if (centered) {
- w = w + (w - rect.w);
- h = h + (h - rect.h);
- }
-
- // Set position depending on anchor and if rescale is centered
- let transformedRect = Rect.fromParams({ x, y, w, h });
-
- if (centered) {
- transformedRect = transformedRect.alignToTarget(rect, {
- x: 'center',
- y: 'center',
- });
- } else {
- switch (anchor) {
- case Edges.Top:
- transformedRect = transformedRect.alignToTarget(rect, {
- x: 'center',
- y: 'bottom',
- });
- break;
- case Edges.Right:
- transformedRect = transformedRect.alignToTarget(rect, {
- x: 'left',
- y: 'center',
- });
- break;
- case Edges.Bottom:
- transformedRect = transformedRect.alignToTarget(rect, {
- x: 'center',
- y: 'top',
- });
- break;
- case Edges.Left:
- transformedRect = transformedRect.alignToTarget(rect, {
- x: 'right',
- y: 'center',
- });
- break;
- case Corners.TopLeft:
- transformedRect = transformedRect.alignToTarget(rect, {
- x: 'right',
- y: 'bottom',
- });
- break;
- case Corners.TopRight:
- transformedRect = transformedRect.alignToTarget(rect, {
- x: 'left',
- y: 'bottom',
- });
- break;
- case Corners.BottomRight:
- transformedRect = transformedRect.alignToTarget(rect, {
- x: 'left',
- y: 'top',
- });
- break;
- case Corners.BottomLeft:
- transformedRect = transformedRect.alignToTarget(rect, {
- x: 'right',
- y: 'top',
- });
- break;
- }
- }
-
- return transformedRect;
- },
-
- calculateRatioRectangle(inner: Rectangle, outer: Rectangle): Rectangle {
- // TODO: (seamus) Diabling this check for now. Should add epsilon tolerances to
- // many of the vector and rectangle operation.
- // if (!outer.containsRect(inner)) {
- // throw new Error(
- // 'calulateRatioRectangle: inner rectangle must be contained within outer: inner = ' +
- // inner.toString() +
- // ' outer = ' +
- // outer.toString()
- // );
- // }
-
- return Rect.fromParams({
- x: (inner.x - outer.x) / outer.w,
- y: (inner.y - outer.y) / outer.h,
- w: inner.w / outer.w,
- h: inner.h / outer.h,
- });
- },
-
- applyRatioRectangle(inner: Rectangle, outer: Rectangle): Rectangle {
- return Rect.fromParams({
- x: inner.x * outer.w + outer.x,
- y: inner.y * outer.h + outer.y,
- w: inner.w * outer.w,
- h: inner.h * outer.h,
- });
- },
-
- intersectLineSegment(
- rect: Rectangle,
- start: Vector2,
- end: Vector2
- ): Vector2[] {
- const intersections: Vector2[] = [];
-
- const edges = [
- { start: vec2(rect.left, rect.top), end: vec2(rect.right, rect.top) },
- { start: vec2(rect.right, rect.top), end: vec2(rect.right, rect.bottom) },
- {
- start: vec2(rect.right, rect.bottom),
- end: vec2(rect.left, rect.bottom),
- },
- { start: vec2(rect.left, rect.bottom), end: vec2(rect.left, rect.top) },
- ];
-
- edges.forEach((edge) => {
- const intersection = lineSegmentIntersection(
- start,
- end,
- edge.start,
- edge.end
- );
- if (intersection) intersections.push(intersection);
- });
-
- return intersections;
- },
-
- centerPointOfEdge(rect: Rectangle | CanvasNode, edge: Edge): Vector2 {
- const { x, y, width, height } = rect;
- const point = vec2(x + width / 2, y + height / 2);
- if (edge === 'top') point.y = y;
- if (edge === 'right') point.x = x + width;
- if (edge === 'bottom') point.y = y + height;
- if (edge === 'left') point.x = x;
- return point;
- },
-
- checkPencilIntersection(node: PencilNode, rect: Rectangle): boolean {
- const { x, y, width, height, coords, wScale, hScale } = node;
-
- const pencilRect = Rect.fromParams({
- x,
- y,
- w: width * wScale,
- h: height * hScale,
- });
-
- // The selection box can either contain the entire penicl or intersect
- // one or more of the segments.
- if (rect.containsRect(pencilRect)) return true;
-
- // Cannot intersect a segment if you don't intersect the bounding rect.
- if (!pencilRect.intersects(rect)) return false;
-
- for (let i = 0; i < coords.length - 1; i++) {
- const start = vec2(x + coords[i][0] * wScale, y + coords[i][1] * hScale);
- const end = vec2(
- x + coords[i + 1][0] * wScale,
- y + coords[i + 1][1] * hScale
- );
- if (Rect.intersectLineSegment(rect, start, end).length > 0) {
- return true;
- }
- }
- return false;
- },
-};
diff --git a/apps/web/src/features/block-canvas/util/renderQueue.ts b/apps/web/src/features/block-canvas/util/renderQueue.ts
deleted file mode 100644
index 7ddd268d47..0000000000
--- a/apps/web/src/features/block-canvas/util/renderQueue.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import { createMemo, createSignal, type Setter, untrack } from 'solid-js';
-import type { SetStoreFunction, Store } from 'solid-js/store';
-import {
- type CanvasEdge,
- type CanvasEntity,
- type CanvasGroup,
- type CanvasId,
- type CanvasNode,
- isCanvasNode,
-} from '../model/CanvasModel';
-
-export type Renderable = {
- id: CanvasId;
- type: 'node' | 'edge' | 'group';
- sortOrder: number;
- layer: number;
-};
-
-function createRenderable(entity: CanvasEntity): Renderable {
- return {
- id: entity.id,
- type: isCanvasNode(entity) ? 'node' : 'edge',
- sortOrder: entity.sortOrder ?? 0,
- layer: 0,
- };
-}
-
-/**
- * Update the layer and order of a renderable in place by reading from the
- * canvas data stores.
- */
-function updateSort(
- item: Renderable,
- getNode: (id: CanvasId) => CanvasNode,
- getEdge: (id: CanvasId) => CanvasEdge,
- getGroup: (id: CanvasId) => CanvasGroup
-): void {
- if (item.type === 'node') {
- const node = getNode(item.id);
- const group = node.groupId ? getGroup(node.groupId) : undefined;
- item.layer = group ? group.layer : node.layer;
- item.sortOrder = group
- ? group.sortOrder + node.sortOrder / 1000
- : node.sortOrder;
- return;
- }
- if (item.type === 'edge') {
- const edge = getEdge(item.id);
- const group = edge.groupId ? getGroup(edge.groupId) : undefined;
- const connected =
- edge.to.type === 'connected' || edge.from.type === 'connected';
-
- if (!connected) {
- item.layer = group ? group.layer : edge.layer;
- item.sortOrder = group
- ? group.sortOrder + edge.sortOrder / 1000
- : edge.sortOrder;
- return;
- }
-
- let sortOrder = -Infinity;
- let layer = 0;
- if (edge.from.type === 'connected') {
- const fromNode = getNode(edge.from.node);
- if (fromNode.layer > layer) {
- layer = fromNode.layer;
- }
- if (fromNode.sortOrder > sortOrder) {
- sortOrder = fromNode.sortOrder + 0.5;
- }
- }
-
- if (edge.to.type === 'connected') {
- const toNode = getNode(edge.to.node);
- if (toNode.layer > layer) {
- layer = toNode.layer;
- }
- if (toNode.sortOrder > sortOrder) {
- sortOrder = toNode.sortOrder + 0.5;
- }
- }
- item.layer = layer;
- item.sortOrder = sortOrder;
- }
-}
-
-function compare(a: Renderable, b: Renderable): number {
- const aLayer = a.layer ?? 0;
- const bLayer = b.layer ?? 0;
- if (aLayer !== bLayer) {
- return aLayer - bLayer;
- }
- const aSortOrder = a.sortOrder ?? 0;
- const bSortOrder = b.sortOrder ?? 0;
- if (aSortOrder !== bSortOrder) {
- return aSortOrder - bSortOrder;
- }
- return 0;
-}
-
-export function createRenderQueue(
- nodeStore: [
- Store<Record<CanvasId, CanvasNode>>,
- SetStoreFunction<Record<CanvasId, CanvasNode>>,
- ],
- edgeStore: [
- Store<Record<CanvasId, CanvasEdge>>,
- SetStoreFunction<Record<CanvasId, CanvasEdge>>,
- ],
- groupStore: [
- Store<Record<CanvasId, CanvasGroup>>,
- SetStoreFunction<Record<CanvasId, CanvasGroup>>,
- ],
- setHighestOrder: Setter<number>
-) {
- const [nodes, setNodes] = nodeStore;
- const [edges, setEdges] = edgeStore;
- const [groups, setGroups] = groupStore;
- const [list, setList] = createSignal<Renderable[]>([]);
- const sorted = createMemo(() => {
- const _list = list();
-
- for (const item of _list) {
- updateSort(
- item,
- (id) => nodes[id],
- (id) => edges[id],
- (id) => groups[id]
- );
- }
-
- return [..._list].sort(compare);
- });
-
- return {
- addNode(id: CanvasId) {
- const node = nodes[id];
- if (node) {
- const renderable = createRenderable(node);
- setList((prev) => [...prev, renderable]);
- }
- },
-
- addEdge: (id: CanvasId) => {
- const edge = edges[id];
- if (edge) {
- const renderable = createRenderable(edge);
- setList((prev) => [...prev, renderable]);
- }
- },
-
- addGroup: (id: CanvasId) => {
- const group = groups[id];
- if (group) {
- const renderable = createRenderable(group);
- setList((prev) => [...prev, renderable]);
- }
- },
-
- remove(id: CanvasId) {
- setList((prev) => prev.filter((renderable) => renderable.id !== id));
- },
-
- sorted: sorted,
-
- list: list,
-
- length: () => list().length,
-
- nodes: createMemo(() => {
- return list().filter((renderable) => renderable.type === 'node');
- }),
-
- edges: createMemo(() => {
- return list().filter((renderable) => renderable.type === 'edge');
- }),
-
- groups: createMemo(() => {
- return list().filter((renderable) => renderable.type === 'group');
- }),
-
- clear() {
- setList([]);
- },
-
- forceSet(renderables: Renderable[]) {
- let existingById = new Map<CanvasId, Renderable>(
- list().map((r) => [r.id, r])
- );
- setList(
- renderables.map((r) => {
- if (existingById.has(r.id)) {
- existingById.get(r.id)!.sortOrder = r.sortOrder;
- return existingById.get(r.id)!;
- }
- return r;
- })
- );
- },
-
- normalize() {
- let order = 1;
- let lastLayer = -Infinity;
- for (const renderable of untrack(sorted)) {
- if (lastLayer !== renderable.layer) {
- lastLayer = renderable.layer;
- order = 1;
- }
- if (renderable.type === 'node') {
- setNodes(renderable.id, { sortOrder: order++ });
- } else if (renderable.type === 'edge') {
- setEdges(renderable.id, { sortOrder: order++ });
- } else if (renderable.type === 'group') {
- setGroups(renderable.id, { sortOrder: order++ });
- }
- }
- setHighestOrder(order);
- },
- };
-}
-
-export type RenderQueue = ReturnType<typeof createRenderQueue>;
diff --git a/apps/web/src/features/block-canvas/util/sharedInstance.ts b/apps/web/src/features/block-canvas/util/sharedInstance.ts
deleted file mode 100644
index 74fe248038..0000000000
--- a/apps/web/src/features/block-canvas/util/sharedInstance.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { type Accessor, runWithOwner } from 'solid-js';
-import { useCanvasDocument } from '../context/canvas-document-context';
-
-/**
- * Utility for creating a document-shared set of utilities that for
- * performance or data-safety reasons should be enforced as a singleton
- * within one canvas. The document context owns each initialized instance.
- */
-export function sharedInstance<T>(factory: () => T): Accessor<T> {
- const key = Symbol();
- return () => {
- const canvas = useCanvasDocument();
- const instances = canvas.state.instances;
- if (!instances.has(key)) {
- if (!canvas.instanceOwner) {
- throw new Error('Canvas document instance owner is not initialized');
- }
- const instance = runWithOwner(canvas.instanceOwner, factory);
- instances.set(key, instance);
- }
- return instances.get(key) as T;
- };
-}
diff --git a/apps/web/src/features/block-canvas/util/simplify.ts b/apps/web/src/features/block-canvas/util/simplify.ts
deleted file mode 100644
index ac99e3150f..0000000000
--- a/apps/web/src/features/block-canvas/util/simplify.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * Algorithm and code by Vladimir Agafonkin.
- * (c) 2017, Vladimir Agafonkin
- * Simplify.js, a high-performance JS polyline simplification library
- * mourner.github.io/simplify-js released under the BSD license.
- *
- * Note: I (seamus) copy-pasted for the sake of ESM import modification and types.
- */
-
-import type { Vector2 } from './vector2';
-
-type Point = Vector2;
-
-function getSqDist(p1: Point, p2: Point): number {
- const dx = p1.x - p2.x;
- const dy = p1.y - p2.y;
- return dx * dx + dy * dy;
-}
-
-// Square distance from a point to a segment
-function getSqSegDist(p: Point, p1: Point, p2: Point): number {
- let x = p1.x;
- let y = p1.y;
- const dx = p2.x - x;
- const dy = p2.y - y;
-
- if (dx !== 0 || dy !== 0) {
- const t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);
- if (t > 1) {
- x = p2.x;
- y = p2.y;
- } else if (t > 0) {
- x += dx * t;
- y += dy * t;
- }
- }
-
- const dx2 = p.x - x;
- const dy2 = p.y - y;
- return dx2 * dx2 + dy2 * dy2;
-}
-
-// Basic distance-based simplification
-function simplifyRadialDist(points: Point[], sqTolerance: number): Point[] {
- let prevPoint = points[0];
- const newPoints: Point[] = [prevPoint];
- let point: Point;
-
- for (let i = 1, len = points.length; i < len; i++) {
- point = points[i];
- if (getSqDist(point, prevPoint) > sqTolerance) {
- newPoints.push(point);
- prevPoint = point;
- }
- }
-
- //@ts-ignore
- if (prevPoint !== point) newPoints.push(point);
- return newPoints;
-}
-
-function simplifyDPStep(
- points: Point[],
- first: number,
- last: number,
- sqTolerance: number,
- simplified: Point[]
-): void {
- let maxSqDist = sqTolerance;
- let index: number | undefined;
-
- for (let i = first + 1; i < last; i++) {
- const sqDist = getSqSegDist(points[i], points[first], points[last]);
- if (sqDist > maxSqDist) {
- index = i;
- maxSqDist = sqDist;
- }
- }
-
- if (maxSqDist > sqTolerance) {
- if (index && index - first > 1)
- simplifyDPStep(points, first, index, sqTolerance, simplified);
-
- if (index) simplified.push(points[index]);
-
- if (last - (index || last) > 1)
- simplifyDPStep(points, index || last, last, sqTolerance, simplified);
- }
-}
-
-// Simplification using Ramer-Douglas-Peucker algorithm
-function simplifyDouglasPeucker(points: Point[], sqTolerance: number): Point[] {
- const last = points.length - 1;
- const simplified: Point[] = [points[0]];
-
- simplifyDPStep(points, 0, last, sqTolerance, simplified);
- simplified.push(points[last]);
-
- return simplified;
-}
-
-// Both algorithms combined for awesome performance
-export function simplify(
- points: Point[],
- tolerance?: number,
- highestQuality?: boolean
-): Point[] {
- if (points.length <= 2) return points;
-
- const sqTolerance = tolerance !== undefined ? tolerance * tolerance : 1;
-
- const simplifiedPoints = highestQuality
- ? points
- : simplifyRadialDist(points, sqTolerance);
-
- return simplifyDouglasPeucker(simplifiedPoints, sqTolerance);
-}
diff --git a/apps/web/src/features/block-canvas/util/style.ts b/apps/web/src/features/block-canvas/util/style.ts
deleted file mode 100644
index df383fd2ba..0000000000
--- a/apps/web/src/features/block-canvas/util/style.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-// @ts-ignore vite understands, TS does not (don't try switching the module standard)
-
-import { oklchToHex } from '@core/util/oklchToRgb';
-import { withRecall } from '@core/util/withRecall';
-import colors from 'tailwindcss/colors';
-import { type CanvasNode, StyleSchema } from '../model/CanvasModel';
-import type { Color, Hex } from './color';
-import { clamp } from './math';
-
-export const allStyleProps = Object.keys(StyleSchema.shape);
-
-function validateHex(hex: Hex | string): hex is Hex {
- hex = hex.replace('#', '');
- if (/^[0-9A-Fa-f]{3}$/.test(hex)) return true;
- if (/^[0-9A-Fa-f]{6}$/.test(hex)) return true;
- if (/^[0-9A-Fa-f]{8}$/.test(hex)) return true;
- return false;
-}
-
-const getHex = withRecall(oklchToHex);
-
-export function getTailwindColor(colorClass: string): Color {
- const [colorName, shade] = colorClass.split('-');
- if (!shade) {
- if (colorName === 'white') return '#ffffff';
- if (colorName === 'transparent') return 'transparent';
- }
- // @ts-ignore
- const oklch = colors[colorName]?.[shade];
- // hex colors are sometimes, rarely used
- if (oklch.startsWith('#')) return oklch;
- if (!oklch) return 'transparent';
- const hex = getHex(oklch);
- if (!hex) return 'transparent';
- if (!validateHex(hex)) return 'transparent';
- return hex;
-}
-
-/**
- * Adds opacity to a hex color or returns 'transparent'
- * @param color - Hex color string (3, 6, or 8 digits) or 'transparent'
- * @param opacity - Number between 0 and 100
- * @returns Hex color string with opacity
- * @throws Error if color format is invalid or opacity is out of range
- */
-export function opacity(color: Color, opacity: number): string {
- if (color === 'transparent') return 'transparent';
-
- const o = clamp(opacity, 0, 100) / 100;
- const a = Math.round(255 * o);
-
- const col = color.replace('#', '');
-
- let hex: string;
- if (col.length === 3) {
- hex = col
- .split('')
- .map((char) => char + char)
- .join('');
- } else if (col.length === 6) {
- hex = col;
- } else if (col.length === 8) {
- hex = col.substring(0, 6);
- } else {
- throw new Error('Invalid color format. Use 3, 6, or 8-digit hex color.');
- }
-
- // validate hex
- if (!/^[0-9A-Fa-f]{6}$/.test(hex)) {
- // throw new Error('Invalid hex color characters');
- return 'transparent';
- }
-
- const alphaHex = a.toString(16).padStart(2, '0');
- return `#${hex}${alphaHex} `;
-}
-
-export function getBorderRadius(node: CanvasNode) {
- if (!node.style?.cornerRadius) return '0px';
- if (node.style?.cornerRadius >= 100) {
- return 'calc(infinity * 1px)';
- }
- return node.style.cornerRadius + 'px';
-}
-
-export const LineEndStyles = ['None', 'Caret', 'Triangle', 'Circle'];
-
-export function getLineEndStyle(style: number) {
- if (style >= 0 && style < LineEndStyles.length) {
- return LineEndStyles[style];
- } else {
- return LineEndStyles[0];
- }
-}
-
-export function getTextNodeHeight(fontSize: any): number {
- return 2.25 * (fontSize ?? 24);
-}
diff --git a/apps/web/src/features/block-canvas/util/svg.ts b/apps/web/src/features/block-canvas/util/svg.ts
deleted file mode 100644
index dc37789b46..0000000000
--- a/apps/web/src/features/block-canvas/util/svg.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import type { CanvasEntityStyle } from '@block-canvas/model/CanvasModel';
-import type { JSX } from 'solid-js';
-import { type Vector2, vec2 } from './vector2';
-
-type Segment = string;
-
-export class PathBuilder {
- private segments: Segment[];
- private prevPoint: Vector2 = vec2(0, 0);
- private startPoint: Vector2 = vec2(0, 0);
- private started = false;
-
- constructor(start?: Vector2) {
- this.segments = [];
- if (start) {
- this.startPoint.setTo(start.x, start.y);
- this.prevPoint.setTo(start.x, start.y);
- this.started = true;
- }
- }
-
- moveTo(x: number, y: number) {
- this.segments.push(`M ${x} ${y}`);
- this.prevPoint = vec2(x, y);
- if (!this.started) {
- this.started = true;
- this.startPoint.setTo(x, y);
- }
- return this;
- }
-
- lineTo(x: number, y: number) {
- this.segments.push(`L ${x} ${y}`);
- this.prevPoint.setTo(x, y);
- return this;
- }
-
- cubicBezierTo(
- cp1x: number,
- cp1y: number,
- cp2x: number,
- cp2y: number,
- x: number,
- y: number
- ) {
- this.segments.push(`C ${cp1x} ${cp1y} ${cp2x} ${cp2y} ${x} ${y}`);
- this.prevPoint.setTo(x, y);
- return this;
- }
-
- quadraticBezierTo(cpx: number, cpy: number, x: number, y: number) {
- this.segments.push(`Q ${cpx} ${cpy} ${x} ${y}`);
- this.prevPoint.setTo(x, y);
- return this;
- }
-
- close() {
- this.segments.push('Z');
- this.prevPoint.setTo(this.startPoint.x, this.startPoint.y);
- return this;
- }
-
- arcTo(
- radius: number,
- x: number,
- y: number,
- largeArc: boolean,
- sweep: boolean
- ) {
- this.segments.push(
- `A ${radius} ${radius} 0 ${largeArc ? 1 : 0} ${sweep ? 1 : 0} ${x} ${y}`
- );
- this.prevPoint.setTo(x, y);
- return this;
- }
-
- toString() {
- return this.segments.join(' ');
- }
-
- flush() {
- const str = this.toString();
- this.segments = [];
- this.started = false;
- this.startPoint.setTo(0, 0);
- this.prevPoint.setTo(0, 0);
- return str;
- }
-
- roundedPolyline(points: Vector2[], radius: number) {
- if (points.length < 2) {
- console.error('Polyline must have at least 2 points');
- return this;
- }
-
- this.moveTo(points[0].x, points[0].y);
-
- if (points.length === 2) {
- this.lineTo(points[1].x, points[1].y);
- return this;
- }
-
- for (let i = 0; i < points.length - 1; i++) {
- const current = points[i];
- const next = points[i + 1];
-
- if (i < points.length - 2) {
- const afterNext = points[i + 2];
-
- const v1 = next.subtract(current);
- const v2 = afterNext.subtract(next);
-
- const v1Norm = v1.normalize();
- const v2Norm = v2.normalize();
-
- const v1Len = v1.length();
- const v2Len = v2.length();
-
- const maxRadius = Math.min(v1Len, v2Len) / 2;
- const limitedRadius = Math.min(radius, maxRadius);
-
- const cornerStart = next.subtract(v1Norm.multiply(limitedRadius));
- const cornerEnd = next.add(v2Norm.multiply(limitedRadius));
-
- const cp1 = vec2(
- cornerStart.x + v1Norm.x * limitedRadius * 0.55,
- cornerStart.y + v1Norm.y * limitedRadius * 0.55
- );
-
- const cp2 = vec2(
- cornerEnd.x - v2Norm.x * limitedRadius * 0.55,
- cornerEnd.y - v2Norm.y * limitedRadius * 0.55
- );
-
- this.lineTo(cornerStart.x, cornerStart.y);
-
- this.cubicBezierTo(
- cp1.x,
- cp1.y,
- cp2.x,
- cp2.y,
- cornerEnd.x,
- cornerEnd.y
- );
- } else {
- this.lineTo(next.x, next.y);
- }
- }
-
- return this;
- }
-}
-
-export const parseTranslate = (transformText: string): Vector2 => {
- const matches = transformText.match(/translate\(\s?(\d+),\s?(\d+)/);
- const x = parseInt(matches?.at(1) || '0');
- const y = parseInt(matches?.at(2) || '0');
- return vec2(x, y);
-};
-
-export const parseScale = (transformText: string): number => {
- const matches = transformText.match(/scale\(\s?(\d*\.?\d*)/);
- return parseFloat(matches?.at(1) || '1');
-};
-
-export const getTextWidth = (text: string, font: string): number => {
- const canvas: HTMLCanvasElement = document.createElement('canvas');
- const ctx = canvas.getContext('2d');
- if (ctx) {
- ctx.font = font;
- return ctx.measureText(text).width;
- }
- return 0;
-};
-
-type entityStyleType = 'number' | 'string';
-
-type svgEntityStyleEntry = {
- svgAttribute:
- | keyof JSX.UseSVGAttributes<SVGGElement>
- | 'rx'
- | 'ry'
- | 'cx'
- | 'cy';
- styleProperty: keyof CanvasEntityStyle;
- type: entityStyleType;
- applyScale: boolean;
-};
-
-export const svgEntityStyles: svgEntityStyleEntry[] = [
- {
- svgAttribute: 'font-size',
- styleProperty: 'textSize',
- type: 'number',
- applyScale: true,
- },
- {
- svgAttribute: 'fill',
- styleProperty: 'fillColor',
- type: 'string',
- applyScale: false,
- },
- {
- svgAttribute: 'stroke',
- styleProperty: 'strokeColor',
- type: 'string',
- applyScale: false,
- },
- {
- svgAttribute: 'stroke-width',
- styleProperty: 'strokeWidth',
- type: 'number',
- applyScale: true,
- },
- {
- svgAttribute: 'opacity',
- styleProperty: 'opacity',
- type: 'number',
- applyScale: false,
- },
-] as const;
diff --git a/apps/web/src/features/block-canvas/util/vector2.ts b/apps/web/src/features/block-canvas/util/vector2.ts
deleted file mode 100644
index 02f33d2c8c..0000000000
--- a/apps/web/src/features/block-canvas/util/vector2.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-import type { CanvasEdge } from '../model/CanvasModel';
-import type { Rectangle } from './rectangle';
-
-/*
- * Vector data and operation for the Canvas Block.
- */
-export type Vector2 = [number, number] & {
- x: number;
- y: number;
- add(other: Vector2): Vector2;
- subtract(other: Vector2): Vector2;
- multiply(scalar: Vector2 | number): Vector2;
- divide(scalar: Vector2 | number): Vector2;
- dot(other: Vector2): number;
- length(): number;
- normalize(): Vector2;
- distance(other: Vector2): number;
- angle(): number;
- clone(): Vector2;
- equals(other: Vector2): boolean;
- setTo(x: number, y: number): void;
- setFrom(other: Vector2): void;
- mag(): number;
- distanceSq(other: Vector2): number;
-};
-
-export type Vector2Like =
- | Vector2
- | {
- x: number;
- y: number;
- };
-
-const vectorMethods = {
- add(this: Vector2, other: Vector2): Vector2 {
- return vec2(this[0] + other[0], this[1] + other[1]);
- },
-
- subtract(this: Vector2, other: Vector2): Vector2 {
- return vec2(this[0] - other[0], this[1] - other[1]);
- },
-
- multiply(this: Vector2, scalar: number | Vector2): Vector2 {
- if (typeof scalar === 'number') {
- return vec2(this[0] * scalar, this[1] * scalar);
- }
- return vec2(this[0] * scalar[0], this[1] * scalar[1]);
- },
-
- divide(this: Vector2, scalar: number | Vector2): Vector2 {
- if (typeof scalar === 'number') {
- if (scalar === 0) throw new Error('Division by zero');
- return vec2(this[0] / scalar, this[1] / scalar);
- }
- if (scalar[0] === 0) throw new Error('Division by zero');
- if (scalar[1] === 0) throw new Error('Division by zero');
- return vec2(this[0] / scalar[0], this[1] / scalar[1]);
- },
-
- dot(this: Vector2, other: Vector2): number {
- return this[0] * other[0] + this[1] * other[1];
- },
-
- length(this: Vector2): number {
- return Math.sqrt(this[0] * this[0] + this[1] * this[1]);
- },
-
- normalize(this: Vector2): Vector2 {
- const len = this.length();
- if (len === 0) return vec2(0, 0);
- return this.divide(len);
- },
-
- distance(this: Vector2, other: Vector2): number {
- return Math.sqrt(
- Math.pow(other[0] - this[0], 2) + Math.pow(other[1] - this[1], 2)
- );
- },
-
- angle(this: Vector2): number {
- return Math.atan2(this[1], this[0]);
- },
-
- clone(this: Vector2): Vector2 {
- return vec2(this[0], this[1]);
- },
-
- equals(this: Vector2, other: Vector2): boolean {
- return this[0] === other[0] && this[1] === other[1];
- },
-
- toString(this: Vector2): string {
- return `vec2(${this[0]}, ${this[1]})`;
- },
-
- setTo(this: Vector2, x: number, y: number): void {
- this[0] = x;
- this[1] = y;
- },
-
- setFrom(this: Vector2, other: Vector2): void {
- this[0] = other[0];
- this[1] = other[1];
- },
-
- mag(this: Vector2): number {
- return Math.sqrt(this[0] * this[0] + this[1] * this[1]);
- },
-
- distanceSq(this: Vector2, other: Vector2): number {
- const dx = other[0] - this[0];
- const dy = other[1] - this[1];
- return dx * dx + dy * dy;
- },
-};
-
-// Shared handler for all Vector2 proxies
-const vectorHandler: ProxyHandler<Vector2> = {
- get(target, prop, receiver) {
- if (prop === 'x') return target[0];
- if (prop === 'y') return target[1];
- if (prop in vectorMethods)
- return vectorMethods[prop as keyof typeof vectorMethods].bind(receiver);
- return target[prop as any];
- },
-
- set(target, prop, value) {
- if (prop === 'x') target[0] = value;
- if (prop === 'y') target[1] = value;
- if (prop === '0') target[0] = value;
- if (prop === '1') target[1] = value;
- return true;
- },
-};
-
-/**
- * Creates a new Vector2 instance.
- * @param x The x-coordinate of the vector.
- * @param y The y-coordinate of the vector.
- * @returns A new Vector2 instance.
- */
-export function vec2(x: number, y: number): Vector2 {
- return new Proxy([x, y] as Vector2, vectorHandler);
-}
-
-// Vec2 namespace with some static helpers.
-export const Vec2 = {
- zero: vec2(0, 0),
- one: vec2(1, 1),
- up: vec2(0, 1),
- down: vec2(0, -1),
- left: vec2(-1, 0),
- right: vec2(1, 0),
-
- fromAngle(angle: number, length = 1): Vector2 {
- return vec2(Math.cos(angle) * length, Math.sin(angle) * length);
- },
-
- lerp(a: Vector2, b: Vector2, t: number): Vector2 {
- return vec2(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t);
- },
-
- calculateRatioVect(
- edge: CanvasEdge,
- initialBoundingRect: Rectangle
- ): { from: Vector2 | undefined; to: Vector2 | undefined } {
- const from =
- edge.from.type === 'free'
- ? vec2(
- (edge.from.x - initialBoundingRect.x) / initialBoundingRect.w,
- (edge.from.y - initialBoundingRect.y) / initialBoundingRect.h
- )
- : undefined;
- const to =
- edge.to.type === 'free'
- ? vec2(
- (edge.to.x - initialBoundingRect.x) / initialBoundingRect.w,
- (edge.to.y - initialBoundingRect.y) / initialBoundingRect.h
- )
- : undefined;
-
- return { from, to };
- },
-
- applyRatioVect(inner: Vector2Like, outer: Rectangle): Vector2 {
- return vec2(inner.x * outer.w + outer.x, inner.y * outer.h + outer.y);
- },
-
- // Offset a source vector towards a target vector by a given fixed-pixel offset.
- offsetTowards(source: Vector2, target: Vector2, offset: number): Vector2 {
- return source.add(target.subtract(source).normalize().multiply(offset));
- },
-};
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/asset-picker.tsx b/apps/web/src/features/block-canvas/views/asset-picker.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/asset-picker.tsx
rename to apps/web/src/features/block-canvas/views/asset-picker.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/canvas-context-menu.tsx b/apps/web/src/features/block-canvas/views/canvas-context-menu.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/canvas-context-menu.tsx
rename to apps/web/src/features/block-canvas/views/canvas-context-menu.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/canvas-read-only-view.tsx b/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/canvas-read-only-view.tsx
rename to apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/canvas-toolbars.tsx b/apps/web/src/features/block-canvas/views/canvas-toolbars.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/canvas-toolbars.tsx
rename to apps/web/src/features/block-canvas/views/canvas-toolbars.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/canvas-view.tsx b/apps/web/src/features/block-canvas/views/canvas-view.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/canvas-view.tsx
rename to apps/web/src/features/block-canvas/views/canvas-view.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/connector-targets.tsx b/apps/web/src/features/block-canvas/views/connector-targets.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/connector-targets.tsx
rename to apps/web/src/features/block-canvas/views/connector-targets.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/embedded-items.tsx b/apps/web/src/features/block-canvas/views/embedded-items.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/embedded-items.tsx
rename to apps/web/src/features/block-canvas/views/embedded-items.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/text-content.tsx b/apps/web/src/features/block-canvas/views/text-content.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/text-content.tsx
rename to apps/web/src/features/block-canvas/views/text-content.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/text-editing-view.tsx b/apps/web/src/features/block-canvas/views/text-editing-view.tsx
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/text-editing-view.tsx
rename to apps/web/src/features/block-canvas/views/text-editing-view.tsx
diff --git a/apps/web/src/features/block-canvas/canvas-next/views/text.css b/apps/web/src/features/block-canvas/views/text.css
similarity index 100%
rename from apps/web/src/features/block-canvas/canvas-next/views/text.css
rename to apps/web/src/features/block-canvas/views/text.css
diff --git a/apps/web/src/features/drive-view/views/CanvasDetail.tsx b/apps/web/src/features/drive-view/views/CanvasDetail.tsx
index 2d5425ca9f..ea2489c155 100644
--- a/apps/web/src/features/drive-view/views/CanvasDetail.tsx
+++ b/apps/web/src/features/drive-view/views/CanvasDetail.tsx
@@ -1,6 +1,5 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { CanvasDocument } from '@block-canvas/component/CanvasDocument';
-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import {
getPermissions,
hasPermissions,
@@ -58,7 +57,6 @@ export function CanvasDetailDocument(props: {
data: CanvasDocumentData;
children?: (context: CanvasDetailContext) => JSX.Element;
}) {
- const panel = useSplitPanelOrThrow();
const [searchParams] = useSearchParams();
const canEdit = () =>
hasPermissions(
@@ -76,8 +74,6 @@ export function CanvasDetailDocument(props: {
documentId={props.documentId}
file={props.data.file}
canEdit={canEdit()}
- hotkeyScope={panel.splitHotkeyScope}
- portalScope="split"
locationParams={searchParams}
>
{(content, state) => (
diff --git a/apps/web/src/lib/core/component/SlidableNumberInput.tsx b/apps/web/src/lib/core/component/SlidableNumberInput.tsx
deleted file mode 100644
index c325109310..0000000000
--- a/apps/web/src/lib/core/component/SlidableNumberInput.tsx
+++ /dev/null
@@ -1,283 +0,0 @@
-import { clamp } from '@block-canvas/util/math';
-import { type Vector2, vec2 } from '@block-canvas/util/vector2';
-import CaretDown from '@phosphor/caret-down.svg';
-import { cn, Dropdown, Tooltip } from '@ui';
-import {
- type Component,
- type ComponentProps,
- createEffect,
- createSignal,
- For,
- type JSX,
- onCleanup,
- onMount,
- Show,
-} from 'solid-js';
-import { Dynamic } from 'solid-js/web';
-
-export type DropdownPreset = {
- value: string;
- displayName?: JSX.Element;
- icon?: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
-};
-
-type SlidableNumberInput = ComponentProps<'div'> & {
- label?: string;
- labelPosition?: 'top' | 'left';
- icon: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
- inputChanged: (newValue: string) => void;
- onSlideStart?: () => void;
- onSlidePreview?: (newValue?: string) => void;
- onSlideEnd?: (newValue?: string) => void;
- onEditingChange?: (editing: boolean) => void;
- currentValue: string;
- presets: DropdownPreset[];
- showPresets?: boolean;
- isSlidable?: boolean; // If true, must have a numerical range
- width?: 'sm' | 'md' | 'lg' | number;
- range?: Vector2; // Numerical range
- hideValue?: boolean;
- fullIcon?: boolean;
- flip?: boolean;
- tooltip?: string;
-};
-
-const OptionalTooltipWrapper = (props: {
- children: JSX.Element;
- tooltip?: string;
-}) => {
- if (props.tooltip) {
- return <Tooltip label={props.tooltip}>{props.children}</Tooltip>;
- }
- return <>{props.children}</>;
-};
-
-export type SlidableNumberInputProps = SlidableNumberInput;
-
-export function SlidableNumberInput(props: SlidableNumberInputProps) {
- const [dropdownOpen, setDropdownOpen] = createSignal<boolean>(false);
- const [mouseDownPos, setMouseDownPos] = createSignal<Vector2>();
- const [currentValue, setCurrentValue] = createSignal<string>(
- props.currentValue
- );
- const [mouseDownValue, setMouseDownValue] = createSignal<string>();
-
- function pointerMove(e: PointerEvent) {
- if (!mouseDownPos()) return;
- const difference = mouseDownPos()?.subtract(vec2(e.clientX, e.clientY));
- const angle = difference?.angle();
- // Dragging left/down reduces value while dragging right/up increases value
- const direction =
- angle && (angle >= Math.PI / 4 || angle <= (-3 * Math.PI) / 4) ? -1 : 1;
-
- if (props.range) {
- let currentWithRange = Number.parseInt(currentValue());
- // If current value is mixed (i.e. multiselect), start from midpoint of valid range
- if (Number.isNaN(currentWithRange))
- currentWithRange = Math.round((props.range!.y - props.range!.x) / 2);
- setMouseDownValue(
- clamp(
- // 150 is an arbitrary value adjusted for sliding feel and control
- currentWithRange -
- Math.round(
- ((difference?.mag() ?? 0) * direction) /
- (100 / (props.range.y - props.range.x))
- ),
- props.range.x,
- props.range.y
- ).toString()
- );
- props.onSlidePreview?.(mouseDownValue());
- } else {
- let currentWithPreset = props.presets.findIndex(
- (preset) => preset.value === props.currentValue
- );
- if (currentWithPreset < -1)
- currentWithPreset = Number.parseInt(
- props.presets[Math.round(props.presets.length / 2)].value
- );
- setMouseDownValue(
- props.presets[
- clamp(
- currentWithPreset -
- Math.round(
- ((difference?.mag() ?? 0) * direction) /
- (150 / props.presets.length)
- ),
- 0,
- props.presets.length - 1
- )
- ].value
- );
- }
- }
-
- function pointerUp() {
- if (!mouseDownPos()) return;
- const mouseDownVal = mouseDownValue();
- if (mouseDownVal) {
- setCurrentValue(mouseDownVal);
- if (props.onSlideEnd) {
- props.onSlideEnd(mouseDownVal);
- } else {
- props.inputChanged(mouseDownVal);
- }
- setMouseDownValue();
- }
- setMouseDownPos();
- }
-
- onMount(() => {
- document.addEventListener('pointermove', pointerMove);
- document.addEventListener('pointerup', pointerUp);
- });
- onCleanup(() => {
- document.removeEventListener('pointermove', pointerMove);
- document.removeEventListener('pointerup', pointerUp);
- });
-
- // Keep current value updated to changing props
- createEffect(() => {
- setCurrentValue(props.currentValue);
- });
-
- return (
- <div
- class={cn(
- 'flex justify-items-center',
- props.labelPosition === 'top' ? 'flex-col' : 'flex-row items-center'
- )}
- >
- <Show when={props.label}>
- <div
- class={cn(
- 'text-[0.67rem] opacity-75 truncate mb-1',
- props.labelPosition === 'left' && 'w-28'
- )}
- >
- {props.label}&nbsp
- </div>
- </Show>
- <OptionalTooltipWrapper tooltip={props.tooltip}>
- <div
- class={cn(
- 'flex flex-row items-center bg-surface rounded px-1.5 h-8',
- props.labelPosition === 'top' &&
- (props.width === 'sm'
- ? 'w-22'
- : props.width === 'lg'
- ? 'w-48'
- : 'w-32')
- )}
- >
- <Dynamic
- component={props.icon}
- class={cn(
- 'fill-ink-muted ml-.5 mr-1 min-w-5',
- props.isSlidable && 'cursor-ew-resize'
- )}
- style={{
- 'overflow-clip-margin': 'content-box',
- transform: props.flip ? 'rotateY(180deg)' : '',
- }}
- width={18}
- height={18}
- onmousedown={(e: MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation();
- if (props.isSlidable) setMouseDownPos(vec2(e.clientX, e.clientY));
- if (props.isSlidable) props.onSlideStart?.();
- }}
- />
- <Show when={!props.fullIcon}>
- <div
- class={cn(
- 'text-ink text-nowrap overflow-hidden cursor-text',
- props.labelPosition === 'top'
- ? props.width === 'sm'
- ? 'w-18'
- : props.width === 'lg'
- ? 'w-44'
- : 'w-28'
- : 'max-w-18'
- )}
- contenteditable
- onFocus={() => {
- props.onEditingChange?.(true);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- e.currentTarget.blur();
- }
- }}
- onBlur={(e) => {
- const innerText = e.currentTarget.innerText;
- var regExp = /[a-zA-Z]/g;
- if (regExp.test(innerText)) {
- const matchingPreset = props.presets.find(
- (p) => p.displayName === innerText
- );
- if (matchingPreset) props.inputChanged(matchingPreset.value);
- } else props.inputChanged(e.currentTarget.innerText);
- props.onEditingChange?.(false);
- }}
- >
- {mouseDownValue() ?? currentValue()}
- </div>
- </Show>
- <Show when={props.showPresets}>
- <div class="flex h-full items-center ml-auto mr-.5">
- <Dropdown
- open={dropdownOpen()}
- onOpenChange={setDropdownOpen}
- placement={'bottom'}
- gutter={8}
- >
- <Dropdown.Trigger
- variant="ghost"
- class="dropdown-menu__trigger"
- >
- <div class="w-3 h-5 ml-1.5 flex items-center text-ink-muted">
- <CaretDown width={12} height={12} />
- </div>
- </Dropdown.Trigger>
- <Dropdown.Content>
- <Dropdown.Group>
- <For each={props.presets}>
- {(preset, _index) => (
- <Dropdown.Item
- onSelect={() => {
- props.inputChanged(preset.value);
- setDropdownOpen(false);
- }}
- >
- <Show when={preset.icon}>
- <Dynamic
- component={preset.icon!}
- class="size-4 shrink-0"
- classList={{
- 'rotate-y-180': props.flip,
- }}
- />
- </Show>
- <div class="flex flex-1 w-full gap-2 justify-between">
- <span class="truncate">{preset.displayName}</span>
- <span class="text-ink-extra-muted">
- {preset.value}
- </span>
- </div>
- </Dropdown.Item>
- )}
- </For>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- </div>
- </Show>
- </div>
- </OptionalTooltipWrapper>
- </div>
- );
-}
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 1aaacf155d..d6536396ea 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -91,13 +91,6 @@ export function defineFlag(config: RemoteFlagConfig | EnvFlagConfig): Flag {
};
}
-/** Opt-in versioned canvas documents. Unset overrides defer to PostHog. */
-export const enableCanvasNext = defineFlag({
- key: 'enable-canvas-next',
- env: 'ENABLE_CANVAS_NEXT',
- default: LOCAL_ONLY ? false : undefined,
-});
-
/** Opt into the carousel create menu; otherwise use the detailed launcher. */
export const enableCarouselCreateMenu = defineFlag({
key: 'enable-carousel-create-menu',
@@ -296,22 +289,6 @@ export const ENABLE_MARKDOWN_SEARCH_TEXT = defineFlag({
default: DEV_MODE_ENV,
}).enabled;
-export const CANVAS_SVG_IMPORT = defineFlag({
- env: 'CANVAS_SVG_IMPORT',
- default: true,
-}).enabled;
-
-export const ENABLE_CANVAS_VIDEO = defineFlag({
- env: 'ENABLE_CANVAS_VIDEO',
- default: true,
-}).enabled;
-
-// TODO: figure out why the image does not load into canvas after upload
-export const ENABLE_CANVAS_HEIC = defineFlag({
- env: 'ENABLE_CANVAS_HEIC',
- default: false,
-}).enabled;
-
// TODO - comments are not stable in markdown multiplayer, they will need more work.
export const ENABLE_MARKDOWN_COMMENTS = defineFlag({
env: 'ENABLE_MARKDOWN_COMMENTS',
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index ffbdec7051..34fb67dd5a 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -42,7 +42,15 @@ embeds and check that their preview bodies load; also check that a code or canva
mention offers **Convert to Embed** in its preview menu.
Drag an embed's bottom-right resize grip, then release and select the card. Its
height should stay at the dragged size and persist after reopening the document.
-Canvas Next embeds are read-only: **Select** selects shapes without moving them,
+All canvases open in Canvas Next, including drive details and Markdown embeds;
+there is no rollout flag or legacy editor. Unversioned/version 1 files migrate
+in memory. Opening a file alone does not save the migration; the first edit saves
+version 2 while retaining the original JSON for recovery. Unsupported legacy
+records and unknown versions show an error without changing the saved file.
+To verify migration, open a supported legacy canvas, edit it, then reopen it and
+check that its shapes, text, and connectors remain intact.
+
+Canvas embeds are read-only: **Select** selects shapes without moving them,
and **Hand** pans the canvas. The toolbar contains only those two tools; property
inspector details and drawing/editing controls are absent. Check toolbar clicks,
drag-to-pan, and the V/H shortcuts with focus inside the canvas. These interactions
diff --git a/docs/CANVAS_ARCHITECTURE.md b/docs/CANVAS_ARCHITECTURE.md
index 137d36d953..8b6b409988 100644
--- a/docs/CANVAS_ARCHITECTURE.md
+++ b/docs/CANVAS_ARCHITECTURE.md
@@ -40,5 +40,5 @@ integration and conflict-policy approval remain separate work.
See the [graphics package README](../packages/graphics/README.md),
[scene foundation](GRAPHICS_SCENE_FOUNDATION.md),
-[Canvas Next README](../apps/web/src/features/block-canvas/canvas-next/README.md),
+[Canvas Next README](../apps/web/src/features/block-canvas/README.md),
and [collaboration notes](../packages/graphics/src/loro/README.md).
diff --git a/docs/CANVAS_LEGACY_BRIDGE.md b/docs/CANVAS_LEGACY_BRIDGE.md
index c498006d7c..061d06c27c 100644
--- a/docs/CANVAS_LEGACY_BRIDGE.md
+++ b/docs/CANVAS_LEGACY_BRIDGE.md
@@ -1,7 +1,7 @@
# Canvas legacy bridge
-The legacy bridge converts between legacy Canvas records and the Canvas Next
-document model. It belongs to the Canvas application layer, not
+The legacy migration imports version 1 Canvas records into the Canvas Next
+version 2 document model. The old editor and downgrade path are not available. It belongs to the Canvas application layer, not
`@macro-inc/graphics`, because it understands old schemas, Lexical payloads,
Macro entities, and product rollout policy.
@@ -26,13 +26,15 @@ chrome and must be resolved before crossing the document boundary. Import should
preserve legacy color and alpha values exactly; export must report values the old
format cannot represent.
-## Rollout
+## Loading and saving
-Build the bridge behind the existing Canvas Next rollout boundary. Compare both
-renderers on representative fixtures, make diagnostics visible to the host, and
-only enable write-back for documents whose supported subset round-trips without
-silent loss.
+Canvas Next opens all saved canvases without a rollout flag. Supported legacy
+files migrate in memory and retain their original JSON in migration metadata.
+The first committed edit saves version 2; opening a file alone does not save it.
+Unsupported records and unknown versions show an error without changing the
+saved document. Validate any expanded import support against representative
+fixtures before allowing write-back.
See the [architecture overview](CANVAS_ARCHITECTURE.md),
[parity plan](GRAPHICS_PARITY.md), and
-[Canvas Next format notes](../apps/web/src/features/block-canvas/canvas-next/README.md).
+[Canvas Next format notes](../apps/web/src/features/block-canvas/README.md).
diff --git a/docs/GRAPHICS_PARITY.md b/docs/GRAPHICS_PARITY.md
index e5d5eea3a5..8ef087a645 100644
--- a/docs/GRAPHICS_PARITY.md
+++ b/docs/GRAPHICS_PARITY.md
@@ -1,7 +1,7 @@
# Graphics and Canvas parity
Canvas Next implements the shared graphics foundation and the main local editing
-flows. It opens supported saved documents behind the Canvas Next rollout, migrates
+flows. It is the editor for all saved canvases and embeds, migrates
older JSON at the host boundary, and writes the current versioned format.
## Current coverage
@@ -24,7 +24,7 @@ migration, sharing, and product rollout.
## Remaining priorities
-1. Finish and validate the bidirectional legacy bridge with explicit diagnostics.
+1. Expand legacy import coverage with explicit diagnostics for unsupported records.
2. Lock down durable artwork colors separately from theme-driven application UI.
3. Integrate production collaboration, offline recovery, and permission handling.
4. Add high-value whiteboard gaps such as snapping, touch, crop, frames, export,
@@ -39,4 +39,4 @@ identity.
See the [Canvas architecture](CANVAS_ARCHITECTURE.md),
[legacy bridge](CANVAS_LEGACY_BRIDGE.md),
[graphics README](../packages/graphics/README.md), and
-[Canvas Next README](../apps/web/src/features/block-canvas/canvas-next/README.md).
+[Canvas Next README](../apps/web/src/features/block-canvas/README.md).
diff --git a/packages/graphics/README.md b/packages/graphics/README.md
index 828dfaeddb..9874296255 100644
--- a/packages/graphics/README.md
+++ b/packages/graphics/README.md
@@ -7,8 +7,9 @@ For a short implementation-based reference, start with the
Status reviewed 2026-09-28. The [parity plan](../../docs/GRAPHICS_PARITY.md) is the
progress/next-checkpoint index. Canvas Next now includes rich text/mentions,
-shape labels, connectors, media, document cards and full embeds behind its rollout
-flag. The Loro adapter remains experimental; production persistence is not wired.
+shape labels, connectors, media, document cards and full embeds as the default
+canvas editor. Versioned JSON persistence is wired at the Canvas host boundary.
+The Loro adapter remains experimental; production collaboration is not wired.
The next product checkpoint is a
[legacy bridge and color policy](../../docs/CANVAS_LEGACY_BRIDGE.md), kept outside
the pure core. Expanding peer support is deferred.
@@ -319,7 +320,7 @@ Built-ins: `selectAllCommand`, `nudgeCommand`, `duplicateCommand`, `pasteCommand
selected subtrees in paint order, with root transforms expressed in world space.
`parseFragment` validates bounded clipboard input; `pasteFragment` remaps every ID
and reconstructs local transforms in the destination parent. Canvas supplies OS
-clipboard and shortcut policy. See the [Canvas Next notes](../../apps/web/src/features/block-canvas/canvas-next/README.md).
+clipboard and shortcut policy. See the [Canvas Next notes](../../apps/web/src/features/block-canvas/README.md).
Groups have no inherited appearance. Styling a group updates its leaves. Stroke
width (default 2), opacity (1), and rectangle radius (0) are optional typed fields;
@@ -370,7 +371,7 @@ measurer and Solid TextView treat content as literal plain text. A host using an
encoded format supplies a `contentView` to TextView/RectangleView/EllipseView and a
matching TextMeasurer. Graphics does not parse editor JSON or infer empty content.
-Canvas Next owns its Lexical codec in `canvas-next/core/text-codec.ts`, including
+Canvas Next owns its Lexical codec in `apps/web/src/features/block-canvas/core/text-codec.ts`, including
bounded tree validation, seed construction, serialization and empty-content
checks. Its clipboard adapter validates imported text/labels.
It uses the shared Markdown builder and StaticLexical renderer for editing,