Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: macro-graphics and canvas-next (#7609)
Seamusecf625521f65
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 8d21ab2b36..a6246871a9 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -71,6 +71,7 @@"@ironcalc/wasm": "workspace:*","@kobalte/core": "^0.13.11","@leeoniya/ufuzzy": "^1.0.19",+ "@lexical/extension": "0.45.0","@lexical/history": "0.45.0","@lexical/html": "0.45.0","@lexical/link": "0.45.0",@@ -88,6 +89,7 @@"@lukemorales/query-key-factory": "^1.3.4","@macro-inc/collaboration": "workspace:*","@macro-inc/email-renderer": "workspace:*",+ "@macro-inc/graphics": "workspace:*","@macro-inc/lexical-core": "workspace:*","@macro-inc/machine": "workspace:*","@macro-inc/observability": "workspace:*",diff --git a/apps/web/src/components/ui/components/ColorPicker.docs.tsx b/apps/web/src/components/ui/components/ColorPicker.docs.tsxnew file mode 100644index 0000000000..0d2832ebe1--- /dev/null+++ b/apps/web/src/components/ui/components/ColorPicker.docs.tsx@@ -0,0 +1,60 @@+import { defineDoc } from '@app/features/ui-gallery/types';+import { createSignal } from 'solid-js';+import { ColorPicker } from './ColorPicker';++// #region demo:basic+function BasicDemo() {+ const [value, setValue] = createSignal('#528bff');+ return (+ <ColorPicker.Root value={value()} onChange={setValue} class="w-56">+ <ColorPicker.Field />+ <ColorPicker.HueTrack />+ <ColorPicker.AlphaTrack />+ <div class="flex items-center gap-2">+ <ColorPicker.Preview />+ <ColorPicker.Input />+ </div>+ </ColorPicker.Root>+ );+}+// #endregion++// #region demo:disabled+function DisabledDemo() {+ return (+ <ColorPicker.Root defaultValue="#528bff80" disabled class="w-56">+ <ColorPicker.Field />+ <ColorPicker.HueTrack />+ <ColorPicker.AlphaTrack />+ <ColorPicker.Input />+ </ColorPicker.Root>+ );+}+// #endregion++export default defineDoc({+ name: 'ColorPicker',+ category: 'Inputs',+ description:+ 'A compound RGB/hex picker with a saturation and brightness field, hue and opacity tracks, and hex input. Uses plain HSV math and Kobalte sliders.',+ status: 'stable',+ exports: ['ColorPicker'],+ import: "import { ColorPicker } from '@ui';",+ propTypes: ['ColorPickerRootProps'],+ demos: [+ {+ id: 'basic',+ title: 'Controlled picker',+ render: BasicDemo,+ description:+ 'Compose the slots you need inside Root. `onChange` previews a hex color; `onChangeEnd` marks the end of a gesture. Input accepts short or long hex with optional alpha and commits on Enter or blur. Tab between saturation, brightness, hue, opacity, and text; arrows adjust channels and Shift makes larger steps. Unsupported values display black without changing the host value. Resolve CSS variables in the host before passing them to the picker.',+ },+ {+ id: 'disabled',+ title: 'Disabled',+ render: DisabledDemo,+ description:+ '`disabled` locks every slot. `readOnly` keeps text and field values available for inspection while preventing changes.',+ },+ ],+});diff --git a/apps/web/src/components/ui/components/ColorPicker.tsx b/apps/web/src/components/ui/components/ColorPicker.tsxnew file mode 100644index 0000000000..d596076125--- /dev/null+++ b/apps/web/src/components/ui/components/ColorPicker.tsx@@ -0,0 +1,529 @@+import * as Slider from '@kobalte/core/slider';+import {+ batch,+ type ComponentProps,+ createContext,+ createMemo,+ createSignal,+ type JSX,+ onCleanup,+ splitProps,+ useContext,+} from 'solid-js';+import { match } from 'ts-pattern';+import { cn } from '../utils/classname';+import {+ normalizePickerColor,+ type PickerColor,+ parsePickerColor,+ pickerColorToHex,+ preservePickerHue,+} from '../utils/color';++export type ColorPickerRootProps = Omit<ComponentProps<'div'>, 'onChange'> & {+ value?: string;+ defaultValue?: string;+ onChange?: (value: string) => void;+ /** Runs once when a drag or keyboard edit ends, or a text value is committed. */+ onChangeEnd?: (value: string) => void;+ disabled?: boolean;+ readOnly?: boolean;+};++type PickerContext = {+ color: () => PickerColor;+ value: () => string;+ disabled: () => boolean;+ readOnly: () => boolean;+ locked: () => boolean;+ set: (color: PickerColor) => void;+ finish: () => void;+};++const Context = createContext<PickerContext>();++function usePicker() {+ const context = useContext(Context);+ if (!context) throw new Error('ColorPicker slots require ColorPicker.Root');+ return context;+}++function Root(props: ColorPickerRootProps) {+ const [local, rest] = splitProps(props, [+ 'value',+ 'defaultValue',+ 'onChange',+ 'onChangeEnd',+ 'disabled',+ 'readOnly',+ 'children',+ 'class',+ ]);+ const fallback: PickerColor = { h: 0, s: 0, v: 0, a: 1 };+ const [internal, setInternal] = createSignal(local.defaultValue ?? '#000000');+ const [draft, setDraft] = createSignal(+ parsePickerColor(local.value ?? internal()) ?? fallback+ );+ const color = createMemo<PickerColor>((previous) => {+ const parsed = parsePickerColor(local.value ?? internal()) ?? fallback;+ const pending = draft();+ // Echoing hex loses hue in gray/black and rounds channels. Keep the exact+ // picker position until the host supplies a different color.+ if (pickerColorToHex(parsed) === pickerColorToHex(pending)) return pending;+ return preservePickerHue(parsed, previous ?? pending);+ });+ let changed = false;+ const context: PickerContext = {+ color,+ value: () => pickerColorToHex(color()),+ disabled: () => !!local.disabled,+ readOnly: () => !!local.readOnly,+ locked: () => !!local.disabled || !!local.readOnly,+ set(next) {+ if (context.locked()) return;+ const output = pickerColorToHex(next);+ const previous = context.value();+ batch(() => {+ setDraft(next);+ if (local.value === undefined) setInternal(output);+ if (output !== previous) {+ changed = true;+ local.onChange?.(output);+ }+ });+ },+ finish() {+ if (!changed) return;+ changed = false;+ local.onChangeEnd?.(context.value());+ },+ };+ return (+ <Context.Provider value={context}>+ <div+ role="group"+ aria-label="Color picker"+ data-color-picker+ data-disabled={local.disabled || undefined}+ data-readonly={local.readOnly || undefined}+ class={cn(+ 'flex flex-col gap-3 text-ink data-disabled:opacity-50',+ local.class+ )}+ {...rest}+ >+ {local.children}+ </div>+ </Context.Provider>+ );+}++type SlotProps = Omit<ComponentProps<'div'>, 'children' | 'style'> & {+ style?: JSX.CSSProperties;+};++export type ColorPickerFieldProps = SlotProps;++function Field(props: ColorPickerFieldProps) {+ const context = usePicker();+ const [local, rest] = splitProps(props, ['class', 'style', 'aria-label']);+ let saturationInput!: HTMLInputElement;+ let pointer:+ | { id: number; start: PickerColor; target: HTMLDivElement }+ | undefined;+ const updatePointer = (event: PointerEvent, target: HTMLDivElement) => {+ const bounds = target.getBoundingClientRect();+ if (bounds.width <= 0 || bounds.height <= 0) return;+ const clamp = (number: number) => Math.max(0, Math.min(1, number));+ context.set({+ ...context.color(),+ s: clamp((event.clientX - bounds.left) / bounds.width),+ v: 1 - clamp((event.clientY - bounds.top) / bounds.height),+ });+ };+ const endPointer = (cancel = false) => {+ if (!pointer) return;+ const active = pointer;+ pointer = undefined;+ if (cancel) context.set(active.start);+ if (active.target.hasPointerCapture?.(active.id))+ active.target.releasePointerCapture(active.id);+ context.finish();+ };+ onCleanup(() => endPointer());+ const keyDown = (event: KeyboardEvent, channel: 's' | 'v') => {+ if (event.key === 'Escape' && pointer) {+ event.preventDefault();+ event.stopPropagation();+ endPointer(true);+ return;+ }+ const step = event.shiftKey ? 0.1 : 0.01;+ const current = context.color()[channel];+ const next = match(event.key)+ .with('ArrowRight', 'ArrowUp', () => current + step)+ .with('ArrowLeft', 'ArrowDown', () => current - step)+ .with('PageUp', () => current + 0.1)+ .with('PageDown', () => current - 0.1)+ .with('Home', () => 0)+ .with('End', () => 1)+ .otherwise(() => undefined);+ if (next === undefined) return;+ event.preventDefault();+ event.stopPropagation();+ if (context.locked()) return;+ context.set({+ ...context.color(),+ [channel]: Math.max(0, Math.min(1, next)),+ });+ };+ return (+ <div+ {...rest}+ role="group"+ aria-label={local['aria-label'] ?? 'Saturation and brightness'}+ data-color-picker-field+ data-slot="color-picker-field"+ class={cn(+ 'group/color-picker-field relative h-40 w-full touch-none rounded-md border border-edge-muted',+ local.class+ )}+ style={{+ background: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent), hsl(${context.color().h} 100% 50%)`,+ ...local.style,+ }}+ onPointerDown={(event) => {+ if (context.locked() || event.button !== 0 || pointer) return;+ event.preventDefault();+ saturationInput.focus({ preventScroll: true });+ pointer = {+ id: event.pointerId,+ start: context.color(),+ target: event.currentTarget,+ };+ event.currentTarget.setPointerCapture(event.pointerId);+ updatePointer(event, event.currentTarget);+ }}+ onPointerMove={(event) => {+ if (pointer?.id === event.pointerId)+ updatePointer(event, event.currentTarget);+ }}+ onPointerUp={(event) => {+ if (pointer?.id !== event.pointerId) return;+ updatePointer(event, event.currentTarget);+ endPointer();+ }}+ onPointerCancel={() => endPointer(true)}+ onLostPointerCapture={() => endPointer()}+ >+ <span+ aria-hidden="true"+ class="pointer-events-none absolute size-3.5 rounded-full border-2 shadow-sm group-has-[:focus-visible]/color-picker-field:outline-2 group-has-[:focus-visible]/color-picker-field:outline-offset-2 group-has-[:focus-visible]/color-picker-field:outline-accent"+ style={{+ left: `${context.color().s * 100}%`,+ top: `${(1 - context.color().v) * 100}%`,+ transform: 'translate(-50%, -50%)',+ 'border-color': '#fff',+ background: pickerColorToHex({ ...context.color(), a: 1 }),+ 'box-shadow': '0 0 0 1px #0008',+ }}+ />+ <input+ ref={saturationInput}+ type="range"+ class="sr-only"+ aria-label="Saturation"+ aria-valuetext={`${Math.round(context.color().s * 100)}% saturation`}+ min="0"+ max="100"+ step="1"+ value={context.color().s * 100}+ disabled={context.disabled()}+ aria-readonly={context.readOnly() || undefined}+ onInput={(event) =>+ context.set({+ ...context.color(),+ s: Number(event.currentTarget.value) / 100,+ })+ }+ onKeyDown={(event) => keyDown(event, 's')}+ onKeyUp={() => context.finish()}+ onChange={() => context.finish()}+ onBlur={() => context.finish()}+ />+ <input+ type="range"+ class="sr-only"+ aria-label="Brightness"+ aria-valuetext={`${Math.round(context.color().v * 100)}% brightness`}+ min="0"+ max="100"+ step="1"+ value={context.color().v * 100}+ disabled={context.disabled()}+ aria-readonly={context.readOnly() || undefined}+ onInput={(event) =>+ context.set({+ ...context.color(),+ v: Number(event.currentTarget.value) / 100,+ })+ }+ onKeyDown={(event) => keyDown(event, 'v')}+ onKeyUp={() => context.finish()}+ onChange={() => context.finish()}+ onBlur={() => context.finish()}+ />+ </div>+ );+}++const checkerStyle: JSX.CSSProperties = {+ 'background-image':+ 'repeating-conic-gradient(var(--color-surface-2) 0 25%, var(--color-surface-4) 0 50%)',+ 'background-size': '8px 8px',+};++export type ColorPickerTrackProps = SlotProps;++function TrackParts(props: { channel: 'h' | 'a'; label: string }) {+ const context = usePicker();+ const slider = Slider.useSliderContext();+ let start:+ | { color: PickerColor; target: HTMLElement; id: number }+ | undefined;+ const cancel = () => {+ if (!start) return;+ const original = start;+ start = undefined;+ context.set(original.color);+ if (original.target.hasPointerCapture?.(original.id))+ original.target.releasePointerCapture(original.id);+ slider.onSlideEnd?.();+ context.finish();+ };+ return (+ <div+ class="contents"+ on:pointerdown={{+ capture: true,+ handleEvent: (event) => {+ if (context.locked() || event.button !== 0 || start) {+ event.preventDefault();+ event.stopPropagation();+ return;+ }+ start = {+ color: context.color(),+ target: event.target as HTMLElement,+ id: event.pointerId,+ };+ },+ }}+ onPointerUp={() => {+ start = undefined;+ }}+ onPointerCancel={cancel}+ onLostPointerCapture={() => {+ start = undefined;+ slider.onSlideEnd?.();+ }}+ on:keydown={{+ capture: true,+ handleEvent: (event) => {+ if (event.key === 'Escape' && start) {+ event.preventDefault();+ event.stopPropagation();+ cancel();+ }+ },+ }}+ >+ <Slider.Track+ class="relative h-3 w-full rounded-full border border-edge-muted"+ style={props.channel === 'a' ? checkerStyle : undefined}+ >+ <div+ class="pointer-events-none absolute inset-0 rounded-full"+ style={{+ background:+ props.channel === 'h'+ ? 'linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)'+ : `linear-gradient(to right, ${pickerColorToHex({ ...context.color(), a: 0 })}, ${pickerColorToHex({ ...context.color(), a: 1 })})`,+ }}+ />+ <Slider.Thumb+ aria-label={props.label}+ class="top-1/2 -mt-2 size-4 rounded-full border-2 shadow-sm outline-none focus-visible:ring-2 focus-visible:ring-accent"+ style={{+ 'border-color': '#fff',+ background:+ props.channel === 'h'+ ? `hsl(${context.color().h} 100% 50%)`+ : context.value(),+ 'box-shadow': '0 0 0 1px #0008',+ }}+ onKeyUp={() => context.finish()}+ >+ <Slider.Input aria-label={props.label} />+ </Slider.Thumb>+ </Slider.Track>+ </div>+ );+}++function Track(props: ColorPickerTrackProps & { channel: 'h' | 'a' }) {+ const context = usePicker();+ const [local, rest] = splitProps(props, ['channel', 'class', 'aria-label']);+ const label = () =>+ local['aria-label'] ?? (local.channel === 'h' ? 'Hue' : 'Opacity');+ return (+ <Slider.Root+ {...rest}+ data-slot={+ local.channel === 'h'+ ? 'color-picker-hue-track'+ : 'color-picker-alpha-track'+ }+ class={cn(+ 'relative flex h-5 w-full touch-none items-center',+ local.class+ )}+ value={[context.color()[local.channel]]}+ minValue={0}+ maxValue={local.channel === 'h' ? 360 : 1}+ step={local.channel === 'h' ? 1 : 0.01}+ disabled={context.locked()}+ getValueLabel={({ values }) =>+ local.channel === 'h'+ ? `${Math.round(values[0])}°`+ : `${Math.round(values[0] * 100)}%`+ }+ onChange={(values) =>+ context.set({ ...context.color(), [local.channel]: values[0] })+ }+ onChangeEnd={() => context.finish()}+ >+ <TrackParts channel={local.channel} label={label()} />+ </Slider.Root>+ );+}++function HueTrack(props: ColorPickerTrackProps) {+ return <Track {...props} channel="h" />;+}++function AlphaTrack(props: ColorPickerTrackProps) {+ return <Track {...props} channel="a" />;+}++export type ColorPickerInputProps = Omit<+ ComponentProps<'input'>,+ 'value' | 'defaultValue' | 'onChange' | 'onInput'+>;++function Input(props: ColorPickerInputProps) {+ const context = usePicker();+ const [local, rest] = splitProps(props, [+ 'class',+ 'onKeyDown',+ 'onBlur',+ 'disabled',+ 'readOnly',+ ]);+ const [draft, setDraft] = createSignal<string>();+ const commit = (input: HTMLInputElement) => {+ if (+ draft() === undefined ||+ context.locked() ||+ local.disabled ||+ local.readOnly+ )+ return;+ const value = draft()!.trim();+ const color = parsePickerColor(value.startsWith('#') ? value : `#${value}`);+ if (!color) return;+ context.set(preservePickerHue(color, context.color()));+ context.finish();+ setDraft(undefined);+ input.value = context.value();+ };+ return (+ <input+ type="text"+ aria-label="Hex color"+ spellcheck={false}+ autocomplete="off"+ {...rest}+ disabled={context.disabled() || local.disabled}+ readOnly={context.readOnly() || local.readOnly}+ class={cn(+ 'h-8 w-full min-w-0 rounded-md border border-edge-muted bg-input px-2 font-mono text-sm text-ink outline-none focus-visible:ring-2 focus-visible:ring-edge-muted aria-invalid:border-failure aria-invalid:ring-2 aria-invalid:ring-failure/20 disabled:opacity-50',+ local.class+ )}+ value={draft() ?? context.value()}+ aria-invalid={+ (draft() !== undefined &&+ normalizePickerColor(+ draft()!.startsWith('#') ? draft()! : `#${draft()}`+ ) === undefined) ||+ undefined+ }+ onInput={(event) => {+ if (!context.locked() && !local.disabled && !local.readOnly)+ setDraft(event.currentTarget.value);+ }}+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ event.preventDefault();+ event.stopPropagation();+ commit(event.currentTarget);+ } else if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ setDraft(undefined);+ event.currentTarget.value = context.value();+ }+ if (typeof local.onKeyDown === 'function') local.onKeyDown(event);+ }}+ onBlur={(event) => {+ commit(event.currentTarget);+ if (typeof local.onBlur === 'function') local.onBlur(event);+ }}+ />+ );+}++export type ColorPickerPreviewProps = SlotProps;++function Preview(props: ColorPickerPreviewProps) {+ const context = usePicker();+ const [local, rest] = splitProps(props, ['class', 'style']);+ return (+ <div+ role="img"+ aria-label={`Current color ${context.value()}`}+ {...rest}+ class={cn(+ 'relative size-8 shrink-0 overflow-hidden rounded-md border border-edge-muted',+ local.class+ )}+ style={{ ...checkerStyle, ...local.style }}+ >+ <div class="absolute inset-0" style={{ background: context.value() }} />+ </div>+ );+}++/**+ * @do Compose the slots you need inside `ColorPicker.Root`; the root owns their+ * shared color, disabled, and read-only state.+ * @dont Render ColorPicker slots outside `ColorPicker.Root`.+ */+export const ColorPicker = {+ Root,+ Field,+ HueTrack,+ AlphaTrack,+ Input,+ Preview,+};diff --git a/apps/web/src/components/ui/components/Dropdown.tsx b/apps/web/src/components/ui/components/Dropdown.tsxindex e6e7d41092..344f00e0e4 100644--- a/apps/web/src/components/ui/components/Dropdown.tsx+++ b/apps/web/src/components/ui/components/Dropdown.tsx@@ -5,6 +5,7 @@ import CheckIcon from '@phosphor/check.svg';import {type ComponentProps,createSignal,+ type JSX,onCleanup,Show,splitProps,@@ -68,7 +69,9 @@ export type DropdownItemIndicatorProps = ComponentProps<>;export type DropdownCheckboxItemProps = ComponentProps<typeof KobalteDropdownMenu.CheckboxItem->;+> & {+ indicator?: JSX.Element;+};export type DropdownSubTriggerProps = ComponentProps<typeof KobalteDropdownMenu.SubTrigger>;@@ -319,17 +322,19 @@ const CHECKBOX_ITEM_BOX_CLASS = cn();function DropdownCheckboxItem(props: DropdownCheckboxItemProps) {- const [local, rest] = splitProps(props, ['class', 'children']);+ const [local, rest] = splitProps(props, ['class', 'children', 'indicator']);return (<KobalteDropdownMenu.CheckboxItemclass={cn(ROW_CLASS, local.class)}{...rest}>- <div class={CHECKBOX_ITEM_BOX_CLASS}>- <KobalteDropdownMenu.ItemIndicator>- <CheckIcon class="size-2.5" />- </KobalteDropdownMenu.ItemIndicator>- </div>+ {local.indicator ?? (+ <div class={CHECKBOX_ITEM_BOX_CLASS}>+ <KobalteDropdownMenu.ItemIndicator>+ <CheckIcon class="size-2.5" />+ </KobalteDropdownMenu.ItemIndicator>+ </div>+ )}{local.children}</KobalteDropdownMenu.CheckboxItem>);diff --git a/apps/web/src/components/ui/components/Hotkey.tsx b/apps/web/src/components/ui/components/Hotkey.tsxindex aa4b8c222c..6caeabf08e 100644--- a/apps/web/src/components/ui/components/Hotkey.tsx+++ b/apps/web/src/components/ui/components/Hotkey.tsx@@ -23,6 +23,7 @@ const symbolMap = {ARROWUP: '↑',DELETE: '⌦',ENTER: '↵',+ PLUS: '+',};const hotkeyStyles: Record<Theme, { label: string; hotkey: string }> = {diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.tsindex 1f8c6f8d3e..2d7acddcf3 100644--- a/apps/web/src/components/ui/index.ts+++ b/apps/web/src/components/ui/index.ts@@ -48,6 +48,14 @@ export {} from './components/Checkbox';export type { CollapsedInputProps } from './components/CollapsedInput';export { CollapsedInput } from './components/CollapsedInput';+export type {+ ColorPickerFieldProps,+ ColorPickerInputProps,+ ColorPickerPreviewProps,+ ColorPickerRootProps,+ ColorPickerTrackProps,+} from './components/ColorPicker';+export { ColorPicker } from './components/ColorPicker';export {type CommandListController,CommandMenuEmptyState,diff --git a/apps/web/src/components/ui/utils/color.test.ts b/apps/web/src/components/ui/utils/color.test.tsnew file mode 100644index 0000000000..5904eadbdb--- /dev/null+++ b/apps/web/src/components/ui/utils/color.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';+import {+ normalizePickerColor,+ parsePickerColor,+ pickerColorToHex,+ preservePickerHue,+} from './color';++describe('picker colors', () => {+ it.each([+ ['#f00', '#ff0000'],+ ['#F008', '#ff000088'],+ ['#FfAACC', '#ffaacc'],+ ['#ffaacc00', '#ffaacc00'],+ ['rgb(255, 128, 0)', '#ff8000'],+ ['rgba(255, 0, 0, .5)', '#ff000080'],+ ['rgb(100% 0% 50% / 25%)', '#ff008040'],+ ['transparent', '#00000000'],+ ['none', '#00000000'],+ ['rgb(300, -10, 20)', '#ff0014'],+ ])('normalizes %s', (input, expected) => {+ expect(normalizePickerColor(input)).toBe(expected);+ });++ it.each([+ '',+ '#12',+ '#abcde',+ '#1122334455',+ 'rgb(1, 2)',+ 'rgb(, 2, 3)',+ 'rgba(1, 2, 3, nope)',+ 'rgb(NaN 0 0)',+ 'oklch(0.5 0.1 30)',+ 'var(--color-ink)',+ 'red',+ ])('rejects unsupported %s without throwing', (value) => {+ expect(normalizePickerColor(value)).toBeUndefined();+ });++ it('round trips RGB and alpha exactly through HSV', () => {+ for (let r = 0; r < 256; r += 17) {+ for (let g = 0; g < 256; g += 17) {+ for (let b = 0; b < 256; b += 17) {+ const hex = `#${[r, g, b, 128].map((value) => value.toString(16).padStart(2, '0')).join('')}`;+ expect(pickerColorToHex(parsePickerColor(hex)!)).toBe(hex);+ }+ }+ }+ });++ it('preserves hue for gray and hue plus saturation for black', () => {+ const blue = parsePickerColor('#0000ff')!;+ expect(preservePickerHue(parsePickerColor('#888')!, blue)).toMatchObject({+ h: 240,+ s: 0,+ });+ expect(preservePickerHue(parsePickerColor('#000')!, blue)).toMatchObject({+ h: 240,+ s: 1,+ v: 0,+ });+ });+});diff --git a/apps/web/src/components/ui/utils/color.ts b/apps/web/src/components/ui/utils/color.tsnew file mode 100644index 0000000000..b9066d5ef5--- /dev/null+++ b/apps/web/src/components/ui/utils/color.ts@@ -0,0 +1,107 @@+export type PickerColor = {+ /** Hue in degrees; saturation, value, and alpha are in [0, 1]. */+ h: number;+ s: number;+ v: number;+ a: number;+};++const clamp = (value: number, max = 1) => Math.min(max, Math.max(0, value));++function fromRgb(r: number, g: number, b: number, a: number): PickerColor {+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const delta = max - min;+ let hue = 0;+ if (delta !== 0) {+ if (max === r) hue = (g - b) / delta;+ else if (max === g) hue = (b - r) / delta + 2;+ else hue = (r - g) / delta + 4;+ }+ return {+ h: (hue * 60 + 360) % 360,+ s: max === 0 ? 0 : delta / max,+ v: max / 255,+ a,+ };+}++function channel(value: string, max: number): number | undefined {+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)%?$/.test(value)) return;+ const number = Number.parseFloat(value);+ if (!Number.isFinite(number)) return;+ return clamp(value.endsWith('%') ? (number * max) / 100 : number, max);+}++/** Only hex and RGB are accepted. CSS variables and other spaces are host concerns. */+export function parsePickerColor(value: string): PickerColor | undefined {+ const input = value.trim().toLowerCase();+ if (input === 'transparent' || input === 'none') return fromRgb(0, 0, 0, 0);+ if (/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/.test(input)) {+ const hex =+ input.length <= 5+ ? [...input.slice(1)].map((digit) => digit + digit).join('')+ : input.slice(1);+ return fromRgb(+ Number.parseInt(hex.slice(0, 2), 16),+ Number.parseInt(hex.slice(2, 4), 16),+ Number.parseInt(hex.slice(4, 6), 16),+ hex.length === 8 ? Number.parseInt(hex.slice(6, 8), 16) / 255 : 1+ );+ }+ const rgb = /^rgba?\((.*)\)$/.exec(input);+ if (!rgb) return;+ const body = rgb[1].trim();+ const parts = body.includes(',')+ ? body.split(',').map((part) => part.trim())+ : body.split(/\s*\/\s*|\s+/);+ if (parts.length !== 3 && parts.length !== 4) return;+ const r = channel(parts[0], 255);+ const g = channel(parts[1], 255);+ const b = channel(parts[2], 255);+ const a = parts[3] === undefined ? 1 : channel(parts[3], 1);+ if (r === undefined || g === undefined || b === undefined || a === undefined)+ return;+ return fromRgb(r, g, b, a);+}++export function pickerColorToHex(color: PickerColor): string {+ const hue = (((color.h % 360) + 360) % 360) / 60;+ const chroma = clamp(color.v) * clamp(color.s);+ const x = chroma * (1 - Math.abs((hue % 2) - 1));+ const m = clamp(color.v) - chroma;+ const rgb =+ hue < 1+ ? [chroma, x, 0]+ : hue < 2+ ? [x, chroma, 0]+ : hue < 3+ ? [0, chroma, x]+ : hue < 4+ ? [0, x, chroma]+ : hue < 5+ ? [x, 0, chroma]+ : [chroma, 0, x];+ const byte = (value: number) =>+ Math.round(clamp(value) * 255 + Number.EPSILON * 255)+ .toString(16)+ .padStart(2, '0');+ const hex = rgb.map((value) => byte(value + m)).join('');+ const alpha = byte(color.a);+ return `#${hex}${alpha === 'ff' ? '' : alpha}`;+}++export function normalizePickerColor(value: string): string | undefined {+ const color = parsePickerColor(value);+ return color && pickerColorToHex(color);+}++/** RGB cannot encode hue for gray, or hue/saturation for black. Keep the user's choice. */+export function preservePickerHue(+ next: PickerColor,+ previous: PickerColor+): PickerColor {+ if (next.v === 0) return { ...next, h: previous.h, s: previous.s };+ if (next.s === 0) return { ...next, h: previous.h };+ return next;+}diff --git a/apps/web/src/features/block-canvas/README.md b/apps/web/src/features/block-canvas/README.mdindex 62be088c68..70b669a84e 100644--- a/apps/web/src/features/block-canvas/README.md+++ b/apps/web/src/features/block-canvas/README.md@@ -1,3 +1,19 @@# block-canvas+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.++This block is a canvas where you can create, export, and import diagrams.++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.++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.diff --git a/apps/web/src/features/block-canvas/canvas-next/README.md b/apps/web/src/features/block-canvas/canvas-next/README.mdnew file mode 100644index 0000000000..017952d933--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/README.md@@ -0,0 +1,369 @@+# 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+navigation-only surface without editing, paste/drop, or embedded editing handlers.+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/block-embed-adapter.tsx b/apps/web/src/features/block-canvas/canvas-next/block-embed-adapter.tsxnew file mode 100644index 0000000000..6d481af8fb--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/block-embed-adapter.tsx@@ -0,0 +1,186 @@+import {+ createPriorityCollapseController,+ PriorityCollapseOverflowSensor,+} from '@components/app/split-layout/components/PriorityCollapseOverflowSensor';+import {+ type SplitFileMenuActionGroups,+ SplitPanelContext,+ type SplitPanelContextType,+} from '@components/app/split-layout/context';+import type {+ SplitHandle,+ SplitId,+} from '@components/app/split-layout/layoutManager';+import { createOwnedSlots } from '@components/app/split-layout/utils/createOwnedSlots';+import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';+import { createBlockInstance } from '@core/orchestrator';+import {+ createEffect,+ createSignal,+ createUniqueId,+ on,+ Suspense,+ useContext,+} from 'solid-js';+import { Dynamic } from 'solid-js/web';+import type { CanvasEmbedViewProps } from './components/embed-view';+import { CanvasAncestry } from './context/canvas-ancestry';++/** The existing app's block loader/sync boundary; graphics only stores a reference. */+export function CanvasBlockEmbed(props: CanvasEmbedViewProps) {+ const ancestors = useContext(CanvasAncestry);+ if (ancestors.includes(props.geometry.documentId) || ancestors.length >= 8)+ return (+ <div class="p-4 text-sm text-ink-muted">+ Open this canvas separately to view it.+ </div>+ );+ return <CanvasBlockEmbedContent {...props} />;+}++function CanvasBlockEmbedContent(props: CanvasEmbedViewProps) {+ const kind = props.geometry.fileType === 'canvas' ? 'canvas' : 'md';+ const documentId = props.geometry.documentId;+ // Unmanaged block-in-block instances deliberately support repeated references.+ // Legacy `nested` means a read-only thumbnail. Mount the full editor here;+ // our isolated panel and the host's inert boundary own embed interaction.+ const instance = createBlockInstance(kind, documentId);+ const [attachHotkeys, scopeId] = useHotkeyDOMScope('canvas-embed');+ const [panelRef, setPanelRef] = createSignal<HTMLElement | null>(null);+ const [displayName, setDisplayName] = createSignal(props.geometry.name);+ const [contentOffsetTop, setContentOffsetTop] = createSignal(0);+ const [titleFileMenuRef, setTitleFileMenuRef] =+ createSignal<HTMLDivElement>();+ const [titleFileMenuTrigger, setTitleFileMenuTrigger] =+ createSignal<() => void>();+ const [titleFileMenuActions, setTitleFileMenuActions] =+ createSignal<SplitFileMenuActionGroups>();+ const slots = createOwnedSlots();+ const header = createPriorityCollapseController();+ const toolbar = createPriorityCollapseController();+ const layoutRefs: SplitPanelContextType['layoutRefs'] = {};+ // A local panel handle prevents an embedded block from changing the outer+ // canvas title, navigation history, toolbar, or hotkey registrations.+ const handle: SplitHandle = {+ id: `canvas-embed-${createUniqueId()}` as SplitId,+ content: () => ({ type: kind, id: documentId }),+ close: props.onExit,+ canGoBack: () => false,+ canGoForward: () => false,+ goBack: () => {},+ goBackTo: () => false,+ goForward: () => {},+ reset: () => {},+ activate: () => {},+ isActive: () => props.active,+ isFirst: () => true,+ isLast: () => true,+ displayName,+ setDisplayName,+ toggleSpotlight: () => {},+ isSpotLight: () => false,+ isPopover: () => true,+ replace: () => {},+ adoptContentId: () => {},+ removeFromHistory: () => {},+ registerContentChangeListener: () => {},+ unregisterContentChangeListener: () => {},+ previousContent: () => null,+ history: () => [],+ meta: () => undefined,+ updateMeta: undefined,+ referredFrom: () => null,+ lastNavigationCause: () => 'fresh',+ registerEntryStateCaptor: () => () => {},+ captureEntryState: () => {},+ currentEntryState: () => undefined,+ updateCurrentEntry: () => {},+ };+ const panel: SplitPanelContextType = {+ handle,+ splitHotkeyScope: scopeId,+ isInlinePreview: true,+ isPanelActive: () => props.active,+ panelRef,+ panelSize: { width: null, height: null },+ contentOffsetTop,+ setContentOffsetTop,+ bottomPanel: () => undefined,+ registerBottomPanel: () => () => {},+ layoutRefs,+ titleFileMenuRef,+ setTitleFileMenuRef,+ titleFileMenuTrigger,+ setTitleFileMenuTrigger,+ titleFileMenuActions,+ setTitleFileMenuActions,+ replaceOwnedSlot: slots.replace,+ headerCollapser: header.collapser,+ toolbarCollapser: toolbar.collapser,+ };+ createEffect(+ on(+ () => props.active,+ (active) => {+ if (active) panelRef()?.focus({ preventScroll: true });+ }+ )+ );+ return (+ <div+ tabIndex={-1}+ class="flex size-full min-h-0 flex-col"+ ref={(element) => {+ setPanelRef(element);+ attachHotkeys(element);+ }}+ >+ <div+ ref={header.setRow}+ class="flex h-10 shrink-0 items-center border-b border-edge-muted px-2"+ >+ <PriorityCollapseOverflowSensor+ controller={header}+ truncateAsLastResort+ class="min-w-0 flex-1"+ contentClass="flex items-center gap-1"+ contentRef={(element) => {+ layoutRefs.headerLeft = element;+ }}+ />+ <div+ ref={(element) => {+ layoutRefs.headerRight = element;+ }}+ class="flex items-center"+ />+ </div>+ <div ref={toolbar.setRow} class="flex shrink-0 items-center px-2">+ <PriorityCollapseOverflowSensor+ controller={toolbar}+ class="min-w-0 flex-1"+ contentClass="flex items-center gap-1"+ contentRef={(element) => {+ layoutRefs.toolbarLeft = element;+ }}+ />+ <div+ ref={(element) => {+ layoutRefs.toolbarRight = element;+ }}+ />+ </div>+ <div class="relative min-h-0 flex-1 overflow-hidden">+ <SplitPanelContext.Provider value={panel}>+ <Suspense+ fallback={+ <div class="p-4 text-base text-ink-muted">Loading editor…</div>+ }+ >+ <Dynamic component={instance.element} />+ </Suspense>+ </SplitPanelContext.Provider>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/canvas-next-document.tsx b/apps/web/src/features/block-canvas/canvas-next/canvas-next-document.tsxnew file mode 100644index 0000000000..e17125069c--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/canvas-next-document.tsx@@ -0,0 +1,143 @@+import type { GraphicsEditor } from '@macro-inc/graphics';+import {+ createEffect,+ createResource,+ createSignal,+ onCleanup,+ 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 { CanvasAncestry } from './context/canvas-ancestry';+import type { CanvasFile } from './core/document-format';+import { createDocumentPersistence } from './primitives/create-document-persistence';+import { canvasDocumentSource } from './queries/document';++const parseLocation = createNumericParser<{+ x?: number;+ y?: number;+ scale?: number;+}>({+ x: ['x', 'canvas_x'],+ y: ['y', 'canvas_y'],+ scale: ['s', 'scale', 'canvas_scale'],+});++export default function CanvasNextDocument(+ props: CanvasDocumentProps & { initial: CanvasFile }+) {+ const ancestors = useContext(CanvasAncestry);+ const documentId = props.documentId;+ const initial = props.initial;+ const [persistence, setPersistence] =+ createSignal<ReturnType<typeof createDocumentPersistence>>();+ const [editor, setEditor] = createSignal<GraphicsEditor>();+ const [savedLocation] = createResource(async () =>+ props.isNested || props.view ? null : fetchCanvasViewLocation(documentId)+ );+ const location = () =>+ props.view ?? parseLocation(props.locationParams ?? {}) ?? savedLocation();+ const applyLocation = (+ view: { x?: number; y?: number; scale?: number } | null | undefined+ ) => {+ const current = editor();+ if (!current || !view) return;+ const camera = current.getCamera();+ const scale =+ view.scale != null && Number.isFinite(view.scale) && view.scale > 0+ ? view.scale / 100+ : camera.scale;+ current.zoomAt({ x: 0, y: 0 }, scale);+ const next = current.getCamera();+ current.panBy({+ x: Number.isFinite(view.x) ? view.x! - next.x : 0,+ y: Number.isFinite(view.y) ? view.y! - next.y : 0,+ });+ };+ createEffect(() => applyLocation(location()));+ const currentLocation = () => {+ const camera = editor()?.getCamera() ?? { x: 0, y: 0, scale: 1 };+ return {+ x: Math.round(camera.x),+ y: Math.round(camera.y),+ s: Math.round(camera.scale * 100),+ };+ };+ const content = (+ <div class="relative flex size-full min-h-0 flex-col">+ <Show when={!savedLocation.loading}>+ <CanvasAncestry.Provider value={[...ancestors, documentId]}>+ <CanvasNextEditor+ initial={initial}+ canEdit={props.canEdit}+ fitOnLoad={!location()}+ onReady={(current, finishText) => {+ setEditor(current);+ const saving = createDocumentPersistence(+ current,+ initial,+ canvasDocumentSource(documentId, () => props.canEdit)+ );+ setPersistence(saving);+ props.registerMethods?.({+ exportCanvas: async () => {+ if (props.canEdit) finishText();+ return { ...initial, document: current.document };+ },+ goToLocationFromParams: (params) =>+ applyLocation(parseLocation(params)),+ });+ let viewTimer: ReturnType<typeof setTimeout> | undefined;+ const unsubscribe = current.subscribeCamera((camera) => {+ props.onLocationChange?.({+ x: camera.x,+ y: camera.y,+ scale: camera.scale * 100,+ });+ if (props.isNested) return;+ clearTimeout(viewTimer);+ viewTimer = setTimeout(() => {+ void saveCanvasViewLocation(documentId, camera);+ }, 500);+ });+ const flush = () => {+ if (props.canEdit) finishText();+ void saving.flush();+ };+ const beforeUnload = (event: BeforeUnloadEvent) => {+ flush();+ if (saving.dirty()) {+ event.preventDefault();+ event.returnValue = '';+ }+ };+ window.addEventListener('pagehide', flush);+ window.addEventListener('beforeunload', beforeUnload);+ onCleanup(() => {+ flush();+ saving.dispose();+ unsubscribe();+ clearTimeout(viewTimer);+ window.removeEventListener('pagehide', flush);+ window.removeEventListener('beforeunload', beforeUnload);+ });+ }}+ />+ </CanvasAncestry.Provider>+ </Show>+ </div>+ );+ return props.children+ ? props.children(content, {+ mode: 'next',+ savedFile: () => persistence()?.savedFile(),+ location: currentLocation,+ })+ : content;+}diff --git a/apps/web/src/features/block-canvas/canvas-next/canvas-next.tsx b/apps/web/src/features/block-canvas/canvas-next/canvas-next.tsxnew file mode 100644index 0000000000..66fa8e8102--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/canvas-next.tsx@@ -0,0 +1,143 @@+import { useSplitLayout } from '@components/app/split-layout/layout';+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { parseMacroAppUrl } from '@core/component/LexicalMarkdown/plugins';+import {+ fileTypeToBlockName,+ resolveBlockAlias,+} from '@core/constant/allBlocks';+import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';+import type { GraphicsEditor, TextMeasurer } from '@macro-inc/graphics';+import { createGraphicsEditor, screenToWorld } from '@macro-inc/graphics';+import { fetchDocumentMetadata } from '@queries/storage/document-metadata';+import { onCleanup, Show } from 'solid-js';+import { CanvasBlockEmbed } from './block-embed-adapter';+import { createCanvasClipboard } from './clipboard';+import type { CanvasFile } from './core/document-format';+import { registerCanvasNextHotkeys } from './hotkeys';+import { createAssetState } from './primitives/create-asset-state';+import { createCanvasState } from './primitives/create-canvas-state';+import { importTextClipboard } from './primitives/text-lexical';+import { canvasAssetSource } from './queries/assets';+import { CanvasReadOnlyView } from './views/canvas-read-only-view';+import { CanvasView } from './views/canvas-view';+import { createCanvasTextMeasurer } from './views/text-content';++export function CanvasNextEditor(props: {+ initial: CanvasFile;+ canEdit: boolean;+ fitOnLoad?: boolean;+ onReady?: (editor: GraphicsEditor, finishText: () => void) => void;+}) {+ const measurement = createCanvasTextMeasurer();+ onCleanup(measurement.dispose);+ const editor = createGraphicsEditor(props.initial.document, {+ measureText: measurement.measure,+ });+ onCleanup(editor.dispose);+ let finishText = () => {};+ props.onReady?.(editor, () => finishText());+ return (+ <StaticMarkdownContext>+ <Show+ when={props.canEdit}+ fallback={+ <CanvasReadOnlyView editor={editor} fitOnLoad={props.fitOnLoad} />+ }+ >+ <EditableCanvasNext+ editor={editor}+ measureText={measurement.measure}+ fitOnLoad={props.fitOnLoad}+ canEdit={() => props.canEdit}+ onFinishReady={(finish) => {+ finishText = finish;+ }}+ />+ </Show>+ </StaticMarkdownContext>+ );+}++function EditableCanvasNext(props: {+ editor: GraphicsEditor;+ measureText: TextMeasurer;+ fitOnLoad?: boolean;+ canEdit: () => boolean;+ onFinishReady: (finish: () => void) => void;+}) {+ const editor = props.editor;+ const state = createCanvasState(editor, props.measureText);+ const assets = createAssetState(state, canvasAssetSource);+ const { openWithSplit } = useSplitLayout();+ let viewport: HTMLElement | undefined;+ const center = () =>+ screenToWorld(editor.getCamera(), {+ x: (viewport?.clientWidth ?? 800) / 2,+ y: (viewport?.clientHeight ?? 600) / 2,+ });+ const clipboard = createCanvasClipboard(+ editor,+ state.setNotice,+ (text, html) => {+ const link = parseMacroAppUrl(text);+ if (link.isValid && link.id && link.block) {+ assets.document(+ { id: link.id, name: 'Document', fileType: link.block },+ center()+ );+ return;+ }+ state.text.insert(importTextClipboard(text, html), center());+ state.chooseTool('select');+ },+ (files) => {+ void assets.files(files, center());+ }+ );+ const [attachScope, scopeId] = useHotkeyDOMScope('canvas-next');+ registerCanvasNextHotkeys(scopeId, state, clipboard, props.canEdit);+ props.onFinishReady(state.text.finish);+ onCleanup(() => {+ state.text.finish();+ state.inspector.cancel();+ state.text.cancel();+ state.eraser.cancel();+ state.connector.interaction.cancel();+ state.embeds.exit();+ assets.cancelPending();+ editor.cancelShape();+ editor.cancelTransform();+ props.onFinishReady(() => {});+ });+ return (+ <CanvasView+ fitOnLoad={props.fitOnLoad}+ state={state}+ scopeId={scopeId}+ embedView={CanvasBlockEmbed}+ assets={assets}+ onViewport={(element) => {+ viewport = element;+ }}+ onOpenDocument={async (item) => {+ try {+ const fileType =+ item.fileType === 'unknown'+ ? (await fetchDocumentMetadata(item.documentId)).fileType+ : item.fileType;+ openWithSplit(+ {+ id: item.documentId,+ type: resolveBlockAlias(fileTypeToBlockName(fileType)),+ },+ { activate: true }+ );+ } catch {+ state.setNotice('Could not open this document');+ }+ }}+ clipboard={clipboard}+ attachScope={attachScope}+ />+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/clipboard.test.ts b/apps/web/src/features/block-canvas/canvas-next/clipboard.test.tsnew file mode 100644index 0000000000..5b33f89799--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/clipboard.test.ts@@ -0,0 +1,200 @@+import {+ createGraphicsEditor,+ drawableIds,+ setShapeLabelCommand,+} from '@macro-inc/graphics';+import { afterEach, expect, it, vi } from 'vitest';+import { createCanvasClipboard } from './clipboard';+import { createCanvasNextScene } from './core/seed-scene';+import { plainRichText } from './core/text-codec';++const cleanup: (() => void)[] = [];+afterEach(() => {+ cleanup.splice(0).forEach((fn) => fn());+ vi.unstubAllGlobals();+});++function setup() {+ const editor = createGraphicsEditor(createCanvasNextScene());+ const host = document.createElement('div');+ const input = document.createElement('input');+ host.append(input);+ const notify = vi.fn();+ const clipboard = createCanvasClipboard(editor, notify);+ cleanup.push(clipboard.attach(host), editor.dispose);+ const data = new Map<string, string>();+ const event = (type: string, target: HTMLElement = host) => {+ const event = new Event(type, { bubbles: true, cancelable: true });+ Object.defineProperty(event, 'clipboardData', {+ value: {+ setData: (key: string, value: string) => data.set(key, value),+ getData: (key: string) => data.get(key) ?? '',+ },+ });+ target.dispatchEvent(event);+ return event;+ };+ return { editor, input, host, data, event, clipboard, notify };+}++it('copies/cuts/pastes native events, offsets repeated pastes, and undoes the whole fragment', () => {+ const { editor, data, event } = setup();+ editor.select('welcome-rectangle');+ expect(event('copy').defaultPrevented).toBe(true);+ expect(data.get('application/x-macro-graphics')).toBe(data.get('text/plain'));+ expect(event('paste').defaultPrevented).toBe(true);+ const first = editor.document.items[editor.getSession().selectedIds[0]!]!;+ event('paste');+ const second = editor.document.items[editor.getSession().selectedIds[0]!]!;+ expect(first.type !== 'surface' && first.transform[4]).toBe(124);+ expect(second.type !== 'surface' && second.transform[4]).toBe(148);+ expect(drawableIds(editor.document)).toHaveLength(5);+ event('cut');+ expect(drawableIds(editor.document)).toHaveLength(4);+ editor.undo();+ expect(drawableIds(editor.document)).toHaveLength(5);+});++it('leaves clipboard editing in inputs alone and rejects unrelated external clipboard data', () => {+ const { editor, input, data, event } = setup();+ editor.select('welcome-rectangle');+ expect(event('cut', input).defaultPrevented).toBe(false);+ data.set('text/plain', 'ordinary text');+ expect(event('paste').defaultPrevented).toBe(false);+ expect(drawableIds(editor.document)).toHaveLength(3);+ expect(editor.getSession().canUndo).toBe(false);+});++it.each([plainRichText('Pasted label'), '{broken'])(+ 'validates host text when importing shape fragments (%s)',+ (content) => {+ const { editor, event, notify } = setup();+ editor.execute(setShapeLabelCommand, {+ id: 'welcome-rectangle',+ label: { content, fontSize: 24, fontFamily: 'sans', height: 32 },+ });+ event('copy');+ const before = editor.document;+ event('paste');+ if (content === '{broken') {+ expect(editor.document).toBe(before);+ expect(notify).toHaveBeenLastCalledWith(+ 'Clipboard has invalid Canvas Next text'+ );+ } else {+ expect(+ editor.document.items[editor.getSession().selectedId!]+ ).toMatchObject({ geometry: { label: { content } } });+ expect(drawableIds(editor.document)).toHaveLength(4);+ }+ }+);++it('never deletes on failed clipboard write or deletes a newer selection after an async cut', async () => {+ const { editor, clipboard, notify } = setup();+ editor.select('welcome-rectangle');+ vi.stubGlobal('navigator', {+ clipboard: { writeText: () => Promise.reject(new Error('denied')) },+ });+ await clipboard.cut();+ expect(drawableIds(editor.document)).toHaveLength(3);+ expect(notify).toHaveBeenCalledWith(+ expect.stringContaining('permission denied')+ );+ let finish!: () => void;+ vi.stubGlobal('navigator', {+ clipboard: {+ writeText: () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ },+ });+ const cut = clipboard.cut();+ editor.select('welcome-ellipse');+ finish();+ await cut;+ expect(drawableIds(editor.document)).toHaveLength(3);+});++it('leaves native rich-text paste and already-handled clipboard events to the text editor', () => {+ const editor = createGraphicsEditor();+ cleanup.push(editor.dispose);+ const host = document.createElement('div'),+ editable = document.createElement('div');+ editable.setAttribute('contenteditable', '');+ host.append(editable);+ const pasteText = vi.fn(),+ clipboard = createCanvasClipboard(editor, () => {}, pasteText);+ cleanup.push(clipboard.attach(host));+ function paste(target: HTMLElement, handled = false) {+ const event = new Event('paste', { bubbles: true, cancelable: true });+ Object.defineProperty(event, 'clipboardData', {+ value: { getData: () => 'Rich text' },+ });+ if (handled) event.preventDefault();+ target.dispatchEvent(event);+ }+ paste(editable);+ paste(host, true);+ expect(pasteText).not.toHaveBeenCalled();+ paste(host);+ expect(pasteText).toHaveBeenCalledOnce();+});++it('routes pasted media to the host and preserves native paste inside text editing', async () => {+ const editor = createGraphicsEditor();+ cleanup.push(editor.dispose);+ const host = document.createElement('div');+ const editable = document.createElement('div');+ editable.setAttribute('contenteditable', 'true');+ host.append(editable);+ const pasteText = vi.fn(),+ pasteFiles = vi.fn();+ const clipboard = createCanvasClipboard(+ editor,+ vi.fn(),+ pasteText,+ pasteFiles+ );+ cleanup.push(clipboard.attach(host));+ const file = new File(['image'], 'picture.png', { type: 'image/png' });+ function paste(target: HTMLElement) {+ const event = new Event('paste', { bubbles: true, cancelable: true });+ Object.defineProperty(event, 'clipboardData', {+ value: { files: [file], getData: () => 'image caption' },+ });+ target.dispatchEvent(event);+ return event;+ }+ expect(paste(editable).defaultPrevented).toBe(false);+ expect(pasteFiles).not.toHaveBeenCalled();+ expect(paste(host).defaultPrevented).toBe(true);+ expect(pasteFiles).toHaveBeenCalledWith([file]);+ expect(pasteText).not.toHaveBeenCalled();+ vi.stubGlobal('navigator', {+ clipboard: {+ read: async () => [{ types: ['image/png'], getType: async () => file }],+ },+ });+ await clipboard.paste();+ const uploaded = pasteFiles.mock.lastCall![0][0] as File;+ expect(uploaded.type).toBe('image/png');+ expect(uploaded.size).toBe(file.size);+ expect(editor.getSession().canUndo).toBe(false);+});++it('leaves native clipboard events owned by an active nested canvas alone', () => {+ const { editor, host, data, event } = setup();+ const embed = document.createElement('div');+ embed.dataset.canvasEmbedActive = 'nested';+ const innerCanvas = document.createElement('div');+ embed.append(innerCanvas);+ host.append(embed);+ editor.select('welcome-rectangle');+ data.set('text/plain', 'nested canvas data');+ for (const type of ['copy', 'cut', 'paste'])+ expect(event(type, innerCanvas).defaultPrevented).toBe(false);+ expect(drawableIds(editor.document)).toHaveLength(3);+ expect(editor.getSession().canUndo).toBe(false);+});diff --git a/apps/web/src/features/block-canvas/canvas-next/clipboard.ts b/apps/web/src/features/block-canvas/canvas-next/clipboard.tsnew file mode 100644index 0000000000..5f9fe2dc26--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/clipboard.ts@@ -0,0 +1,190 @@+import {+ copyFragment,+ type GraphicsEditor,+ type GraphicsFragment,+ parseFragment,+ pasteCommand,+} from '@macro-inc/graphics';+import { importExcalidraw } from './core/excalidraw';+import { validCanvasTextDocument } from './core/text-codec';++const mime = 'application/x-macro-graphics';+const editingText = (target: EventTarget | null) =>+ target instanceof Element &&+ !!target.closest(+ '[data-canvas-embed-active], input, textarea, select, [contenteditable]:not([contenteditable="false"])'+ );++/** OS clipboard and DOM events belong to the host, never to graphics core. */+export function createCanvasClipboard(+ editor: GraphicsEditor,+ notify: (message: string) => void,+ pasteText?: (text: string, html?: string) => void,+ pasteFiles?: (files: File[]) => void+) {+ let pastedText = '',+ pasteCount = 0;+ const serialize = () => {+ const fragment = copyFragment(+ editor.document,+ editor.getSession().selectedIds+ );+ return fragment ? JSON.stringify(fragment) : undefined;+ };+ const insert = (fragment: GraphicsFragment, text: string) => {+ if (!validCanvasTextDocument(fragment.scene)) {+ notify('Clipboard has invalid Canvas Next text');+ return false;+ }+ pasteCount = text === pastedText ? pasteCount + 1 : 1;+ pastedText = text;+ editor.execute(pasteCommand, {+ fragment,+ createId: () => crypto.randomUUID(),+ offset: { x: 24 * pasteCount, y: 24 * pasteCount },+ });+ return true;+ };+ const paste = (text: string, html?: string) => {+ const fragment = parseFragment(text);+ if (fragment) {+ const pasted = insert(fragment, text);+ if (pasted) notify('Pasted selection');+ return pasted;+ }+ const excalidraw = importExcalidraw(text);+ if (excalidraw) {+ const pasted = insert(excalidraw.fragment, text);+ if (pasted) notify(excalidrawNotice(excalidraw));+ return pasted;+ }+ if (pasteText && text.trim()) {+ pasteText(text, html);+ notify('Pasted text');+ return true;+ }+ notify('Clipboard has no Canvas Next shapes');+ return false;+ };+ async function copy(cut = false) {+ const text = serialize();+ if (!text) return;+ const document = editor.document,+ selection = editor.getSession().selectedIds.join('\n');+ try {+ await navigator.clipboard.writeText(text);+ pastedText = '';+ pasteCount = 0;+ if (+ cut &&+ editor.document === document &&+ editor.getSession().selectedIds.join('\n') === selection+ )+ editor.deleteSelection();+ notify(cut ? 'Cut selection' : 'Copied selection');+ } catch {+ notify('Clipboard permission denied. Use the keyboard shortcut instead.');+ }+ }+ return {+ copy: () => copy(),+ cut: () => copy(true),+ async paste() {+ try {+ if (pasteFiles && navigator.clipboard.read) {+ const items = await navigator.clipboard.read();+ const files: File[] = [];+ let text = '',+ html = '';+ for (const item of items) {+ const media = item.types.find(+ (type) => type.startsWith('image/') || type.startsWith('video/')+ );+ if (media)+ files.push(+ new File(+ [await item.getType(media)],+ `Pasted.${media.split('/')[1]}`,+ { type: media }+ )+ );+ else {+ if (item.types.includes('text/plain'))+ text = await (await item.getType('text/plain')).text();+ if (item.types.includes('text/html'))+ html = await (await item.getType('text/html')).text();+ }+ }+ if (files.length) pasteFiles(files);+ else paste(text, html);+ } else paste(await navigator.clipboard.readText());+ } catch {+ notify('Clipboard permission denied. Use the paste keyboard shortcut.');+ }+ },+ attach(element: HTMLElement) {+ const write = (event: ClipboardEvent) => {+ if (+ event.defaultPrevented ||+ editingText(event.target) ||+ !event.clipboardData+ )+ return;+ const text = serialize();+ if (!text) return;+ event.clipboardData.setData(mime, text);+ event.clipboardData.setData('text/plain', text);+ event.preventDefault();+ event.stopPropagation();+ pastedText = '';+ pasteCount = 0;+ if (event.type === 'cut') editor.deleteSelection();+ notify(event.type === 'cut' ? 'Cut selection' : 'Copied selection');+ };+ const read = (event: ClipboardEvent) => {+ if (+ event.defaultPrevented ||+ editingText(event.target) ||+ !event.clipboardData+ )+ return;+ if (pasteFiles && event.clipboardData.files.length) {+ event.preventDefault();+ event.stopPropagation();+ pasteFiles(Array.from(event.clipboardData.files));+ return;+ }+ if (+ paste(+ event.clipboardData.getData(mime) ||+ event.clipboardData.getData('text/plain'),+ event.clipboardData.getData('text/html')+ )+ ) {+ event.preventDefault();+ event.stopPropagation();+ }+ };+ element.addEventListener('copy', write);+ element.addEventListener('cut', write);+ element.addEventListener('paste', read);+ return () => {+ element.removeEventListener('copy', write);+ element.removeEventListener('cut', write);+ element.removeEventListener('paste', read);+ };+ },+ };+}+export type CanvasClipboard = ReturnType<typeof createCanvasClipboard>;++function excalidrawNotice(result: ReturnType<typeof importExcalidraw>): string {+ if (!result) return 'Pasted selection';+ const extras: string[] = [];+ if (result.approximated) extras.push(`${result.approximated} approximated`);+ if (result.skipped) extras.push(`${result.skipped} unsupported`);+ const shapes = `${result.imported} Excalidraw ${result.imported === 1 ? 'shape' : 'shapes'}`;+ return extras.length+ ? `Imported ${shapes} (${extras.join(', ')})`+ : `Imported ${shapes}`;+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/arrange-controls.tsx b/apps/web/src/features/block-canvas/canvas-next/components/arrange-controls.tsxnew file mode 100644index 0000000000..f57198d3c5--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/arrange-controls.tsx@@ -0,0 +1,86 @@+import type { Alignment } from '@macro-inc/graphics';+import AlignBottom from '@phosphor/align-bottom-simple.svg';+import AlignCenter from '@phosphor/align-center-horizontal-simple.svg';+import AlignMiddle from '@phosphor/align-center-vertical-simple.svg';+import AlignLeft from '@phosphor/align-left-simple.svg';+import AlignRight from '@phosphor/align-right-simple.svg';+import AlignTop from '@phosphor/align-top-simple.svg';+import ArrowsHorizontal from '@phosphor/arrows-horizontal.svg';+import ArrowsVertical from '@phosphor/arrows-vertical.svg';+import { Button, ButtonGroup } from '@ui';+import { For, Show } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import { INSPECTOR_CONTROL_FRAME_CLASS } from './inspector-control-frame';++export function CanvasAlignmentControls(props: {+ count: number;+ onAlign: (alignment: Alignment) => void;+ onDistribute: (axis: 'horizontal' | 'vertical') => void;+}) {+ return (+ <div class="space-y-2">+ <div class="grid grid-cols-2 gap-2">+ <For+ each={+ [+ [+ ['left', AlignLeft],+ ['center', AlignCenter],+ ['right', AlignRight],+ ],+ [+ ['top', AlignTop],+ ['middle', AlignMiddle],+ ['bottom', AlignBottom],+ ],+ ] as const+ }+ >+ {(alignments) => (+ <ButtonGroup+ size="icon-sm"+ class={`w-full data-[orientation=horizontal]:rounded-lg ${INSPECTOR_CONTROL_FRAME_CLASS}`}+ >+ <For each={alignments}>+ {([alignment, icon]) => (+ <>+ <Button+ fullWidth+ class="bg-transparent"+ label={`Align ${alignment}`}+ disabled={props.count < 2}+ onClick={() => props.onAlign(alignment)}+ >+ <Dynamic component={icon} />+ </Button>+ </>+ )}+ </For>+ </ButtonGroup>+ )}+ </For>+ </div>+ <Show when={props.count >= 3}>+ <ButtonGroup+ size="icon-sm"+ class={`data-[orientation=horizontal]:rounded-lg ${INSPECTOR_CONTROL_FRAME_CLASS}`}+ >+ <Button+ label="Distribute horizontal"+ disabled={props.count < 3}+ onClick={() => props.onDistribute('horizontal')}+ >+ <ArrowsHorizontal />+ </Button>+ <Button+ label="Distribute vertical"+ disabled={props.count < 3}+ onClick={() => props.onDistribute('vertical')}+ >+ <ArrowsVertical />+ </Button>+ </ButtonGroup>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/connector-inspector.tsx b/apps/web/src/features/block-canvas/canvas-next/components/connector-inspector.tsxnew file mode 100644index 0000000000..186dd0c742--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/connector-inspector.tsx@@ -0,0 +1,62 @@+import type { ConnectorStyle } from '@macro-inc/graphics';+import { For } from 'solid-js';+import {+ ConnectorEndpointIcon,+ ConnectorRouteIcon,+} from './connector-style-icon';+import { InspectorField } from './inspector-field';+import { InspectorSection } from './inspector-section';+import { InspectorSelect } from './inspector-select';++export function ConnectorInspector(props: {+ value: Partial<ConnectorStyle>;+ onChange: (patch: Partial<ConnectorStyle>) => void;+}) {+ return (+ <InspectorSection title="Connection">+ <InspectorField label="Route">+ <InspectorSelect+ label="Connector route"+ value={props.value.route}+ renderIcon={(route) => <ConnectorRouteIcon route={route} />}+ options={[+ { value: 'straight', label: 'Straight' },+ { value: 'stepped', label: 'Elbow' },+ { value: 'smooth', label: 'Smooth' },+ ]}+ onChange={(route) => props.onChange({ route })}+ />+ </InspectorField>+ <div class="grid grid-cols-2 gap-2">+ <For each={['startHead', 'endHead'] as const}>+ {(key) => (+ <InspectorField label={key === 'startHead' ? 'Start' : 'End'}>+ <InspectorSelect+ label={+ key === 'startHead'+ ? 'Connector start style'+ : 'Connector end style'+ }+ value={props.value[key]}+ renderIcon={(head) => (+ <ConnectorEndpointIcon+ head={head}+ start={key === 'startHead'}+ />+ )}+ options={[+ { value: 'none', label: 'None' },+ { value: 'arrow', label: 'Arrow' },+ { value: 'arrow-filled', label: 'Filled arrow' },+ { value: 'circle', label: 'Dot' },+ { value: 'circle-small', label: 'Small dot' },+ ]}+ onChange={(value) => props.onChange({ [key]: value })}+ />+ </InspectorField>+ )}+ </For>+ </div>+ </InspectorSection>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/connector-style-icon.tsx b/apps/web/src/features/block-canvas/canvas-next/components/connector-style-icon.tsxnew file mode 100644index 0000000000..85c6030a55--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/connector-style-icon.tsx@@ -0,0 +1,87 @@+import type { Appearance, ConnectorStyle } from '@macro-inc/graphics';+import { Match, Switch } from 'solid-js';++/** Small previews use the same visual vocabulary as the connector on the canvas. */+export function ConnectorRouteIcon(props: { route: ConnectorStyle['route'] }) {+ const path = () =>+ ({+ straight: 'M3 13 21 3',+ stepped: 'M3 13H12V3H21',+ smooth: 'M3 13C15 13 9 3 21 3',+ })[props.route];+ return (+ <svg+ aria-hidden="true"+ viewBox="0 0 24 16"+ class="h-3 w-[18px] shrink-0 text-ink-muted"+ fill="none"+ stroke="currentColor"+ stroke-width="1.25"+ stroke-linecap="round"+ stroke-linejoin="round"+ >+ <path d={path()} />+ </svg>+ );+}++export function ConnectorEndpointIcon(props: {+ head: ConnectorStyle['startHead'];+ start?: boolean;+}) {+ return (+ <svg+ aria-hidden="true"+ viewBox="0 0 24 16"+ class="h-3 w-[18px] shrink-0 text-ink-muted"+ fill="none"+ stroke="currentColor"+ stroke-width="1.25"+ stroke-linecap="round"+ stroke-linejoin="round"+ >+ <g transform={props.start ? 'translate(24 0) scale(-1 1)' : undefined}>+ <path d="M3 8H20" />+ <Switch>+ <Match when={props.head === 'arrow'}>+ <path d="m15 3 5 5-5 5" />+ </Match>+ <Match when={props.head === 'arrow-filled'}>+ <path d="m14 3 7 5-7 5Z" fill="currentColor" />+ </Match>+ <Match when={props.head === 'circle'}>+ <circle cx="18" cy="8" r="4" fill="currentColor" />+ </Match>+ <Match when={props.head === 'circle-small'}>+ <circle cx="19" cy="8" r="2" fill="currentColor" />+ </Match>+ </Switch>+ </g>+ </svg>+ );+}++export function StrokeStyleIcon(props: { style: Appearance['strokeStyle'] }) {+ return (+ <svg+ aria-hidden="true"+ viewBox="0 0 24 16"+ class="h-3 w-[18px] shrink-0 text-ink-muted"+ fill="none"+ stroke="currentColor"+ stroke-width="1.25"+ stroke-linecap="round"+ >+ <path+ d="M3 8H21"+ stroke-dasharray={+ props.style === 'dashed'+ ? '4 3'+ : props.style === 'dotted'+ ? '0.1 4'+ : undefined+ }+ />+ </svg>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/embed-view.ts b/apps/web/src/features/block-canvas/canvas-next/components/embed-view.tsnew file mode 100644index 0000000000..4b8a295b4b--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/embed-view.ts@@ -0,0 +1,6 @@+import type { DocumentGeometry } from '@macro-inc/graphics';+export type CanvasEmbedViewProps = {+ geometry: DocumentGeometry;+ active: boolean;+ onExit: () => void;+};diff --git a/apps/web/src/features/block-canvas/canvas-next/components/eraser-trail.tsx b/apps/web/src/features/block-canvas/canvas-next/components/eraser-trail.tsxnew file mode 100644index 0000000000..721987fd76--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/eraser-trail.tsx@@ -0,0 +1,35 @@+import {+ IDENTITY,+ type PencilPoint,+ type ShapeItem,+} from '@macro-inc/graphics';+import { defaultRenderers } from '@macro-inc/graphics/solid';+import { createMemo, Show } from 'solid-js';++const Pencil = defaultRenderers.pencil;++export function EraserTrail(props: { points: readonly PencilPoint[] }) {+ const item = createMemo<ShapeItem<'pencil'>>(() => ({+ id: 'eraser-trail',+ type: 'pencil',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: IDENTITY,+ geometry: { points: props.points, simulatePressure: false },+ appearance: {+ fill: 'transparent',+ stroke: 'var(--color-ink-muted)',+ strokeWidth: 8,+ },+ }));+ return (+ <div+ aria-hidden="true"+ data-eraser-trail+ class="pointer-events-none absolute inset-0 opacity-25"+ >+ <Show when={props.points.length}>+ <Pencil item={item()} scale={1} />+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-color-field.tsx b/apps/web/src/features/block-canvas/canvas-next/components/inspector-color-field.tsxnew file mode 100644index 0000000000..4304aedc4e--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/inspector-color-field.tsx@@ -0,0 +1,199 @@+import { Popover } from '@kobalte/core/popover';+import { ColorPicker, InputGroup, Layer } from '@ui';+import { PALETTE_COLORS } from '@ui/utils/palette';+import { createSignal, For } from 'solid-js';+import { readSwatchColor } from '../primitives/read-swatch-color';++const swatches = [+ { label: 'None', value: 'transparent' },+ { label: 'Ink', value: 'var(--color-ink)' },+ { label: 'Surface', value: 'var(--color-panel)' },+ { label: 'Accent', value: 'var(--color-accent)' },+ ...PALETTE_COLORS.map((color) => ({+ label: color[0].toUpperCase() + color.slice(1),+ value: `var(--color-${color})`,+ })),+];++export function InspectorColorField(props: {+ canvasColors: readonly string[];+ label: string;+ value: string | undefined;+ onChange: (color: string) => void;+}) {+ const [invalid, setInvalid] = createSignal(false);+ const [picker, setPicker] = createSignal('#000000');+ let swatch!: HTMLSpanElement;+ const named = () =>+ swatches.find((color) => color.value === props.value)?.label;+ const display = () => {+ if (named()) return named();+ if (!props.value) return '';+ if (props.value.startsWith('#')) return props.value.slice(1).toUpperCase();+ return 'Custom';+ };+ return (+ <div class="space-y-2">+ <InputGroup+ size="sm"+ class="border-transparent bg-hover/50 hover:border-edge-muted has-[button:focus-visible]:border-edge has-[button:focus-visible]:ring-2 has-[button:focus-visible]:ring-edge-muted"+ >+ <InputGroup.Addon>+ <Popover+ placement="left-start"+ gutter={8}+ onOpenChange={(open) => {+ if (open) setPicker(readSwatchColor(swatch));+ }}+ >+ <Popover.Trigger+ aria-label={`${props.label} color picker`}+ class="block rounded-sm p-0 outline-none"+ >+ <span+ ref={swatch}+ class="block size-4 rounded-sm border border-ink/10"+ style={{ background: props.value ?? 'transparent' }}+ >+ {props.value === 'transparent' && (+ <span class="block text-center text-xs text-ink-muted">+ ╱+ </span>+ )}+ </span>+ </Popover.Trigger>+ <Popover.Portal>+ <Layer depth={3}>+ <Popover.Content+ aria-label={`${props.label} color picker`}+ class="z-modal max-h-[min(calc(100vh-2rem),var(--kb-popper-content-available-height))] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-xl border border-edge bg-panel p-4 shadow-lg"+ >+ <ColorPicker.Root+ value={picker()}+ onChange={(color) => {+ setPicker(color);+ setInvalid(false);+ props.onChange(color);+ }}+ class="gap-4"+ >+ <ColorPicker.Field class="aspect-square h-auto" />+ <ColorPicker.HueTrack />+ <ColorPicker.AlphaTrack />+ <div class="flex items-center gap-2">+ <ColorPicker.Preview />+ <ColorPicker.Input+ aria-label={`${props.label} picker hex color`}+ />+ <span class="text-[10px] text-ink-muted">HEX</span>+ </div>+ <For+ each={[+ {+ title: 'Palette',+ label: `${props.label} palette`,+ colors: swatches,+ },+ {+ title: 'On this canvas',+ label: `${props.label} canvas colors`,+ colors: props.canvasColors.map((value) => ({+ value,+ label:+ swatches.find((color) => color.value === value)+ ?.label ?? value,+ })),+ },+ ]}+ >+ {(section) => (+ <div class="space-y-3 border-t border-edge pt-3">+ <p class="text-xs font-medium text-ink-muted">+ {section.title}+ </p>+ <div+ class="grid grid-cols-[repeat(16,minmax(0,1fr))] gap-1"+ role="group"+ aria-label={section.label}+ >+ <For each={section.colors}>+ {(color) => (+ <button+ type="button"+ aria-label={`${props.label}: ${color.label}`}+ title={color.label}+ aria-pressed={props.value === color.value}+ class="aspect-square min-w-0 rounded-[2px] border border-ink/10 outline-none hover:ring-1 hover:ring-ink-muted focus-visible:ring-2 focus-visible:ring-ink-muted aria-pressed:ring-1 aria-pressed:ring-ink aria-pressed:ring-offset-1 aria-pressed:ring-offset-surface"+ style={{ background: color.value }}+ onClick={(event) => {+ setInvalid(false);+ setPicker(+ readSwatchColor(+ event.currentTarget,+ picker()+ )+ );+ props.onChange(color.value);+ }}+ >+ {color.value === 'transparent' ? (+ <span class="block text-[8px] leading-none text-ink-muted">+ ╱+ </span>+ ) : null}+ </button>+ )}+ </For>+ </div>+ {section.colors.length === 0 && (+ <p class="text-xs text-ink-muted">No colors yet</p>+ )}+ </div>+ )}+ </For>+ </ColorPicker.Root>+ </Popover.Content>+ </Layer>+ </Popover.Portal>+ </Popover>+ </InputGroup.Addon>+ <InputGroup.Input+ onClick={(event) => event.currentTarget.select()}+ aria-label={`${props.label} color`}+ aria-invalid={invalid()}+ placeholder={props.value === undefined ? 'Mixed' : display()}+ spellcheck={false}+ class="text-xs"+ value={display()}+ onInput={() => setInvalid(false)}+ onChange={(event) => {+ const raw = event.currentTarget.value.trim();+ if (+ /^#?(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i.test(raw)+ ) {+ setInvalid(false);+ props.onChange(`#${raw.replace(/^#/, '')}`);+ } else if (raw !== display()) setInvalid(true);+ }}+ onKeyDown={(event) => {+ if (event.key === 'Enter') event.currentTarget.blur();+ if (event.key === 'Escape') {+ event.stopPropagation();+ setInvalid(false);+ event.currentTarget.value = display() ?? '';+ event.currentTarget.blur();+ }+ }}+ />+ <InputGroup.Addon align="inline-end" class="text-[10px]">+ {named() ? 'Palette' : 'HEX'}+ </InputGroup.Addon>+ </InputGroup>+ {invalid() && (+ <p class="text-[10px] text-failure" role="alert">+ Enter a 3, 4, 6, or 8 digit hex color.+ </p>+ )}+ </div>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-control-frame.ts b/apps/web/src/features/block-canvas/canvas-next/components/inspector-control-frame.tsnew file mode 100644index 0000000000..ae8ed7b971--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/inspector-control-frame.ts@@ -0,0 +1,2 @@+export const INSPECTOR_CONTROL_FRAME_CLASS =+ 'border-transparent bg-hover/50 hover:border-edge-muted has-[button:focus]:border-[color-mix(in_oklch,var(--color-edge)_80%,var(--color-ink))] has-[button:focus]:ring-2 has-[button:focus]:ring-edge-muted';diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-field.tsx b/apps/web/src/features/block-canvas/canvas-next/components/inspector-field.tsxnew file mode 100644index 0000000000..e571696658--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/inspector-field.tsx@@ -0,0 +1,14 @@+import type { JSX } from 'solid-js';++/** Keeps property labels and controls on the inspector's shared column grid. */+export function InspectorField(props: {+ label: string;+ children: JSX.Element;+}) {+ return (+ <div class="min-w-0 space-y-1">+ <div class="text-[10px] text-ink-muted">{props.label}</div>+ {props.children}+ </div>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-number-field.tsx b/apps/web/src/features/block-canvas/canvas-next/components/inspector-number-field.tsxnew file mode 100644index 0000000000..af07ebe830--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/inspector-number-field.tsx@@ -0,0 +1,186 @@+import { InputGroup } from '@ui';+import { createSignal, type JSX, onCleanup } from 'solid-js';+import type { InspectorNumberScrub } from '../primitives/create-inspector-preview';+import { INSPECTOR_CONTROL_FRAME_CLASS } from './inspector-control-frame';++/** A numeric control with a pointer-captured scrub handle and a single commit per drag. */+export function InspectorNumberField(props: {+ label: string;+ icon: JSX.Element;+ value: number | undefined;+ disabled?: boolean;+ min?: number;+ max?: number;+ step?: number | 'any';+ unit?: string;+ onChange: (value: number) => void;+ onScrub?: () => InspectorNumberScrub;+}) {+ const [draft, setDraft] = createSignal<number>();+ let drag:+ | {+ x: number;+ value: number;+ original: number | undefined;+ pointer: number;+ target: HTMLButtonElement;+ scrub: InspectorNumberScrub | undefined;+ }+ | undefined;+ const increment = () => (typeof props.step === 'number' ? props.step : 1);+ const normalize = (value: number) => {+ const step = increment();+ return Math.min(+ props.max ?? Infinity,+ Math.max(+ props.min ?? 0,+ props.step === 'any' ? value : Math.round(value / step) * step+ )+ );+ };+ const initialValue = () =>+ props.value ?? (Number.isFinite(props.min) ? props.min! : 0);+ const finish = (commit = false) => {+ const current = drag;+ const value = draft();+ drag = undefined;+ setDraft(undefined);+ window.removeEventListener('blur', cancel);+ if (!current) return;+ if (current.target.hasPointerCapture(current.pointer))+ current.target.releasePointerCapture(current.pointer);+ if (commit && value !== undefined && value !== current.original) {+ if (current.scrub) current.scrub.commit(value);+ else props.onChange(value);+ } else current.scrub?.cancel();+ };+ const cancel = () => finish();+ onCleanup(cancel);+ const update = (event: PointerEvent) => {+ if (!drag || drag.pointer !== event.pointerId) return;+ if (event.clientX === drag.x && draft() === undefined) return;+ const value = normalize(+ drag.value ++ (event.clientX - drag.x) * increment() * (event.shiftKey ? 10 : 1)+ );+ if (value === draft()) return;+ setDraft(value);+ drag.scrub?.preview(value);+ };+ return (+ <InputGroup size="sm" class={INSPECTOR_CONTROL_FRAME_CLASS}>+ <InputGroup.Addon class="ps-0">+ <button+ type="button"+ disabled={props.disabled}+ aria-label={`Adjust ${props.label}`}+ title={`Drag to adjust ${props.label.toLowerCase()}. Shift for larger steps.`}+ class="flex h-full w-6 shrink-0 touch-none select-none items-center justify-center rounded-l-md text-ink-muted outline-none cursor-ew-resize"+ onPointerDown={(event) => {+ if (event.button !== 0 || drag) return;+ event.preventDefault();+ event.currentTarget.focus();+ drag = {+ x: event.clientX,+ value: initialValue(),+ original: props.value,+ pointer: event.pointerId,+ target: event.currentTarget,+ scrub: props.onScrub?.(),+ };+ event.currentTarget.setPointerCapture(event.pointerId);+ window.addEventListener('blur', cancel);+ }}+ onPointerMove={update}+ onPointerUp={(event) => {+ if (!drag || drag.pointer !== event.pointerId) return;+ update(event);+ finish(true);+ }}+ onPointerCancel={(event) => {+ if (drag?.pointer === event.pointerId) cancel();+ }}+ onLostPointerCapture={(event) => {+ if (drag?.pointer === event.pointerId) cancel();+ }}+ onBlur={cancel}+ onKeyDown={(event) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ cancel();+ }+ if (+ !['ArrowLeft', 'ArrowDown', 'ArrowRight', 'ArrowUp'].includes(+ event.key+ )+ )+ return;+ event.preventDefault();+ event.stopPropagation();+ cancel();+ const direction =+ event.key === 'ArrowLeft' || event.key === 'ArrowDown' ? -1 : 1;+ props.onChange(+ normalize(+ initialValue() ++ direction * increment() * (event.shiftKey ? 10 : 1)+ )+ );+ }}+ >+ {props.icon}+ </button>+ </InputGroup.Addon>+ <InputGroup.Input+ onClick={(event) => event.currentTarget.select()}+ disabled={props.disabled}+ type="text"+ inputMode="decimal"+ aria-label={props.label}+ min={props.min === -Infinity ? undefined : (props.min ?? 0)}+ max={props.max}+ step={props.step ?? 1}+ placeholder={+ props.disabled+ ? '—'+ : props.value === undefined+ ? 'Mixed'+ : String(props.value)+ }+ value={draft() ?? props.value ?? ''}+ class="px-1 text-xs tabular-nums [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"+ onChange={(event) => {+ const raw = event.currentTarget.value.trim();+ const value = raw === '' ? NaN : Number(raw);+ if (Number.isFinite(value)) props.onChange(normalize(value));+ event.currentTarget.value = String(props.value ?? '');+ }}+ onKeyDown={(event) => {+ if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {+ event.preventDefault();+ event.stopPropagation();+ const raw = event.currentTarget.value.trim();+ const value = raw === '' ? initialValue() : Number(raw);+ if (Number.isFinite(value)) {+ props.onChange(+ normalize(+ value ++ (event.key === 'ArrowUp' ? 1 : -1) *+ increment() *+ (event.shiftKey ? 10 : 1)+ )+ );+ event.currentTarget.value = String(props.value ?? '');+ event.currentTarget.select();+ }+ }+ if (event.key === 'Enter') event.currentTarget.blur();+ }}+ />+ <InputGroup.Addon align="inline-end" class="text-[10px]">+ {props.unit}+ </InputGroup.Addon>+ </InputGroup>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-section.tsx b/apps/web/src/features/block-canvas/canvas-next/components/inspector-section.tsxnew file mode 100644index 0000000000..e572d9ed77--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/inspector-section.tsx@@ -0,0 +1,16 @@+import type { JSX } from 'solid-js';++export function InspectorSection(props: {+ title: string;+ children: JSX.Element;+}) {+ return (+ <section+ class="space-y-2 border-b border-edge-muted px-3 py-3 last:border-b-0"+ aria-label={props.title}+ >+ <h2 class="text-xs font-medium text-ink">{props.title}</h2>+ {props.children}+ </section>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/inspector-select.tsx b/apps/web/src/features/block-canvas/canvas-next/components/inspector-select.tsxnew file mode 100644index 0000000000..21540f63e4--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/inspector-select.tsx@@ -0,0 +1,54 @@+import { Select } from '@ui';+import { inputClasses } from '@ui/components/Input';+import type { JSX } from 'solid-js';++export function InspectorSelect<T extends string>(props: {+ label: string;+ value: T | undefined;+ options: { value: T; label: string }[];+ onChange: (value: T) => void;+ renderIcon?: (value: T) => JSX.Element;+}) {+ type Option = { value: T; label: string };+ const optionLabel = (option: Option) => (+ <span class="flex min-w-0 items-center gap-1.5" title={option.label}>+ {props.renderIcon?.(option.value)}+ <span class="truncate">{option.label}</span>+ </span>+ );+ return (+ <Select<Option>+ options={props.options}+ value={+ props.options.find((option) => option.value === props.value) ?? null+ }+ optionValue="value"+ optionTextValue="label"+ placeholder="Mixed"+ onChange={(option) => option && props.onChange(option.value)}+ itemComponent={(item) => (+ <Select.Item item={item.item} class="text-xs">+ <Select.ItemLabel>{optionLabel(item.item.rawValue)}</Select.ItemLabel>+ <Select.ItemIndicator class="text-ink-muted" />+ </Select.Item>+ )}+ >+ <Select.Trigger+ aria-label={props.label}+ class={inputClasses({+ size: 'sm',+ class:+ 'border-transparent bg-hover/50 text-xs hover:border-edge-muted',+ })}+ >+ <Select.Value<Option>>+ {(state) => optionLabel(state.selectedOption())}+ </Select.Value>+ <Select.Icon />+ </Select.Trigger>+ <Select.Content>+ <Select.Listbox />+ </Select.Content>+ </Select>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/selection-layout-inspector.tsx b/apps/web/src/features/block-canvas/canvas-next/components/selection-layout-inspector.tsxnew file mode 100644index 0000000000..656c6dbf88--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/selection-layout-inspector.tsx@@ -0,0 +1,165 @@+import type { Alignment } from '@macro-inc/graphics';+import ArrowClockwise from '@phosphor/arrow-clockwise.svg';+import ArrowsHorizontal from '@phosphor/arrows-horizontal.svg';+import ArrowsVertical from '@phosphor/arrows-vertical.svg';+import Lock from '@phosphor/lock-simple.svg';+import LockOpen from '@phosphor/lock-simple-open.svg';+import { Button, ButtonGroup } from '@ui';+import { Show } from 'solid-js';+import type { LayoutField } from '../core/selection-layout';+import type { InspectorNumberScrub } from '../primitives/create-inspector-preview';+import { CanvasAlignmentControls } from './arrange-controls';+import { INSPECTOR_CONTROL_FRAME_CLASS } from './inspector-control-frame';+import { InspectorNumberField } from './inspector-number-field';+import { InspectorSection } from './inspector-section';++export function SelectionLayoutInspector(props: {+ count: number;+ snapUnit: number | undefined;+ lockAspectRatio: boolean;+ onLockAspectRatio: (locked: boolean) => void;+ onAlign: (alignment: Alignment) => void;+ onDistribute: (axis: 'horizontal' | 'vertical') => void;+ value: (field: LayoutField) => number | undefined;+ onChange: (field: LayoutField, value: number) => void;+ onScrub: (field: LayoutField) => InspectorNumberScrub;+ onTransform: (action: 'rotate90' | 'flipX' | 'flipY') => void;+}) {+ return (+ <fieldset disabled={props.count === 0} class="min-w-0">+ <InspectorSection title="Position">+ <CanvasAlignmentControls+ count={props.count}+ onAlign={props.onAlign}+ onDistribute={props.onDistribute}+ />+ <div class="grid grid-cols-2 gap-2">+ <InspectorNumberField+ disabled={props.count === 0}+ label="Position X"+ icon={<span>X</span>}+ value={props.value('x')}+ min={-Infinity}+ step={props.snapUnit ?? 'any'}+ onChange={(value) => props.onChange('x', value)}+ onScrub={() => props.onScrub('x')}+ />+ <InspectorNumberField+ disabled={props.count === 0}+ label="Position Y"+ icon={<span>Y</span>}+ value={props.value('y')}+ min={-Infinity}+ step={props.snapUnit ?? 'any'}+ onChange={(value) => props.onChange('y', value)}+ onScrub={() => props.onScrub('y')}+ />+ </div>+ <p class="text-[10px] text-ink-muted">Rotation</p>+ <div class="grid grid-cols-2 items-center gap-2">+ <InspectorNumberField+ disabled={props.count === 0}+ label="Rotation"+ icon={<ArrowClockwise class="size-4" />}+ value={props.value('rotation')}+ min={-Infinity}+ step={1}+ unit="°"+ onChange={(value) => props.onChange('rotation', value)}+ onScrub={() => props.onScrub('rotation')}+ />+ <ButtonGroup+ size="icon-sm"+ class={`w-full data-[orientation=horizontal]:rounded-lg ${INSPECTOR_CONTROL_FRAME_CLASS}`}+ >+ <Button+ fullWidth+ class="bg-transparent"+ label="Rotate 90°"+ onClick={() => props.onTransform('rotate90')}+ >+ <ArrowClockwise />+ </Button>+ <Button+ fullWidth+ class="bg-transparent"+ label="Flip horizontal"+ onClick={() => props.onTransform('flipX')}+ >+ <ArrowsHorizontal />+ </Button>+ <Button+ fullWidth+ class="bg-transparent"+ label="Flip vertical"+ onClick={() => props.onTransform('flipY')}+ >+ <ArrowsVertical />+ </Button>+ </ButtonGroup>+ </div>+ </InspectorSection>+ <InspectorSection title="Layout">+ <p class="text-[10px] text-ink-muted">Dimensions</p>+ <div class="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] items-center gap-2">+ <InspectorNumberField+ disabled={props.count === 0}+ label="Width"+ icon={<span>W</span>}+ value={props.value('width')}+ min={props.snapUnit ?? 0}+ step={props.snapUnit ?? 'any'}+ onChange={(value) => props.onChange('width', value)}+ onScrub={() => props.onScrub('width')}+ />+ <InspectorNumberField+ disabled={props.count === 0}+ label="Height"+ icon={<span>H</span>}+ value={props.value('height')}+ min={props.snapUnit ?? 0}+ step={props.snapUnit ?? 'any'}+ onChange={(value) => props.onChange('height', value)}+ onScrub={() => props.onScrub('height')}+ />+ <Button+ size="icon-sm"+ label="Lock aspect ratio"+ aria-pressed={props.lockAspectRatio}+ class="aria-pressed:bg-active aria-pressed:text-ink"+ onClick={() => props.onLockAspectRatio(!props.lockAspectRatio)}+ >+ <Show when={props.lockAspectRatio} fallback={<LockOpen />}>+ <Lock />+ </Show>+ </Button>+ </div>+ <Show when={props.count > 1}>+ <p class="text-[10px] text-ink-muted">Spacing</p>+ <div class="grid grid-cols-2 gap-2">+ <InspectorNumberField+ disabled={props.count === 0}+ label="Horizontal spacing"+ icon={<ArrowsHorizontal class="size-4" />}+ value={props.value('gapX')}+ min={-Infinity}+ step={props.snapUnit ?? 'any'}+ onChange={(value) => props.onChange('gapX', value)}+ onScrub={() => props.onScrub('gapX')}+ />+ <InspectorNumberField+ disabled={props.count === 0}+ label="Vertical spacing"+ icon={<ArrowsVertical class="size-4" />}+ value={props.value('gapY')}+ min={-Infinity}+ step={props.snapUnit ?? 'any'}+ onChange={(value) => props.onChange('gapY', value)}+ onScrub={() => props.onScrub('gapY')}+ />+ </div>+ </Show>+ </InspectorSection>+ </fieldset>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/style-inspector.tsx b/apps/web/src/features/block-canvas/canvas-next/components/style-inspector.tsxnew file mode 100644index 0000000000..89d588a2b2--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/style-inspector.tsx@@ -0,0 +1,112 @@+import type { Appearance } from '@macro-inc/graphics';+import Corners from '@phosphor/corners-out.svg';+import Drop from '@phosphor/drop.svg';+import Line from '@phosphor/line-segment.svg';+import { Show } from 'solid-js';+import type { InspectorNumberScrub } from '../primitives/create-inspector-preview';+import { StrokeStyleIcon } from './connector-style-icon';+import { InspectorColorField } from './inspector-color-field';+import { InspectorField } from './inspector-field';+import { InspectorNumberField } from './inspector-number-field';+import { InspectorSection } from './inspector-section';+import { InspectorSelect } from './inspector-select';++export function StyleInspector(props: {+ canvasColors: readonly string[];+ fill: boolean;+ stroke: boolean;+ strokePattern: boolean;+ corners: boolean;+ text: boolean;+ value: <K extends keyof Appearance>(key: K) => Appearance[K] | undefined;+ onChange: (patch: Partial<Appearance>) => void;+ onScrub: (+ key: 'opacity' | 'strokeWidth' | 'cornerRadius'+ ) => InspectorNumberScrub;+}) {+ return (+ <>+ <InspectorSection title="Appearance">+ <div class="grid grid-cols-2 gap-2">+ <InspectorField label="Opacity">+ <InspectorNumberField+ label="Opacity (%)"+ icon={<Drop class="size-3" />}+ value={+ props.value('opacity') === undefined+ ? undefined+ : Math.round(props.value('opacity')! * 100)+ }+ max={100}+ unit="%"+ onChange={(value) => props.onChange({ opacity: value / 100 })}+ onScrub={() => props.onScrub('opacity')}+ />+ </InspectorField>+ <Show when={props.corners}>+ <InspectorField label="Corner radius">+ <InspectorNumberField+ label="Corner radius"+ icon={<Corners class="size-3" />}+ value={props.value('cornerRadius')}+ max={500}+ onChange={(cornerRadius) => props.onChange({ cornerRadius })}+ onScrub={() => props.onScrub('cornerRadius')}+ />+ </InspectorField>+ </Show>+ </div>+ </InspectorSection>+ <Show when={props.fill || props.text}>+ <InspectorSection title="Fill">+ <InspectorColorField+ label={props.text ? 'Text' : 'Fill'}+ canvasColors={props.canvasColors}+ value={props.value(props.text ? 'stroke' : 'fill')}+ onChange={(color) =>+ props.onChange(props.text ? { stroke: color } : { fill: color })+ }+ />+ </InspectorSection>+ </Show>+ <Show when={props.stroke}>+ <InspectorSection title="Stroke">+ <InspectorColorField+ label="Stroke"+ canvasColors={props.canvasColors}+ value={props.value('stroke')}+ onChange={(stroke) => props.onChange({ stroke })}+ />+ <div class="grid grid-cols-2 gap-2">+ <InspectorField label="Weight">+ <InspectorNumberField+ label="Stroke width"+ icon={<Line class="size-3" />}+ value={props.value('strokeWidth')}+ max={40}+ step={0.5}+ onChange={(strokeWidth) => props.onChange({ strokeWidth })}+ onScrub={() => props.onScrub('strokeWidth')}+ />+ </InspectorField>+ <Show when={props.strokePattern}>+ <InspectorField label="Style">+ <InspectorSelect+ label="Stroke style"+ value={props.value('strokeStyle')}+ renderIcon={(style) => <StrokeStyleIcon style={style} />}+ options={[+ { value: 'solid', label: 'Solid' },+ { value: 'dashed', label: 'Dashed' },+ { value: 'dotted', label: 'Dotted' },+ ]}+ onChange={(strokeStyle) => props.onChange({ strokeStyle })}+ />+ </InspectorField>+ </Show>+ </div>+ </InspectorSection>+ </Show>+ </>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/components/text-inspector.tsx b/apps/web/src/features/block-canvas/canvas-next/components/text-inspector.tsxnew file mode 100644index 0000000000..19747b4750--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/components/text-inspector.tsx@@ -0,0 +1,60 @@+import type { TextGeometry } from '@macro-inc/graphics';+import Text from '@phosphor/text-t.svg';+import { Show } from 'solid-js';+import type { InspectorNumberScrub } from '../primitives/create-inspector-preview';+import { InspectorField } from './inspector-field';+import { InspectorNumberField } from './inspector-number-field';+import { InspectorSection } from './inspector-section';+import { InspectorSelect } from './inspector-select';+export function TextInspector(props: {+ label?: boolean;+ onScrub: () => InspectorNumberScrub;+ geometry: Pick<TextGeometry, 'fontSize' | 'fontFamily'> &+ Partial<Pick<TextGeometry, 'autoWidth'>>;+ onChange: (+ patch: Partial<Pick<TextGeometry, 'fontSize' | 'fontFamily' | 'autoWidth'>>+ ) => void;+}) {+ return (+ <InspectorSection title="Typography">+ <div class="grid grid-cols-2 gap-2">+ <InspectorField label="Font">+ <InspectorSelect+ label="Font family"+ value={props.geometry.fontFamily}+ options={[+ { value: 'sans', label: 'Sans' },+ { value: 'serif', label: 'Serif' },+ { value: 'mono', label: 'Mono' },+ ]}+ onChange={(fontFamily) => props.onChange({ fontFamily })}+ />+ </InspectorField>+ <InspectorField label="Size">+ <InspectorNumberField+ label="Font size"+ icon={<Text class="size-3" />}+ value={Math.round(props.geometry.fontSize * 10) / 10}+ min={4}+ max={512}+ unit="px"+ onChange={(fontSize) => props.onChange({ fontSize })}+ onScrub={props.onScrub}+ />+ </InspectorField>+ </div>+ <Show when={!props.label}>+ <button+ type="button"+ aria-pressed={props.geometry.autoWidth}+ class="h-6 w-full rounded-md bg-hover/50 px-2 text-xs outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-edge-muted"+ onClick={() =>+ props.onChange({ autoWidth: !props.geometry.autoWidth })+ }+ >+ {props.geometry.autoWidth ? 'Auto width' : 'Wrap to width'}+ </button>+ </Show>+ </InspectorSection>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/context/canvas-ancestry.ts b/apps/web/src/features/block-canvas/canvas-next/context/canvas-ancestry.tsnew file mode 100644index 0000000000..5c10d760b5--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/context/canvas-ancestry.ts@@ -0,0 +1,4 @@+import { createContext } from 'solid-js';++/** Prevent document references from recursively mounting the same canvas. */+export const CanvasAncestry = createContext<readonly string[]>([]);diff --git a/apps/web/src/features/block-canvas/canvas-next/context/document-source.ts b/apps/web/src/features/block-canvas/canvas-next/context/document-source.tsnew file mode 100644index 0000000000..75aadcaf98--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/context/document-source.ts@@ -0,0 +1,7 @@+import type { CanvasFile } from '../core/document-format';++/** The document session only needs permission and a completed JSON write. */+export type CanvasDocumentSource = {+ canEdit: () => boolean;+ save: (file: CanvasFile) => Promise<Blob>;+};diff --git a/apps/web/src/features/block-canvas/canvas-next/core/assets.ts b/apps/web/src/features/block-canvas/canvas-next/core/assets.tsnew file mode 100644index 0000000000..55ec951fda--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/assets.ts@@ -0,0 +1,10 @@+import type { MediaGeometry } from '@macro-inc/graphics';+export type CanvasAsset = { id: string; name: string; fileType: string };+export type PreparedMedia = {+ type: 'image' | 'video';+ geometry: MediaGeometry;+};+export type CanvasAssetSource = {+ upload(file: File): Promise<PreparedMedia>;+ media(asset: CanvasAsset): Promise<PreparedMedia>;+};diff --git a/apps/web/src/features/block-canvas/canvas-next/core/defaults.ts b/apps/web/src/features/block-canvas/canvas-next/core/defaults.tsnew file mode 100644index 0000000000..39a4bde34d--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/defaults.ts@@ -0,0 +1,9 @@+import type { Appearance } from '@macro-inc/graphics';++export const initialAppearance: Appearance = {+ fill: 'transparent',+ stroke: 'var(--color-ink)',+ strokeWidth: 2,+ opacity: 1,+ cornerRadius: 0,+};diff --git a/apps/web/src/features/block-canvas/canvas-next/core/document-display.ts b/apps/web/src/features/block-canvas/canvas-next/core/document-display.tsnew file mode 100644index 0000000000..33752b11be--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/document-display.ts@@ -0,0 +1,33 @@+import type { GraphicsCommand } from '@macro-inc/graphics';++export const canEmbedDocument = (fileType: string) =>+ fileType === 'md' || fileType === 'canvas';++/** Presentation is durable; focus and input ownership stay local to the host. */+export const setDocumentDisplayCommand: GraphicsCommand<{+ id: string;+ display: 'preview' | 'embed';+}> = {+ id: 'set-document-display',+ apply: ({ document }, { id, display }) => {+ const item = document.items[id];+ if (+ item?.type !== 'document' ||+ (display === 'embed' && !canEmbedDocument(item.geometry.fileType)) ||+ (item.geometry.display ?? 'preview') === display+ )+ return { document };+ return {+ document: {+ ...document,+ items: {+ ...document.items,+ [id]: {+ ...item,+ geometry: { ...item.geometry, display },+ },+ },+ },+ };+ },+};diff --git a/apps/web/src/features/block-canvas/canvas-next/core/document-format.ts b/apps/web/src/features/block-canvas/canvas-next/core/document-format.tsnew file mode 100644index 0000000000..dcc6f3cb3b--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/document-format.ts@@ -0,0 +1,51 @@+import { freezeDocument, type GraphicsDocument } from '@macro-inc/graphics';+import { validCanvasTextDocument } from './text-codec';++export const CANVAS_VERSION = 2;+export type CanvasFile = Readonly<{+ version: typeof CANVAS_VERSION;+ document: GraphicsDocument;+ /** Original input is retained for recovery; it is never replayed over edits. */+ legacy?: Readonly<{+ version: 1;+ source: Record<string, unknown>;+ notes: readonly string[];+ }>;+}>;+export const isRecord = (value: unknown): value is Record<string, unknown> =>+ value !== null && typeof value === 'object' && !Array.isArray(value);++export function canvasVersion(value: unknown): 1 | 2 {+ if (!isRecord(value)) throw new Error('Invalid canvas file');+ if (value.version === undefined || value.version === 1) {+ if (+ !['nodes', 'edges', 'groups'].some((key) => key in value) &&+ Object.keys(value).some((key) => key !== 'version')+ )+ throw new Error('Unrecognized canvas format');+ return 1;+ }+ if (value.version === CANVAS_VERSION) return CANVAS_VERSION;+ throw new Error(+ `Unsupported canvas version: ${String(value.version)}. Update the app to open this canvas.`+ );+}++export function readCanvasFile(value: unknown): CanvasFile {+ if (canvasVersion(value) !== CANVAS_VERSION || !isRecord(value))+ throw new Error('Canvas needs migration');+ const document = freezeDocument(value.document as GraphicsDocument);+ if (!validCanvasTextDocument(document))+ throw new Error('Invalid canvas text');+ if (+ value.legacy !== undefined &&+ (!isRecord(value.legacy) ||+ value.legacy.version !== 1 ||+ !isRecord(value.legacy.source) ||+ !Array.isArray(value.legacy.notes) ||+ !value.legacy.notes.every((note) => typeof note === 'string'))+ )+ throw new Error('Invalid canvas migration metadata');+ // Retain same-version extension fields rather than stripping them on save.+ return { ...value, version: CANVAS_VERSION, document } as CanvasFile;+}diff --git a/apps/web/src/features/block-canvas/canvas-next/core/eraser.test.ts b/apps/web/src/features/block-canvas/canvas-next/core/eraser.test.tsnew file mode 100644index 0000000000..010dde237e--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/eraser.test.ts@@ -0,0 +1,42 @@+import {+ createGraphicsEditor,+ drawableIds,+ groupNodes,+} from '@macro-inc/graphics';+import { expect, it } from 'vitest';+import { eraseCommand, eraserHits } from './eraser';+import { createCanvasNextScene } from './seed-scene';++it('sweeps between events and finds every crossed shape, not just the topmost', () => {+ const scene = createCanvasNextScene();+ expect(eraserHits(scene, { x: 0, y: 200 }, { x: 700, y: 200 }, 6)).toEqual([+ 'welcome-rectangle',+ 'welcome-ellipse',+ ]);+ expect(eraserHits(scene, { x: 0, y: 0 }, { x: 80, y: 500 }, 6)).toEqual([]);+ // Empty ellipse interiors are not painted; its bounding box is not an eraser hit.+ expect(eraserHits(scene, { x: 490, y: 250 }, { x: 530, y: 250 }, 6)).toEqual(+ []+ );+});+it('erases a touched group as one object', () => {+ const scene = groupNodes(+ createCanvasNextScene(),+ ['welcome-rectangle', 'welcome-small'],+ 'group'+ );+ expect(eraserHits(scene, { x: 120, y: 120 }, { x: 150, y: 150 }, 6)).toEqual([+ 'group',+ ]);+});+it('undoes and redoes an entire eraser stroke in one step', () => {+ const editor = createGraphicsEditor(createCanvasNextScene());+ editor.execute(eraseCommand, ['welcome-rectangle', 'welcome-ellipse']);+ expect(drawableIds(editor.document)).toEqual(['welcome-small']);+ editor.undo();+ expect(drawableIds(editor.document)).toHaveLength(3);+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ expect(drawableIds(editor.document)).toEqual(['welcome-small']);+ editor.dispose();+});diff --git a/apps/web/src/features/block-canvas/canvas-next/core/eraser.ts b/apps/web/src/features/block-canvas/canvas-next/core/eraser.tsnew file mode 100644index 0000000000..c6c9718798--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/eraser.ts@@ -0,0 +1,76 @@+import {+ deleteSubtrees,+ drawableIds,+ type GraphicsCommand,+ type GraphicsDocument,+ inverse,+ outermost,+ type Point,+ resolveAppearance,+ resolvedShape,+ shapeDefinition,+ transformPoint,+ worldBounds,+ worldMatrix,+} from '@macro-inc/graphics';++/** Sample the entire swept path, including fast moves between pointer events. */+export function eraserHits(+ document: GraphicsDocument,+ from: Point,+ to: Point,+ radius: number,+ excluded: ReadonlySet<string> = new Set()+): string[] {+ const hits = new Set<string>();+ const steps = Math.max(+ 1,+ Math.ceil(Math.hypot(to.x - from.x, to.y - from.y) / (radius / 2))+ );+ for (const id of drawableIds(document)) {+ const root = outermost(document, id);+ if (excluded.has(root)) continue;+ const item = resolvedShape(document, id)!;+ const worldTransform = worldMatrix(document, id);+ const padding =+ radius ++ (resolveAppearance(item.appearance).strokeWidth / 2) *+ Math.max(+ Math.hypot(worldTransform[0], worldTransform[1]),+ Math.hypot(worldTransform[2], worldTransform[3])+ );+ const bounds = worldBounds(document, id);+ if (+ bounds.x > Math.max(from.x, to.x) + padding ||+ bounds.y > Math.max(from.y, to.y) + padding ||+ bounds.x + bounds.width < Math.min(from.x, to.x) - padding ||+ bounds.y + bounds.height < Math.min(from.y, to.y) - padding+ )+ continue;+ const local = inverse(worldTransform);+ for (let i = 0; i <= steps; i++) {+ const point = {+ x: from.x + ((to.x - from.x) * i) / steps,+ y: from.y + ((to.y - from.y) * i) / steps,+ };+ if (+ shapeDefinition(item.type).hitTest(item, transformPoint(local, point), {+ worldTransform,+ tolerance: radius,+ })+ ) {+ hits.add(root);+ break;+ }+ }+ }+ return [...hits];+}++export const eraseCommand: GraphicsCommand<readonly string[]> = {+ id: 'canvas.erase',+ apply: ({ document }, ids) => ({+ document: ids.length ? deleteSubtrees(document, ids) : document,+ selection: [],+ }),+};diff --git a/apps/web/src/features/block-canvas/canvas-next/core/excalidraw.test.ts b/apps/web/src/features/block-canvas/canvas-next/core/excalidraw.test.tsnew file mode 100644index 0000000000..baffdcc6ef--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/excalidraw.test.ts@@ -0,0 +1,354 @@+import {+ children,+ createGraphicsEditor,+ drawableIds,+ pasteCommand,+} from '@macro-inc/graphics';+import { expect, it } from 'vitest';+import { importExcalidraw } from './excalidraw';+import { richTextPlainText } from './text-codec';++const wrap = (elements: unknown[], type = 'excalidraw/clipboard') =>+ JSON.stringify({ type, elements });++const shape = (overrides: Record<string, unknown>) => ({+ id: 'shape',+ type: 'rectangle',+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ angle: 0,+ strokeColor: '#1e1e1e',+ backgroundColor: 'transparent',+ strokeWidth: 2,+ strokeStyle: 'solid',+ opacity: 100,+ groupIds: [],+ isDeleted: false,+ ...overrides,+});++it('rejects payloads that are not Excalidraw scenes', () => {+ expect(importExcalidraw('not json')).toBeUndefined();+ expect(+ importExcalidraw(JSON.stringify({ kind: 'macro-graphics-fragment' }))+ ).toBeUndefined();+ expect(importExcalidraw(wrap([]))).toBeUndefined();+ expect(+ importExcalidraw(JSON.stringify({ type: 'excalidraw' }))+ ).toBeUndefined();+});++it('accepts both file and clipboard envelopes', () => {+ expect(importExcalidraw(wrap([shape({})], 'excalidraw'))?.imported).toBe(1);+ expect(+ importExcalidraw(wrap([shape({})], 'excalidraw/clipboard'))?.imported+ ).toBe(1);+});++it('maps shapes, position/rotation, fill, stroke and corner radius', () => {+ const result = importExcalidraw(+ wrap([+ shape({+ id: 'rect',+ x: 100,+ y: 200,+ width: 40,+ height: 20,+ backgroundColor: '#a5d8ff',+ strokeColor: '#1971c2',+ strokeWidth: 4,+ strokeStyle: 'dashed',+ opacity: 50,+ roundness: { type: 3, value: 8 },+ }),+ shape({ id: 'oval', type: 'ellipse', x: 10, y: 10 }),+ ])+ );+ const scene = result!.fragment.scene;+ const rect = scene.items.rect!;+ expect(rect.type).toBe('rectangle');+ if (rect.type !== 'rectangle') throw new Error('unreachable');+ // angle 0 keeps the top-left translation.+ expect(rect.transform[4]).toBe(100);+ expect(rect.transform[5]).toBe(200);+ expect(rect.appearance).toMatchObject({+ fill: '#a5d8ff',+ stroke: '#1971c2',+ strokeWidth: 4,+ strokeStyle: 'dashed',+ opacity: 0.5,+ cornerRadius: 8,+ });+ expect(scene.items.oval!.type).toBe('ellipse');+});++it('rotates around the element center like Excalidraw', () => {+ const result = importExcalidraw(+ wrap([+ shape({+ id: 'r',+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ angle: Math.PI / 2,+ }),+ ])+ );+ const r = result!.fragment.scene.items.r!;+ if (r.type === 'surface') throw new Error('unreachable');+ // A quarter turn about the center maps local (0,0) to world (100,0).+ expect(Math.round(r.transform[4])).toBe(100);+ expect(Math.round(r.transform[5])).toBe(0);+});++it('converts standalone text and folds container-bound text into a label', () => {+ const result = importExcalidraw(+ wrap([+ shape({+ id: 'note',+ type: 'text',+ text: 'Hello\nworld',+ fontSize: 24,+ textAlign: 'center',+ }),+ shape({ id: 'box', width: 120, height: 60 }),+ shape({+ id: 'caption',+ type: 'text',+ text: 'Inside',+ containerId: 'box',+ fontSize: 16,+ }),+ ])+ );+ const scene = result!.fragment.scene;+ const note = scene.items.note!;+ if (note.type !== 'text') throw new Error('unreachable');+ expect(note.geometry.fontSize).toBe(24);+ expect(richTextPlainText(note.geometry.content)).toBe('Hello\nworld');+ // The container text is consumed as a label, not a standalone item.+ expect(scene.items.caption).toBeUndefined();+ const box = scene.items.box!;+ if (box.type !== 'rectangle') throw new Error('unreachable');+ expect(richTextPlainText(box.geometry.label!.content)).toBe('Inside');+});++it('converts arrows to connectors with heads and only keeps resolvable bindings', () => {+ const result = importExcalidraw(+ wrap([+ shape({ id: 'target', width: 50, height: 50 }),+ shape({+ id: 'link',+ type: 'arrow',+ x: 10,+ y: 10,+ points: [+ [0, 0],+ [40, 30],+ ],+ startBinding: { elementId: 'target' },+ endBinding: { elementId: 'missing' },+ }),+ ])+ );+ const connector = result!.fragment.scene.items.link!;+ if (connector.type !== 'connector') throw new Error('unreachable');+ expect(connector.geometry.endHead).toBe('arrow');+ expect(connector.geometry.start.point).toEqual({ x: 0, y: 0 });+ expect(connector.geometry.end.point).toEqual({ x: 40, y: 30 });+ expect(connector.geometry.start.binding?.targetId).toBe('target');+ expect(connector.geometry.end.binding).toBeUndefined();+});++it('converts freedraw strokes to pencil samples with pressure', () => {+ const result = importExcalidraw(+ wrap([+ shape({+ id: 'ink',+ type: 'freedraw',+ points: [+ [0, 0],+ [5, 5],+ [10, 2],+ ],+ pressures: [0.1, 0.5, 0.9],+ simulatePressure: false,+ }),+ ])+ );+ const ink = result!.fragment.scene.items.ink!;+ if (ink.type !== 'pencil') throw new Error('unreachable');+ expect(ink.geometry.simulatePressure).toBe(false);+ expect(ink.geometry.points).toEqual([+ [0, 0, 0.1],+ [5, 5, 0.5],+ [10, 2, 0.9],+ ]);+});++it('rebuilds nested groups into the local-transform tree', () => {+ const result = importExcalidraw(+ wrap([+ shape({ id: 'a', groupIds: ['inner', 'outer'] }),+ shape({ id: 'b', groupIds: ['inner', 'outer'] }),+ shape({ id: 'c', groupIds: ['outer'] }),+ shape({ id: 'loose', groupIds: [] }),+ ])+ );+ const scene = result!.fragment.scene;+ expect(scene.items.outer!.type).toBe('group');+ expect(scene.items.inner!.type).toBe('group');+ // outer and loose sit at the root; inner nests under outer; a/b under inner.+ expect([...children(scene)].sort()).toEqual(['loose', 'outer']);+ expect(children(scene, 'outer')).toContain('inner');+ expect(children(scene, 'outer')).toContain('c');+ expect([...children(scene, 'inner')].sort()).toEqual(['a', 'b']);+});++it('approximates diamonds and drops unsupported elements', () => {+ const result = importExcalidraw(+ wrap([+ shape({ id: 'd', type: 'diamond' }),+ shape({ id: 'pic', type: 'image', fileId: 'x' }),+ shape({ id: 'frame', type: 'frame' }),+ ])+ );+ expect(result!.imported).toBe(1);+ expect(result!.approximated).toBe(1);+ expect(result!.skipped).toBe(2);+ expect(result!.fragment.scene.items.d!.type).toBe('rectangle');+});++it('produces a fragment the paste command can insert', () => {+ const result = importExcalidraw(+ wrap([+ shape({ id: 'a', groupIds: ['g'] }),+ shape({ id: 'b', type: 'ellipse', groupIds: ['g'] }),+ ])+ );+ const editor = createGraphicsEditor();+ let next = 0;+ editor.execute(pasteCommand, {+ fragment: result!.fragment,+ createId: () => `paste-${next++}`,+ });+ expect(drawableIds(editor.document)).toHaveLength(2);+ editor.dispose();+});++it.each(['arrow', 'line'])(+ 'imports bound text as a native %s connector label',+ (type) => {+ const result = importExcalidraw(+ wrap([+ shape({+ id: 'link',+ type,+ points: [+ [0, 0],+ [200, 50],+ ],+ groupIds: ['g'],+ }),+ shape({+ id: 'caption',+ type: 'text',+ containerId: 'link',+ text: 'Connects\nto',+ fontSize: 18,+ fontFamily: 3,+ width: 90,+ height: 45,+ textAlign: 'center',+ }),+ ])+ )!;+ expect(result.imported).toBe(1);+ expect(result.skipped).toBe(0);+ expect(result.fragment.scene.items.caption).toBeUndefined();+ const item = result.fragment.scene.items.link;+ if (item?.type !== 'connector') throw Error();+ expect(item.geometry.label).toMatchObject({+ fontSize: 18,+ fontFamily: 'mono',+ width: 90,+ height: 45,+ });+ expect(richTextPlainText(item.geometry.label!.content)).toBe(+ 'Connects\nto'+ );+ const editor = createGraphicsEditor();+ try {+ let next = 0;+ editor.execute(pasteCommand, {+ fragment: result.fragment,+ createId: () => `label-${next++}`,+ });+ const copied = editor.document.items[drawableIds(editor.document)[0]!];+ expect(copied).toMatchObject({+ type: 'connector',+ geometry: { label: item.geometry.label },+ });+ } finally {+ editor.dispose();+ }+ }+);++it.each([+ { roundness: { type: 2 }, expected: 'smooth' },+ { elbowed: true, expected: 'stepped' },+ { expected: 'straight' },+])(+ 'keeps $expected routing only when both imported bindings resolve',+ ({ expected, ...route }) => {+ for (const [start, end, doublyBound] of [+ [undefined, undefined, false],+ ['a', undefined, false],+ [undefined, 'b', false],+ ['a', 'missing', false],+ ['a', 'unsupported', false],+ ['a', 'b', true],+ ] as const) {+ const result = importExcalidraw(+ wrap([+ shape({ id: 'a' }),+ shape({ id: 'b', x: 300 }),+ shape({ id: 'unsupported', type: 'image' }),+ shape({+ id: 'link',+ type: 'arrow',+ points: [+ [0, 0],+ [200, 50],+ ],+ startBinding: start ? { elementId: start } : null,+ endBinding: end ? { elementId: end } : null,+ ...route,+ }),+ ])+ )!;+ expect(result.fragment.scene.items.link).toMatchObject({+ geometry: { route: doublyBound ? expected : 'straight' },+ });+ }+ }+);++it('keeps text standalone when its connector cannot be imported', () => {+ const result = importExcalidraw(+ wrap([+ shape({ id: 'link', type: 'arrow', points: [] }),+ shape({+ id: 'caption',+ type: 'text',+ containerId: 'link',+ text: 'Still here',+ }),+ ])+ )!;+ expect(result.fragment.scene.items.caption?.type).toBe('text');+});diff --git a/apps/web/src/features/block-canvas/canvas-next/core/excalidraw.ts b/apps/web/src/features/block-canvas/canvas-next/core/excalidraw.tsnew file mode 100644index 0000000000..cffa377081--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/excalidraw.ts@@ -0,0 +1,510 @@+import {+ type Appearance,+ type ConnectorAnchor,+ type ConnectorHead,+ type ConnectorRoute,+ freezeDocument,+ type GraphicsDocument,+ type GraphicsFragment,+ type GraphicsItem,+ type GroupItem,+ IDENTITY,+ type Matrix,+ multiply,+ type PencilPoint,+ rotation,+ type ShapeItem,+ type ShapeLabel,+ sortKeysBetween,+ type TextFont,+ translation,+} from '@macro-inc/graphics';+import { plainRichText, type TextAlign } from './text-codec';++/**+ * Excalidraw interop (import only).+ *+ * Converts an Excalidraw `.excalidraw` file or `excalidraw/clipboard` payload+ * into a native graphics {@link GraphicsFragment} so the existing paste command+ * can insert it. Pure and host-free: no DOM, uploads or document mutation.+ *+ * Excalidraw's flat `groupIds` membership is rebuilt into our nested+ * local-transform tree using identity-transform group nodes, so every element+ * keeps its world transform. Container-bound text collapses into the host+ * shape's label. Unsupported elements (images, frames, embeds) are dropped and+ * reported; diamonds are approximated as rectangles.+ */++const SCENE_ROOT = 'scene-root';+const MAX_ELEMENTS = 5000;+const MAX_PENCIL_POINTS = 16384;+/** Excalidraw's `FONT_FAMILY.Cascadia` (code) is our only monospace match. */+const EXCALIDRAW_CODE_FONT = 3;++export type ExcalidrawImport = Readonly<{+ fragment: GraphicsFragment;+ /** Elements placed into the scene. */+ imported: number;+ /** Unsupported elements dropped (images, frames, embeddables, …). */+ skipped: number;+ /** Elements converted with reduced fidelity (diamonds → rectangles). */+ approximated: number;+}>;++type Raw = Record<string, unknown>;++const isRecord = (value: unknown): value is Raw =>+ !!value && typeof value === 'object' && !Array.isArray(value);+const num = (value: unknown, fallback = 0): number =>+ typeof value === 'number' && Number.isFinite(value) ? value : fallback;+const str = (value: unknown, fallback = ''): string =>+ typeof value === 'string' ? value : fallback;+const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));++/** Accepts both the `.excalidraw` file and `excalidraw/clipboard` envelopes. */+export function importExcalidraw(text: string): ExcalidrawImport | undefined {+ if (typeof text !== 'string' || text.length > 2_000_000) return;+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch {+ return;+ }+ if (!isRecord(parsed)) return;+ if (parsed.type !== 'excalidraw' && parsed.type !== 'excalidraw/clipboard')+ return;+ const elements = parsed.elements;+ if (+ !Array.isArray(elements) ||+ elements.length === 0 ||+ elements.length > MAX_ELEMENTS+ )+ return;+ return convertElements(elements);+}++/** Every reconstructed node carries placement; the surface root is added last. */+type SceneNode = ShapeItem | GroupItem;++type Draft = {+ readonly node: SceneNode;+ parentId: string;+ readonly order: number;+};++function convertElements(+ elements: readonly unknown[]+): ExcalidrawImport | undefined {+ const raw = elements+ .filter(isRecord)+ .filter((el) => el.isDeleted !== true && !!str(el.id));++ // Container-bound text becomes the host shape's label, not a standalone item.+ const labelHosts = new Set(+ raw+ .filter(+ (el) =>+ ['rectangle', 'ellipse', 'diamond'].includes(str(el.type)) ||+ (['line', 'arrow'].includes(str(el.type)) &&+ connectorGeometry(el, new Set()) !== undefined)+ )+ .map((el) => str(el.id))+ );+ const boundText = new Map<string, Raw>();+ for (const el of raw) {+ const container = str(el.containerId);+ if (+ el.type === 'text' &&+ labelHosts.has(container) &&+ !boundText.has(container)+ )+ boundText.set(container, el);+ }+ const consumedText = new Set([...boundText.values()].map((el) => str(el.id)));++ // Connectors may only bind to shapes that actually enter the scene.+ const bindable = new Set(+ raw+ .filter((el) => {+ const type = str(el.type);+ if (type === 'text') return !consumedText.has(str(el.id));+ return ['rectangle', 'ellipse', 'diamond'].includes(type);+ })+ .map((el) => str(el.id))+ );++ const chainOf = (el: Raw, id: string): string[] =>+ Array.isArray(el.groupIds)+ ? el.groupIds.filter(+ (g): g is string =>+ typeof g === 'string' && !!g && g !== SCENE_ROOT && g !== id+ )+ : [];++ // Paint order follows the source array; a group ranks with its earliest member.+ const order = new Map<string, number>();+ raw.forEach((el, index) => {+ const id = str(el.id);+ order.set(id, index);+ for (const group of chainOf(el, id))+ order.set(group, Math.min(order.get(group) ?? Infinity, index));+ });++ const drafts = new Map<string, Draft>();+ const groupParent = new Map<string, string>();+ const includedGroups = new Set<string>();+ let imported = 0;+ let skipped = 0;+ let approximated = 0;++ raw.forEach((el, index) => {+ const id = str(el.id);+ if (consumedText.has(id)) return;+ const built = buildNode(el, id, boundText.get(id), bindable);+ if (!built) {+ skipped++;+ return;+ }+ imported++;+ if (built.approximated) approximated++;+ const chain = chainOf(el, id);+ for (let i = 0; i < chain.length; i++) {+ includedGroups.add(chain[i]!);+ if (!groupParent.has(chain[i]!))+ groupParent.set(chain[i]!, chain[i + 1] ?? SCENE_ROOT);+ }+ drafts.set(id, {+ node: built.node,+ parentId: chain[0] ?? SCENE_ROOT,+ order: index,+ });+ });++ if (imported === 0) return;++ // An element id must never collide with a reconstructed group id.+ const groupIds = new Set([...includedGroups].filter((id) => !drafts.has(id)));+ for (const id of groupIds)+ drafts.set(id, {+ node: {+ id,+ type: 'group',+ transform: IDENTITY,+ placement: { parentId: SCENE_ROOT, sortKey: 'a0' },+ },+ parentId: groupParent.get(id) ?? SCENE_ROOT,+ order: order.get(id) ?? 0,+ });++ // Resolve parents to a valid group or the root, then allocate sibling keys.+ const resolveParent = (parentId: string) =>+ parentId === SCENE_ROOT || groupIds.has(parentId) ? parentId : SCENE_ROOT;+ const byParent = new Map<string, string[]>();+ for (const [id, draft] of drafts) {+ const parentId = resolveParent(draft.parentId);+ draft.parentId = parentId;+ (byParent.get(parentId) ?? byParent.set(parentId, []).get(parentId)!).push(+ id+ );+ }++ const items: Record<string, GraphicsItem> = {+ [SCENE_ROOT]: { id: SCENE_ROOT, type: 'surface' },+ };+ for (const [parentId, siblings] of byParent) {+ siblings.sort((a, b) => {+ const left = drafts.get(a)!.order;+ const right = drafts.get(b)!.order;+ return left - right || (a < b ? -1 : a > b ? 1 : 0);+ });+ const keys = sortKeysBetween(null, null, siblings.length);+ siblings.forEach((id, i) => {+ const { node } = drafts.get(id)!;+ items[id] = { ...node, placement: { parentId, sortKey: keys[i]! } };+ });+ }++ const scene: GraphicsDocument = freezeDocument({ rootId: SCENE_ROOT, items });+ return {+ fragment: { kind: 'macro-graphics-fragment', scene },+ imported,+ skipped,+ approximated,+ };+}++type BuiltNode = { node: SceneNode; approximated: boolean };++function buildNode(+ el: Raw,+ id: string,+ label: Raw | undefined,+ bindable: ReadonlySet<string>+): BuiltNode | undefined {+ const transform = elementTransform(el);+ const placement = { parentId: SCENE_ROOT, sortKey: 'a0' };+ switch (str(el.type)) {+ case 'rectangle':+ case 'diamond': {+ const diamond = el.type === 'diamond';+ const width = Math.max(1, num(el.width, 1));+ const height = Math.max(1, num(el.height, 1));+ return {+ node: {+ id,+ type: 'rectangle',+ transform,+ placement,+ geometry: {+ width,+ height,+ ...(label ? { label: labelGeometry(label) } : {}),+ },+ appearance: appearanceOf(el, {+ cornerRadius: diamond ? 0 : cornerRadius(el, width, height),+ }),+ },+ approximated: diamond,+ };+ }+ case 'ellipse': {+ const width = Math.max(1, num(el.width, 1));+ const height = Math.max(1, num(el.height, 1));+ return {+ node: {+ id,+ type: 'ellipse',+ transform,+ placement,+ geometry: {+ width,+ height,+ ...(label ? { label: labelGeometry(label) } : {}),+ },+ appearance: appearanceOf(el),+ },+ approximated: false,+ };+ }+ case 'text': {+ const fontSize = clamp(num(el.fontSize, 20), 1, 10000);+ return {+ node: {+ id,+ type: 'text',+ transform,+ placement,+ geometry: {+ width: Math.max(1, num(el.width, fontSize)),+ height: Math.max(1, num(el.height, fontSize)),+ autoWidth: false,+ fontSize,+ fontFamily: fontOf(el),+ content: plainRichText(str(el.text), alignOf(el)),+ },+ appearance: appearanceOf(el, { fill: false }),+ },+ approximated: false,+ };+ }+ case 'freedraw': {+ const points = freedrawPoints(el);+ if (!points.length) return;+ return {+ node: {+ id,+ type: 'pencil',+ transform,+ placement,+ geometry: {+ points,+ simulatePressure:+ !Array.isArray(el.pressures) || el.pressures.length === 0+ ? el.simulatePressure !== false+ : false,+ },+ appearance: appearanceOf(el, { fill: false }),+ },+ approximated: false,+ };+ }+ case 'line':+ case 'arrow': {+ const geometry = connectorGeometry(el, bindable);+ if (!geometry) return;+ return {+ node: {+ id,+ type: 'connector',+ transform,+ placement,+ geometry: {+ ...geometry,+ ...(label+ ? {+ label: {+ ...labelGeometry(label),+ width: Math.max(1, num(label.width, 240)),+ },+ }+ : {}),+ },+ appearance: appearanceOf(el, { fill: false }),+ },+ approximated: false,+ };+ }+ default:+ return;+ }+}++/** Excalidraw places the top-left at (x, y) and rotates around the center. */+function elementTransform(el: Raw): Matrix {+ const x = num(el.x);+ const y = num(el.y);+ const width = num(el.width);+ const height = num(el.height);+ const angle = num(el.angle);+ return multiply(+ translation(x + width / 2, y + height / 2),+ multiply(rotation(angle), translation(-width / 2, -height / 2))+ );+}++function appearanceOf(+ el: Raw,+ options: { fill?: boolean; cornerRadius?: number } = {}+): Appearance {+ const background = str(el.backgroundColor, 'transparent');+ const strokeStyle = str(el.strokeStyle);+ return {+ fill:+ options.fill === false || !background || background === 'transparent'+ ? 'transparent'+ : background,+ stroke: str(el.strokeColor, '#1e1e1e') || 'transparent',+ strokeWidth: Math.max(0, num(el.strokeWidth, 2)),+ strokeStyle:+ strokeStyle === 'dashed' || strokeStyle === 'dotted'+ ? strokeStyle+ : 'solid',+ opacity: clamp(num(el.opacity, 100) / 100, 0, 1),+ ...(options.cornerRadius !== undefined+ ? { cornerRadius: Math.max(0, options.cornerRadius) }+ : {}),+ };+}++function cornerRadius(el: Raw, width: number, height: number): number {+ if (!isRecord(el.roundness)) return 0;+ const value = num(el.roundness.value, NaN);+ return Number.isFinite(value)+ ? Math.max(0, value)+ : Math.min(32, Math.min(width, height) * 0.25);+}++function fontOf(el: Raw): TextFont {+ return num(el.fontFamily) === EXCALIDRAW_CODE_FONT ? 'mono' : 'sans';+}++function alignOf(el: Raw): TextAlign {+ const align = str(el.textAlign);+ return align === 'center' || align === 'right' ? align : 'left';+}++function labelGeometry(el: Raw): ShapeLabel {+ const fontSize = clamp(num(el.fontSize, 20), 1, 10000);+ return {+ content: plainRichText(str(el.text), alignOf(el)),+ fontSize,+ fontFamily: fontOf(el),+ height: Math.max(1, num(el.height, fontSize)),+ };+}++function freedrawPoints(el: Raw): PencilPoint[] {+ const points = Array.isArray(el.points) ? el.points : [];+ const pressures = Array.isArray(el.pressures) ? el.pressures : [];+ return points+ .filter(+ (point): point is number[] =>+ Array.isArray(point) &&+ point.length >= 2 &&+ Number.isFinite(point[0]) &&+ Number.isFinite(point[1])+ )+ .slice(0, MAX_PENCIL_POINTS)+ .map((point, i) => {+ const pressure = Number.isFinite(pressures[i])+ ? clamp(pressures[i] as number, 0, 1)+ : point.length >= 3 && Number.isFinite(point[2])+ ? clamp(point[2]!, 0, 1)+ : 0.5;+ return [point[0]!, point[1]!, pressure] as PencilPoint;+ });+}++function connectorGeometry(el: Raw, bindable: ReadonlySet<string>) {+ const points = (Array.isArray(el.points) ? el.points : []).filter(+ (point): point is number[] =>+ Array.isArray(point) &&+ point.length >= 2 &&+ Number.isFinite(point[0]) &&+ Number.isFinite(point[1])+ );+ if (points.length < 2) return;+ const first = points[0]!;+ const last = points[points.length - 1]!;+ const arrow = el.type === 'arrow';+ const anchor: ConnectorAnchor = 'center';+ const binding = (value: unknown) => {+ const targetId = isRecord(value) ? str(value.elementId) : '';+ return targetId && bindable.has(targetId)+ ? { binding: { targetId, anchor } }+ : {};+ };+ const startBinding = binding(el.startBinding);+ const endBinding = binding(el.endBinding);+ return {+ start: {+ point: { x: first[0]!, y: first[1]! },+ ...startBinding,+ },+ end: { point: { x: last[0]!, y: last[1]! }, ...endBinding },+ route:+ startBinding.binding && endBinding.binding+ ? routeOf(el)+ : ('straight' as const),+ startHead: headOf(el.startArrowhead, 'none'),+ endHead: headOf(el.endArrowhead, arrow ? 'arrow' : 'none'),+ };+}++function routeOf(el: Raw): ConnectorRoute {+ if (el.elbowed === true) return 'stepped';+ if (isRecord(el.roundness)) return 'smooth';+ return 'straight';+}++function headOf(value: unknown, fallback: ConnectorHead): ConnectorHead {+ if (value === null) return 'none';+ if (value === undefined) return fallback;+ switch (value) {+ case 'arrow':+ return 'arrow';+ case 'triangle':+ case 'triangle_outline':+ case 'diamond':+ case 'diamond_outline':+ return 'arrow-filled';+ case 'dot':+ case 'circle':+ return 'circle';+ case 'circle_outline':+ return 'circle-small';+ default:+ return 'arrow';+ }+}diff --git a/apps/web/src/features/block-canvas/canvas-next/core/load-document.ts b/apps/web/src/features/block-canvas/canvas-next/core/load-document.tsnew file mode 100644index 0000000000..cd0e33b390--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/load-document.ts@@ -0,0 +1,44 @@+import {+ type CanvasFile,+ canvasVersion,+ readCanvasFile,+} from './document-format';+import { type LegacyTextCodec, migrateLegacyCanvas } from './migrate-legacy';++export type CanvasLoadResult =+ | { kind: 'legacy' }+ | { kind: 'next'; file: CanvasFile }+ | { kind: 'error'; message: string; canOpenLegacy: boolean };++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+ ? readCanvasFile(value)+ : migrateLegacyCanvas(value, text),+ };+ } catch (error) {+ 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/canvas-next/core/migrate-legacy.test.tsnew file mode 100644index 0000000000..191e347278--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.test.ts@@ -0,0 +1,308 @@+import {+ createGraphicsEditor,+ drawableIds,+ setShapeLabelCommand,+} from '@macro-inc/graphics';+import { describe, expect, it, vi } from 'vitest';+import { readCanvasFile } from './document-format';+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',+ shape: 'rectangle',+ x: 20,+ y: 30,+ width: 120,+ height: 80,+ ...extra,+});++describe('versioned canvas migration', () => {+ it('keeps connector anchors on the same visual side of flipped media', () => {+ const file = migrateLegacyCanvas(+ {+ nodes: [+ {+ ...shape('image'),+ type: 'image',+ uuid: 'stored-image',+ flipX: true,+ flipY: true,+ },+ ],+ edges: [+ {+ id: 'edge',+ from: { type: 'connected', node: 'image', side: 'left' },+ to: { type: 'connected', node: 'image', side: 'bottom' },+ },+ ],+ },+ plainRichText+ );+ expect(file.document.items.edge).toMatchObject({+ geometry: {+ start: { binding: { anchor: 'right' } },+ end: { binding: { anchor: 'top' } },+ },+ });+ });+ it('preserves identity, geometry, order, group membership, labels, bindings and sources', () => {+ const source = {+ nodes: [+ shape('box', { groupId: 'group', label: 'Label', sortOrder: 1 }),+ {+ id: 'image',+ type: 'image',+ uuid: 'stored-image',+ status: 'dss',+ x: 200,+ y: 10,+ width: 40,+ height: 50,+ flipX: true,+ layer: 2,+ },+ ],+ groups: [{ id: 'group', childNodes: ['box'] }],+ edges: [+ {+ id: 'edge',+ from: { type: 'connected', node: 'box', side: 'right' },+ to: { type: 'free', x: 500, y: 100 },+ style: { toEndStyle: 'arrow', connectionStyle: 'smooth' },+ },+ ],+ };+ const before = structuredClone(source);+ const file = migrateLegacyCanvas(source, plainRichText);+ expect(source).toEqual(before);+ expect(file.legacy?.source).toEqual(before);+ expect(drawableIds(file.document)).toEqual(['box', 'edge', 'image']);+ expect(file.document.items.box).toMatchObject({+ placement: { parentId: 'group' },+ transform: [1, 0, 0, 1, 20, 30],+ geometry: {+ width: 120,+ height: 80,+ label: { content: plainRichText('Label', 'center') },+ },+ });+ expect(file.document.items.image).toMatchObject({+ transform: [-1, 0, 0, 1, 240, 10],+ geometry: { source: { type: 'document', id: 'stored-image' } },+ });+ expect(file.document.items.edge).toMatchObject({+ geometry: {+ start: { binding: { targetId: 'box', anchor: 'right' } },+ endHead: 'arrow',+ route: 'smooth',+ },+ });+ expect(readCanvasFile(JSON.parse(JSON.stringify(file)))).toEqual(file);+ });++ it('retains same-version extension fields through validation and freezing', () => {+ const file = migrateLegacyCanvas(+ {+ nodes: [+ shape('box'),+ {+ ...shape('pencil'),+ type: 'pencil',+ coords: [[1, 2]],+ wScale: 1,+ hScale: 1,+ },+ ],+ },+ plainRichText+ );+ const serialized = JSON.parse(JSON.stringify(file));+ const futureBox = { mode: 'v3' };+ serialized.document.items.box.geometry.futureBox = futureBox;+ serialized.document.items.pencil.geometry.futureInk = true;+ const read = readCanvasFile(serialized);+ expect(read.document.items.box).toMatchObject({+ geometry: { futureBox: { mode: 'v3' } },+ });+ expect(read.document.items.pencil).toMatchObject({+ geometry: { futureInk: true },+ });+ futureBox.mode = 'mutated';+ expect(read.document.items.box).toMatchObject({+ geometry: { futureBox: { mode: 'v3' } },+ });+ expect(+ Object.isFrozen(+ (+ read.document.items.box as unknown as {+ geometry: { futureBox: object };+ }+ ).geometry.futureBox+ )+ ).toBe(true);+ });++ it('migrates old file references without mutating the legacy preprocessing input', () => {+ const source = {+ nodes: [{ ...shape('reference'), type: 'file', file: 'doc-id' }],+ };+ const file = migrateLegacyCanvas(source, plainRichText);+ expect(source.nodes[0].type).toBe('file');+ expect(file.document.items.reference).toMatchObject({+ type: 'document',+ geometry: {+ documentId: 'doc-id',+ entityType: 'document',+ fileType: 'unknown',+ },+ });+ });++ it.each(['document', 'chat', 'project', 'channel', 'email', 'call'] as const)(+ 'migrates %s entity references',+ (entityType) => {+ const file = migrateLegacyCanvas(+ {+ nodes: [+ shape('reference', {+ type: 'entitymention',+ entityType,+ file: `${entityType}-id`,+ subpath: 'retained-location',+ }),+ ],+ },+ plainRichText+ );+ expect(file.document.items.reference).toMatchObject({+ type: 'document',+ geometry: {+ documentId: `${entityType}-id`,+ entityType,+ fileType: entityType === 'document' ? 'unknown' : entityType,+ subpath: 'retained-location',+ },+ });+ }+ );++ it('uses the supplied Markdown importer and preserves pencil coordinates', () => {+ const text = vi.fn(() => plainRichText('Rich text'));+ const file = migrateLegacyCanvas(+ {+ nodes: [+ { ...shape('text'), type: 'text', text: '**Rich text**' },+ {+ ...shape('pencil'),+ type: 'pencil',+ coords: [+ [1, 2],+ [3, 4],+ ],+ wScale: 2,+ hScale: 3,+ },+ ],+ },+ text+ );+ expect(text).toHaveBeenCalledWith('**Rich text**');+ expect(file.document.items.pencil).toMatchObject({+ geometry: {+ points: [+ [2, 6, 0.5],+ [6, 12, 0.5],+ ],+ },+ });+ });++ it('never migrates a v2 document again or replays its archived legacy data', () => {+ const file = migrateLegacyCanvas({ nodes: [shape()] }, plainRichText);+ const editor = createGraphicsEditor(file.document);+ editor.execute(setShapeLabelCommand, {+ id: 'box',+ label: {+ content: plainRichText('Edited'),+ fontSize: 20,+ fontFamily: 'sans',+ height: 27,+ },+ });+ 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(text).not.toHaveBeenCalled();+ editor.dispose();+ });++ it.each([undefined, 1])(+ 'opens legacy version %s unchanged with the flag off',+ (version) => {+ const text = vi.fn();+ expect(+ loadCanvasFile({ version, nodes: [shape()] }, false, text)+ ).toEqual({ kind: 'legacy' });+ expect(text).not.toHaveBeenCalled();+ }+ );++ it.each([2, 3, '2', null])(+ 'protects version %s from the legacy editor',+ (version) => {+ expect(loadCanvasFile({ version }, false, plainRichText)).toMatchObject({+ kind: 'error',+ canOpenLegacy: false,+ });+ }+ );++ it.each([+ { nodes: [shape('duplicate'), shape('duplicate')] },+ { nodes: [shape('unknown', { type: 'future-shape' })] },+ { nodes: [shape('link', { type: 'link', url: 'https://macro.com' })] },+ {+ edges: [+ {+ id: 'edge',+ from: { type: 'connected', node: 'missing', side: 'top' },+ to: { type: 'free', x: 0, y: 0 },+ },+ ],+ },+ ])(+ 'offers the original legacy editor instead of discarding unsupported records (%j)',+ (source) => {+ expect(loadCanvasFile(source, true, plainRichText)).toMatchObject({+ kind: 'error',+ canOpenLegacy: true,+ });+ }+ );++ it('rejects malformed v2 files without a legacy fallback', () => {+ expect(+ loadCanvasFile({ version: 2, document: {} }, true, plainRichText)+ ).toMatchObject({ kind: 'error', canOpenLegacy: false });+ });++ it('handles empty canvases and root-id collisions', () => {+ expect(+ Object.keys(migrateLegacyCanvas({}, plainRichText).document.items)+ ).toHaveLength(1);+ const file = migrateLegacyCanvas(+ { nodes: [shape('scene-root')] },+ plainRichText+ );+ expect(file.document.rootId).not.toBe('scene-root');+ expect(file.document.items['scene-root']?.type).toBe('rectangle');+ });+});diff --git a/apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.ts b/apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.tsnew file mode 100644index 0000000000..4c196391de--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/migrate-legacy.ts@@ -0,0 +1,405 @@+import {+ type Appearance,+ type ConnectorEndpoint,+ freezeDocument,+ type GraphicsItem,+ type ShapeItem,+ sortKeysBetween,+ translation,+} from '@macro-inc/graphics';+import { match } from 'ts-pattern';+import {+ type Canvas,+ type CanvasEntityStyle,+ CanvasSchema,+ type EdgeEnd,+} from '../../model/CanvasModel';+import { CANVAS_VERSION, type CanvasFile, isRecord } from './document-format';+import {+ plainRichText,+ validCanvasText,+ validCanvasTextDocument,+} from './text-codec';++type LegacyNode = NonNullable<Canvas['nodes']>[number];+type LegacyEdge = NonNullable<Canvas['edges']>[number];+type LegacyGroup = NonNullable<Canvas['groups']>[number];+type Placement = { parentId: string; sortKey: string };+export type LegacyTextCodec = (markdown: string) => string;++function appearance(+ style: CanvasEntityStyle | undefined,+ shape = false+): Appearance {+ const fill = style?.fillColor ?? '#e5e7eb';+ // The legacy renderer replaces the fill alpha with 80%, including 8-digit hex.+ const hex =+ fill.length === 4+ ? fill+ .slice(1)+ .split('')+ .map((c) => c + c)+ .join('')+ : fill.slice(1, 7);+ return {+ fill: shape && fill !== 'transparent' ? `#${hex}cc` : 'transparent',+ stroke: style?.strokeColor ?? '#374151',+ strokeWidth: style?.strokeWidth ?? 2,+ opacity: style?.opacity ?? 1,+ cornerRadius: style?.cornerRadius ?? 0,+ };+}++function migrateNode(+ node: LegacyNode,+ placement: Placement,+ text: LegacyTextCodec,+ notes: Set<string>+): GraphicsItem {+ const base = {+ id: node.id,+ placement,+ transform: translation(node.x, node.y),+ appearance: appearance(node.style),+ };+ const box = {+ width: Math.max(1, node.width),+ height: Math.max(1, node.height),+ };+ return match(node)+ .with(+ { type: 'shape' },+ (node): ShapeItem<'rectangle' | 'ellipse'> => ({+ ...base,+ type: node.shape,+ appearance: {+ ...appearance(node.style, true),+ cornerRadius:+ (node.style?.cornerRadius ?? 0) >= 100+ ? Math.min(box.width, box.height) / 2+ : (node.style?.cornerRadius ?? 0),+ },+ geometry: {+ ...box,+ ...(node.label+ ? {+ label: {+ content: plainRichText(node.label, 'center'),+ fontSize: node.style?.textSize ?? 12,+ fontFamily: 'sans',+ height: (node.style?.textSize ?? 12) * 1.35,+ },+ }+ : {}),+ },+ })+ )+ .with({ type: 'text' }, (node): ShapeItem<'text'> => {+ const content = text(node.text);+ if (!validCanvasText(content))+ throw new Error(`Text ${node.id} could not be migrated`);+ return {+ ...base,+ type: 'text',+ geometry: {+ ...box,+ content,+ fontSize: node.style?.textSize ?? 24,+ fontFamily: 'sans',+ autoWidth: node.followTextWidth ?? false,+ },+ };+ })+ .with({ type: 'pencil' }, (node): ShapeItem<'pencil'> => {+ notes.add(+ 'Pencil strokes use the new brush renderer; their original samples are retained in the migration source.'+ );+ return {+ ...base,+ type: 'pencil',+ geometry: {+ points: node.coords.map(+ ([x, y]) => [x * node.wScale, y * node.hScale, 0.5] as const+ ),+ simulatePressure: false,+ },+ };+ })+ .with(+ { type: 'image' },+ { type: 'video' },+ (node): ShapeItem<'image' | 'video'> => {+ if (node.status === 'loading')+ throw new Error(`Media ${node.id} has no saved source yet`);+ return {+ ...base,+ type: node.type,+ appearance: {+ ...base.appearance,+ stroke:+ node.style?.fillColor === 'transparent'+ ? 'transparent'+ : (node.style?.strokeColor ?? 'transparent'),+ },+ transform: [+ node.flipX ? -1 : 1,+ 0,+ 0,+ node.flipY ? -1 : 1,+ node.x + (node.flipX ? box.width : 0),+ node.y + (node.flipY ? box.height : 0),+ ],+ geometry: {+ ...box,+ name: node.type === 'image' ? 'Image' : 'Video',+ source: {+ type: node.status === 'static' ? 'static' : 'document',+ id: node.uuid,+ },+ },+ };+ }+ )+ .with({ type: 'entitymention' }, (node): ShapeItem<'document'> => {+ // Metadata is resolved by the host's document preview, not persisted guesses.+ return {+ ...base,+ type: 'document',+ geometry: {+ ...box,+ documentId: node.file,+ name: node.entityType[0]!.toUpperCase() + node.entityType.slice(1),+ fileType:+ node.entityType === 'document' ? 'unknown' : node.entityType,+ entityType: node.entityType,+ ...(node.subpath ? { subpath: node.subpath } : {}),+ },+ };+ })+ .with({ type: 'link' }, (): never => {+ throw new Error(`Link ${node.id} requires the legacy editor`);+ })+ .exhaustive();+}++function legacyParents(+ nodes: LegacyNode[],+ edges: LegacyEdge[],+ groups: LegacyGroup[],+ ids: Set<string>,+ byGroup: Map<string, LegacyGroup>+) {+ const parents = new Map<string, string>();+ for (const group of groups) {+ for (const id of [+ ...(group.childNodes ?? []),+ ...(group.childEdges ?? []),+ ]) {+ if (!ids.has(id) || byGroup.has(id))+ throw new Error(`Invalid member ${id} in group ${group.id}`);+ const previous = parents.get(id);+ if (previous && previous !== group.id)+ throw new Error(`Conflicting membership for ${id}`);+ parents.set(id, group.id);+ }+ }+ for (const item of [...nodes, ...edges]) {+ if (!item.groupId) continue;+ if (+ !byGroup.has(item.groupId) ||+ (parents.has(item.id) && parents.get(item.id) !== item.groupId)+ )+ throw new Error(`Invalid group for ${item.id}`);+ parents.set(item.id, item.groupId);+ }+ return parents;+}++function legacyLayout(canvas: Canvas) {+ const nodes = canvas.nodes ?? [],+ edges = canvas.edges ?? [],+ groups = canvas.groups ?? [];+ const all = [...nodes, ...edges, ...groups];+ const ids = new Set<string>();+ for (const item of all) {+ if (!item.id || ids.has(item.id))+ throw new Error(`Duplicate or empty canvas id: ${item.id}`);+ ids.add(item.id);+ }+ let rootId = 'scene-root';+ while (ids.has(rootId)) rootId = `_${rootId}`;+ const byNode = new Map(nodes.map((n) => [n.id, n]));+ const byGroup = new Map(groups.map((g) => [g.id, g]));+ const parents = legacyParents(nodes, edges, groups, ids, byGroup);+ const order = (item: LegacyNode | LegacyEdge): [number, number] => {+ if (+ 'from' in item &&+ (item.from.type === 'connected' || item.to.type === 'connected')+ ) {+ const targets = [item.from, item.to].flatMap((end) => {+ if (end.type === 'free') return [];+ const target = byNode.get(end.node);+ if (!target) throw new Error(`Missing connector target ${end.node}`);+ return [target];+ });+ return [+ Math.max(0, ...targets.map((n) => n.layer)),+ Math.max(...targets.map((n) => n.sortOrder)) + 0.5,+ ];+ }+ const group = byGroup.get(parents.get(item.id) ?? '');+ return group+ ? [group.layer, group.sortOrder + item.sortOrder / 1000]+ : [item.layer, item.sortOrder];+ };+ const ordered = [...nodes, ...edges].sort((a, b) => {+ const x = order(a),+ y = order(b);+ return x[0] - y[0] || x[1] - y[1];+ });+ const rootOrder: string[] = [],+ memberOrder = new Map<string, string[]>();+ let previous: string | undefined;+ for (const item of ordered) {+ const parent = parents.get(item.id);+ const root = parent ?? item.id;+ if (root !== previous) {+ if (rootOrder.includes(root))+ throw new Error('Interleaved group layers require the legacy editor');+ rootOrder.push(root);+ previous = root;+ }+ if (parent)+ memberOrder.set(parent, [...(memberOrder.get(parent) ?? []), item.id]);+ }+ for (const group of groups)+ if (!rootOrder.includes(group.id)) rootOrder.push(group.id);+ const placements = new Map<string, Placement>();+ for (const [parentId, siblings] of [[rootId, rootOrder], ...memberOrder] as [+ string,+ string[],+ ][]) {+ const keys = sortKeysBetween(null, null, siblings.length);+ siblings.forEach((id, i) =>+ placements.set(id, { parentId, sortKey: keys[i]! })+ );+ }+ return { rootId, placements, byNode };+}++function migrateEdges(+ edges: LegacyEdge[],+ placements: Map<string, Placement>,+ byNode: Map<string, LegacyNode>+): GraphicsItem[] {+ const items: GraphicsItem[] = [];+ const endpoint = (end: EdgeEnd): ConnectorEndpoint => {+ if (end.type === 'free') return { point: { x: end.x, y: end.y } };+ const node = byNode.get(end.node);+ if (!node) throw new Error(`Missing connector target ${end.node}`);+ const point = match(end.side)+ .with('top', () => ({ x: node.x + node.width / 2, y: node.y }))+ .with('bottom', () => ({+ x: node.x + node.width / 2,+ y: node.y + node.height,+ }))+ .with('left', () => ({ x: node.x, y: node.y + node.height / 2 }))+ .with('right', () => ({+ x: node.x + node.width,+ y: node.y + node.height / 2,+ }))+ .exhaustive();+ // Legacy media flips only its pixels. In graphics the flip is the item's+ // transform, so compensate to retain the endpoint's visual side.+ let anchor = end.side;+ if (node.type === 'image' || node.type === 'video') {+ if (node.flipX && (anchor === 'left' || anchor === 'right'))+ anchor = anchor === 'left' ? 'right' : 'left';+ if (node.flipY && (anchor === 'top' || anchor === 'bottom'))+ anchor = anchor === 'top' ? 'bottom' : 'top';+ }+ return { point, binding: { targetId: end.node, anchor } };+ };+ const heads = [+ 'none',+ 'arrow',+ 'arrow-filled',+ 'circle',+ 'circle-small',+ ] as const;+ 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`);+ const startHead = heads[edge.style?.fromEndStyle ?? 0],+ endHead = heads[edge.style?.toEndStyle ?? 0],+ route = routes[edge.style?.connectionStyle ?? 0];+ if (!startHead || !endHead || !route)+ throw new Error(`Unsupported connector style ${edge.id}`);+ items.push({+ id: edge.id,+ type: 'connector',+ placement: placements.get(edge.id)!,+ transform: translation(0, 0),+ appearance: appearance(edge.style),+ geometry: {+ start: endpoint(edge.from),+ end: endpoint(edge.to),+ route,+ startHead,+ endHead,+ },+ });+ }+ return items;+}++/** One-way migration at the application boundary. Never mutate the source or+ * discard an unsupported record. Callers keep the legacy editor available on error. */+export function migrateLegacyCanvas(+ source: unknown,+ text: LegacyTextCodec+): CanvasFile {+ if (+ !isRecord(source) ||+ (source.version !== undefined && source.version !== 1)+ )+ throw new Error('Invalid legacy canvas');+ if (+ !['nodes', 'edges', 'groups'].some((key) => key in source) &&+ Object.keys(source).some((key) => key !== 'version')+ )+ throw new Error('Unrecognized legacy canvas');+ const canvas = CanvasSchema.parse(structuredClone(source));+ const nodes = canvas.nodes ?? [],+ edges = canvas.edges ?? [],+ groups = canvas.groups ?? [];+ const { rootId, placements, byNode } = legacyLayout(canvas);+ const notes = new Set<string>();+ const items: GraphicsItem[] = groups.map((g) => ({+ id: g.id,+ type: 'group',+ placement: placements.get(g.id)!,+ transform: translation(0, 0),+ }));+ items.push(+ ...nodes.map((node) =>+ migrateNode(node, placements.get(node.id)!, text, notes)+ )+ );+ items.push(...migrateEdges(edges, placements, byNode));+ const document = freezeDocument({+ rootId,+ items: Object.fromEntries([+ [rootId, { id: rootId, type: 'surface' }],+ ...items.map((item) => [item.id, item]),+ ]),+ });+ if (!validCanvasTextDocument(document))+ throw new Error('Canvas text requires the legacy editor');+ return {+ version: CANVAS_VERSION,+ document,+ legacy: { version: 1, source: structuredClone(source), notes: [...notes] },+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/core/seed-scene.ts b/apps/web/src/features/block-canvas/canvas-next/core/seed-scene.tsnew file mode 100644index 0000000000..e5bc3be495--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/seed-scene.ts@@ -0,0 +1,43 @@+import { createScene, translation } from '@macro-inc/graphics';+import { initialAppearance } from './defaults';++export { initialAppearance } from './defaults';++/** Shared test fixture for Canvas Next state and interaction tests. */+export function createCanvasNextScene() {+ return createScene([+ {+ id: 'welcome-rectangle',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(100, 100),+ geometry: { width: 240, height: 160 },+ appearance: {+ ...initialAppearance,+ fill: 'var(--color-accent-bg)',+ stroke: 'var(--color-accent)',+ cornerRadius: 16,+ },+ },+ {+ id: 'welcome-ellipse',+ type: 'ellipse',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: translation(430, 160),+ geometry: { width: 180, height: 180 },+ appearance: {+ ...initialAppearance,+ stroke: 'var(--color-accent)',+ strokeWidth: 4,+ },+ },+ {+ id: 'welcome-small',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a2' },+ transform: translation(180, 350),+ geometry: { width: 160, height: 110 },+ appearance: initialAppearance,+ },+ ]);+}diff --git a/apps/web/src/features/block-canvas/canvas-next/core/selection-layout.test.ts b/apps/web/src/features/block-canvas/canvas-next/core/selection-layout.test.tsnew file mode 100644index 0000000000..faa0155e9b--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/selection-layout.test.ts@@ -0,0 +1,261 @@+import {+ createGraphicsEditor,+ multiply,+ rotation,+ type ShapeItem,+ scaling,+ type TextMeasurer,+ translation,+ worldBounds,+ worldMatrix,+} from '@macro-inc/graphics';+import { expect, it } from 'vitest';+import { createCanvasNextScene } from './seed-scene';+import { layoutValue, selectionLayoutCommand } from './selection-layout';++it('edits position, dimensions and rotation with undo', () => {+ const editor = createGraphicsEditor(createCanvasNextScene());+ editor.select('welcome-rectangle');+ editor.execute(selectionLayoutCommand, { field: 'x', value: -30 });+ expect(worldBounds(editor.document, 'welcome-rectangle').x).toBe(-30);+ editor.execute(selectionLayoutCommand, { field: 'width', value: 120 });+ expect(worldBounds(editor.document, 'welcome-rectangle').width).toBeCloseTo(+ 120+ );+ editor.execute(selectionLayoutCommand, { field: 'rotation', value: 45 });+ expect(layoutValue(editor.document, ['welcome-rectangle'], 'rotation')).toBe(+ 45+ );+ editor.undo();+ expect(layoutValue(editor.document, ['welcome-rectangle'], 'rotation')).toBe(+ 0+ );+ editor.dispose();+});+it('sets equal spacing without changing item sizes and preserves the first item', () => {+ const editor = createGraphicsEditor(createCanvasNextScene());+ editor.select('welcome-rectangle');+ editor.toggleSelection('welcome-ellipse');+ editor.toggleSelection('welcome-small');+ const ids = editor.getSession().selectedIds;+ editor.execute(selectionLayoutCommand, { field: 'gapX', value: 20 });+ expect(layoutValue(editor.document, ids, 'gapX')).toBe(20);+ expect(worldBounds(editor.document, 'welcome-rectangle').x).toBe(100);+ expect(worldBounds(editor.document, 'welcome-ellipse').width).toBe(180);+ editor.dispose();+});+it('flips twice without losing the original transform', () => {+ const editor = createGraphicsEditor(createCanvasNextScene());+ editor.select('welcome-rectangle');+ const before = worldMatrix(editor.document, 'welcome-rectangle');+ editor.execute(selectionLayoutCommand, { field: 'flipX' });+ editor.execute(selectionLayoutCommand, { field: 'flipX' });+ expect(worldMatrix(editor.document, 'welcome-rectangle')).toEqual(before);+ editor.dispose();+});++it('preserves each selected item aspect ratio for locked width and height edits', () => {+ const editor = createGraphicsEditor(createCanvasNextScene());+ editor.select('welcome-rectangle');+ editor.toggleSelection('welcome-ellipse');+ const ids = editor.getSession().selectedIds;+ const before = ids.map((id) => worldBounds(editor.document, id));+ for (const field of ['width', 'height'] as const) {+ editor.execute(selectionLayoutCommand, {+ field,+ value: 240,+ lockAspectRatio: true,+ });+ ids.forEach((id, index) => {+ const bounds = worldBounds(editor.document, id);+ expect(bounds[field]).toBeCloseTo(240);+ expect(bounds.width / bounds.height).toBeCloseTo(+ before[index]!.width / before[index]!.height+ );+ });+ editor.undo();+ ids.forEach((id, index) =>+ expect(worldBounds(editor.document, id)).toEqual(before[index])+ );+ }+ editor.execute(selectionLayoutCommand, { field: 'width', value: 240 });+ ids.forEach((id, index) =>+ expect(worldBounds(editor.document, id).height).toBeCloseTo(+ before[index]!.height+ )+ );+ editor.dispose();+});++it('snaps position, size and gaps while preserving explicit angle values', () => {+ const editor = createGraphicsEditor(createCanvasNextScene(), { snapUnit: 8 });+ editor.select('welcome-rectangle');+ editor.execute(selectionLayoutCommand, { field: 'x', value: -13 });+ expect(layoutValue(editor.document, ['welcome-rectangle'], 'x')).toBe(-16);+ editor.execute(selectionLayoutCommand, { field: 'width', value: 1 });+ expect(layoutValue(editor.document, ['welcome-rectangle'], 'width')).toBe(8);+ const before = editor.document;+ editor.execute(selectionLayoutCommand, { field: 'width', value: -1 });+ expect(editor.document).toBe(before);+ editor.execute(selectionLayoutCommand, { field: 'rotation', value: 13.2 });+ expect(layoutValue(editor.document, ['welcome-rectangle'], 'rotation')).toBe(+ 13.2+ );+ editor.toggleSelection('welcome-ellipse');+ editor.execute(selectionLayoutCommand, { field: 'gapX', value: 19 });+ expect(+ layoutValue(editor.document, editor.getSession().selectedIds, 'gapX')+ ).toBe(16);+ editor.dispose();+});++const labeledShape = (+ type: 'rectangle' | 'ellipse'+): ShapeItem<'rectangle' | 'ellipse'> => ({+ id: 'shape',+ type,+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(30, 40),+ appearance: { fill: 'transparent', stroke: 'black' },+ geometry: {+ width: 200,+ height: 100,+ label: {+ content: 'A label that wraps',+ fontSize: 20,+ fontFamily: 'sans',+ height: 27,+ },+ },+});+const measureLabel: TextMeasurer = (g) => ({+ width: g.width,+ height: g.width < 120 ? 81 : 27,+});++it.each(['rectangle', 'ellipse'] as const)(+ 'matches canvas side resizing for %s labels, including undo',+ (type) => {+ for (const field of ['width', 'height'] as const) {+ const shape = labeledShape(type);+ const panel = createGraphicsEditor([shape], {+ measureText: measureLabel,+ });+ const direct = createGraphicsEditor([shape], {+ measureText: measureLabel,+ });+ panel.select('shape');+ direct.select('shape');+ panel.execute(selectionLayoutCommand, {+ field,+ value: field === 'width' ? 100 : 160,+ });+ direct.beginTransform(+ 'shape',+ field === 'width' ? { x: 230, y: 90 } : { x: 130, y: 140 },+ field === 'width' ? 'e' : 's'+ );+ direct.updateTransform(+ field === 'width' ? { x: 130, y: 90 } : { x: 130, y: 200 }+ );+ direct.commitTransform();+ expect(panel.document.items.shape).toEqual(direct.document.items.shape);+ expect(worldMatrix(panel.document, 'shape').slice(0, 4)).toEqual([+ 1, 0, 0, 1,+ ]);+ panel.undo();+ expect(panel.document.items.shape).toEqual(shape);+ panel.dispose();+ direct.dispose();+ }+ }+);++it('remeasures labels inside scaled groups without magnifying their typography', () => {+ const shape = labeledShape('rectangle');+ const editor = createGraphicsEditor(+ [+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: scaling(2, 2),+ },+ { ...shape, placement: { ...shape.placement, parentId: 'group' } },+ ],+ { measureText: measureLabel }+ );+ editor.select('group');+ editor.execute(selectionLayoutCommand, { field: 'width', value: 200 });+ expect(layoutValue(editor.document, ['group'], 'width')).toBe(200);+ expect(editor.document.items.shape).toMatchObject({+ geometry: { width: 100, label: { fontSize: 20, height: 81 } },+ });+ expect(worldMatrix(editor.document, 'shape').slice(0, 4)).toEqual([+ 2, 0, 0, 2,+ ]);+ editor.dispose();+});++it('keeps rotated labels unsheared when editing world dimensions', () => {+ const shape = {+ ...labeledShape('rectangle'),+ transform: multiply(translation(30, 40), rotation(Math.PI / 4)),+ };+ const editor = createGraphicsEditor([shape], { measureText: measureLabel });+ editor.select('shape');+ editor.execute(selectionLayoutCommand, { field: 'width', value: 300 });+ expect(layoutValue(editor.document, ['shape'], 'width')).toBeCloseTo(300);+ expect(worldMatrix(editor.document, 'shape').slice(0, 4)).toEqual(+ shape.transform.slice(0, 4)+ );+ editor.dispose();+});++it('matches direct width reflow and proportional height resizing for standalone text', () => {+ const text: ShapeItem<'text'> = {+ id: 'text',+ type: 'text',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(30, 40),+ appearance: { fill: 'transparent', stroke: 'black' },+ geometry: {+ width: 200,+ height: 27,+ fontSize: 20,+ fontFamily: 'sans',+ autoWidth: true,+ content: 'Wrapping text',+ },+ };+ for (const field of ['width', 'height'] as const) {+ const panel = createGraphicsEditor([text], { measureText: measureLabel });+ const direct = createGraphicsEditor([text], { measureText: measureLabel });+ panel.select('text');+ direct.select('text');+ panel.execute(selectionLayoutCommand, {+ field,+ value: field === 'width' ? 100 : 54,+ });+ direct.beginTransform(+ 'text',+ field === 'width' ? { x: 230, y: 53.5 } : { x: 130, y: 67 },+ field === 'width' ? 'e' : 's'+ );+ direct.updateTransform(+ field === 'width' ? { x: 130, y: 53.5 } : { x: 130, y: 94 }+ );+ direct.commitTransform();+ expect(panel.document.items.text).toMatchObject({+ geometry:+ direct.document.items.text?.type === 'text'+ ? direct.document.items.text.geometry+ : undefined,+ // Inspector dimensions retain the top-left anchor; bottom handles keep+ // the horizontal center while proportionally scaling standalone text.+ transform: text.transform,+ });+ panel.dispose();+ direct.dispose();+ }+});diff --git a/apps/web/src/features/block-canvas/canvas-next/core/selection-layout.ts b/apps/web/src/features/block-canvas/canvas-next/core/selection-layout.tsnew file mode 100644index 0000000000..c58064c8e1--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/selection-layout.ts@@ -0,0 +1,204 @@+import {+ around,+ enclosing,+ type GraphicsCommand,+ type GraphicsDocument,+ inverse,+ layoutBounds,+ layoutRoots,+ multiply,+ regenerateScaledShapes,+ rotation,+ scaling,+ selectionFrame,+ snapValue,+ stretchShapes,+ translation,+ worldMatrix,+} from '@macro-inc/graphics';++export type LayoutField =+ | 'x'+ | 'y'+ | 'width'+ | 'height'+ | 'rotation'+ | 'gapX'+ | 'gapY';+export function layoutEntries(+ document: GraphicsDocument,+ selection: readonly string[]+) {+ return layoutRoots(document, selection).map((id) => {+ const matrix = worldMatrix(document, id);+ return {+ id,+ ...layoutBounds(document, id),+ rotation:+ ((((Math.atan2(matrix[1], matrix[0]) * 180) / Math.PI) % 360) + 360) %+ 360,+ };+ });+}+export function layoutValue(+ document: GraphicsDocument,+ selection: readonly string[],+ field: LayoutField+) {+ return entryValue(layoutEntries(document, selection), field);+}+function entryValue(+ entries: ReturnType<typeof layoutEntries>,+ field: LayoutField+) {+ let values: number[];+ if (field === 'gapX' || field === 'gapY') {+ const axis = field === 'gapX' ? 'x' : 'y';+ const size = field === 'gapX' ? 'width' : 'height';+ const sorted = [...entries].sort((a, b) => a[axis] - b[axis]);+ values = sorted+ .slice(1)+ .map((entry, i) => entry[axis] - sorted[i]![axis] - sorted[i]![size]);+ } else values = entries.map((entry) => entry[field]);+ return values.length &&+ values.every((value) => Math.abs(value - values[0]!) < 0.01)+ ? Math.round(values[0]! * 100) / 100+ : undefined;+}+export function selectionLayoutInfo(+ document: GraphicsDocument,+ selection: readonly string[]+) {+ const entries = layoutEntries(document, selection);+ return {+ count: entries.length,+ values: {+ x: entryValue(entries, 'x'),+ y: entryValue(entries, 'y'),+ width: entryValue(entries, 'width'),+ height: entryValue(entries, 'height'),+ rotation: entryValue(entries, 'rotation'),+ gapX: entryValue(entries, 'gapX'),+ gapY: entryValue(entries, 'gapY'),+ },+ };+}+export const selectionLayoutCommand: GraphicsCommand<{+ field: LayoutField | 'flipX' | 'flipY' | 'rotate90';+ value?: number;+ lockAspectRatio?: boolean;+}> = {+ id: 'canvas.selection-layout',+ apply: (+ { document, selection, snapUnit, measureText },+ { field, value = 0, lockAspectRatio = false }+ ) => {+ if (!Number.isFinite(value)) return { document };+ if ((field === 'width' || field === 'height') && value <= 0)+ return { document };+ if (+ field === 'x' ||+ field === 'y' ||+ field === 'width' ||+ field === 'height' ||+ field === 'gapX' ||+ field === 'gapY'+ ) {+ value = snapValue(value, snapUnit);+ if ((field === 'width' || field === 'height') && snapUnit !== undefined)+ value = Math.max(snapUnit, value);+ }+ const entries = layoutEntries(document, selection);+ if (!entries.length) return { document };+ const items = { ...document.items };+ const bounds = enclosing(+ entries.flatMap((e) => [+ { x: e.x, y: e.y },+ { x: e.x + e.width, y: e.y + e.height },+ ])+ );+ const pivot = {+ x: bounds.x + bounds.width / 2,+ y: bounds.y + bounds.height / 2,+ };+ const gap = field === 'gapX' || field === 'gapY';+ const axis = field === 'gapY' ? 'y' : 'x';+ if (gap) entries.sort((a, b) => a[axis] - b[axis]);+ let position = entries[0]![axis];+ for (const entry of entries) {+ const item = items[entry.id];+ if (!item || item.type === 'surface') continue;+ let delta = translation(0, 0);+ if (field === 'x' || field === 'y')+ delta = translation(+ field === 'x' ? value - entry.x : 0,+ field === 'y' ? value - entry.y : 0+ );+ if (field === 'width' || field === 'height') {+ if (value <= 0 || entry[field] <= 0) continue;+ const world = worldMatrix(document, entry.id);+ const aligned =+ (Math.abs(world[1]) < 1e-8 && Math.abs(world[2]) < 1e-8) ||+ (Math.abs(world[0]) < 1e-8 && Math.abs(world[3]) < 1e-8);+ // World-bound edits cannot deform rotated axes without shearing text.+ // Match the canvas's uniform fallback for incompatible group axes.+ const proportional =+ lockAspectRatio ||+ (item.type === 'text' && field === 'height') ||+ (item.type === 'group'+ ? !selectionFrame(document, [entry.id])?.canDeform+ : !aligned);+ const ratio = value / entry[field];+ delta = around(+ { x: entry.x, y: entry.y },+ scaling(+ proportional || field === 'width' ? ratio : 1,+ proportional || field === 'height' ? ratio : 1+ )+ );+ if (item.type !== 'group' || !proportional) {+ Object.assign(+ items,+ stretchShapes(+ document,+ [entry.id],+ delta,+ measureText,+ field === 'width' ? 'e' : 's'+ )+ );+ continue;+ }+ }+ if (field === 'rotation')+ delta = around(+ { x: entry.x + entry.width / 2, y: entry.y + entry.height / 2 },+ rotation(((value - entry.rotation) * Math.PI) / 180)+ );+ if (field === 'rotate90') delta = around(pivot, rotation(Math.PI / 2));+ if (field === 'flipX' || field === 'flipY')+ delta = around(+ pivot,+ scaling(field === 'flipX' ? -1 : 1, field === 'flipY' ? -1 : 1)+ );+ if (gap) {+ delta = translation(+ axis === 'x' ? position - entry.x : 0,+ axis === 'y' ? position - entry.y : 0+ );+ position += entry[axis === 'x' ? 'width' : 'height'] + value;+ }+ const parent = worldMatrix(document, item.placement.parentId);+ items[entry.id] = {+ ...item,+ transform: multiply(+ inverse(parent),+ multiply(delta, worldMatrix(document, entry.id))+ ),+ };+ if (field === 'width' || field === 'height')+ regenerateScaledShapes(document, [entry.id], items);+ }+ return { document: { ...document, items } };+ },+};diff --git a/apps/web/src/features/block-canvas/canvas-next/core/snapping.ts b/apps/web/src/features/block-canvas/canvas-next/core/snapping.tsnew file mode 100644index 0000000000..5b431af3eb--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/snapping.ts@@ -0,0 +1,14 @@+import { dotGridLevels } from '@macro-inc/graphics';++export type CanvasSnapMode = 'none' | 'pixel' | 'auto';++export function canvasSnapUnit(+ mode: CanvasSnapMode,+ scale: number,+ gridVisible: boolean+): number | undefined {+ if (mode === 'none') return undefined;+ if (mode === 'pixel') return 1;+ if (!gridVisible) return undefined;+ return dotGridLevels(scale).find((level) => level.opacity > 0)?.unit;+}diff --git a/apps/web/src/features/block-canvas/canvas-next/core/text-codec.test.ts b/apps/web/src/features/block-canvas/canvas-next/core/text-codec.test.tsnew file mode 100644index 0000000000..84509a2b12--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/text-codec.test.ts@@ -0,0 +1,86 @@+import type { SerializedEditorState } from 'lexical';+import { expect, it } from 'vitest';+import {+ plainRichText,+ richTextPlainText,+ serializeCanvasTextState,+ validCanvasText,+} from './text-codec';++it('preserves unfinished mention searches as text without persisting picker state', () => {+ const state = JSON.parse(plainRichText('@Ada'));+ state.root.children[0].children[0].type = 'inline-search';+ state.root.children[0].children[0].format = 1;+ const saved = JSON.parse(serializeCanvasTextState(state));+ expect(saved.root.children[0].children[0]).toMatchObject({+ type: 'text',+ text: '@Ada',+ format: 1,+ });+ expect(state.root.children[0].children[0].type).toBe('inline-search');+});++it('retains complete mention nodes as part of the serialized string', () => {+ const state = JSON.parse(plainRichText());+ state.root.children[0].children = [+ {+ type: 'user-mention',+ version: 1,+ userId: 'user-1',+ email: '[email protected]',+ displayName: 'Ada',+ },+ {+ type: 'document-mention',+ version: 1,+ documentId: 'doc-1',+ documentName: 'Spec',+ blockName: 'write',+ },+ ];+ const saved = serializeCanvasTextState(state as SerializedEditorState);+ expect(typeof saved).toBe('string');+ expect(JSON.parse(saved)).toEqual(state);+ expect(validCanvasText(saved)).toBe(true);+ expect(richTextPlainText(saved).trim()).not.toBe('');+});++it('validates the editor envelope and bounds tree depth, node count and text size', () => {+ expect(validCanvasText(plainRichText('First\nSecond', 'center'))).toBe(true);+ expect(richTextPlainText(plainRichText('First\nSecond'))).toBe(+ 'First\nSecond'+ );+ expect(richTextPlainText(plainRichText(' \n ')).trim()).toBe('');+ for (const invalid of [+ '',+ '{broken',+ '{}',+ JSON.stringify({ root: { type: 'root', version: 1 } }),+ plainRichText('x'.repeat(100_001)),+ 'x'.repeat(2_000_001),+ ])+ expect(validCanvasText(invalid)).toBe(false);+ let child: unknown = { type: 'text', version: 1, text: 'Deep' };+ for (let i = 0; i < 65; i++)+ child = { type: 'paragraph', version: 1, children: [child] };+ expect(+ validCanvasText(+ JSON.stringify({ root: { type: 'root', version: 1, children: [child] } })+ )+ ).toBe(false);+ expect(+ validCanvasText(+ JSON.stringify({+ root: {+ type: 'root',+ version: 1,+ children: Array.from({ length: 10_000 }, () => ({+ type: 'paragraph',+ version: 1,+ children: [],+ })),+ },+ })+ )+ ).toBe(false);+});diff --git a/apps/web/src/features/block-canvas/canvas-next/core/text-codec.ts b/apps/web/src/features/block-canvas/canvas-next/core/text-codec.tsnew file mode 100644index 0000000000..31e64f64cb--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/core/text-codec.ts@@ -0,0 +1,119 @@+import {+ canLabel,+ type GraphicsDocument,+ type RichText,+ validRichText,+} from '@macro-inc/graphics';+import type { SerializedEditorState } from 'lexical';++export type TextAlign = 'left' | 'center' | 'right';++const record = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === 'object' && !Array.isArray(value);++/** Bound the serialized editor tree before passing it to the shared renderer. */+export function validCanvasText(value: unknown): value is RichText {+ if (!validRichText(value)) return false;+ try {+ const state: unknown = JSON.parse(value);+ let count = 0,+ characters = 0;+ const node = (value: unknown, depth: number): boolean => {+ if (!record(value) || depth > 64 || ++count > 10000) return false;+ if (typeof value.text === 'string') characters += value.text.length;+ return (+ characters <= 100000 &&+ typeof value.type === 'string' &&+ typeof value.version === 'number' &&+ (value.children === undefined ||+ (Array.isArray(value.children) &&+ value.children.every((child) => node(child, depth + 1))))+ );+ };+ return (+ record(state) &&+ record(state.root) &&+ state.root.type === 'root' &&+ Array.isArray(state.root.children) &&+ node(state.root, 0)+ );+ } catch {+ return false;+ }+}++/** Seed/clipboard convenience; preserves the standard Lexical JSON wire format. */+export const plainRichText = (text = '', align: TextAlign = 'left'): RichText =>+ JSON.stringify({+ root: {+ type: 'root',+ version: 1,+ direction: null,+ format: '',+ indent: 0,+ children: text.split('\n').map((line) => ({+ type: 'paragraph',+ version: 1,+ direction: null,+ format: align,+ indent: 0,+ children: line+ ? [+ {+ type: 'text',+ version: 1,+ text: line,+ format: 0,+ detail: 0,+ mode: 'normal',+ style: '',+ },+ ]+ : [],+ })),+ },+ });++/** Extract text for host-owned empty-content decisions; decorators count as content. */+export function richTextPlainText(content: RichText): string {+ const read = (value: unknown): string => {+ if (!record(value)) return '';+ if (value.type === 'linebreak') return '\n';+ if (typeof value.text === 'string') return value.text;+ if (Array.isArray(value.children)) {+ const separator = ['root', 'list'].includes(String(value.type))+ ? '\n'+ : '';+ return value.children.map(read).join(separator);+ }+ // Decorators count as content even when they contain no text leaves.+ return '\uFFFC';+ };+ return read((JSON.parse(content) as { root: unknown }).root);+}++/** A pending picker query is ordinary text outside the active editor. */+export function serializeCanvasTextState(+ state: SerializedEditorState+): RichText {+ return JSON.stringify(state, (_key, value: unknown) =>+ value !== null &&+ typeof value === 'object' &&+ 'type' in value &&+ value.type === 'inline-search'+ ? { ...value, type: 'text' }+ : value+ );+}++/** Graphics validates geometry; this host validates its editor payloads on import. */+export function validCanvasTextDocument(document: GraphicsDocument): boolean {+ return Object.values(document.items).every((item) => {+ if (item.type === 'text') return validCanvasText(item.geometry.content);+ return (+ !canLabel(item) ||+ !item.geometry.label ||+ validCanvasText(item.geometry.label.content)+ );+ });+}diff --git a/apps/web/src/features/block-canvas/canvas-next/hotkeys.ts b/apps/web/src/features/block-canvas/canvas-next/hotkeys.tsnew file mode 100644index 0000000000..048f25df62--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/hotkeys.ts@@ -0,0 +1,220 @@+import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';+import { TOKENS } from '@core/hotkey/tokens';+import type { HotkeyRegistrationOptions } from '@core/hotkey/types';+import { nudgeCommand, selectAllCommand } from '@macro-inc/graphics';+import { onCleanup } from 'solid-js';+import type { CanvasClipboard } from './clipboard';+import type { CanvasState } from './primitives/create-canvas-state';++export function registerCanvasNextHotkeys(+ scopeId: string,+ state: CanvasState,+ clipboard: CanvasClipboard,+ canEdit: () => boolean = () => true+) {+ const group = createHotkeyGroup(),+ editor = state.editor;+ const register = (+ hotkey: HotkeyRegistrationOptions['hotkey'],+ description: string,+ action: () => void,+ token?: HotkeyRegistrationOptions['hotkeyToken'],+ proxiedHotkey = false+ ) => {+ group.add(+ registerHotkey({+ scopeId,+ hotkey,+ hotkeyToken: token,+ description,+ proxiedHotkey,+ keyDownHandler: () => {+ if (!canEdit() || state.text.draft() || state.embeds.active())+ return false;+ action();+ return true;+ },+ })+ );+ };+ register(+ 'v',+ 'Selection tool',+ () => state.chooseTool('select'),+ TOKENS.canvas.selectTool+ );+ register(+ 'r',+ 'Rectangle tool',+ () => state.chooseTool('rectangle'),+ TOKENS.canvas.shapeTool+ );+ register('a', 'Arrow tool', () => state.chooseTool('arrow'));+ register('l', 'Line tool', () => state.chooseTool('line'));+ register('e', 'Eraser tool', () => state.chooseTool('eraser'));+ register('t', 'Text tool', () => state.chooseTool('text'));+ register('enter', 'Edit selected text', () => {+ const id = editor.getSession().selectedId;+ if (id) state.text.edit(id);+ });+ register('o', 'Ellipse tool', () => state.chooseTool('ellipse'));+ register(+ 'p',+ 'Pencil tool',+ () => state.chooseTool('pencil'),+ TOKENS.canvas.pencilTool+ );+ register(+ 'h',+ 'Hand tool',+ () => state.chooseTool('pan'),+ TOKENS.canvas.handTool+ );+ register(+ 'cmd+a',+ 'Select all',+ () => {+ state.chooseTool('select');+ editor.execute(selectAllCommand, undefined);+ },+ TOKENS.canvas.selectAll+ );+ register('cmd+d', 'Duplicate selection', state.duplicate);+ register(+ 'cmd+c',+ 'Copy selection',+ () => {+ void clipboard.copy();+ },+ TOKENS.canvas.copy,+ true+ );+ register(+ 'cmd+x',+ 'Cut selection',+ () => {+ void clipboard.cut();+ },+ TOKENS.canvas.cut,+ true+ );+ register(+ 'cmd+v',+ 'Paste shapes',+ () => {+ void clipboard.paste();+ },+ TOKENS.canvas.paste,+ true+ );+ register('cmd+z', 'Undo', editor.undo, TOKENS.canvas.undo);+ register(['shift+cmd+z', 'cmd+y'], 'Redo', editor.redo, TOKENS.canvas.redo);+ register(+ ['delete', 'backspace'],+ 'Delete selection',+ editor.deleteSelection,+ TOKENS.canvas.delete+ );+ register('cmd+g', 'Group selection', state.group, TOKENS.canvas.group);+ register(+ 'shift+cmd+g',+ 'Ungroup selection',+ state.ungroup,+ TOKENS.canvas.ungroup+ );+ register(+ ']',+ 'Bring to front',+ () => editor.reorderSelection('front'),+ TOKENS.canvas.bringToFront+ );+ register(+ '[',+ 'Send to back',+ () => editor.reorderSelection('back'),+ TOKENS.canvas.sendToBack+ );+ register(+ 'opt+]',+ 'Bring forward',+ () => editor.reorderSelection('forward'),+ TOKENS.canvas.bringForward+ );+ register(+ 'opt+[',+ 'Send backward',+ () => editor.reorderSelection('backward'),+ TOKENS.canvas.sendBackward+ );+ for (const [key, x, y] of [+ ['arrowleft', -1, 0],+ ['arrowright', 1, 0],+ ['arrowup', 0, -1],+ ['arrowdown', 0, 1],+ ] as const) {+ register(key, `Nudge ${key.slice(5)}`, () =>+ editor.execute(nudgeCommand, {+ x: x * (editor.getSnapUnit() ?? 1),+ y: y * (editor.getSnapUnit() ?? 1),+ })+ );+ register(`shift+${key}`, `Nudge ${key.slice(5)} by 10`, () =>+ editor.execute(nudgeCommand, {+ x: x * 10 * (editor.getSnapUnit() ?? 1),+ y: y * 10 * (editor.getSnapUnit() ?? 1),+ })+ );+ }+ register(+ 'escape',+ 'Clear selection / cancel',+ () => {+ state.chooseTool('select');+ editor.select();+ },+ TOKENS.canvas.cancel+ );+ // Surface also handles Escape and space-pan to release pointer capture.+ onCleanup(() => group.dispose());+}++export function registerCanvasZoomHotkeys(+ scopeId: string,+ state: CanvasState,+ zoom: (factor: number) => void,+ fit: () => void+) {+ const group = createHotkeyGroup();+ for (const [hotkey, description, factor, token] of [+ ['cmd+=', 'Zoom In', 1.2, TOKENS.canvas.zoomIn],+ ['cmd+-', 'Zoom Out', 1 / 1.2, TOKENS.canvas.zoomOut],+ ] as const) {+ group.add(+ registerHotkey({+ scopeId,+ hotkey,+ description,+ hotkeyToken: token,+ keyDownHandler: () => {+ if (state.text.draft() || state.embeds.active()) return false;+ zoom(factor);+ return true;+ },+ })+ );+ }+ group.add(+ registerHotkey({+ scopeId,+ hotkey: '.',+ description: 'Zoom to fit',+ hotkeyToken: TOKENS.canvas.zoomFit,+ keyDownHandler: () => {+ if (state.text.draft() || state.embeds.active()) return false;+ fit();+ return true;+ },+ })+ );+ onCleanup(() => group.dispose());+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/asset-drop.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/asset-drop.tsnew file mode 100644index 0000000000..9bc499f48e--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/asset-drop.ts@@ -0,0 +1,39 @@+import { fileTypeToBlockName } from '@core/constant/allBlocks';+import { isEntityDragEvent } from '@entity';+import type { Point } from '@macro-inc/graphics';+import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';+import { createUniqueId } from 'solid-js';+import type { CanvasAssetState } from './create-asset-state';++/** App drag/drop bridge; nothing in the document model knows about DOM or soup. */+export function createCanvasAssetDrop(+ assets: CanvasAssetState,+ point: (x: number, y: number) => Point,+ enabled: () => boolean = () => true+) {+ const id = `canvas-next-${createUniqueId()}`;+ const droppable = createDroppable(id);+ const context = useDragDropContext();+ if (context) {+ const [state, actions] = context;+ actions.onDragEnd((event) => {+ if (!enabled() || !isEntityDragEvent(event) || event.droppable?.id !== id)+ return;+ const entity = event.draggable.data;+ if (entity.type !== 'document') return;+ const coordinates = state.active.sensor?.coordinates.current;+ if (!coordinates) return;+ const asset = {+ id: String(entity.id),+ name: entity.name ?? 'Document',+ fileType: entity.fileType ?? 'unknown',+ };+ const position = point(coordinates.x, coordinates.y);+ const kind = fileTypeToBlockName(asset.fileType);+ if (kind === 'image' || kind === 'video')+ void assets.media(asset, position);+ else assets.document(asset, position);+ });+ }+ return droppable;+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.test.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.test.tsnew file mode 100644index 0000000000..f0bf3ee67d--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.test.ts@@ -0,0 +1,158 @@+import {+ copyFragment,+ createGraphicsEditor,+ drawableIds,+ parseFragment,+ pasteCommand,+} from '@macro-inc/graphics';+import { createRoot } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import type { CanvasAssetSource, PreparedMedia } from '../core/assets';+import { setDocumentDisplayCommand } from '../core/document-display';+import { createAssetState } from './create-asset-state';+import { createCanvasState } from './create-canvas-state';++const disposers: (() => void)[] = [];+afterEach(() => disposers.splice(0).forEach((fn) => fn()));+const media: PreparedMedia = {+ type: 'image',+ geometry: {+ width: 200,+ height: 100,+ name: 'image',+ source: { type: 'static', id: 'asset' },+ },+};+function setup(source: CanvasAssetSource) {+ return createRoot((dispose) => {+ disposers.push(dispose);+ const editor = createGraphicsEditor();+ disposers.push(editor.dispose);+ const canvas = createCanvasState(editor, (g) => ({+ width: g.width,+ height: g.height,+ }));+ return { editor, assets: createAssetState(canvas, source), canvas };+ });+}+it('batches file inserts as one undo entry and preserves stable references on redo', async () => {+ const { editor, assets } = setup({+ upload: vi.fn(async () => media),+ media: vi.fn(async () => media),+ });+ await assets.files([new File(['a'], 'a.png'), new File(['b'], 'b.png')], {+ x: 300,+ y: 200,+ });+ expect(drawableIds(editor.document)).toHaveLength(2);+ expect(editor.document.items[drawableIds(editor.document)[0]!]).toMatchObject(+ {+ transform: [1, 0, 0, 1, 200, 150],+ geometry: { source: { type: 'static', id: 'asset' } },+ }+ );+ editor.undo();+ expect(drawableIds(editor.document)).toHaveLength(0);+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ expect(drawableIds(editor.document)).toHaveLength(2);+});+it('does not insert an async upload after resetting canvas state', async () => {+ let resolve!: (value: PreparedMedia) => void;+ const { editor, assets } = setup({+ upload: () =>+ new Promise((r) => {+ resolve = r;+ }),+ media: vi.fn(async () => media),+ });+ const pending = assets.files([new File(['a'], 'a.png')], { x: 0, y: 0 });+ assets.cancelPending();+ resolve(media);+ await pending;+ expect(drawableIds(editor.document)).toHaveLength(0);+ expect(assets.busy()).toBe(0);+});+it('reports a failed file without discarding successful files or leaving pending state', async () => {+ const { editor, assets, canvas } = setup({+ upload: async (file) => {+ if (file.name === 'bad') throw Error('bad');+ return media;+ },+ media: vi.fn(async () => media),+ });+ await assets.files([new File(['a'], 'good'), new File(['b'], 'bad')], {+ x: 0,+ y: 0,+ });+ expect(drawableIds(editor.document)).toHaveLength(1);+ expect(canvas.notice()).toContain('1 could not be loaded');+ expect(assets.busy()).toBe(0);+});++it('keeps embed presentation in copy/undo while input ownership stays local', () => {+ const { editor, assets, canvas } = setup({+ upload: vi.fn(async () => media),+ media: vi.fn(async () => media),+ });+ assets.document(+ { id: 'existing-doc', name: 'Note', fileType: 'md' },+ { x: 320, y: 240 },+ 'embed'+ );+ const id = editor.getSession().selectedId!;+ const item = editor.document.items[id];+ expect(item).toMatchObject({+ type: 'document',+ geometry: { display: 'embed', width: 640, height: 480 },+ });+ canvas.embeds.enter(id);+ expect(canvas.embeds.active()).toBe(id);+ canvas.chooseTool('rectangle');+ expect(canvas.embeds.active()).toBeUndefined();+ const fragment = parseFragment(+ JSON.stringify(copyFragment(editor.document, [id]))+ )!;+ editor.execute(pasteCommand, { fragment, createId: () => 'copy' });+ expect(editor.document.items.copy).toMatchObject({+ geometry: { documentId: 'existing-doc', display: 'embed' },+ });+ expect(canvas.embeds.active()).toBeUndefined();+ editor.undo();+ canvas.embeds.enter(id);+ editor.execute(setDocumentDisplayCommand, { id, display: 'preview' });+ expect(canvas.embeds.active()).toBeUndefined();+ editor.undo();+ expect(editor.document.items[id]).toMatchObject({+ geometry: { display: 'embed' },+ });+ editor.deleteSelection();+ expect(canvas.embeds.active()).toBeUndefined();+});+it('admits documents and canvases as embeds but leaves unsupported references alone', () => {+ const { editor, assets, canvas } = setup({+ upload: vi.fn(async () => media),+ media: vi.fn(async () => media),+ });+ assets.document(+ { id: 'nested', name: 'Board', fileType: 'canvas' },+ { x: 0, y: 0 },+ 'embed'+ );+ canvas.embeds.enter(editor.getSession().selectedId!);+ expect(canvas.embeds.active()).toBeDefined();+ assets.document(+ { id: 'pdf', name: 'PDF', fileType: 'pdf' },+ { x: 0, y: 0 },+ 'embed'+ );+ expect(drawableIds(editor.document)).toHaveLength(1);+ assets.document({ id: 'pdf', name: 'PDF', fileType: 'pdf' }, { x: 0, y: 0 });+ const id = editor.getSession().selectedId!;+ editor.execute(setDocumentDisplayCommand, { id, display: 'embed' });+ canvas.embeds.enter(id);+ expect(canvas.embeds.active()).toBeUndefined();+ expect(editor.document.items[id]).toMatchObject({+ geometry: { display: 'preview' },+ });+});diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.tsnew file mode 100644index 0000000000..f16abb3e44--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-asset-state.ts@@ -0,0 +1,117 @@+import { insertShapesCommand, type Point } from '@macro-inc/graphics';+import { createSignal, onCleanup } from 'solid-js';+import type {+ CanvasAsset,+ CanvasAssetSource,+ PreparedMedia,+} from '../core/assets';+import { canEmbedDocument } from '../core/document-display';+import type { CanvasState } from './create-canvas-state';++export function createAssetState(+ state: CanvasState,+ source: CanvasAssetSource+) {+ const [busy, setBusy] = createSignal(0);+ const [playing, setPlaying] = createSignal<string>();+ let generation = 0,+ disposed = false;+ onCleanup(() => {+ disposed = true;+ generation++;+ });+ const appearance = {+ fill: 'transparent',+ stroke: 'transparent',+ strokeWidth: 0,+ opacity: 1,+ };+ const insert = (items: readonly PreparedMedia[], point: Point) => {+ state.chooseTool('select');+ state.editor.execute(+ insertShapesCommand,+ items.map((media, index) => ({+ item: { id: crypto.randomUUID(), ...media, appearance },+ point: {+ x: point.x - media.geometry.width / 2 + index * 24,+ y: point.y - media.geometry.height / 2 + index * 24,+ },+ }))+ );+ };+ async function load(tasks: (() => Promise<PreparedMedia>)[], point: Point) {+ const started = generation;+ setBusy((value) => value + 1);+ state.setNotice('Loading media…');+ try {+ const results = await Promise.allSettled(tasks.map((task) => task()));+ if (disposed || started !== generation) return;+ const media = results.flatMap((result) =>+ result.status === 'fulfilled' ? [result.value] : []+ );+ if (media.length) insert(media, point);+ const failed = results.filter(+ (result) => result.status === 'rejected'+ ).length;+ state.setNotice(+ failed+ ? `${media.length} inserted; ${failed} could not be loaded`+ : `Inserted ${media.length} media item${media.length === 1 ? '' : 's'}`+ );+ } finally {+ if (!disposed) setBusy((value) => value - 1);+ }+ }+ return {+ busy,+ playing,+ togglePlayback: (id: string) =>+ setPlaying((current) => (current === id ? undefined : id)),+ stopPlayback: () => setPlaying(undefined),+ cancelPending: () => {+ generation++;+ setPlaying(undefined);+ },+ files: (files: readonly File[], point: Point) =>+ load(+ files.map((file) => () => source.upload(file)),+ point+ ),+ media: (asset: CanvasAsset, point: Point) =>+ load([() => source.media(asset)], point),+ document: (+ asset: CanvasAsset,+ point: Point,+ display: 'preview' | 'embed' = 'preview'+ ) => {+ if (display === 'embed' && !canEmbedDocument(asset.fileType)) return;+ const width = display === 'embed' ? 640 : 340;+ const height = display === 'embed' ? 480 : 136;+ state.chooseTool('select');+ state.editor.execute(insertShapesCommand, [+ {+ item: {+ id: crypto.randomUUID(),+ type: 'document',+ appearance,+ geometry: {+ documentId: asset.id,+ name: asset.name,+ fileType: asset.fileType,+ width,+ height,+ display,+ },+ },+ point: { x: point.x - width / 2, y: point.y - height / 2 },+ },+ ]);+ state.setNotice(+ display === 'embed'+ ? 'Inserted full embed — double-click to interact'+ : 'Inserted document preview'+ );+ },+ };+}+export type CanvasAssetState = ReturnType<typeof createAssetState>;diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.test.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.test.tsnew file mode 100644index 0000000000..f36900e995--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.test.ts@@ -0,0 +1,120 @@+import {+ createGraphicsEditor,+ dotGridLevels,+ IDENTITY,+} from '@macro-inc/graphics';+import { createRoot } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { canvasSnapUnit } from '../core/snapping';+import { createCanvasSnapping } from './create-canvas-snapping';++const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((dispose) => dispose()));+function setup() {+ return createRoot((dispose) => {+ const editor = createGraphicsEditor([+ {+ id: 'rect',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: IDENTITY,+ geometry: { width: 160, height: 100 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ ]);+ const cancel = vi.fn();+ const snapping = createCanvasSnapping(editor, cancel);+ cleanups.push(() => {+ dispose();+ editor.dispose();+ });+ return { editor, snapping, cancel, dispose };+ });+}++it.each([+ [0.01, 1024],+ [0.125, 64],+ [0.25, 64],+ [0.5, 16],+ [1, 16],+ [1.001, 4],+ [2, 4],+ [4, 4],+ [4.001, 1],+ [8, 1],+])('matches the smallest visible dots at zoom %s', (scale, unit) => {+ expect(canvasSnapUnit('auto', scale, true)).toBe(unit);+ const visible = dotGridLevels(scale).filter((level) => level.opacity > 0);+ expect(unit).toBe(Math.min(...visible.map((level) => level.unit)));+ expect(canvasSnapUnit('none', scale, true)).toBeUndefined();+ expect(canvasSnapUnit('pixel', scale, false)).toBe(1);+ expect(canvasSnapUnit('auto', scale, false)).toBeUndefined();+});++it('defaults to free placement and changes only local policy when choosing a mode', () => {+ const { editor, snapping } = setup();+ const document = editor.document;+ expect(snapping.snapMode()).toBe('none');+ expect(editor.getSnapUnit()).toBeUndefined();+ editor.beginRectangle({ x: 1.25, y: 2.75 });+ editor.updateRectangle({ x: 11.5, y: 23.5 });+ expect(editor.getPreview()).toEqual({+ x: 1.25,+ y: 2.75,+ width: 10.25,+ height: 20.75,+ });+ editor.cancelRectangle();+ snapping.setSnapMode('pixel');+ editor.beginRectangle({ x: 1.25, y: 2.75 });+ editor.updateRectangle({ x: 11.5, y: 23.5 });+ expect(editor.getPreview()).toEqual({ x: 1, y: 3, width: 11, height: 21 });+ editor.cancelRectangle();+ snapping.setSnapMode('none');+ expect(editor.getSnapUnit()).toBeUndefined();+ expect(editor.document).toBe(document);+ expect(editor.getSession().canUndo).toBe(false);+});++it('follows zoom and grid visibility in auto mode while pixel mode stays at one', () => {+ const { editor, snapping } = setup();+ snapping.setSnapMode('auto');+ expect(editor.getSnapUnit()).toBe(16);+ editor.zoomAt({ x: 0, y: 0 }, 2);+ expect(editor.getSnapUnit()).toBe(4);+ editor.zoomAt({ x: 0, y: 0 }, 8);+ expect(editor.getSnapUnit()).toBe(1);+ snapping.setGrid(false);+ editor.zoomAt({ x: 0, y: 0 }, 0.125);+ expect(snapping.snapMode()).toBe('auto');+ expect(editor.getSnapUnit()).toBeUndefined();+ snapping.setGrid(true);+ expect(editor.getSnapUnit()).toBe(64);+ snapping.setSnapMode('pixel');+ snapping.setGrid(false);+ editor.zoomAt({ x: 0, y: 0 }, 8);+ expect(editor.getSnapUnit()).toBe(1);+ snapping.setSnapMode('none');+ editor.zoomAt({ x: 0, y: 0 }, 1);+ expect(editor.getSnapUnit()).toBeUndefined();+});++it('invalidates host previews only when the unit changes, and unsubscribes on disposal', () => {+ const { editor, snapping, cancel, dispose } = setup();+ snapping.setSnapMode('auto');+ cancel.mockClear();+ editor.beginRectangle({ x: 0, y: 0 });+ editor.updateRectangle({ x: 100, y: 100 });+ editor.panBy({ x: 10, y: 20 });+ editor.zoomAt({ x: 0, y: 0 }, 0.8);+ expect(editor.getSnapUnit()).toBe(16);+ expect(cancel).not.toHaveBeenCalled();+ editor.zoomAt({ x: 0, y: 0 }, 2);+ expect(cancel).toHaveBeenCalledOnce();+ expect(editor.getPreview()).toBeUndefined();+ expect(editor.getSession().canUndo).toBe(false);+ dispose();+ editor.zoomAt({ x: 0, y: 0 }, 8);+ expect(editor.getSnapUnit()).toBe(4);+});diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.tsnew file mode 100644index 0000000000..db3e4cc3de--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-snapping.ts@@ -0,0 +1,36 @@+import type { GraphicsEditor } from '@macro-inc/graphics';+import { batch, createSignal, onCleanup } from 'solid-js';+import { type CanvasSnapMode, canvasSnapUnit } from '../core/snapping';++/** Canvas policy translates the visible grid into the engine's arbitrary unit. */+export function createCanvasSnapping(+ editor: GraphicsEditor,+ cancelPreviews: () => void+) {+ const [snapMode, setMode] = createSignal<CanvasSnapMode>('none');+ const [grid, setGridVisible] = createSignal(true);+ const apply = () => {+ const unit = canvasSnapUnit(snapMode(), editor.getCamera().scale, grid());+ if (unit === editor.getSnapUnit()) return;+ cancelPreviews();+ editor.setSnapUnit(unit);+ };+ apply();+ onCleanup(editor.subscribeCamera(apply));+ return {+ snapMode,+ grid,+ setSnapMode(mode: CanvasSnapMode) {+ batch(() => {+ setMode(mode);+ apply();+ });+ },+ setGrid(visible: boolean) {+ batch(() => {+ setGridVisible(visible);+ apply();+ });+ },+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.test.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.test.tsnew file mode 100644index 0000000000..93bd0cabee--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.test.ts@@ -0,0 +1,124 @@+import {+ type Appearance,+ createGraphicsEditor,+ IDENTITY,+} from '@macro-inc/graphics';+import { createRoot } from 'solid-js';+import { expect, it } from 'vitest';+import { initialAppearance } from '../core/seed-scene';+import { createCanvasState } from './create-canvas-state';++it.each(['arrow', 'pencil', 'line', 'connector'] as const)(+ '%s restores visible drawing defaults without changing the selected shape',+ (tool) => {+ createRoot((dispose) => {+ const editor = createGraphicsEditor([+ {+ id: 'rect',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: IDENTITY,+ geometry: { width: 160, height: 100 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ ]);+ try {+ const state = createCanvasState(editor, (geometry) => ({+ width: geometry.width,+ height: geometry.height,+ }));+ editor.select('rect');+ for (const stroke of [+ 'transparent',+ 'none',+ '#1230',+ '#12345600',+ 'rgba(1, 2, 3, 0)',+ ]) {+ state.chooseTool('select');+ state.style({ stroke, strokeWidth: 0, opacity: 0 });+ const before = editor.document;+ state.chooseTool(tool);+ expect(state.defaults()).toMatchObject({+ stroke: initialAppearance.stroke,+ strokeWidth: initialAppearance.strokeWidth,+ opacity: initialAppearance.opacity,+ });+ expect(editor.document).toBe(before);+ }+ } finally {+ dispose();+ editor.dispose();+ }+ });+ }+);++it('preserves visible stroke choices and lets filled shapes keep no-stroke defaults', () => {+ createRoot((dispose) => {+ const editor = createGraphicsEditor([]);+ try {+ const state = createCanvasState(editor, (geometry) => ({+ width: geometry.width,+ height: geometry.height,+ }));+ const visible: Partial<Appearance> = {+ stroke: '#12345680',+ strokeWidth: 8,+ opacity: 0.4,+ strokeStyle: 'dashed',+ };+ state.style(visible);+ for (const tool of ['arrow', 'pencil', 'line', 'connector'] as const) {+ state.chooseTool(tool);+ expect(state.defaults()).toMatchObject(visible);+ }+ state.style({ stroke: 'transparent' });+ state.chooseTool('rectangle');+ expect(state.defaults().stroke).toBe('transparent');+ state.chooseTool('pencil');+ expect(state.defaults()).toMatchObject({+ ...visible,+ stroke: initialAppearance.stroke,+ });+ expect(editor.getSession().canUndo).toBe(false);+ } finally {+ dispose();+ editor.dispose();+ }+ });+});++it('shows a canvas radius drag in the inspector before committing and restores it on cancel', () => {+ createRoot((dispose) => {+ const editor = createGraphicsEditor([+ {+ id: 'rect',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: IDENTITY,+ geometry: { width: 160, height: 100 },+ appearance: { fill: 'red', stroke: 'black', cornerRadius: 8 },+ },+ ]);+ try {+ const state = createCanvasState(editor, (geometry) => ({+ width: geometry.width,+ height: geometry.height,+ }));+ editor.select('rect');+ editor.beginTransform('rect', { x: 16, y: 16 }, 'radius-nw');+ editor.updateTransform({ x: 40, y: 40 });+ expect(state.appearanceValue('cornerRadius')).toBe(32);+ expect(editor.document.items.rect).toMatchObject({+ appearance: { cornerRadius: 8 },+ });+ editor.cancelTransform();+ expect(state.appearanceValue('cornerRadius')).toBe(8);+ expect(editor.getSession().canUndo).toBe(false);+ } finally {+ dispose();+ editor.dispose();+ }+ });+});diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.tsnew file mode 100644index 0000000000..ee68810be8--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-canvas-state.ts@@ -0,0 +1,195 @@+import {+ type Appearance,+ duplicateCommand,+ type GraphicsEditor,+ isShape,+ resolveAppearance,+ roots,+ type ShapeKind,+ selectedShapeIds,+ type TextMeasurer,+} from '@macro-inc/graphics';+import { createGraphicsProjection } from '@macro-inc/graphics/solid';+import { parsePickerColor } from '@ui/utils/color';+import { createMemo, createSignal } from 'solid-js';+import { initialAppearance } from '../core/defaults';+import { createCanvasSnapping } from './create-canvas-snapping';+import { createConnectorState } from './create-connector-state';+import { createEmbedState } from './create-embed-state';+import { createEraserState } from './create-eraser-state';+import { createInspectorPreview } from './create-inspector-preview';+import { createTextState } from './create-text-state';++export type CanvasTool =+ | 'eraser'+ | 'select'+ | 'pan'+ | 'arrow'+ | 'line'+ | Exclude<ShapeKind, 'image' | 'video' | 'document'>;+export type CanvasState = ReturnType<typeof createCanvasState>;++export function createCanvasState(+ editor: GraphicsEditor,+ measureText: TextMeasurer+) {+ const projection = createGraphicsProjection(editor);+ const inspector = createInspectorPreview(editor, measureText);+ const [tool, setTool] = createSignal<CanvasTool>('select');+ const eraser = createEraserState(editor, () => tool() === 'eraser');+ const [defaults, setDefaults] = createSignal(initialAppearance);+ const text = createTextState(editor, measureText, defaults);+ const connector = createConnectorState(editor);+ const [notice, setNotice] = createSignal('Ready');+ const selection = createMemo(+ () => roots(projection.snapshot(), projection.session().selectedIds),+ undefined,+ {+ equals: (a, b) =>+ a.length === b.length && a.every((id, i) => id === b[i]),+ }+ );+ const shapes = createMemo(() =>+ selectedShapeIds(projection.snapshot(), selection()).flatMap((id) => {+ const item = projection.snapshot().items[id];+ return isShape(item) ? [item] : [];+ })+ );+ const canvasColors = createMemo(() => {+ const colors = new Set<string>();+ for (const item of Object.values(projection.document.items)) {+ if (!isShape(item)) continue;+ if (item.type === 'rectangle' || item.type === 'ellipse') {+ colors.add(item.appearance.fill);+ }+ if (+ ['rectangle', 'ellipse', 'connector', 'pencil', 'text'].includes(+ item.type+ )+ ) {+ colors.add(item.appearance.stroke);+ }+ }+ return [...colors].filter(+ (color) => color && color !== 'transparent' && color !== 'none'+ );+ });+ const radiusPreview = createMemo(() => {+ const gesture = projection.session().transform;+ return gesture?.kind === 'radius' ? gesture.nodes : undefined;+ });+ function appearanceValue<K extends keyof Appearance>(key: K) {+ const fallback = resolveAppearance(defaults())[key];+ const values = shapes()+ .filter((shape) => {+ if (key === 'cornerRadius') return shape.type === 'rectangle';+ if (key === 'fill')+ return shape.type === 'rectangle' || shape.type === 'ellipse';+ if (key === 'strokeStyle')+ return ['rectangle', 'ellipse', 'connector'].includes(shape.type);+ if (key === 'strokeWidth')+ return ['rectangle', 'ellipse', 'connector', 'pencil'].includes(+ shape.type+ );+ return true;+ })+ .map((shape) => {+ const preview =+ key === 'cornerRadius' ? radiusPreview()?.[shape.id] : undefined;+ const item = isShape(preview) ? preview : shape;+ return resolveAppearance(item.appearance)[key] ?? fallback;+ });+ if (!values.length) return resolveAppearance(defaults())[key];+ return values.every((value) => value === values[0]) ? values[0] : undefined;+ }+ const chooseTool = (next: CanvasTool) => {+ inspector.cancel();+ eraser.cancel();+ embeds.exit();+ text.finish();+ connector.interaction.cancel();+ if (next === 'arrow' || next === 'line' || next === 'connector')+ connector.preset(next);+ if (['arrow', 'line', 'connector', 'pencil'].includes(next)) {+ // Stroke-only tools cannot inherit an invisible style from filled shapes.+ setDefaults((value) => ({+ ...value,+ stroke:+ !value.stroke.trim() || parsePickerColor(value.stroke)?.a === 0+ ? initialAppearance.stroke+ : value.stroke,+ strokeWidth:+ value.strokeWidth === 0+ ? initialAppearance.strokeWidth+ : value.strokeWidth,+ opacity:+ value.opacity === 0 ? initialAppearance.opacity : value.opacity,+ }));+ }+ editor.cancelShape();+ editor.cancelTransform();+ setTool(next);+ };+ const embeds = createEmbedState(editor, projection.document, () =>+ chooseTool('select')+ );+ const canGroup = () => {+ const nodes = selection().map((id) => projection.document.items[id]);+ const first = nodes[0];+ return (+ nodes.length > 1 &&+ first?.type !== 'surface' &&+ !!first &&+ nodes.every(+ (node) =>+ node?.type !== 'surface' &&+ node?.placement.parentId === first.placement.parentId+ )+ );+ };+ const snapping = createCanvasSnapping(editor, () => {+ inspector.cancel();+ connector.interaction.cancel();+ eraser.cancel();+ });+ return {+ editor,+ ...snapping,+ snapUnit: () => projection.session().snapUnit,+ inspector,+ eraser,+ embeds,+ text,+ connector,+ isConnectorTool: () => ['connector', 'arrow', 'line'].includes(tool()),+ ...projection,+ tool,+ chooseTool,+ defaults,+ notice,+ setNotice,+ selection,+ shapes,+ appearanceValue,+ canvasColors,+ canGroup,+ canUngroup: () =>+ selection().length === 1 &&+ projection.document.items[selection()[0]!]?.type === 'group',+ style(patch: Partial<Appearance>) {+ setDefaults((value) => ({ ...value, ...patch }));+ editor.setSelectionAppearance(patch);+ },+ duplicate: () =>+ editor.execute(duplicateCommand, { createId: () => crypto.randomUUID() }),+ group: () => {+ if (canGroup()) editor.groupSelection(crypto.randomUUID());+ },+ ungroup: () => editor.ungroupSelection(),+ shapeCreated(id: string) {+ if (tool() === 'pencil') return;+ editor.select(id);+ setTool('select');+ },+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-connector-state.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-connector-state.tsnew file mode 100644index 0000000000..a6a255acb7--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-connector-state.ts@@ -0,0 +1,49 @@+import {+ type ConnectorGesture,+ type ConnectorStyle,+ type ConnectorTarget,+ connectorStyleCommand,+ createConnectorInteraction,+ type GraphicsEditor,+ setConnectorCommand,+} from '@macro-inc/graphics';+import { batch, createSignal, onCleanup } from 'solid-js';++export function createConnectorState(editor: GraphicsEditor) {+ const [gesture, setGesture] = createSignal<ConnectorGesture>();+ const [target, setTarget] = createSignal<ConnectorTarget>();+ const [defaults, setDefaults] = createSignal<ConnectorStyle>({+ route: 'stepped',+ startHead: 'none',+ endHead: 'arrow',+ });+ const interaction = createConnectorInteraction({+ getDocument: () => editor.document,+ getSnapUnit: editor.getSnapUnit,+ commit: (item) => editor.execute(setConnectorCommand, item),+ onChange: () =>+ batch(() => {+ setGesture(interaction.getState());+ setTarget(interaction.getTarget());+ }),+ });+ onCleanup(interaction.cancel);+ return {+ interaction,+ gesture,+ target,+ defaults,+ preview: () => (gesture() ? interaction.getPreviewDocument() : undefined),+ preset(tool: 'arrow' | 'line' | 'connector') {+ setDefaults({+ route: tool === 'connector' ? 'stepped' : 'straight',+ startHead: 'none',+ endHead: tool === 'line' ? 'none' : 'arrow',+ });+ },+ style(patch: Partial<ConnectorStyle>) {+ setDefaults((value) => ({ ...value, ...patch }));+ editor.execute(connectorStyleCommand, patch);+ },+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.test.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.test.tsnew file mode 100644index 0000000000..704865407e--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.test.ts@@ -0,0 +1,117 @@+import {+ createGraphicsEditor,+ setShapeLabelCommand,+} from '@macro-inc/graphics';+import { afterEach, expect, it, vi } from 'vitest';+import type { CanvasFile } from '../core/document-format';+import { createCanvasNextScene } from '../core/seed-scene';+import { plainRichText } from '../core/text-codec';+import { createDocumentPersistence } from './create-document-persistence';++const cleanups: (() => void)[] = [];+afterEach(() => {+ cleanups.splice(0).forEach((f) => f());+ vi.useRealTimers();+});+function setup(+ save = vi.fn(async (_file: CanvasFile) => new Blob()),+ canEdit = () => true+) {+ vi.useFakeTimers();+ const initial: CanvasFile = { version: 2, document: createCanvasNextScene() };+ const editor = createGraphicsEditor(initial.document);+ const persistence = createDocumentPersistence(editor, initial, {+ save,+ canEdit,+ });+ cleanups.push(() => {+ persistence.dispose();+ editor.dispose();+ });+ const edit = (text: string) =>+ editor.execute(setShapeLabelCommand, {+ id: 'welcome-rectangle',+ label: {+ content: plainRichText(text),+ fontSize: 24,+ fontFamily: 'sans',+ height: 32,+ },+ });+ return { editor, persistence, edit, save };+}++it('does not save on load, view changes, or in read-only mode', async () => {+ const { editor, persistence, edit, save } = setup(undefined, () => false);+ editor.panBy({ x: 10, y: 20 });+ await vi.advanceTimersByTimeAsync(1000);+ await persistence.flush();+ expect(save).not.toHaveBeenCalled();+ edit('Blocked');+ await vi.advanceTimersByTimeAsync(1000);+ await persistence.flush();+ expect(save).not.toHaveBeenCalled();+});++it('debounces edits and round-trips a versioned snapshot', async () => {+ const { editor, persistence, edit, save } = setup();+ await persistence.flush();+ expect(save).not.toHaveBeenCalled();+ edit('One');+ edit('Two');+ await vi.advanceTimersByTimeAsync(500);+ expect(save).toHaveBeenCalledTimes(1);+ expect(save.mock.calls[0]?.[0]).toEqual({+ version: 2,+ document: editor.document,+ });+ expect(persistence.dirty()).toBe(false);+});++it('serializes saves and drains edits made while a request is pending', async () => {+ let finish!: (blob: Blob) => void;+ const save = vi.fn(+ (_file: CanvasFile) =>+ new Promise<Blob>((resolve) => {+ finish = resolve;+ })+ );+ const { editor, persistence, edit } = setup(save);+ edit('First');+ const flushing = persistence.flush();+ edit('Second');+ await vi.advanceTimersByTimeAsync(500);+ expect(save).toHaveBeenCalledTimes(1);+ finish(new Blob());+ await Promise.resolve();+ expect(save).toHaveBeenCalledTimes(2);+ expect(save.mock.calls[1]?.[0].document).toBe(editor.document);+ finish(new Blob());+ await flushing;+ expect(persistence.status()).toBe('saved');+});++it('keeps failed edits dirty and retries the latest snapshot', async () => {+ const save = vi+ .fn(async (_file: CanvasFile) => new Blob())+ .mockRejectedValueOnce(new Error('offline'));+ const { editor, persistence, edit } = setup(save);+ edit('Unsaved');+ await persistence.flush();+ expect(persistence.status()).toBe('error');+ expect(persistence.dirty()).toBe(true);+ edit('Newest');+ await persistence.flush();+ expect(save.mock.calls[1]?.[0].document).toBe(editor.document);+ expect(persistence.dirty()).toBe(false);+});++it('rechecks permissions after a queued edit', async () => {+ let writable = true;+ const { persistence, edit, save } = setup(undefined, () => writable);+ edit('Change');+ writable = false;+ await vi.advanceTimersByTimeAsync(500);+ expect(save).not.toHaveBeenCalled();+ expect(persistence.dirty()).toBe(true);+});diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.tsnew file mode 100644index 0000000000..40f3e457f3--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-document-persistence.ts@@ -0,0 +1,75 @@+import type { GraphicsEditor } from '@macro-inc/graphics';+import { createSignal } from 'solid-js';+import type { CanvasDocumentSource } from '../context/document-source';+import type { CanvasFile } from '../core/document-format';++export function createDocumentPersistence(+ editor: GraphicsEditor,+ initial: CanvasFile,+ source: CanvasDocumentSource+) {+ const [status, setStatus] = createSignal<+ 'saved' | 'pending' | 'saving' | 'error'+ >('saved');+ const [savedFile, setSavedFile] = createSignal<Blob>();+ let saved = editor.document;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let running: Promise<void> | undefined;+ let disposed = false;+ const dirty = () => editor.document !== saved;+ async function drain() {+ while (dirty() && source.canEdit()) {+ const snapshot = editor.document;+ setStatus('saving');+ try {+ const file = await source.save({ ...initial, document: snapshot });+ saved = snapshot;+ setSavedFile(file);+ } catch {+ setStatus('error');+ return;+ }+ }+ setStatus(dirty() ? 'pending' : 'saved');+ }+ function flush(): Promise<void> {+ clearTimeout(timer);+ if (running) return running;+ running = drain();+ return finishRun(running);+ }+ async function finishRun(promise: Promise<void>) {+ try {+ await promise;+ } finally {+ running = undefined;+ }+ }+ const unsubscribe = editor.subscribeDocument(() => {+ if (disposed) return;+ if (!dirty()) {+ clearTimeout(timer);+ setStatus(running ? 'saving' : 'saved');+ return;+ }+ if (!source.canEdit()) return;+ setStatus('pending');+ clearTimeout(timer);+ timer = setTimeout(() => {+ void flush();+ }, 500);+ });+ return {+ status,+ savedFile,+ dirty,+ flush,+ dispose() {+ disposed = true;+ unsubscribe();+ clearTimeout(timer);+ // The captured source keeps this document's identity even after navigation.+ void flush();+ },+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-embed-state.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-embed-state.tsnew file mode 100644index 0000000000..7774bf1641--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-embed-state.ts@@ -0,0 +1,36 @@+import type { GraphicsDocument, GraphicsEditor } from '@macro-inc/graphics';+import { createSignal } from 'solid-js';+import { canEmbedDocument } from '../core/document-display';++export function createEmbedState(+ editor: GraphicsEditor,+ document: GraphicsDocument,+ prepare: () => void+) {+ const [activeId, setActiveId] = createSignal<string>();+ const active = () => {+ const id = activeId();+ const item = id ? document.items[id] : undefined;+ return item?.type === 'document' &&+ item.geometry.display === 'embed' &&+ canEmbedDocument(item.geometry.fileType)+ ? id+ : undefined;+ };+ return {+ active,+ enter(id: string) {+ const item = document.items[id];+ if (+ item?.type !== 'document' ||+ item.geometry.display !== 'embed' ||+ !canEmbedDocument(item.geometry.fileType)+ )+ return;+ prepare();+ editor.select(id);+ setActiveId(id);+ },+ exit: () => setActiveId(undefined),+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.test.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.test.tsnew file mode 100644index 0000000000..22a3ac1560--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.test.ts@@ -0,0 +1,95 @@+import { createGraphicsEditor, drawableIds } from '@macro-inc/graphics';+import { createRoot } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { createCanvasNextScene } from '../core/seed-scene';+import { createEraserState } from './create-eraser-state';++const cleanups: (() => void)[] = [];+afterEach(() => {+ cleanups.splice(0).forEach((fn) => fn());+ vi.useRealTimers();+});+function setup() {+ return createRoot((dispose) => {+ cleanups.push(dispose);+ const editor = createGraphicsEditor(createCanvasNextScene());+ cleanups.push(editor.dispose);+ const state = createEraserState(editor, () => true);+ const element = document.createElement('div');+ element.setPointerCapture = vi.fn();+ element.hasPointerCapture = () => false;+ cleanups.push(state.attach(element));+ const pointer = (type: string, x: number, y: number) =>+ element.dispatchEvent(+ Object.assign(+ new MouseEvent(type, { clientX: x, clientY: y, button: 0 }),+ { pointerId: 1 }+ )+ );+ return { editor, state, pointer };+ });+}+it('previews removals, cancels without history, and fades the trail', () => {+ vi.useFakeTimers();+ const { editor, state, pointer } = setup();+ pointer('pointerdown', 120, 130);+ pointer('pointermove', 300, 130);+ expect(drawableIds(state.preview()!)).toHaveLength(3);+ expect(drawableIds(editor.document)).toHaveLength(3);+ vi.advanceTimersByTime(16);+ expect(state.trail().length).toBeGreaterThan(0);+ state.cancel();+ expect(state.preview()).toBeUndefined();+ expect(editor.getSession().canUndo).toBe(false);+ vi.advanceTimersByTime(350);+ expect(state.trail()).toEqual([]);+});+it('commits crossed shapes together on release and cancels a lost pointer', () => {+ const { editor, state, pointer } = setup();+ pointer('pointerdown', 0, 200);+ pointer('pointermove', 700, 200);+ pointer('pointerup', 700, 200);+ expect(state.preview()).toBeUndefined();+ expect(drawableIds(editor.document)).toEqual(['welcome-small']);+ editor.undo();+ expect(drawableIds(editor.document)).toHaveLength(3);+ pointer('pointerdown', 120, 130);+ pointer('pointercancel', 120, 130);+ expect(state.preview()).toBeUndefined();+ expect(drawableIds(editor.document)).toHaveLength(3);+});++it('thins points with age, expires them by time, and preserves the preview while moving', () => {+ vi.useFakeTimers();+ const { state, pointer } = setup();+ pointer('pointerdown', 120, 130);+ const preview = state.preview();+ for (let x = 122; x <= 220; x += 2) pointer('pointermove', x, 130);+ vi.advanceTimersByTime(16);+ expect(state.trail().length).toBeGreaterThan(10);+ const pressure = state.trail()[0]![2];+ vi.advanceTimersByTime(160);+ pointer('pointermove', 230, 130);+ vi.advanceTimersByTime(16);+ expect(state.trail()[0]![2]).toBeLessThan(pressure);+ expect(state.trail().at(-1)![2]).toBeGreaterThan(state.trail()[0]![2]);+ expect(state.preview()).toBe(preview);+ vi.advanceTimersByTime(144);+ expect(state.trail()).toHaveLength(1);+ vi.advanceTimersByTime(200);+ expect(state.trail()).toEqual([]);+});+it('previews erased shapes at one fifth of their original opacity without changing the document', () => {+ const { editor, state, pointer } = setup();+ editor.select('welcome-rectangle');+ editor.setSelectionAppearance({ opacity: 0.5 });+ pointer('pointerdown', 120, 130);+ expect(state.preview()!.items['welcome-rectangle']).toMatchObject({+ appearance: { opacity: 0.1 },+ });+ expect(editor.document.items['welcome-rectangle']).toMatchObject({+ appearance: { opacity: 0.5 },+ });+ pointer('pointercancel', 120, 130);+ expect(state.preview()).toBeUndefined();+});diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.tsnew file mode 100644index 0000000000..7115399339--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-eraser-state.ts@@ -0,0 +1,148 @@+import {+ type GraphicsEditor,+ isShape,+ type PencilPoint,+ type Point,+ screenToWorld,+ selectedShapeIds,+} from '@macro-inc/graphics';+import { type Accessor, createMemo, createSignal, onCleanup } from 'solid-js';+import { eraseCommand, eraserHits } from '../core/eraser';++export function createEraserState(+ editor: GraphicsEditor,+ active: Accessor<boolean>+) {+ const [hits, setHits] = createSignal<readonly string[]>([]);+ const lifetime = 300;+ let samples: (Point & { time: number })[] = [];+ const [trail, setTrail] = createSignal<readonly PencilPoint[]>([]);+ let pointer: number | undefined;+ let previous: Point | undefined;+ let surface: HTMLElement | undefined;+ let frame: number | undefined;+ const erased = new Set<string>();+ const preview = createMemo(() => {+ if (!hits().length) return;+ const document = editor.document;+ const items = { ...document.items };+ for (const id of selectedShapeIds(document, hits())) {+ const item = items[id];+ if (isShape(item))+ items[id] = {+ ...item,+ appearance: {+ ...item.appearance,+ opacity: (item.appearance.opacity ?? 1) * 0.2,+ },+ };+ }+ return { ...document, items };+ });+ const cancel = () => {+ const id = pointer;+ pointer = undefined;+ previous = undefined;+ setHits([]);+ erased.clear();+ if (id !== undefined && surface?.hasPointerCapture(id))+ surface.releasePointerCapture(id);+ };+ const animate = () => {+ const now = performance.now();+ samples = samples.filter((point) => now - point.time < lifetime);+ setTrail(+ samples.map(+ (point): PencilPoint => [+ point.x,+ point.y,+ Math.max(0, 1 - (now - point.time) / lifetime),+ ]+ )+ );+ frame = samples.length ? requestAnimationFrame(animate) : undefined;+ };+ const append = (point: Point) => {+ samples.push({ ...point, time: performance.now() });+ if (frame === undefined) frame = requestAnimationFrame(animate);+ };+ const sample = (event: PointerEvent, force = false) => {+ if (!surface) return;+ const rect = surface.getBoundingClientRect();+ const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };+ const distance = previous+ ? Math.hypot(point.x - previous.x, point.y - previous.y)+ : Infinity;+ if (!force && distance < 2) return;+ const camera = editor.getCamera();+ const found = eraserHits(+ editor.document,+ screenToWorld(camera, previous ?? point),+ screenToWorld(camera, point),+ 6 / camera.scale,+ erased+ );+ if (found.length) {+ for (const id of found) erased.add(id);+ setHits([...erased]);+ }+ previous = point;+ if (distance >= 2) append(point);+ };+ onCleanup(() => {+ cancel();+ if (frame !== undefined) cancelAnimationFrame(frame);+ });+ return {+ preview,+ trail,+ cancel,+ attach(element: HTMLElement) {+ surface = element;+ const down = (event: PointerEvent) => {+ if (!active() || event.button !== 0 || pointer !== undefined) return;+ event.preventDefault();+ event.stopImmediatePropagation();+ element.focus({ preventScroll: true });+ editor.select();+ pointer = event.pointerId;+ previous = undefined;+ samples = [];+ setTrail([]);+ element.setPointerCapture(pointer);+ sample(event);+ };+ const move = (event: PointerEvent) => {+ if (pointer !== event.pointerId) return;+ event.preventDefault();+ event.stopImmediatePropagation();+ sample(event);+ };+ const up = (event: PointerEvent) => {+ if (pointer !== event.pointerId) return;+ event.preventDefault();+ event.stopImmediatePropagation();+ sample(event, true);+ editor.execute(eraseCommand, hits());+ cancel();+ };+ const lost = (event: PointerEvent) => {+ if (pointer === event.pointerId) cancel();+ };+ element.addEventListener('pointerdown', down, true);+ element.addEventListener('pointermove', move, true);+ element.addEventListener('pointerup', up, true);+ element.addEventListener('pointercancel', lost, true);+ element.addEventListener('lostpointercapture', lost, true);+ return () => {+ cancel();+ element.removeEventListener('pointerdown', down, true);+ element.removeEventListener('pointermove', move, true);+ element.removeEventListener('pointerup', up, true);+ element.removeEventListener('pointercancel', lost, true);+ element.removeEventListener('lostpointercapture', lost, true);+ surface = undefined;+ };+ },+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.test.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.test.tsnew file mode 100644index 0000000000..ddff61bc9f--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.test.ts@@ -0,0 +1,226 @@+import {+ createGraphicsEditor,+ setShapeLabelCommand,+ styleCommand,+} from '@macro-inc/graphics';+import { createRoot } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { createCanvasNextScene } from '../core/seed-scene';+import { layoutValue, selectionLayoutCommand } from '../core/selection-layout';+import { plainRichText } from '../core/text-codec';+import { createInspectorPreview } from './create-inspector-preview';+import { createTextState } from './create-text-state';++const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((cleanup) => cleanup()));++function setup() {+ return createRoot((dispose) => {+ cleanups.push(dispose);+ const editor = createGraphicsEditor(createCanvasNextScene());+ cleanups.push(editor.dispose);+ editor.select('welcome-rectangle');+ const preview = createInspectorPreview(editor);+ const style = () =>+ preview.begin(+ (context, opacity) => styleCommand.apply(context, { opacity }).document,+ (opacity) => editor.setSelectionAppearance({ opacity })+ );+ const text = createTextState(+ editor,+ (geometry) => ({+ width: geometry.width,+ height: geometry.fontSize * 1.35,+ }),+ () => ({ fill: 'transparent', stroke: '#000000' })+ );+ return { editor, preview, style, text, dispose };+ });+}++it('previews without publishing saved document changes and commits one undo step', () => {+ const { editor, preview, style } = setup();+ const before = editor.document;+ const changed = vi.fn();+ editor.subscribeDocument(changed);+ const drag = style();+ drag.preview(0.7);+ drag.preview(0.4);+ expect(preview.document()?.items['welcome-rectangle']).toMatchObject({+ appearance: { opacity: 0.4 },+ });+ expect(editor.document).toBe(before);+ expect(changed).not.toHaveBeenCalled();+ expect(editor.getSession().canUndo).toBe(false);+ drag.commit(0.4);+ expect(preview.document()).toBeUndefined();+ expect(changed).toHaveBeenCalledTimes(1);+ editor.undo();+ expect(editor.document).toEqual(before);+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ expect(editor.document.items['welcome-rectangle']).toMatchObject({+ appearance: { opacity: 0.4 },+ });+});++it('derives rotation previews from the starting scene, not previous samples', () => {+ const { editor, preview } = setup();+ const payload = (value: number) => ({ field: 'rotation' as const, value });+ const drag = preview.begin(+ (context, value) =>+ selectionLayoutCommand.apply(context, payload(value)).document,+ (value) => editor.execute(selectionLayoutCommand, payload(value))+ );+ drag.preview(90);+ drag.preview(30);+ expect(+ layoutValue(preview.document()!, ['welcome-rectangle'], 'rotation')+ ).toBe(30);+ expect(layoutValue(editor.document, ['welcome-rectangle'], 'rotation')).toBe(+ 0+ );+ drag.cancel();+ expect(preview.document()).toBeUndefined();+ expect(editor.getSession().canUndo).toBe(false);+});++it.each(['selection', 'document', 'dispose'] as const)(+ 'invalidates stale gestures after %s changes',+ (kind) => {+ const { editor, preview, style, dispose } = setup();+ const drag = style();+ drag.preview(0.5);+ if (kind === 'selection') editor.select('welcome-ellipse');+ if (kind === 'document') editor.setSelectionAppearance({ strokeWidth: 8 });+ if (kind === 'dispose') dispose();+ const before = editor.document;+ drag.preview(0.2);+ drag.commit(0.2);+ expect(preview.document()).toBeUndefined();+ expect(editor.document).toBe(before);+ }+);++it('previews shape-label font size and leaves the original geometry intact on cancel', () => {+ const { editor, text, preview } = setup();+ text.edit('welcome-rectangle');+ text.change(plainRichText('Label'));+ text.finish();+ const before = editor.document;+ const drag = text.scrubFontSize(preview);+ drag.preview(48);+ expect(preview.document()?.items['welcome-rectangle']).toMatchObject({+ geometry: { label: { fontSize: 48 } },+ });+ expect(editor.document).toBe(before);+ drag.cancel();+ expect(editor.document).toBe(before);+ const next = text.scrubFontSize(preview);+ next.preview(36);+ next.commit(36);+ expect(editor.document.items['welcome-rectangle']).toMatchObject({+ geometry: { label: { fontSize: 36 } },+ });+ editor.undo();+ expect(editor.document).toEqual(before);+});++it('restores an active text draft and its defaults on cancellation', () => {+ const { editor, text, preview } = setup();+ text.begin({ x: 10, y: 20 });+ text.change(plainRichText('Draft'));+ const original = text.draft();+ const drag = text.scrubFontSize(preview);+ drag.preview(48);+ expect(text.draft()?.geometry.fontSize).toBe(48);+ expect(text.defaults().fontSize).toBe(24);+ drag.cancel();+ expect(text.draft()).toBe(original);+ expect(editor.getSession().canUndo).toBe(false);+ const next = text.scrubFontSize(preview);+ next.preview(36);+ next.commit(36);+ expect(text.draft()?.geometry.fontSize).toBe(36);+ expect(text.defaults().fontSize).toBe(36);+ expect(editor.getSession().canUndo).toBe(false);+});++it('uses the same snap unit for layout scrubbing and commit, and cancels when it changes', () => {+ const { editor, preview } = setup();+ editor.setSnapUnit(8);+ const payload = (value: number) => ({+ field: 'width' as const,+ value,+ lockAspectRatio: true,+ });+ const begin = () =>+ preview.begin(+ (context, value) =>+ selectionLayoutCommand.apply(context, payload(value)).document,+ (value) => editor.execute(selectionLayoutCommand, payload(value))+ );+ const before = editor.document;+ const drag = begin();+ drag.preview(103);+ expect(layoutValue(preview.document()!, ['welcome-rectangle'], 'width')).toBe(+ 104+ );+ expect(editor.document).toBe(before);+ drag.commit(103);+ expect(layoutValue(editor.document, ['welcome-rectangle'], 'width')).toBe(+ 104+ );+ editor.undo();+ expect(editor.document).toEqual(before);+ const restored = editor.document;+ const cancelled = begin();+ cancelled.preview(103);+ editor.setSnapUnit(2);+ expect(preview.document()).toBeUndefined();+ cancelled.commit(103);+ expect(editor.document).toBe(restored);+});++it('uses the same label measurements during dimension scrubbing and commit', () => {+ createRoot((dispose) => {+ cleanups.push(dispose);+ const measure = (g: { width: number }) => ({+ width: g.width,+ height: g.width < 150 ? 81 : 27,+ });+ const editor = createGraphicsEditor(createCanvasNextScene(), {+ measureText: measure,+ });+ cleanups.push(editor.dispose);+ editor.execute(setShapeLabelCommand, {+ id: 'welcome-rectangle',+ label: {+ content: 'Wrapped label',+ fontSize: 20,+ fontFamily: 'sans',+ height: 27,+ },+ });+ editor.select('welcome-rectangle');+ const before = editor.document;+ const preview = createInspectorPreview(editor, measure);+ const drag = preview.begin(+ (context, value) =>+ selectionLayoutCommand.apply(context, { field: 'width', value })+ .document,+ (value) =>+ editor.execute(selectionLayoutCommand, { field: 'width', value })+ );+ drag.preview(100);+ const rendered = preview.document();+ expect(rendered?.items['welcome-rectangle']).toMatchObject({+ geometry: { width: 100, label: { fontSize: 20, height: 81 } },+ });+ expect(editor.document).toBe(before);+ drag.commit(100);+ expect(editor.document).toEqual(rendered);+ editor.undo();+ expect(editor.document).toEqual(before);+ });+});diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.tsnew file mode 100644index 0000000000..5979adb7c2--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-inspector-preview.ts@@ -0,0 +1,81 @@+import type {+ CommandContext,+ GraphicsDocument,+ GraphicsEditor,+ TextMeasurer,+} from '@macro-inc/graphics';+import { batch, createSignal, onCleanup } from 'solid-js';++export type InspectorNumberScrub = {+ preview: (value: number) => void;+ commit: (value: number) => void;+ cancel: () => void;+};++/** Inspector gestures paint a draft scene; only release changes the document. */+export function createInspectorPreview(+ editor: GraphicsEditor,+ measureText?: TextMeasurer+) {+ const [document, setDocument] = createSignal<GraphicsDocument>();+ let cancelActive: (() => void) | undefined;+ const cancel = () => cancelActive?.();+ onCleanup(cancel);++ function begin(+ render: (+ context: CommandContext,+ value: number+ ) => GraphicsDocument | undefined,+ commit: (value: number) => void,+ restore?: () => void+ ): InspectorNumberScrub {+ cancel();+ const context = {+ document: editor.document,+ selection: [...editor.getSession().selectedIds],+ snapUnit: editor.getSnapUnit(),+ measureText,+ };+ let active = true;+ const end = (revert: boolean) => {+ if (!active) return;+ active = false;+ detachDocument();+ detachSession();+ cancelActive = undefined;+ setDocument(undefined);+ if (revert) restore?.();+ };+ const cancelGesture = () => end(true);+ const detachDocument = editor.subscribeDocument(cancelGesture);+ const detachSession = editor.subscribeSession((session) => {+ if (+ session.snapUnit !== context.snapUnit ||+ session.transform ||+ session.box ||+ session.selectedIds.length !== context.selection.length ||+ session.selectedIds.some((id, index) => id !== context.selection[index])+ )+ cancelGesture();+ });+ cancelActive = cancelGesture;+ return {+ preview(value) {+ if (active) setDocument(render(context, value));+ },+ commit(value) {+ if (!active) return;+ batch(() => {+ end(false);+ commit(value);+ });+ },+ cancel: cancelGesture,+ };+ }++ return { document, begin, cancel };+}++export type CanvasInspectorPreview = ReturnType<typeof createInspectorPreview>;diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/create-text-state.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/create-text-state.tsnew file mode 100644index 0000000000..08848dad83--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/create-text-state.ts@@ -0,0 +1,275 @@+import {+ type Appearance,+ canLabel,+ children,+ type GraphicsCommand,+ type GraphicsEditor,+ inverse,+ type LabelShape,+ measureShapeLabel,+ multiply,+ type Point,+ type RichText,+ type ShapeItem,+ setShapeLabelCommand,+ setTextCommand,+ shapeLabelText,+ shapeProjection,+ snapPoint,+ snapValue,+ sortKeysBetween,+ type TextGeometry,+ type TextMeasurer,+ textDefinition,+ translation,+ withShapeLabel,+ worldMatrix,+} from '@macro-inc/graphics';+import { createSignal } from 'solid-js';+import {+ plainRichText,+ richTextPlainText,+ validCanvasText,+} from '../core/text-codec';+import type { CanvasInspectorPreview } from './create-inspector-preview';+export function createTextState(+ editor: GraphicsEditor,+ measure: TextMeasurer,+ appearance: () => Appearance+) {+ type TextDraft =+ | { kind: 'text'; item: ShapeItem<'text'> }+ | { kind: 'label'; item: LabelShape };+ const [editing, setEditing] = createSignal<TextDraft>();+ const draft = () => {+ const current = editing();+ if (current?.kind === 'label' && current.item.type === 'connector') {+ const { item, transform } = shapeProjection(+ editor.document,+ current.item.id,+ { [current.item.id]: current.item }+ );+ if (item?.type !== 'connector') return;+ return shapeLabelText({+ ...item,+ transform: multiply(+ inverse(worldMatrix(editor.document, item.placement.parentId)),+ transform+ ),+ });+ }+ return current?.kind === 'label'+ ? shapeLabelText(current.item)+ : current?.item;+ };+ const isLabel = () => editing()?.kind === 'label';+ const [defaults, setDefaults] = createSignal<+ Pick<TextGeometry, 'fontSize' | 'fontFamily' | 'autoWidth'>+ >({ fontSize: 24, fontFamily: 'sans', autoWidth: true });+ let flush: (() => void) | undefined;+ const resize = (geometry: TextGeometry) =>+ textDefinition.freezeGeometry({ ...geometry, ...measure(geometry) });+ function update(patch: Partial<TextGeometry>) {+ if (patch.content !== undefined && !validCanvasText(patch.content))+ throw new Error('Invalid canvas text');+ setEditing((current) => {+ if (!current) return;+ if (current.kind === 'text')+ return {+ ...current,+ item: {+ ...current.item,+ geometry: resize({ ...current.item.geometry, ...patch }),+ },+ };+ const item = current.item,+ before = item.geometry.label!;+ const label = measureShapeLabel(+ item,+ {+ ...before,+ content: patch.content ?? before.content,+ fontSize: patch.fontSize ?? before.fontSize,+ fontFamily: patch.fontFamily ?? before.fontFamily,+ },+ measure+ );+ return {+ ...current,+ item: withShapeLabel(item, label),+ };+ });+ }+ function finish() {+ flush?.();+ const current = editing();+ setEditing(undefined);+ flush = undefined;+ if (current?.kind === 'text') {+ if (richTextPlainText(current.item.geometry.content).trim())+ editor.execute(setTextCommand, current.item);+ else if (editor.document.items[current.item.id]?.type === 'text') {+ editor.select(current.item.id);+ editor.deleteSelection();+ }+ } else if (current) {+ const label = current.item.geometry.label;+ editor.execute(setShapeLabelCommand, {+ id: current.item.id,+ label:+ label && richTextPlainText(label.content).trim() ? label : undefined,+ });+ }+ }+ function createItem(+ point: Point,+ width: number | undefined,+ content: RichText+ ): ShapeItem<'text'> {+ point = snapPoint(point, editor.getSnapUnit());+ if (width !== undefined) width = snapValue(width, editor.getSnapUnit());+ const document = editor.document,+ ids = children(document),+ last = document.items[ids[ids.length - 1]!];+ return {+ id: crypto.randomUUID(),+ type: 'text',+ placement: {+ parentId: document.rootId,+ sortKey: sortKeysBetween(+ last && last.type !== 'surface' ? last.placement.sortKey : null,+ null,+ 1+ )[0]!,+ },+ transform: translation(point.x, point.y),+ appearance: { ...appearance(), fill: 'transparent' },+ geometry: resize({+ content,+ ...defaults(),+ autoWidth: width === undefined ? defaults().autoWidth : false,+ width: Math.max(40, width ?? 320),+ height: 32,+ }),+ };+ }+ function begin(point: Point, width?: number) {+ finish();+ editor.select();+ setEditing({+ kind: 'text',+ item: createItem(point, width, plainRichText()),+ });+ }+ function insert(content: RichText, point: Point, width = 400) {+ if (!validCanvasText(content)) throw new Error('Invalid canvas text');+ finish();+ if (!richTextPlainText(content).trim()) return;+ editor.execute(setTextCommand, createItem(point, width, content));+ }+ function edit(id: string) {+ if (draft()?.id === id) return;+ finish();+ const item = editor.document.items[id];+ if (item?.type !== 'text' && !canLabel(item)) return;+ const content =+ item.type === 'text'+ ? item.geometry.content+ : item.geometry.label?.content;+ if (content !== undefined && !validCanvasText(content)) return;+ editor.select(id);+ if (item.type === 'text') setEditing({ kind: 'text', item });+ else {+ const content = plainRichText('', 'center');+ const label =+ item.geometry.label ??+ measureShapeLabel(+ item,+ {+ content,+ fontSize: defaults().fontSize,+ fontFamily: defaults().fontFamily,+ height: defaults().fontSize * 1.35,+ },+ measure+ );+ setEditing({+ kind: 'label',+ item: withShapeLabel(item, label),+ });+ }+ }+ type TypographyPatch = Partial<+ Pick<TextGeometry, 'fontSize' | 'fontFamily' | 'autoWidth'>+ >;+ const typographyCommand: GraphicsCommand<TypographyPatch> = {+ id: 'canvas.typography',+ apply(context, patch) {+ if (context.selection.length !== 1) return { document: context.document };+ const item = context.document.items[context.selection[0]!];+ if (item?.type === 'text')+ return setTextCommand.apply(context, {+ ...item,+ geometry: resize({ ...item.geometry, ...patch }),+ });+ if (canLabel(item) && item.geometry.label)+ return setShapeLabelCommand.apply(context, {+ id: item.id,+ label: measureShapeLabel(+ item,+ {+ ...item.geometry.label,+ fontSize: patch.fontSize ?? item.geometry.label.fontSize,+ fontFamily: patch.fontFamily ?? item.geometry.label.fontFamily,+ },+ measure+ ),+ });+ return { document: context.document };+ },+ };+ function typography(patch: TypographyPatch) {+ setDefaults((value) => ({ ...value, ...patch }));+ if (draft()) {+ update(patch);+ return;+ }+ editor.execute(typographyCommand, patch);+ }+ return {+ draft,+ isLabel,+ defaults,+ begin,+ insert,+ edit,+ update,+ finish,+ typography,+ scrubFontSize(preview: CanvasInspectorPreview) {+ const original = editing();+ let last = original;+ return preview.begin(+ (context, fontSize) => {+ if (!original)+ return typographyCommand.apply(context, { fontSize }).document;+ update({ fontSize });+ last = editing();+ },+ (fontSize) => typography({ fontSize }),+ () => {+ if (original && editing() === last) setEditing(original);+ }+ );+ },+ setFlush: (next: (() => void) | undefined) => {+ flush = next;+ },+ change: (content: RichText) => update({ content }),+ cancel: () => {+ setEditing(undefined);+ flush = undefined;+ },+ };+}+export type CanvasTextState = ReturnType<typeof createTextState>;diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.test.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.test.tsnew file mode 100644index 0000000000..ef882b85ff--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.test.ts@@ -0,0 +1,44 @@+import { afterEach, expect, it, vi } from 'vitest';+import { readSwatchColor } from './read-swatch-color';++afterEach(() => vi.restoreAllMocks());++it('reads ordinary RGB swatches without allocating a drawing context', () => {+ const element = document.createElement('span');+ element.style.backgroundColor = 'rgb(51, 102, 153)';+ document.body.append(element);+ const getContext = vi.spyOn(HTMLCanvasElement.prototype, 'getContext');+ expect(readSwatchColor(element)).toBe('#336699');+ expect(getContext).not.toHaveBeenCalled();+ element.remove();+});++it('uses browser rendering for theme colors and retains alpha', () => {+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({+ backgroundColor: 'oklch(0.6 0.1 240)',+ } as CSSStyleDeclaration);+ const fillRect = vi.fn();+ const context = {+ fillStyle: '',+ fillRect,+ getImageData: () => ({ data: new Uint8ClampedArray([51, 102, 153, 128]) }),+ };+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(+ context as unknown as CanvasRenderingContext2D+ );+ expect(readSwatchColor(document.createElement('span'))).toBe('#33669980');+ expect(context.fillStyle).toBe('oklch(0.6 0.1 240)');+ expect(fillRect).toHaveBeenCalledWith(0, 0, 1, 1);+});++it('keeps a safe picker color if the browser cannot sample the swatch', () => {+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({+ backgroundColor: 'color(display-p3 1 0 0)',+ } as CSSStyleDeclaration);+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(() => {+ throw new Error('Unavailable');+ });+ expect(readSwatchColor(document.createElement('span'), '#336699')).toBe(+ '#336699'+ );+});diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.tsnew file mode 100644index 0000000000..5e21dd9308--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/read-swatch-color.ts@@ -0,0 +1,25 @@+import { normalizePickerColor } from '@ui/utils/color';++/** Read an existing CSS palette swatch only when opening its picker. The browser+ * resolves theme colors; the picker itself only receives an sRGB hex value. */+export function readSwatchColor(+ element: HTMLElement,+ fallback = '#000000'+): string {+ try {+ const color = getComputedStyle(element).backgroundColor;+ const parsed = normalizePickerColor(color);+ if (parsed) return parsed;+ const canvas = document.createElement('canvas');+ canvas.width = canvas.height = 1;+ const context = canvas.getContext('2d', { willReadFrequently: true });+ if (!context) return fallback;+ context.fillStyle = color;+ context.fillRect(0, 0, 1, 1);+ const channels = Array.from(context.getImageData(0, 0, 1, 1).data);+ if (channels[3] === 255) channels.pop();+ return `#${channels.map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;+ } catch {+ return fallback;+ }+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/text-input.test.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/text-input.test.tsnew file mode 100644index 0000000000..1042004261--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/text-input.test.ts@@ -0,0 +1,121 @@+import { createGraphicsEditor, insertShapesCommand } from '@macro-inc/graphics';+import { attachCameraControls } from '@macro-inc/graphics/browser';+import { createRoot } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { createCanvasState } from './create-canvas-state';+import { attachTextInput } from './text-input';++const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((fn) => fn()));+function setup() {+ const editor = createGraphicsEditor([+ {+ id: 'box',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: [1, 0, 0, 1, 20, 20],+ geometry: { width: 200, height: 100 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ ]);+ const root = document.createElement('div'),+ viewport = document.createElement('div');+ viewport.setAttribute('aria-label', 'Graphics canvas');+ root.append(viewport);+ document.body.append(root);+ viewport.setPointerCapture = vi.fn();+ viewport.hasPointerCapture = () => false;+ const state = createRoot((dispose) => {+ cleanups.push(dispose);+ return createCanvasState(editor, (g) => ({ width: g.width, height: 32.4 }));+ });+ const detach = attachTextInput(root, state),+ detachCanvas = attachCameraControls(viewport, editor, {+ tool: () => 'select',+ suspended: () => !!state.text.draft(),+ });+ cleanups.push(() => {+ detach();+ detachCanvas();+ editor.dispose();+ root.remove();+ });+ const pointer = (target: EventTarget, type: string, x: number, y: number) => {+ const event = new MouseEvent(type, {+ bubbles: true,+ cancelable: true,+ clientX: x,+ clientY: y,+ });+ Object.defineProperty(event, 'pointerId', { value: 1 });+ target.dispatchEvent(event);+ };+ return { state, viewport, pointer };+}+it('enters a shape label after two stationary taps even without a native dblclick', () => {+ const { state, viewport, pointer } = setup();+ pointer(viewport, 'pointerdown', 100, 60);+ pointer(window, 'pointerup', 100, 60);+ expect(state.text.draft()).toBeUndefined();+ pointer(viewport, 'pointerdown', 100, 60);+ pointer(window, 'pointerup', 100, 60);+ expect(state.text.isLabel()).toBe(true);+ expect(state.text.draft()?.id).toBe('box');+ expect(state.editor.getSession().transform).toBeUndefined();+});+it('does not interpret a move followed by a click as a label double-click', () => {+ const { state, viewport, pointer } = setup();+ pointer(viewport, 'pointerdown', 100, 60);+ pointer(window, 'pointermove', 130, 60);+ pointer(window, 'pointerup', 130, 60);+ pointer(viewport, 'pointerdown', 130, 60);+ pointer(window, 'pointerup', 130, 60);+ expect(state.text.draft()).toBeUndefined();+ expect(state.editor.document.items.box).toMatchObject({+ transform: [1, 0, 0, 1, 50, 20],+ });+});++it('does not create canvas text when double-clicking a document or embed', () => {+ const { viewport, state, pointer } = setup();+ const card = document.createElement('div');+ card.dataset.canvasDocument = 'doc';+ const button = document.createElement('button');+ card.append(button);+ viewport.append(card);+ for (let i = 0; i < 2; i++) {+ pointer(button, 'pointerdown', 50, 50);+ pointer(button, 'pointerup', 50, 50);+ }+ button.dispatchEvent(+ new MouseEvent('dblclick', { bubbles: true, clientX: 50, clientY: 50 })+ );+ expect(state.text.draft()).toBeUndefined();+});++it('opens an embed when pointer capture retargets double-click to the viewport', () => {+ const { viewport, state } = setup();+ state.editor.execute(insertShapesCommand, [+ {+ item: {+ id: 'embed',+ type: 'document',+ geometry: {+ documentId: 'file',+ name: 'Note',+ fileType: 'md',+ display: 'embed',+ width: 320,+ height: 240,+ },+ appearance: { fill: 'white', stroke: 'transparent' },+ },+ point: { x: 0, y: 0 },+ },+ ]);+ viewport.dispatchEvent(+ new MouseEvent('dblclick', { bubbles: true, clientX: 100, clientY: 100 })+ );+ expect(state.embeds.active()).toBe('embed');+ expect(state.text.draft()).toBeUndefined();+});diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/text-input.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/text-input.tsnew file mode 100644index 0000000000..c3f434a540--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/text-input.ts@@ -0,0 +1,182 @@+import { screenToWorld, textTargetAt } from '@macro-inc/graphics';+import type { CanvasState } from './create-canvas-state';+/** Canvas text gestures stay separate from geometric drawing and pointer capture. */+export function attachTextInput(root: HTMLElement, state: CanvasState) {+ let space = false;+ type Tap = { x: number; y: number; time: number; id: number };+ let pendingTap: Tap | undefined, lastTap: Tap | undefined;+ const closeTo = (tap: Tap, event: PointerEvent) =>+ Math.hypot(event.clientX - tap.x, event.clientY - tap.y) <= 4;+ const trackMove = (event: PointerEvent) => {+ if (pendingTap?.id === event.pointerId && !closeTo(pendingTap, event))+ pendingTap = undefined;+ };+ const trackUp = (event: PointerEvent) => {+ if (pendingTap?.id !== event.pointerId) return;+ lastTap = closeTo(pendingTap, event)+ ? { ...pendingTap, time: event.timeStamp }+ : undefined;+ pendingTap = undefined;+ };+ let origin: { x: number; y: number; id: number } | undefined;+ const canvas = () =>+ root.querySelector<HTMLElement>('[aria-label="Graphics canvas"]');+ const point = (x: number, y: number) => {+ const rect = canvas()!.getBoundingClientRect();+ return screenToWorld(state.editor.getCamera(), {+ x: x - rect.left,+ y: y - rect.top,+ });+ };+ const editAt = (p: { x: number; y: number }) => {+ // Pointer capture can retarget dblclick to the viewport rather than a card.+ // Resolve the document reference geometrically before creating canvas text.+ const hit = state.editor.hitTest(p);+ const item = hit ? state.editor.document.items[hit] : undefined;+ if (item?.type === 'document') {+ if (item.geometry.display === 'embed') state.embeds.enter(item.id);+ return;+ }+ const id = textTargetAt(state.editor.document, p);+ if (id) state.text.edit(id);+ else state.text.begin(p);+ };+ const down = (event: PointerEvent) => {+ const target = event.target;+ if (+ !(target instanceof Element) ||+ target.closest(+ '[data-canvas-document], [data-canvas-text-editor], [aria-label="Text style"]'+ )+ )+ return;+ const wasEditing = !!state.text.draft();+ state.text.finish();+ // Captured shape gestures can change the click target between taps, so a+ // native dblclick is not guaranteed. Track completed, stationary taps too.+ if (+ !wasEditing &&+ !space &&+ event.button === 0 &&+ !event.shiftKey &&+ !event.altKey &&+ state.tool() === 'select' &&+ target.closest('[aria-label="Graphics canvas"]') &&+ !target.closest('[data-graphics-handle], [data-graphics-connector-end]')+ ) {+ const double =+ lastTap &&+ event.timeStamp - lastTap.time < 450 &&+ closeTo(lastTap, event);+ lastTap = undefined;+ if (double) {+ pendingTap = undefined;+ editAt(point(event.clientX, event.clientY));+ event.preventDefault();+ event.stopPropagation();+ return;+ }+ pendingTap = {+ x: event.clientX,+ y: event.clientY,+ time: event.timeStamp,+ id: event.pointerId,+ };+ } else {+ pendingTap = undefined;+ lastTap = undefined;+ }+ if (+ space ||+ event.button !== 0 ||+ state.tool() !== 'text' ||+ !target.closest('[aria-label="Graphics canvas"]')+ )+ return;+ event.preventDefault();+ event.stopPropagation();+ const p = point(event.clientX, event.clientY),+ id = textTargetAt(state.editor.document, p);+ if (id) {+ state.text.edit(id);+ return;+ }+ origin = { x: event.clientX, y: event.clientY, id: event.pointerId };+ window.addEventListener('pointerup', up, true);+ window.addEventListener('pointercancel', cancel, true);+ };+ const cancel = () => {+ origin = undefined;+ window.removeEventListener('pointerup', up, true);+ window.removeEventListener('pointercancel', cancel, true);+ };+ const up = (event: PointerEvent) => {+ if (!origin || event.pointerId !== origin.id) return;+ const start = point(origin.x, origin.y),+ end = point(event.clientX, event.clientY);+ const width =+ Math.abs(event.clientX - origin.x) > 3+ ? Math.max(40, Math.abs(end.x - start.x))+ : undefined;+ state.text.begin(+ { x: width ? Math.min(start.x, end.x) : start.x, y: start.y },+ width+ );+ cancel();+ event.stopPropagation();+ };+ const doubleClick = (event: MouseEvent) => {+ if (+ !(event.target instanceof Element) ||+ event.target.closest(+ '[data-canvas-document], [data-canvas-text-editor], [data-graphics-connector-end]'+ ) ||+ !event.target.closest('[aria-label="Graphics canvas"]')+ )+ return;+ if (state.tool() !== 'select' && state.tool() !== 'text') return;+ editAt(point(event.clientX, event.clientY));+ event.preventDefault();+ event.stopPropagation();+ };+ const keyDown = (event: KeyboardEvent) => {+ if (state.embeds.active()) return;+ if (+ event.target instanceof Element &&+ event.target.closest(+ '[contenteditable]:not([contenteditable="false"]),input,select'+ )+ )+ return;+ if (event.code === 'Space') space = true;+ if (event.key === 'Escape') cancel();+ };+ const keyUp = (event: KeyboardEvent) => {+ if (event.code === 'Space') space = false;+ };+ const blur = () => {+ pendingTap = undefined;+ lastTap = undefined;+ space = false;+ cancel();+ };+ root.addEventListener('keydown', keyDown, true);+ window.addEventListener('keyup', keyUp);+ window.addEventListener('blur', blur);+ window.addEventListener('pointermove', trackMove, true);+ window.addEventListener('pointerup', trackUp, true);+ window.addEventListener('pointercancel', blur);+ root.addEventListener('pointerdown', down, true);+ root.addEventListener('dblclick', doubleClick, true);+ return () => {+ cancel();+ root.removeEventListener('keydown', keyDown, true);+ window.removeEventListener('keyup', keyUp);+ window.removeEventListener('blur', blur);+ window.removeEventListener('pointermove', trackMove, true);+ window.removeEventListener('pointerup', trackUp, true);+ window.removeEventListener('pointercancel', blur);+ root.removeEventListener('pointerdown', down, true);+ root.removeEventListener('dblclick', doubleClick, true);+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.test.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.test.tsnew file mode 100644index 0000000000..fee80ee438--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.test.ts@@ -0,0 +1,203 @@+import { createGraphicsEditor } from '@macro-inc/graphics';+import { afterEach, expect, it } from 'vitest';+import { plainRichText, richTextPlainText } from '../core/text-codec';+import { createTextState } from './create-text-state';++const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((fn) => fn()));+it('keeps string drafts outside history and flushes the last edit in one canvas operation', () => {+ const editor = createGraphicsEditor();+ cleanups.push(editor.dispose);+ const state = createTextState(+ editor,+ (g) => ({ width: g.width, height: 32.4 }),+ () => ({ fill: 'transparent', stroke: 'black' })+ );+ state.begin({ x: 10, y: 20 });+ const id = state.draft()!.id;+ state.change(plainRichText('First'));+ state.change(plainRichText('Second'));+ expect(editor.getSession().canUndo).toBe(false);+ expect(editor.document.items[id]).toBeUndefined();+ state.setFlush(() => state.change(plainRichText('Last keystroke')));+ state.finish();+ const item = editor.document.items[id];+ expect(+ item?.type === 'text' && richTextPlainText(item.geometry.content)+ ).toBe('Last keystroke');+ editor.undo();+ expect(editor.document.items[id]).toBeUndefined();+});+it('uses a centered Lexical state for labels and clearing it retains the shape', () => {+ const editor = createGraphicsEditor([+ {+ id: 'box',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: [1, 0, 0, 1, 100, 50],+ geometry: { width: 200, height: 120 },+ appearance: { fill: 'transparent', stroke: 'black' },+ },+ ]);+ cleanups.push(editor.dispose);+ const state = createTextState(+ editor,+ (g) => ({ width: g.width, height: 32.4 }),+ () => ({ fill: 'transparent', stroke: 'black' })+ );+ state.edit('box');+ expect(+ JSON.parse(state.draft()!.geometry.content).root.children[0].format+ ).toBe('center');+ const content = plainRichText('Label');+ state.change(content);+ state.finish();+ expect(editor.document.items.box).toMatchObject({+ geometry: { label: { content } },+ });+ state.edit('box');+ state.change(plainRichText());+ state.finish();+ expect(editor.document.items.box).toMatchObject({+ type: 'rectangle',+ geometry: { width: 200, height: 120 },+ });+ expect(editor.getSession().selectedId).toBe('box');+ const item = editor.document.items.box;+ expect(item?.type === 'rectangle' && item.geometry.label).toBeUndefined();+ editor.undo();+ expect(editor.document.items.box).toMatchObject({+ geometry: { label: { content } },+ });+});++it('abandons empty creations and empty pastes, deletes cleared text, and restores it with undo', () => {+ const editor = createGraphicsEditor();+ cleanups.push(editor.dispose);+ const state = createTextState(+ editor,+ (g) => ({ width: g.width, height: 32.4 }),+ () => ({ fill: 'transparent', stroke: 'black' })+ );+ state.begin({ x: 0, y: 0 });+ state.finish();+ state.insert(plainRichText(' \n '), { x: 0, y: 0 });+ expect(editor.getSession().canUndo).toBe(false);+ state.insert(plainRichText('Keep me'), { x: 0, y: 0 });+ const id = editor.getSession().selectedId!;+ const before = editor.document.items[id];+ state.edit(id);+ state.change(plainRichText(' \n '));+ state.finish();+ expect(editor.document.items[id]).toBeUndefined();+ editor.undo();+ expect(editor.document.items[id]).toEqual(before);+});++it('commits mention-only text and rejects invalid drafts without changing saved content', () => {+ const editor = createGraphicsEditor();+ cleanups.push(editor.dispose);+ const state = createTextState(+ editor,+ (g) => ({ width: g.width, height: 32.4 }),+ () => ({ fill: 'transparent', stroke: 'black' })+ );+ const mention = JSON.parse(plainRichText());+ mention.root.children[0].children = [+ {+ type: 'user-mention',+ version: 1,+ userId: 'user-1',+ email: '[email protected]',+ displayName: 'Ada',+ },+ ];+ const content = JSON.stringify(mention);+ state.begin({ x: 0, y: 0 });+ const id = state.draft()!.id;+ state.change(content);+ expect(() => state.change('{broken')).toThrow('Invalid canvas text');+ state.finish();+ expect(editor.document.items[id]).toMatchObject({ geometry: { content } });+ expect(() => state.insert('plain unencoded text', { x: 0, y: 0 })).toThrow(+ 'Invalid canvas text'+ );+ expect(editor.document.items[id]).toMatchObject({ geometry: { content } });+});+it('finishing a text draft preserves an intervening move', () => {+ const editor = createGraphicsEditor();+ cleanups.push(editor.dispose);+ const state = createTextState(+ editor,+ (g) => ({ width: g.width, height: 32.4 }),+ () => ({ fill: 'transparent', stroke: 'black' })+ );+ state.insert(plainRichText('Before'), { x: 10, y: 20 });+ const id = editor.getSession().selectedId!;+ state.edit(id);+ state.change(plainRichText('After'));+ editor.beginTransform(id, { x: 10, y: 20 });+ editor.updateTransform({ x: 110, y: 20 });+ editor.commitTransform();+ state.finish();+ expect(editor.document.items[id]).toMatchObject({+ transform: [1, 0, 0, 1, 110, 20],+ });+});++it('edits connector labels at their visible bound midpoint and clears only the label', () => {+ const editor = createGraphicsEditor([+ {+ id: 'link',+ type: 'connector',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: [1, 0, 0, 1, 0, 0],+ appearance: { stroke: 'black', fill: 'transparent' },+ geometry: {+ start: { point: { x: 0, y: 0 } },+ end: {+ point: { x: 10, y: 0 },+ binding: { targetId: 'target', anchor: 'left' },+ },+ route: 'straight',+ startHead: 'none',+ endHead: 'arrow',+ },+ },+ {+ id: 'target',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: [1, 0, 0, 1, 400, -50],+ appearance: { stroke: 'black', fill: 'transparent' },+ geometry: { width: 100, height: 100 },+ },+ ]);+ cleanups.push(editor.dispose);+ const before = editor.document.items.link;+ const state = createTextState(+ editor,+ () => ({ width: 100, height: 30 }),+ () => ({ stroke: 'black', fill: 'transparent' })+ );+ state.edit('link');+ expect(state.isLabel()).toBe(true);+ expect(state.draft()?.transform).toEqual([1, 0, 0, 1, 150, -15]);+ state.change(plainRichText('Bound label'));+ expect(editor.document.items.link).toEqual(before);+ state.finish();+ const labeled = editor.document.items.link;+ expect(labeled).toMatchObject({+ type: 'connector',+ geometry: {+ label: { width: 100, height: 30 },+ end: { binding: { targetId: 'target' } },+ },+ });+ state.edit('link');+ state.change(plainRichText());+ state.finish();+ expect(editor.document.items.link).toEqual(before);+ editor.undo();+ expect(editor.document.items.link).toEqual(labeled);+});diff --git a/apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.ts b/apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.tsnew file mode 100644index 0000000000..63ef00ea08--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/primitives/text-lexical.ts@@ -0,0 +1,97 @@+import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';+import { createLexicalWrapper } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';+import { setEditorStateFromMarkdown } from '@core/component/LexicalMarkdown/utils';+import { $generateNodesFromDOM } from '@lexical/html';+import type { RichText } from '@macro-inc/graphics';+import {+ $createParagraphNode,+ $getRoot,+ $isElementNode,+ type LexicalEditor,+} from 'lexical';+import { plainRichText, serializeCanvasTextState } from '../core/text-codec';++/** Legacy files contain internal Markdown, including Macro mention tags. */+export function importCanvasMarkdown(markdown: string): RichText {+ if (!markdown) return plainRichText();+ const wrapper = createLexicalWrapper({+ type: 'markdown',+ namespace: 'canvas-migration',+ isInteractable: () => false,+ });+ try {+ setEditorStateFromMarkdown(wrapper.editor, markdown, 'internal', true);+ return serializeCanvasText(wrapper.editor);+ } finally {+ wrapper.cleanup();+ }+}++/** The canvas persists exactly the tree produced by the shared editor. */+export function serializeCanvasText(editor: LexicalEditor): RichText {+ return editor.read(() =>+ serializeCanvasTextState(editor.getEditorState().toJSON())+ );+}+export function createCanvasTextConfig(onChange: (content: RichText) => void) {+ // Canvas text does not emit source-document mention notifications.+ return buildConfig('markdown')+ .namespace('canvas-next-text')+ .withHistory()+ .withMentions({ block: 'canvas', disableMentionTracking: true })+ .withLinks()+ .withCode()+ .withFloatingFormatMenu({ extendedInlineFormats: true })+ .use((editor) =>+ editor.registerUpdateListener(+ ({ editorState, dirtyElements, dirtyLeaves }) => {+ if (dirtyElements.size || dirtyLeaves.size)+ onChange(serializeCanvasTextState(editorState.toJSON()));+ }+ )+ );+}++/** Rich paste uses the same registered nodes and replacements as the builder. */+export function importTextClipboard(text: string, html?: string): RichText {+ if (!html) return plainRichText(text);+ const wrapper = createLexicalWrapper({+ type: 'markdown',+ namespace: 'canvas-paste',+ isInteractable: () => false,+ });+ try {+ const dom = new DOMParser().parseFromString(html, 'text/html');+ dom+ .querySelectorAll('script,style,iframe,object,embed')+ .forEach((node) => node.remove());+ for (const link of dom.querySelectorAll('a')) {+ const href = link.getAttribute('href') ?? '';+ if (!/^(https?:\/\/|mailto:)/i.test(href)) link.removeAttribute('href');+ }+ wrapper.editor.update(+ () => {+ const root = $getRoot();+ root.clear();+ let paragraph: ReturnType<typeof $createParagraphNode> | undefined;+ for (const node of $generateNodesFromDOM(wrapper.editor, dom)) {+ if ($isElementNode(node) && !node.isInline()) {+ paragraph = undefined;+ root.append(node);+ } else {+ if (!paragraph) {+ paragraph = $createParagraphNode();+ root.append(paragraph);+ }+ paragraph.append(node);+ }+ }+ if (!root.getChildrenSize()) root.append($createParagraphNode());+ },+ { discrete: true }+ );+ return serializeCanvasText(wrapper.editor);+ } finally {+ wrapper.cleanup();+ }+}diff --git a/apps/web/src/features/block-canvas/canvas-next/queries/assets.ts b/apps/web/src/features/block-canvas/canvas-next/queries/assets.tsnew file mode 100644index 0000000000..ff9e8b1670--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/queries/assets.ts@@ -0,0 +1,92 @@+import { fileTypeToBlockName } from '@core/constant/allBlocks';+import { staticFileIdEndpoint } from '@core/constant/servers';+import { uploadFile } from '@core/util/upload';+import { fetchBinaryDocumentData } from '@queries/storage/binary-document';+import type { CanvasAssetSource, PreparedMedia } from '../core/assets';++async function dimensions(url: string, type: 'image' | 'video') {+ return new Promise<{ width: number; height: number }>((resolve, reject) => {+ const element =+ type === 'image' ? new Image() : document.createElement('video');+ const dispose = () => {+ clearTimeout(timeout);+ element.onload = null;+ element.onerror = null;+ if (element instanceof HTMLVideoElement) {+ element.onloadedmetadata = null;+ element.removeAttribute('src');+ element.load();+ }+ };+ const done = () => {+ const width =+ element instanceof HTMLImageElement+ ? element.naturalWidth+ : element.videoWidth;+ const height =+ element instanceof HTMLImageElement+ ? element.naturalHeight+ : element.videoHeight;+ dispose();+ if (!width || !height) {+ reject(new Error('Media has no dimensions'));+ return;+ }+ const scale = Math.min(1, 640 / width, 480 / height);+ resolve({ width: width * scale, height: height * scale });+ };+ const fail = () => {+ dispose();+ reject(new Error('Could not load media'));+ };+ const timeout = setTimeout(fail, 20000);+ element.onerror = fail;+ if (element instanceof HTMLVideoElement) {+ element.preload = 'metadata';+ element.onloadedmetadata = done;+ } else element.onload = done;+ element.src = url;+ });+}+export const canvasAssetSource: CanvasAssetSource = {+ async upload(file) {+ const type = fileTypeToBlockName(file.name.split('.').pop());+ const kind =+ file.type.startsWith('video/') || type === 'video'+ ? 'video'+ : file.type.startsWith('image/') || type === 'image'+ ? 'image'+ : undefined;+ if (!kind) throw new Error('Choose an image or video');+ // The shared uploader handles validation and HEIC conversion.+ const result = await uploadFile(file, 'static', {+ hideProgressIndicator: true,+ });+ if (result.failed) throw result.error;+ const size = await dimensions(staticFileIdEndpoint(result.id), kind);+ return {+ type: kind,+ geometry: {+ ...size,+ source: { type: 'static', id: result.id },+ name: file.name,+ },+ };+ },+ async media(asset): Promise<PreparedMedia> {+ const type = fileTypeToBlockName(asset.fileType);+ if (type !== 'image' && type !== 'video')+ throw new Error('Not an image or video');+ const result = await fetchBinaryDocumentData(asset.id);+ if (result.isErr()) throw new Error('Unable to load this media file');+ const size = await dimensions(result.value.blobUrl, type);+ return {+ type,+ geometry: {+ ...size,+ source: { type: 'document', id: asset.id },+ name: asset.name,+ },+ };+ },+};diff --git a/apps/web/src/features/block-canvas/canvas-next/queries/document.test.ts b/apps/web/src/features/block-canvas/canvas-next/queries/document.test.tsnew file mode 100644index 0000000000..9340bb3a3f--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/queries/document.test.ts@@ -0,0 +1,38 @@+import { createGraphicsEditor } from '@macro-inc/graphics';+import { err, ok } from 'neverthrow';+import { afterEach, expect, it, vi } from 'vitest';+import { canvasDocumentSource } from './document';++const { simpleSave } = vi.hoisted(() => ({ simpleSave: vi.fn() }));+vi.mock('@service-storage/client', () => ({+ storageServiceClient: { simpleSave },+}));+afterEach(() => vi.clearAllMocks());++it('surfaces rejected JSON saves so the session can retry', async () => {+ const editor = createGraphicsEditor();+ const source = canvasDocumentSource('canvas-id', () => true);+ simpleSave+ .mockResolvedValueOnce(err('offline'))+ .mockResolvedValueOnce(ok({}));+ const file = { version: 2 as const, document: editor.document };+ await expect(source.save(file)).rejects.toThrow('Could not save canvas');+ await expect(source.save(file)).resolves.toBeInstanceOf(Blob);+ expect(simpleSave).toHaveBeenLastCalledWith({+ documentId: 'canvas-id',+ file: expect.any(Blob),+ });+ editor.dispose();+});++it('never submits a read-only document', async () => {+ const editor = createGraphicsEditor();+ await expect(+ canvasDocumentSource('viewer', () => false).save({+ version: 2,+ document: editor.document,+ })+ ).rejects.toThrow('read-only');+ expect(simpleSave).not.toHaveBeenCalled();+ editor.dispose();+});diff --git a/apps/web/src/features/block-canvas/canvas-next/queries/document.ts b/apps/web/src/features/block-canvas/canvas-next/queries/document.tsnew file mode 100644index 0000000000..447600e0c5--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/queries/document.ts@@ -0,0 +1,21 @@+import { saveCanvasDocument } from '../../queries/canvas-document';+import type { CanvasDocumentSource } from '../context/document-source';+import { readCanvasFile } from '../core/document-format';++export function canvasDocumentSource(+ documentId: string,+ canEdit: () => boolean+): CanvasDocumentSource {+ return {+ canEdit,+ async save(canvas) {+ if (!canEdit()) throw new Error('This canvas is read-only');+ const { file, saved } = await saveCanvasDocument(+ documentId,+ readCanvasFile(canvas)+ );+ if (!saved) throw new Error('Could not save canvas');+ return file;+ },+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/asset-picker.tsx b/apps/web/src/features/block-canvas/canvas-next/views/asset-picker.tsxnew file mode 100644index 0000000000..9cc3104adb--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/asset-picker.tsx@@ -0,0 +1,105 @@+import { fileTypeToBlockName } from '@core/constant/allBlocks';+import { useHistoryQuery } from '@queries/history/history';+import { createMemo, createSignal, Show } from 'solid-js';+import { VList } from 'virtua/solid';+import type { CanvasAsset } from '../core/assets';+import { canEmbedDocument } from '../core/document-display';++export function CanvasAssetPicker(props: {+ mode: 'media' | 'document' | 'embed';+ onSelect: (asset: CanvasAsset) => void;+ onFiles: (files: File[]) => void;+ onClose: () => void;+}) {+ const history = useHistoryQuery();+ const [search, setSearch] = createSignal('');+ const items = createMemo(() =>+ (history.isSuccess ? (history.data ?? []) : []).flatMap((item) => {+ if (item.type !== 'document' || !item.fileType) return [];+ if (props.mode === 'embed' && !canEmbedDocument(item.fileType)) return [];+ const kind = fileTypeToBlockName(item.fileType);+ if (props.mode === 'media' && kind !== 'image' && kind !== 'video')+ return [];+ if (!item.name.toLowerCase().includes(search().toLowerCase())) return [];+ return [{ id: item.id, name: item.name, fileType: item.fileType }];+ })+ );+ return (+ <section+ aria-label={props.mode === 'media' ? 'Insert media' : 'Insert document'}+ class="absolute right-4 top-4 z-30 flex max-h-[80%] w-80 flex-col gap-3 rounded-xl border border-edge-muted bg-panel p-3 shadow-lg"+ on:keydown={(event) => {+ event.stopPropagation();+ if (event.key === 'Escape') props.onClose();+ }}+ >+ <div class="flex items-center justify-between text-sm font-medium">+ {props.mode === 'media'+ ? 'Image or video'+ : props.mode === 'embed'+ ? 'Embed document or canvas'+ : 'Document preview'}+ <button+ type="button"+ aria-label="Close insert menu"+ class="rounded px-2 py-1 hover:bg-hover"+ onClick={props.onClose}+ >+ ×+ </button>+ </div>+ <Show when={props.mode === 'media'}>+ <label class="rounded border border-edge-muted p-2 text-xs">+ Upload image or video+ <input+ type="file"+ multiple+ accept="image/*,video/*,.heic,.heif"+ aria-label="Upload canvas media"+ class="mt-2 block w-full text-xs"+ onChange={(event) => {+ props.onFiles(Array.from(event.currentTarget.files ?? []));+ event.currentTarget.value = '';+ }}+ />+ </label>+ </Show>+ <input+ type="search"+ aria-label="Search workspace files"+ placeholder="Search your files…"+ class="rounded border border-edge-muted bg-input px-3 py-2 text-sm"+ value={search()}+ onInput={(event) => setSearch(event.currentTarget.value)}+ />+ <div class="min-h-0 overflow-y-auto">+ <Show+ when={!history.isPending}+ fallback={<p class="p-2 text-xs text-ink-muted">Loading files…</p>}+ >+ <Show+ when={items().length}+ fallback={+ <p class="p-2 text-xs text-ink-muted">+ {history.isError ? 'Could not load files' : 'No matching files'}+ </p>+ }+ >+ <VList data={items()} style={{ height: '320px' }}>+ {(item) => (+ <button+ type="button"+ class="flex w-full items-center gap-2 rounded p-2 text-left text-xs hover:bg-hover"+ onClick={() => props.onSelect(item)}+ >+ <span class="min-w-0 flex-1 truncate">{item.name}</span>+ <span class="text-ink-muted">{item.fileType}</span>+ </button>+ )}+ </VList>+ </Show>+ </Show>+ </div>+ </section>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/canvas-context-menu.tsx b/apps/web/src/features/block-canvas/canvas-next/views/canvas-context-menu.tsxnew file mode 100644index 0000000000..c30c66fb5c--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/canvas-context-menu.tsx@@ -0,0 +1,132 @@+import {+ ContextMenuContent,+ MenuItem,+ MenuSeparator,+ SubTrigger,+} from '@core/component/ContextMenu';+import { TOKENS } from '@core/hotkey/tokens';+import { ContextMenu } from '@kobalte/core/context-menu';+import { selectAllCommand } from '@macro-inc/graphics';+import ArrowDown from '@phosphor/arrow-down.svg';+import ArrowLineDown from '@phosphor/arrow-line-down.svg';+import ArrowLineUp from '@phosphor/arrow-line-up.svg';+import ArrowUp from '@phosphor/arrow-up.svg';+import Clipboard from '@phosphor/clipboard.svg';+import Copy from '@phosphor/copy.svg';+import Scissors from '@phosphor/scissors.svg';+import SelectionAll from '@phosphor/selection-all.svg';+import SelectionPlus from '@phosphor/selection-plus.svg';+import SelectionSlash from '@phosphor/selection-slash.svg';+import Stack from '@phosphor/stack.svg';+import Trash from '@phosphor/trash.svg';+import type { CanvasClipboard } from '../clipboard';+import type { CanvasState } from '../primitives/create-canvas-state';++export function CanvasContextMenu(props: {+ state: CanvasState;+ clipboard: CanvasClipboard;+ onClose: () => void;+}) {+ const selected = () => props.state.selection().length > 0;+ return (+ <ContextMenu.Portal>+ <ContextMenuContent+ onCloseAutoFocus={(event) => {+ // The trigger wraps the viewport; return keyboard shortcuts to its+ // focusable graphics surface after the menu closes.+ event.preventDefault();+ props.onClose();+ }}+ >+ <MenuItem+ text="Cut"+ icon={Scissors}+ hotkeyToken={TOKENS.canvas.cut}+ disabled={!selected()}+ onClick={() => void props.clipboard.cut()}+ />+ <MenuItem+ text="Copy"+ icon={Copy}+ hotkeyToken={TOKENS.canvas.copy}+ disabled={!selected()}+ onClick={() => void props.clipboard.copy()}+ />+ <MenuItem+ text="Paste"+ icon={Clipboard}+ hotkeyToken={TOKENS.canvas.paste}+ onClick={() => void props.clipboard.paste()}+ />+ <MenuItem+ text="Duplicate"+ icon={Copy}+ shortcut="cmd+d"+ disabled={!selected()}+ onClick={props.state.duplicate}+ />+ <MenuSeparator />+ <MenuItem+ text="Group"+ icon={SelectionPlus}+ hotkeyToken={TOKENS.canvas.group}+ disabled={!props.state.canGroup()}+ onClick={props.state.group}+ />+ <MenuItem+ text="Ungroup"+ icon={SelectionSlash}+ hotkeyToken={TOKENS.canvas.ungroup}+ disabled={!props.state.canUngroup()}+ onClick={props.state.ungroup}+ />+ <ContextMenu.Sub>+ <SubTrigger text="Arrange" icon={Stack} disabled={!selected()} />+ <ContextMenuContent submenu>+ <MenuItem+ text="Bring to front"+ icon={ArrowLineUp}+ hotkeyToken={TOKENS.canvas.bringToFront}+ onClick={() => props.state.editor.reorderSelection('front')}+ />+ <MenuItem+ text="Bring forward"+ icon={ArrowUp}+ hotkeyToken={TOKENS.canvas.bringForward}+ onClick={() => props.state.editor.reorderSelection('forward')}+ />+ <MenuItem+ text="Send backward"+ icon={ArrowDown}+ hotkeyToken={TOKENS.canvas.sendBackward}+ onClick={() => props.state.editor.reorderSelection('backward')}+ />+ <MenuItem+ text="Send to back"+ icon={ArrowLineDown}+ hotkeyToken={TOKENS.canvas.sendToBack}+ onClick={() => props.state.editor.reorderSelection('back')}+ />+ </ContextMenuContent>+ </ContextMenu.Sub>+ <MenuSeparator />+ <MenuItem+ text="Select all"+ icon={SelectionAll}+ hotkeyToken={TOKENS.canvas.selectAll}+ onClick={() => {+ props.state.chooseTool('select');+ props.state.editor.execute(selectAllCommand, undefined);+ }}+ />+ <MenuItem+ text="Delete"+ icon={Trash}+ hotkeyToken={TOKENS.canvas.delete}+ disabled={!selected()}+ onClick={props.state.editor.deleteSelection}+ />+ </ContextMenuContent>+ </ContextMenu.Portal>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/canvas-read-only-view.tsx b/apps/web/src/features/block-canvas/canvas-next/views/canvas-read-only-view.tsxnew file mode 100644index 0000000000..346768cb88--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/canvas-read-only-view.tsx@@ -0,0 +1,79 @@+import { DocumentPreviewContent } from '@core/component/DocumentPreview';+import { fileTypeToBlockName } from '@core/constant/allBlocks';+import type { GraphicsEditor } from '@macro-inc/graphics';+import {+ ConnectorView,+ EllipseView,+ GraphicsSurface,+ RectangleView,+ TextView,+} from '@macro-inc/graphics/solid';+import { onCleanup, onMount } from 'solid-js';+import { CanvasMediaView } from './embedded-items';+import { CanvasTextContent } from './text-content';++/** Viewers get navigation without mounting editing handlers or embedded editors. */+export function CanvasReadOnlyView(props: {+ editor: GraphicsEditor;+ fitOnLoad?: boolean;+}) {+ let host!: HTMLDivElement;+ const fit = () =>+ props.editor.fitScene({+ width: host.clientWidth,+ height: host.clientHeight,+ });+ onMount(() => {+ const observer = new ResizeObserver(([entry]) => {+ if (!entry?.contentRect.width || !entry.contentRect.height) return;+ if (props.fitOnLoad !== false) fit();+ observer.disconnect();+ });+ observer.observe(host);+ onCleanup(() => observer.disconnect());+ });+ return (+ <div ref={host} class="relative size-full min-h-0">+ <GraphicsSurface+ editor={props.editor}+ input={{ editing: false, tool: () => 'pan' }}+ hideSelection+ renderers={{+ connector: (p) => (+ <ConnectorView {...p} contentView={CanvasTextContent} />+ ),+ rectangle: (p) => (+ <RectangleView {...p} contentView={CanvasTextContent} />+ ),+ ellipse: (p) => (+ <EllipseView {...p} contentView={CanvasTextContent} />+ ),+ text: (p) => <TextView {...p} contentView={CanvasTextContent} />,+ image: (p) => (+ <CanvasMediaView {...p} playing={false} onStop={() => {}} />+ ),+ video: (p) => (+ <CanvasMediaView {...p} playing={false} onStop={() => {}} />+ ),+ document: (p) => (+ <DocumentPreviewContent+ documentInfo={{+ id: p.item.geometry.documentId,+ type: fileTypeToBlockName(p.item.geometry.fileType),+ params: {},+ isOpenable: true,+ }}+ />+ ),+ }}+ />+ <button+ type="button"+ class="absolute bottom-4 left-4 rounded border border-edge-muted bg-panel px-3 py-2 text-sm"+ onClick={fit}+ >+ Fit canvas+ </button>+ </div>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/canvas-toolbars.tsx b/apps/web/src/features/block-canvas/canvas-next/views/canvas-toolbars.tsxnew file mode 100644index 0000000000..67d45ef6b7--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/canvas-toolbars.tsx@@ -0,0 +1,199 @@+import { TOKENS } from '@core/hotkey/tokens';+import Undo from '@phosphor/arrow-u-up-left.svg';+import Redo from '@phosphor/arrow-u-up-right.svg';+import ArrowUpRight from '@phosphor/arrow-up-right.svg';+import CaretDown from '@phosphor/caret-down.svg';+import Check from '@phosphor/check.svg';+import Circle from '@phosphor/circle.svg';+import Cursor from '@phosphor/cursor.svg';+import Eraser from '@phosphor/eraser.svg';+import Hand from '@phosphor/hand.svg';+import Pencil from '@phosphor/pencil-simple.svg';+import Rectangle from '@phosphor/rectangle.svg';+import Text from '@phosphor/text-t.svg';+import { Button, Dropdown, Hotkey, Toolbar } from '@ui';+import { type ComponentProps, For, Show } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import type { CanvasSnapMode } from '../core/snapping';+import type {+ CanvasState,+ CanvasTool,+} from '../primitives/create-canvas-state';++const tools = [+ { id: 'select', label: 'Select', icon: Cursor, key: 'v' },+ { id: 'pan', label: 'Hand', icon: Hand, key: 'h' },+ { id: 'rectangle', label: 'Rectangle', icon: Rectangle, key: 'r' },+ { id: 'ellipse', label: 'Ellipse', icon: Circle, key: 'o' },+ { id: 'arrow', label: 'Arrow', icon: ArrowUpRight, key: 'a' },+ { id: 'pencil', label: 'Pencil', icon: Pencil, key: 'p' },+ { id: 'eraser', label: 'Eraser', icon: Eraser, key: 'e' },+ { id: 'text', label: 'Text', icon: Text, key: 't' },+] as const;++export function CanvasDrawingToolbar(props: {+ tool: CanvasTool;+ onTool: (tool: CanvasTool) => void;+}) {+ return (+ <div class="pointer-events-none absolute bottom-4 left-1/2 z-40 max-w-[calc(100%-2rem)] -translate-x-1/2">+ <Toolbar+ size="icon-md"+ aria-label="Drawing tools"+ class="pointer-events-auto relative max-w-full overflow-x-auto"+ >+ <Toolbar.Group>+ <For each={tools}>+ {(tool) => (+ <Toolbar.Button+ label={`${tool.label} tool`}+ shortcut={tool.key}+ aria-pressed={props.tool === tool.id}+ variant={props.tool === tool.id ? 'cta' : 'ghost'}+ onClick={() => props.onTool(tool.id)}+ >+ <Dynamic component={tool.icon} />+ </Toolbar.Button>+ )}+ </For>+ </Toolbar.Group>+ </Toolbar>+ </div>+ );+}++export function CanvasHistoryControls(props: {+ state: CanvasState;+ onFocusCanvas: () => void;+}) {+ const hasHistory = () =>+ props.state.session().canUndo || props.state.session().canRedo;+ return (+ <Show when={hasHistory()}>+ <div class="flex items-center" role="group" aria-label="Canvas history">+ <Button+ size="icon-xs"+ label="Undo"+ hotkey={TOKENS.canvas.undo}+ disabled={!props.state.session().canUndo}+ onClick={() => {+ props.state.editor.undo();+ props.onFocusCanvas();+ }}+ >+ <Undo />+ </Button>+ <Button+ size="icon-xs"+ label="Redo"+ hotkey={TOKENS.canvas.redo}+ disabled={!props.state.session().canRedo}+ onClick={() => {+ props.state.editor.redo();+ props.onFocusCanvas();+ }}+ >+ <Redo />+ </Button>+ </div>+ </Show>+ );+}++function CanvasViewCheckboxItem(+ props: ComponentProps<typeof Dropdown.CheckboxItem>+) {+ return (+ <Dropdown.CheckboxItem+ {...props}+ indicator={+ <span class="inline-flex size-3.5 shrink-0 items-center justify-center text-ink">+ <Dropdown.ItemIndicator>+ <Check class="size-3.5" />+ </Dropdown.ItemIndicator>+ </span>+ }+ />+ );+}++export function CanvasViewControls(props: {+ scale: number;+ grid: boolean;+ onGrid: (visible: boolean) => void;+ onZoom: (factor: number) => void;+ onFit: () => void;+ snapMode: CanvasSnapMode;+ onSnapMode: (mode: CanvasSnapMode) => void;+}) {+ return (+ <Dropdown placement="bottom-end">+ <Dropdown.Trigger+ variant="ghost"+ size="sm"+ label="Zoom options"+ class="gap-1.5 tabular-nums"+ >+ <output aria-label="Zoom level">+ {Math.round(props.scale * 100)}%+ </output>+ <CaretDown class="size-3" />+ </Dropdown.Trigger>+ <Dropdown.Content class="w-56">+ <Dropdown.Group>+ <Dropdown.Item onSelect={() => props.onZoom(1.2)}>+ <span class="flex-1">Zoom In</span>+ <Hotkey shortcut="cmd+plus" theme="subtle" />+ </Dropdown.Item>+ <Dropdown.Item onSelect={() => props.onZoom(1 / 1.2)}>+ <span class="flex-1">Zoom Out</span>+ <Hotkey token={TOKENS.canvas.zoomOut} theme="subtle" />+ </Dropdown.Item>+ <Dropdown.Item onSelect={props.onFit}>+ <span class="flex-1">Zoom to fit</span>+ <Hotkey token={TOKENS.canvas.zoomFit} theme="subtle" />+ </Dropdown.Item>+ </Dropdown.Group>+ <Dropdown.Group>+ <For each={[25, 50, 100, 200]}>+ {(percent) => (+ <CanvasViewCheckboxItem+ closeOnSelect+ checked={Math.round(props.scale * 100) === percent}+ onChange={() => props.onZoom(percent / 100 / props.scale)}+ >+ Zoom to {percent}%+ </CanvasViewCheckboxItem>+ )}+ </For>+ </Dropdown.Group>+ <Dropdown.Group>+ <CanvasViewCheckboxItem checked={props.grid} onChange={props.onGrid}>+ Toggle dot grid+ </CanvasViewCheckboxItem>+ </Dropdown.Group>+ <Dropdown.Group>+ <For+ each={+ [+ { mode: 'none', label: 'No snapping' },+ { mode: 'pixel', label: 'Snap to px' },+ { mode: 'auto', label: 'Auto snapping' },+ ] as const+ }+ >+ {(option) => (+ <CanvasViewCheckboxItem+ closeOnSelect+ checked={props.snapMode === option.mode}+ onChange={() => props.onSnapMode(option.mode)}+ >+ {option.label}+ </CanvasViewCheckboxItem>+ )}+ </For>+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/canvas-view.tsx b/apps/web/src/features/block-canvas/canvas-next/views/canvas-view.tsxnew file mode 100644index 0000000000..84e4be2cc8--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/canvas-view.tsx@@ -0,0 +1,650 @@+import { useSidePanel } from '@components/app/side-panel';+import { ContextMenu } from '@kobalte/core/context-menu';+import {+ alignCommand,+ canLabel,+ type DocumentGeometry,+ distributeCommand,+ screenToWorld,+ styleCommand,+} from '@macro-inc/graphics';+import { attachConnectorControls } from '@macro-inc/graphics/browser';+import {+ ConnectorView,+ EllipseView,+ GraphicsSurface,+ RectangleView,+ TextView,+} from '@macro-inc/graphics/solid';+import { Layer } from '@ui';+import {+ type Component,+ createMemo,+ createSignal,+ onCleanup,+ onMount,+ Show,+} from 'solid-js';+import type { CanvasClipboard } from '../clipboard';+import { ConnectorInspector } from '../components/connector-inspector';+import type { CanvasEmbedViewProps } from '../components/embed-view';+import { EraserTrail } from '../components/eraser-trail';+import { SelectionLayoutInspector } from '../components/selection-layout-inspector';+import { StyleInspector } from '../components/style-inspector';+import { TextInspector } from '../components/text-inspector';+import {+ canEmbedDocument,+ setDocumentDisplayCommand,+} from '../core/document-display';+import {+ selectionLayoutCommand,+ selectionLayoutInfo,+} from '../core/selection-layout';+import { registerCanvasZoomHotkeys } from '../hotkeys';+import { createCanvasAssetDrop } from '../primitives/asset-drop';+import type { CanvasAssetState } from '../primitives/create-asset-state';+import type {+ CanvasState,+ CanvasTool,+} from '../primitives/create-canvas-state';+import { attachTextInput } from '../primitives/text-input';+import { CanvasContextMenu } from './canvas-context-menu';+import {+ CanvasDrawingToolbar,+ CanvasHistoryControls,+ CanvasViewControls,+} from './canvas-toolbars';+import { ConnectorTargets } from './connector-targets';+import { CanvasDocumentView, CanvasMediaView } from './embedded-items';+import { CanvasTextContent } from './text-content';+import { TextEditingView } from './text-editing-view';++export function CanvasView(props: {+ state: CanvasState;+ fitOnLoad?: boolean;+ scopeId: string;+ embedView: Component<CanvasEmbedViewProps>;+ clipboard: CanvasClipboard;+ assets: CanvasAssetState;+ onViewport: (element: HTMLElement) => void;+ onOpenDocument: (geometry: DocumentGeometry) => void;+ attachScope: (element: Element) => void;+}) {+ const state = props.state,+ editor = state.editor;+ const sidePanel = useSidePanel();+ const layout = createMemo(() =>+ selectionLayoutInfo(state.snapshot(), state.selection())+ );+ let root!: HTMLDivElement, host!: HTMLDivElement;+ const [lockAspectRatio, setLockAspectRatio] = createSignal(false);+ const point = (x: number, y: number) => {+ const rect = host.getBoundingClientRect();+ return screenToWorld(editor.getCamera(), {+ x: x - rect.left,+ y: y - rect.top,+ });+ };+ const droppable = createCanvasAssetDrop(+ props.assets,+ point,+ () => !state.embeds.active()+ );+ const selectedItem = () =>+ state.selection().length === 1+ ? state.document.items[state.selection()[0]!]+ : undefined;+ const styleKinds = () =>+ state.shapes().length+ ? state.shapes().map((item) => item.type)+ : [+ state.tool() === 'select' || state.tool() === 'pan'+ ? 'rectangle'+ : state.tool(),+ ];+ const connectorValue = () => {+ const connectors = state+ .shapes()+ .filter((item) => item.type === 'connector');+ if (!connectors.length) return state.connector.defaults();+ const shared = <K extends 'route' | 'startHead' | 'endHead'>(key: K) => {+ const first = connectors[0]!.geometry[key];+ return connectors.every((item) => item.geometry[key] === first)+ ? first+ : undefined;+ };+ return {+ route: shared('route'),+ startHead: shared('startHead'),+ endHead: shared('endHead'),+ };+ };+ const inspectorWidth = () =>+ Math.min(288, Math.max(0, host.clientWidth - 48));+ const fit = () => {+ editor.fitScene({+ width: host.clientWidth - inspectorWidth(),+ height: host.clientHeight,+ });+ };+ const focus = () =>+ host+ .querySelector<HTMLElement>('[aria-label="Graphics canvas"]')+ ?.focus({ preventScroll: true });+ const zoom = (factor: number) =>+ editor.zoomAt(+ {+ x: (host.clientWidth - inspectorWidth()) / 2,+ y: host.clientHeight / 2,+ },+ editor.getCamera().scale * factor+ );+ registerCanvasZoomHotkeys(props.scopeId, state, zoom, fit);+ const exitEmbed = () => {+ state.embeds.exit();+ focus();+ };+ onMount(() => {+ const outside = (event: PointerEvent) => {+ if (!state.embeds.active()) return;+ const target = event.target;+ // Portaled editor menus remain owned by the embed until the user returns+ // to this canvas. An outside app click only blurs its hotkey scope.+ if (+ target instanceof Element &&+ root.contains(target) &&+ !target.closest('[data-canvas-embed-active]')+ )+ state.embeds.exit();+ };+ const exitOnEscape = (event: KeyboardEvent) => {+ if (+ event.key === 'Escape' &&+ state.embeds.active() &&+ event.target instanceof Node &&+ root.contains(event.target)+ ) {+ event.preventDefault();+ event.stopPropagation();+ exitEmbed();+ }+ };+ root.addEventListener('pointerdown', outside, true);+ window.addEventListener('keydown', exitOnEscape, true);+ onCleanup(() => {+ root.removeEventListener('pointerdown', outside, true);+ window.removeEventListener('keydown', exitOnEscape, true);+ });+ props.attachScope(root);+ props.onViewport(host);+ droppable(host);+ onCleanup(props.clipboard.attach(root));+ onCleanup(attachTextInput(root, state));+ const initialFit = new ResizeObserver(([entry]) => {+ if (!entry?.contentRect.width || !entry.contentRect.height) return;+ if (props.fitOnLoad !== false) fit();+ initialFit.disconnect();+ });+ initialFit.observe(host);+ onCleanup(() => initialFit.disconnect());+ focus();+ });+ const textGeometry = () => {+ const draft = state.text.draft();+ if (draft) return draft.geometry;+ const item = state.document.items[state.selection()[0]!];+ return item?.type === 'text'+ ? item.geometry+ : canLabel(item) && item.geometry.label+ ? item.geometry.label+ : state.text.defaults();+ };+ const labelSelection = () => {+ const item = state.document.items[state.selection()[0]!];+ return (+ state.selection().length === 1 && canLabel(item) && !!item.geometry.label+ );+ };+ const finishText = () => {+ state.text.finish();+ state.chooseTool('select');+ focus();+ };+ return (+ <div+ ref={root}+ class="relative size-full min-h-0 bg-panel text-ink"+ data-canvas-next+ >+ <main class="relative size-full overflow-hidden">+ <Show when={!sidePanel?.isOpen()}>+ <Layer depth={2}>+ <aside+ class="absolute right-4 top-4 z-30 flex max-h-[calc(100%-2rem)] w-64 max-w-[calc(100%-2rem)] flex-col overflow-hidden rounded-xl border border-edge-muted bg-surface shadow-lg"+ style={{+ height:+ state.selection().length > 0+ ? 'calc(100% - 2rem)'+ : undefined,+ }}+ aria-label="Canvas inspector"+ >+ <header class="flex h-10 shrink-0 items-center justify-between px-3">+ <div class="flex items-center gap-1">+ <span class="text-xs font-medium">Canvas</span>+ <CanvasHistoryControls state={state} onFocusCanvas={focus} />+ </div>+ <CanvasViewControls+ scale={state.camera().scale}+ grid={state.grid()}+ onGrid={state.setGrid}+ onZoom={zoom}+ onFit={fit}+ snapMode={state.snapMode()}+ onSnapMode={state.setSnapMode}+ />+ </header>+ <Show when={state.selection().length > 0}>+ <div+ class="min-h-0 flex-1 overflow-y-auto overscroll-contain border-t border-edge-muted pb-4 [scrollbar-gutter:stable]"+ data-canvas-inspector-scroll+ >+ <div class="border-b border-edge-muted px-3 py-3">+ <h1 class="text-xs font-medium capitalize">+ {state.selection().length > 1+ ? `${state.selection().length} selected`+ : (selectedItem()?.type ??+ (state.tool() === 'select' || state.tool() === 'pan'+ ? 'Canvas'+ : state.tool()))}+ </h1>+ </div>++ <SelectionLayoutInspector+ snapUnit={state.snapUnit()}+ lockAspectRatio={lockAspectRatio()}+ onLockAspectRatio={setLockAspectRatio}+ onAlign={(alignment) =>+ editor.execute(alignCommand, alignment)+ }+ onDistribute={(axis) =>+ editor.execute(distributeCommand, axis)+ }+ count={layout().count}+ value={(field) => layout().values[field]}+ onChange={(field, value) =>+ editor.execute(selectionLayoutCommand, {+ field,+ value,+ lockAspectRatio: lockAspectRatio(),+ })+ }+ onScrub={(field) => {+ const locked = lockAspectRatio();+ const payload = (value: number) => ({+ field,+ value,+ lockAspectRatio: locked,+ });+ return state.inspector.begin(+ (context, value) =>+ selectionLayoutCommand.apply(context, payload(value))+ .document,+ (value) =>+ editor.execute(selectionLayoutCommand, payload(value))+ );+ }}+ onTransform={(field) =>+ editor.execute(selectionLayoutCommand, { field })+ }+ />+ <StyleInspector+ fill={styleKinds().some(+ (kind) => kind === 'rectangle' || kind === 'ellipse'+ )}+ stroke={styleKinds().some((kind) =>+ [+ 'rectangle',+ 'ellipse',+ 'connector',+ 'arrow',+ 'line',+ 'pencil',+ ].includes(kind)+ )}+ strokePattern={styleKinds().some((kind) =>+ [+ 'rectangle',+ 'ellipse',+ 'connector',+ 'arrow',+ 'line',+ ].includes(kind)+ )}+ corners={styleKinds().includes('rectangle')}+ text={styleKinds().every((kind) => kind === 'text')}+ canvasColors={state.canvasColors()}+ value={state.appearanceValue}+ onChange={state.style}+ onScrub={(key) => {+ const patch = (value: number) => ({+ [key]: key === 'opacity' ? value / 100 : value,+ });+ return state.inspector.begin(+ (context, value) =>+ styleCommand.apply(context, patch(value)).document,+ (value) => state.style(patch(value))+ );+ }}+ />+ <Show+ when={+ state.isConnectorTool() ||+ state.shapes().some((item) => item.type === 'connector')+ }+ >+ <ConnectorInspector+ value={connectorValue()}+ onChange={state.connector.style}+ />+ </Show>+ <Show+ when={+ state.tool() === 'text' ||+ state.text.draft() ||+ state.shapes().some((item) => item.type === 'text') ||+ labelSelection()+ }+ >+ <TextInspector+ label={+ state.text.isLabel() ||+ (!state.text.draft() && labelSelection())+ }+ geometry={textGeometry()}+ onChange={state.text.typography}+ onScrub={() => state.text.scrubFontSize(state.inspector)}+ />+ </Show>+ <Show when={selectedItem()?.type === 'video'}>+ <button+ type="button"+ class="m-3 rounded border border-edge-muted p-2 text-xs hover:bg-hover"+ onClick={() =>+ props.assets.togglePlayback(state.selection()[0]!)+ }+ >+ {props.assets.playing() === state.selection()[0]+ ? 'Pause video'+ : 'Play video'}+ </button>+ </Show>+ <Show when={selectedItem()?.type === 'document'}>+ <button+ type="button"+ class="m-3 rounded border border-edge-muted p-2 text-xs hover:bg-hover"+ onClick={() => {+ const item = selectedItem();+ if (item?.type === 'document')+ props.onOpenDocument(item.geometry);+ }}+ >+ {(() => {+ const item = selectedItem();+ return item?.type === 'document' &&+ item.geometry.entityType !== undefined &&+ item.geometry.entityType !== 'document'+ ? 'Open item'+ : 'Open document';+ })()}+ </button>+ <Show+ when={(() => {+ const item = selectedItem();+ return (+ item?.type === 'document' &&+ canEmbedDocument(item.geometry.fileType)+ );+ })()}+ >+ <button+ type="button"+ class="mx-3 mb-3 rounded border border-edge-muted p-2 text-xs hover:bg-hover"+ onClick={() => {+ const item = selectedItem();+ if (item?.type !== 'document') return;+ state.embeds.exit();+ editor.execute(setDocumentDisplayCommand, {+ id: item.id,+ display:+ item.geometry.display === 'embed'+ ? 'preview'+ : 'embed',+ });+ }}+ >+ {(() => {+ const item = selectedItem();+ return item?.type === 'document' &&+ item.geometry.display === 'embed'+ ? 'Use preview card'+ : 'Use full embed';+ })()}+ </button>+ </Show>+ </Show>+ </div>+ </Show>+ </aside>+ </Layer>+ </Show>+ <ContextMenu>+ <ContextMenu.Trigger+ class="absolute inset-0"+ disabled={!!state.embeds.active() || !!state.text.draft()}+ >+ <div+ ref={host}+ onDragOver={(event) => {+ if (state.embeds.active()) return;+ if (event.dataTransfer?.types.includes('Files')) {+ event.preventDefault();+ event.dataTransfer.dropEffect = 'copy';+ }+ }}+ onDrop={(event) => {+ if (state.embeds.active()) return;+ if (!event.dataTransfer?.files.length) return;+ event.preventDefault();+ void props.assets.files(+ Array.from(event.dataTransfer.files),+ point(event.clientX, event.clientY)+ );+ }}+ class="absolute inset-0"+ onContextMenu={(event) => {+ if (state.embeds.active() || state.text.draft()) return;+ focus();+ const rect = host.getBoundingClientRect();+ const id = editor.hitTest(+ screenToWorld(editor.getCamera(), {+ x: event.clientX - rect.left,+ y: event.clientY - rect.top,+ })+ );+ if (id && !state.session().selectedIds.includes(id)) {+ state.chooseTool('select');+ editor.select(id);+ }+ }}+ >+ <GraphicsSurface+ editor={editor}+ class={+ state.tool() === 'eraser' ? '!cursor-crosshair' : undefined+ }+ selectionHitArea={+ state.shapes().some((item) => item.type === 'document')+ ? 'shapes'+ : 'bounds'+ }+ attachControls={(surface) => {+ const detachEraser = state.eraser.attach(surface);+ const detachConnector = attachConnectorControls(+ surface,+ editor,+ {+ interaction: state.connector.interaction,+ active: state.isConnectorTool,+ appearance: state.defaults,+ style: state.connector.defaults,+ onCommit: () => state.chooseTool('select'),+ }+ );+ return () => {+ detachEraser();+ detachConnector();+ };+ }}+ hideSelection={+ !!state.embeds.active() ||+ !!state.text.draft() ||+ state.isConnectorTool() ||+ !!state.connector.gesture()+ }+ documentPreview={+ state.inspector.document() ??+ state.eraser.preview() ??+ state.connector.preview()+ }+ renderers={{+ image: (itemProps) => (+ <CanvasMediaView+ {...itemProps}+ playing={false}+ onStop={() => {}}+ />+ ),+ video: (itemProps) => (+ <CanvasMediaView+ {...itemProps}+ playing={props.assets.playing() === itemProps.item.id}+ onStop={props.assets.stopPlayback}+ />+ ),+ document: (itemProps) => (+ <CanvasDocumentView+ {...itemProps}+ embedView={props.embedView}+ active={state.embeds.active() === itemProps.item.id}+ onEnter={() => state.embeds.enter(itemProps.item.id)}+ onEmbed={() =>+ editor.execute(setDocumentDisplayCommand, {+ id: itemProps.item.id,+ display: 'embed',+ })+ }+ onExit={exitEmbed}+ />+ ),+ connector: (props) => (+ <ConnectorView+ {...props}+ hideLabel={state.text.draft()?.id === props.item.id}+ contentView={CanvasTextContent}+ />+ ),+ rectangle: (props) => (+ <RectangleView+ {...props}+ hideLabel={state.text.draft()?.id === props.item.id}+ contentView={CanvasTextContent}+ />+ ),+ ellipse: (props) => (+ <EllipseView+ {...props}+ hideLabel={state.text.draft()?.id === props.item.id}+ contentView={CanvasTextContent}+ />+ ),+ text: (props) => (+ <Show when={state.text.draft()?.id !== props.item.id}>+ <TextView {...props} contentView={CanvasTextContent} />+ </Show>+ ),+ }}+ input={{+ ignoreTarget: (target) =>+ target instanceof Element &&+ !!target.closest('[data-canvas-document]') &&+ !!target.closest(+ 'button,a,input,select,textarea,[role="button"]'+ ),+ tool: () =>+ state.tool() === 'text' ||+ state.tool() === 'eraser' ||+ state.isConnectorTool()+ ? 'select'+ : (state.tool() as Exclude<+ CanvasTool,+ 'text' | 'eraser' | 'connector' | 'arrow' | 'line'+ >),+ suspended: () =>+ !!state.embeds.active() ||+ !!state.text.draft() ||+ !!state.connector.gesture(),+ appearance: state.defaults,+ duplicateOnAltDrag: true,+ onShapeCreated: state.shapeCreated,+ }}+ gridColor={+ state.grid()+ ? 'color-mix(in srgb, var(--color-ink-muted) 35%, var(--color-panel))'+ : 'transparent'+ }+ >+ <EraserTrail points={state.eraser.trail()} />+ <Show+ when={+ (state.isConnectorTool() || state.connector.gesture()) &&+ state.connector.target()+ }+ >+ {(target) => (+ <ConnectorTargets+ camera={state.camera()}+ target={target()}+ />+ )}+ </Show>+ <Show when={state.text.draft()?.id} keyed>+ {(_id) => (+ <TextEditingView+ text={state.text}+ editor={editor}+ camera={state.camera}+ onFinish={finishText}+ />+ )}+ </Show>+ </GraphicsSurface>+ </div>+ </ContextMenu.Trigger>+ <CanvasContextMenu+ state={state}+ clipboard={props.clipboard}+ onClose={focus}+ />+ </ContextMenu>+ <CanvasDrawingToolbar+ tool={state.tool()}+ onTool={(tool) => {+ state.chooseTool(tool);+ focus();+ }}+ />+ </main>+ </div>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/connector-targets.tsx b/apps/web/src/features/block-canvas/canvas-next/views/connector-targets.tsxnew file mode 100644index 0000000000..ccd4554dd9--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/connector-targets.tsx@@ -0,0 +1,58 @@+import {+ type Camera,+ type ConnectorTarget,+ connectorAnchors,+ worldToScreen,+} from '@macro-inc/graphics';+import { For, Show } from 'solid-js';++/** Only the hovered shape exposes ports; the active port gets a larger halo. */+export function ConnectorTargets(props: {+ camera: Camera;+ target: ConnectorTarget;+}) {+ return (+ <svg+ class="pointer-events-none absolute inset-0 size-full overflow-visible"+ aria-label="Connector attachment targets"+ >+ <For each={connectorAnchors}>+ {(anchor) => {+ const point = () =>+ worldToScreen(+ props.camera,+ props.target.ports.find((port) => port.anchor === anchor)!.point+ );+ const active = () => props.target.active?.anchor === anchor;+ return (+ <g>+ <Show when={active()}>+ <circle+ data-connector-target-halo={anchor}+ cx={point().x}+ cy={point().y}+ r="14"+ fill="#5687ff"+ fill-opacity="0.25"+ stroke="#5687ff"+ stroke-opacity="0.6"+ stroke-width="1"+ />+ </Show>+ <circle+ data-connector-target={`${props.target.targetId}:${anchor}`}+ data-active={active()}+ cx={point().x}+ cy={point().y}+ r="6"+ fill="white"+ stroke="#5687ff"+ stroke-width="1"+ />+ </g>+ );+ }}+ </For>+ </svg>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/embedded-items.tsx b/apps/web/src/features/block-canvas/canvas-next/views/embedded-items.tsxnew file mode 100644index 0000000000..5eb89ce7af--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/embedded-items.tsx@@ -0,0 +1,213 @@+import { DocumentPreviewContent } from '@core/component/DocumentPreview';+import { DocumentPreviewSkeleton } from '@core/component/DocumentPreviewSkeleton';+import { fileTypeToBlockName } from '@core/constant/allBlocks';+import { staticFileIdEndpoint } from '@core/constant/servers';+import type { ShapeViewProps } from '@macro-inc/graphics/solid';+import { useBinaryDocumentQuery } from '@queries/storage/binary-document';+import { Card } from '@ui';+import {+ type Component,+ createEffect,+ createSignal,+ ErrorBoundary,+ on,+ onCleanup,+ Show,+ Suspense,+} from 'solid-js';+import { Dynamic } from 'solid-js/web';+import type { CanvasEmbedViewProps } from '../components/embed-view';+import { canEmbedDocument } from '../core/document-display';++export function CanvasMediaView(+ props: ShapeViewProps<'image' | 'video'> & {+ playing: boolean;+ onStop: () => void;+ }+) {+ const source = () => props.item.geometry.source;+ const query = useBinaryDocumentQuery(() => {+ const s = source();+ return s.type === 'document' ? s.id : '';+ });+ const url = () => {+ const value = source();+ if (value.type === 'url') return value.url;+ if (value.type === 'static') return staticFileIdEndpoint(value.id);+ return query.isSuccess ? query.data : undefined;+ };+ const [failed, setFailed] = createSignal(false);+ const [video, setVideo] = createSignal<HTMLVideoElement>();+ createEffect(on(url, () => setFailed(false)));+ createEffect(+ on([video, () => props.playing], ([element, playing]) => {+ if (!element) return;+ if (!playing) {+ element.pause();+ return;+ }+ let cancelled = false;+ onCleanup(() => {+ cancelled = true;+ element.pause();+ });+ async function play() {+ try {+ await element!.play();+ } catch {+ if (!cancelled) props.onStop();+ }+ }+ void play();+ })+ );+ const unavailable = () => failed() || query.isError;+ return (+ <div+ data-canvas-media={props.item.type}+ class="relative size-full overflow-hidden"+ style={{+ opacity: props.item.appearance.opacity ?? 1,+ 'border-radius': `${props.item.appearance.cornerRadius ?? 0}px`,+ border: `${props.item.appearance.strokeWidth ?? 0}px solid ${props.item.appearance.stroke}`,+ 'box-sizing': 'border-box',+ }}+ >+ <Suspense+ fallback={+ <div class="grid size-full place-items-center bg-hover text-sm">+ Loading media…+ </div>+ }+ >+ <Show+ when={url() && !unavailable()}+ fallback={+ <div class="grid size-full place-items-center border border-edge-muted bg-panel p-3 text-xs text-ink-muted">+ {unavailable() ? 'Media unavailable' : 'Loading media…'}+ </div>+ }+ >+ <Show+ when={props.item.type === 'image'}+ fallback={+ <video+ ref={setVideo}+ src={url()}+ preload="metadata"+ playsinline+ class="size-full object-fill"+ onError={() => setFailed(true)}+ onEnded={props.onStop}+ />+ }+ >+ <img+ src={url()}+ alt={props.item.geometry.name}+ draggable={false}+ class="size-full object-fill"+ onError={() => setFailed(true)}+ />+ </Show>+ </Show>+ </Suspense>+ </div>+ );+}+export function CanvasDocumentView(+ props: ShapeViewProps<'document'> & {+ embedView: Component<CanvasEmbedViewProps>;+ active: boolean;+ onEnter: () => void;+ onExit: () => void;+ onEmbed: () => void;+ }+) {+ const embedded = () =>+ props.item.geometry.display === 'embed' &&+ canEmbedDocument(props.item.geometry.fileType);+ return (+ <Card+ offset={embedded() ? 0 : 1}+ variant="filled"+ data-canvas-document={props.item.geometry.documentId}+ class="size-full overflow-hidden border-edge-muted text-base shadow-lg shadow-drop-shadow"+ data-canvas-embed={embedded() ? props.item.id : undefined}+ data-canvas-embed-active={props.active ? props.item.id : undefined}+ onDblClick={(event) => {+ if (embedded() && !props.active) {+ event.stopPropagation();+ props.onEnter();+ }+ }}+ style={{+ opacity: props.item.appearance.opacity ?? 1,+ 'background-color': embedded() ? 'var(--color-panel)' : undefined,+ }}+ >+ <ErrorBoundary+ fallback={+ <div class="p-4 text-sm text-ink-muted">+ Document preview unavailable+ </div>+ }+ >+ <Suspense fallback={<DocumentPreviewSkeleton />}>+ <Show+ when={embedded()}+ fallback={+ <div class="w-full text-base [&_[data-slot=item-title]]:text-base [&_[data-slot=item-description]]:text-base [&_[data-slot=item-metadata]]:text-base">+ <DocumentPreviewContent+ documentInfo={{+ id: props.item.geometry.documentId,+ type: fileTypeToBlockName(props.item.geometry.fileType),+ params: {},+ isOpenable: true,+ }}+ previewInfo={{+ showPreview: canEmbedDocument(props.item.geometry.fileType),+ isPreviewable: true,+ handlePreviewToggle: props.onEmbed,+ }}+ />+ </div>+ }+ >+ <div class="flex size-full min-h-0 flex-col">+ <div class="flex h-9 shrink-0 items-center justify-between gap-2 border-b border-edge-muted px-3 text-xs">+ <span class="truncate">{props.item.geometry.name}</span>+ <button+ type="button"+ class="shrink-0 rounded px-2 py-1 text-accent hover:bg-hover"+ onClick={(event) => {+ event.stopPropagation();+ props.active ? props.onExit() : props.onEnter();+ }}+ >+ {props.active ? 'Done' : 'Interact'}+ </button>+ </div>+ <div+ class="min-h-0 flex-1"+ inert={!props.active}+ style={{+ 'pointer-events': props.active ? 'auto' : 'none',+ 'user-select': 'text',+ }}+ on:wheel={(event) => event.stopPropagation()}+ >+ <Dynamic+ component={props.embedView}+ geometry={props.item.geometry}+ active={props.active}+ onExit={props.onExit}+ />+ </div>+ </div>+ </Show>+ </Suspense>+ </ErrorBoundary>+ </Card>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/text-content.tsx b/apps/web/src/features/block-canvas/canvas-next/views/text-content.tsxnew file mode 100644index 0000000000..bdae152a54--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/text-content.tsx@@ -0,0 +1,66 @@+import {+ StaticLexical,+ StaticMarkdownContext,+} from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import type { RichText, TextGeometry, TextMeasurer } from '@macro-inc/graphics';+import { textLayoutStyle } from '@macro-inc/graphics/browser';+import { createSignal, ErrorBoundary, Show } from 'solid-js';+import { render } from 'solid-js/web';+import { plainRichText, validCanvasText } from '../core/text-codec';+import './text.css';++export function CanvasTextContent(props: { content: RichText }) {+ return (+ <div class="canvas-lexical-text">+ <ErrorBoundary fallback={<span>Unsupported text</span>}>+ <Show+ when={validCanvasText(props.content)}+ fallback={<span>Unsupported text</span>}+ >+ <StaticLexical serializedState={props.content} />+ </Show>+ </ErrorBoundary>+ </div>+ );+}++/** Layout uses the same shared Lexical renderer as the visible canvas items. */+export function createCanvasTextMeasurer() {+ const element = document.createElement('div');+ element.className = 'graphics-rich-text';+ Object.assign(element.style, {+ position: 'fixed',+ left: '-100000px',+ top: '0',+ visibility: 'hidden',+ pointerEvents: 'none',+ });+ element.setAttribute('aria-hidden', 'true');+ document.body.append(element);+ const [content, setContent] = createSignal(plainRichText());+ const dispose = render(+ () => (+ <StaticMarkdownContext>+ <CanvasTextContent content={content()} />+ </StaticMarkdownContext>+ ),+ element+ );+ const measure: TextMeasurer = (geometry: TextGeometry) => {+ for (const [key, value] of Object.entries(textLayoutStyle(geometry)))+ element.style.setProperty(key, value);+ setContent(geometry.content);+ const rect = element.getBoundingClientRect();+ return {+ width: geometry.autoWidth ? Math.max(1, rect.width) : geometry.width,+ height: Math.max(geometry.fontSize * 1.35, rect.height),+ };+ };+ return {+ measure,+ dispose: () => {+ dispose();+ element.remove();+ },+ };+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/text-editing-view.tsx b/apps/web/src/features/block-canvas/canvas-next/views/text-editing-view.tsxnew file mode 100644index 0000000000..f9493eca9e--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/text-editing-view.tsx@@ -0,0 +1,95 @@+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';+import {+ cssMatrix,+ type GraphicsEditor,+ multiply,+ worldMatrix,+} from '@macro-inc/graphics';+import { textLayoutStyle } from '@macro-inc/graphics/browser';+import type { SerializedEditorState } from 'lexical';+import { onCleanup } from 'solid-js';+import type { CanvasTextState } from '../primitives/create-text-state';+import {+ createCanvasTextConfig,+ serializeCanvasText,+} from '../primitives/text-lexical';+import './text.css';++export function TextEditingView(props: {+ text: CanvasTextState;+ editor: GraphicsEditor;+ camera: () => { x: number; y: number; scale: number };+ onFinish: () => void;+}) {+ const draft = () => props.text.draft()!;+ const initialState: SerializedEditorState = JSON.parse(+ draft().geometry.content+ );+ const config = createCanvasTextConfig(props.text.change)+ .onEscape((event) => {+ event.preventDefault();+ props.onFinish();+ return true;+ })+ .onEnter((event) => {+ if (!event.metaKey && !event.ctrlKey) return false;+ props.onFinish();+ return true;+ });+ onCleanup(() => props.text.setFlush(undefined));+ const matrix = () => {+ const { x, y, scale } = props.camera();+ return multiply(+ [scale, 0, 0, scale, x, y],+ multiply(+ worldMatrix(props.editor.document, draft().placement.parentId),+ draft().transform+ )+ );+ };+ return (+ <div+ data-canvas-text-editor+ class="canvas-lexical-text"+ style={{+ position: 'absolute',+ left: '0',+ top: '0',+ 'transform-origin': '0 0',+ transform: cssMatrix(matrix()),+ 'z-index': 2,+ ...textLayoutStyle(draft().geometry),+ 'min-width': '8px',+ color: draft().appearance.stroke,+ opacity: draft().appearance.opacity ?? 1,+ 'user-select': 'text',+ 'touch-action': 'auto',+ cursor: 'text',+ }}+ on:pointerdown={(event) => event.stopPropagation()}+ on:dblclick={(event) => event.stopPropagation()}+ >+ <MarkdownShell+ config={config}+ initialState={initialState}+ autofocus+ placeholder=""+ class="canvas-text-shell"+ refFn={(element) => {+ element.setAttribute('role', 'textbox');+ element.setAttribute(+ 'aria-label',+ props.text.isLabel() ? 'Shape label' : 'Canvas text'+ );+ }}+ onConnect={() => {+ props.text.setFlush(() =>+ props.text.change(serializeCanvasText(config.lexical))+ );+ config.lexical.getRootElement()?.focus({ preventScroll: true });+ config.lexical.focus();+ }}+ />+ </div>+ );+}diff --git a/apps/web/src/features/block-canvas/canvas-next/views/text.css b/apps/web/src/features/block-canvas/canvas-next/views/text.cssnew file mode 100644index 0000000000..73f5af2c1d--- /dev/null+++ b/apps/web/src/features/block-canvas/canvas-next/views/text.css@@ -0,0 +1,36 @@+/* The shared editor and static renderer use identical canvas typography. */+.canvas-lexical-text, .canvas-lexical-text .md, .canvas-lexical-text [data-markdown-editable] {+ font-size: inherit; font-family: inherit; line-height: 1.35; color: inherit;+ outline: none; min-height: 1.35em;+}+.canvas-lexical-text p, .canvas-lexical-text blockquote,+.canvas-lexical-text h1, .canvas-lexical-text h2, .canvas-lexical-text h3,+.canvas-lexical-text ul, .canvas-lexical-text ol { margin-block: 0; }+.canvas-lexical-text [data-markdown-editable] { white-space: pre-wrap; overflow-wrap: anywhere; }+/* Pending mention searches are measured as plain text. Keep their highlight+ from adding width and wrapping an otherwise single-line canvas label. */+.canvas-lexical-text .md-inline-search { padding: 0; }++.canvas-lexical-text[data-canvas-text-editor] { min-width: 8px !important; }+.canvas-lexical-text > .canvas-text-shell { font-size: inherit; height: auto; min-height: 0; overflow: visible; }++/* Canvas-owned markup styles for the shared rich-text renderer. */+.graphics-rich-text p, .graphics-rich-text blockquote, .graphics-rich-text h1, .graphics-rich-text h2, .graphics-rich-text h3, .graphics-rich-text ul, .graphics-rich-text ol { margin: 0; }+.graphics-rich-text p { min-height: 1.35em; }+.graphics-rich-text h1 { font-size: 1.7em; font-weight: 700; line-height: 1.35; }+.graphics-rich-text h2 { font-size: 1.4em; font-weight: 700; line-height: 1.35; }+.graphics-rich-text h3 { font-size: 1.15em; font-weight: 700; line-height: 1.35; }+.graphics-rich-text ul, .graphics-rich-text ol { padding-inline-start: 1.5em; }+.graphics-rich-text ul { list-style: disc outside; }+.graphics-rich-text ol { list-style: decimal outside; }+.graphics-rich-text li { margin: 0; padding: 0; }+.graphics-rich-text blockquote { border-inline-start: .12em solid currentColor; padding-inline-start: .6em; }+.graphics-rich-text strong, .graphics-rich-text .graphics-text-bold { font-weight: 700; }+.graphics-rich-text em, .graphics-rich-text .graphics-text-italic { font-style: italic; }+.graphics-rich-text u, .graphics-rich-text .graphics-text-underline { text-decoration: underline; }+.graphics-rich-text s, .graphics-rich-text .graphics-text-strike { text-decoration: line-through; }+.graphics-rich-text .graphics-text-underline-strike { text-decoration: underline line-through; }+.graphics-rich-text code, .graphics-rich-text .graphics-text-code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; background: color-mix(in srgb, currentColor 10%, transparent); border-radius: .12em; }+.graphics-rich-text mark, .graphics-rich-text .graphics-text-highlight { color: inherit; background: #ffe06680; }+.graphics-rich-text a { color: inherit; text-decoration: underline; }+.graphics-rich-text [data-lexical-list-type] { list-style: inherit; }diff --git a/apps/web/src/features/block-canvas/component/Block.tsx b/apps/web/src/features/block-canvas/component/Block.tsxindex acadb9fefd..bc3035d30a 100644--- a/apps/web/src/features/block-canvas/component/Block.tsx+++ b/apps/web/src/features/block-canvas/component/Block.tsx@@ -37,39 +37,45 @@ export default function BlockCanvas(props: BlockCanvasProps) {return (<DocumentBlockContainer>- <CanvasDocument- documentId={documentId}- file={file()}- canEdit={canEdit()}- hotkeyScope={hotkeyScope()}- isNested={isNested}- portalScope="block"- view={props.view}- locationParams={locationParams}- onLocationChange={- nestedContext?.parentContext?.canvas?.onLocationChange- }- registerMethods={registerMethods}- >- {(content) => (- <div- class="size-full select-none flex flex-col"- on:click={(event) => {- if (isNested) event.stopPropagation();- }}- >- <Show when={!isNested} fallback={content}>- <SidePanel.Layout defaultOpen={false} floating>- <FileSidePanelSections />- <div class="flex size-full min-w-0 flex-col overflow-hidden">- <TopBar />- {content}- </div>- </SidePanel.Layout>- </Show>- </div>- )}- </CanvasDocument>+ <SidePanel.Root defaultOpen={false} floating>+ <CanvasDocument+ documentId={documentId}+ file={file()}+ canEdit={canEdit()}+ hotkeyScope={hotkeyScope()}+ isNested={isNested}+ portalScope="block"+ view={props.view}+ locationParams={locationParams}+ onLocationChange={+ nestedContext?.parentContext?.canvas?.onLocationChange+ }+ registerMethods={registerMethods}+ >+ {(content, state) => {+ return (+ <div+ class="size-full select-none flex flex-col"+ on:click={(event) => {+ if (isNested) event.stopPropagation();+ }}+ >+ <Show when={!isNested} fallback={content}>+ <SidePanel.Layout floating>+ <FileSidePanelSections />+ <div class="flex size-full min-w-0 flex-col overflow-hidden">+ <TopBar+ next={state.mode === 'next' ? state : undefined}+ />+ {content}+ </div>+ </SidePanel.Layout>+ </Show>+ </div>+ );+ }}+ </CanvasDocument>+ </SidePanel.Root></DocumentBlockContainer>);}diff --git a/apps/web/src/features/block-canvas/component/CanvasDocument.tsx b/apps/web/src/features/block-canvas/component/CanvasDocument.tsxindex 679747a0f4..246a0cb9ae 100644--- a/apps/web/src/features/block-canvas/component/CanvasDocument.tsx+++ b/apps/web/src/features/block-canvas/component/CanvasDocument.tsx@@ -1,17 +1,32 @@+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 { 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,@@ -30,6 +45,10 @@ import { CanvasRenderer } from './CanvasRenderer';import { Loading } from './Loading';import { ToolBar } from './ToolBar';+const CanvasNextDocument = lazy(+ () => import('../canvas-next/canvas-next-document')+);+const parseParams = createNumericParser<{x?: number;y?: number;@@ -43,7 +62,7 @@ const parseParams = createNumericParser<{type CanvasDataState = 'loading' | 'error' | 'initialized';export type CanvasDocumentMethods = {- exportCanvas: () => Promise<Canvas>;+ exportCanvas: () => Promise<Canvas | CanvasFile>;goToLocationFromParams: (params: Record<string, unknown>) => void;};@@ -58,10 +77,115 @@ export type CanvasDocumentProps = {locationParams?: Record<string, string | string[] | undefined>;onLocationChange?: (location: CanvasView) => void;registerMethods?: (methods: Partial<CanvasDocumentMethods>) => void;- children?: (content: JSX.Element) => JSX.Element;+ children?: (content: JSX.Element, state: CanvasDocumentChrome) => JSX.Element;+};++export type CanvasDocumentChrome = {+ mode: 'legacy' | 'next';+ savedFile: Accessor<Blob | undefined>;+ location?: () => { x: number; y: number; s: number };};export function CanvasDocument(props: CanvasDocumentProps) {+ return (+ <Show when={props.documentId} keyed>+ {(documentId) => (+ <CanvasDocumentLoader {...props} documentId={documentId} />+ )}+ </Show>+ );+}++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,+ };+ try {+ return loadCanvasFile(+ JSON.parse(await file.text()),+ enabled,+ importCanvasMarkdown+ );+ } catch {+ return {+ kind: 'error',+ message: 'Could not read canvas file',+ canOpenLegacy: false,+ };+ }+ }+ );+ 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 />}+ >+ <Switch>+ <Match+ when={loaded()?.kind === 'legacy' || (legacy() && legacyAllowed())}+ >+ <LegacyCanvasDocument {...props} />+ </Match>+ <Match when={loaded()?.kind === 'next' && loaded()} keyed>+ {(result) =>+ result.kind === 'next' && (+ <CanvasNextDocument {...props} initial={result.file} />+ )+ }+ </Match>+ <Match when={loaded()?.kind === 'error' && loaded()} keyed>+ {(result) =>+ result.kind === 'error' && (+ <div+ role="alert"+ 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>+ )+ }+ </Match>+ </Switch>+ </Show>+ );+}++function LegacyCanvasDocument(props: CanvasDocumentProps) {return (<Show when={props.documentId} keyed>{(documentId) => (@@ -171,6 +295,8 @@ function CanvasDocumentState(props: CanvasDocumentProps) {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) {@@ -262,7 +388,13 @@ function CanvasDocumentState(props: CanvasDocumentProps) {</Show>);- return props.children ? props.children(content) : content;+ return props.children+ ? props.children(content, {+ mode: 'legacy',+ savedFile: () =>+ canvas.state.signals.currentSavedFile[0]() ?? undefined,+ })+ : content;}function getCanvasState(state: {diff --git a/apps/web/src/features/block-canvas/component/TopBar.tsx b/apps/web/src/features/block-canvas/component/TopBar.tsxindex e02904b982..3afcfd8c77 100644--- a/apps/web/src/features/block-canvas/component/TopBar.tsx+++ b/apps/web/src/features/block-canvas/component/TopBar.tsx@@ -38,14 +38,16 @@ 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() {+export function TopBar(props: { next?: CanvasDocumentChrome } = {}) {const analytics = useAnalytics();- const toolManager = useToolManager();- const { getLocation } = useRenderState();- const [getCurrentSavedFile] =- useCanvasDocument().state.signals.currentSavedFile;+ 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,7 +66,7 @@ export function TopBar() {let ref!: HTMLDivElement;onMount(() => {- toolManager.ignoreMouseEvents(ref);+ toolManager?.ignoreMouseEvents(ref);});const downloadDocument = createCallback(async () => {diff --git a/apps/web/src/features/block-canvas/definition.ts b/apps/web/src/features/block-canvas/definition.tsindex 44ab0d213f..924809c33c 100644--- a/apps/web/src/features/block-canvas/definition.ts+++ b/apps/web/src/features/block-canvas/definition.ts@@ -10,6 +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';export const definition = defineBlock({@@ -73,5 +74,5 @@ export const definition = defineBlock({export type CanvasData = ExtractLoadType<(typeof definition)['load']>;export type CanvasSpec = {- exportCanvas: () => Promise<Canvas>;+ exportCanvas: () => Promise<Canvas | CanvasFile>;};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.tsindex 8f85f15e7c..ae2b0db031 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@@ -1,3 +1,4 @@+import { createGraphicsEditor } from '@macro-inc/graphics';import { ok } from 'neverthrow';import { beforeEach, describe, expect, it, vi } from 'vitest';import { fetchCanvasViewLocation, saveCanvasDocument } from './canvas-document';@@ -45,6 +46,21 @@ describe('canvas document queries', () => {});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();+ const canvas = { version: 2 as const, document: editor.document };+ const result = await saveCanvasDocument('canvas-next', canvas);+ expect(result.saved).toBe(true);+ expect(result.file.type).toBe('application/x-macro-canvas');+ expect(JSON.parse(await readBlob(result.file))).toEqual(canvas);+ expect(storageMocks.simpleSave).toHaveBeenCalledWith({+ documentId: 'canvas-next',+ file: result.file,+ });+ editor.dispose();+ });});function readBlob(blob: Blob) {diff --git a/apps/web/src/features/block-canvas/queries/canvas-document.ts b/apps/web/src/features/block-canvas/queries/canvas-document.tsindex cdf46da2f1..0400d6d868 100644--- a/apps/web/src/features/block-canvas/queries/canvas-document.ts+++ b/apps/web/src/features/block-canvas/queries/canvas-document.ts@@ -1,4 +1,5 @@import { storageServiceClient } from '@service-storage/client';+import type { CanvasFile } from '../canvas-next/core/document-format';import type { Canvas } from '../model/CanvasModel';export type CanvasViewLocation = {@@ -31,7 +32,7 @@ export async function fetchCanvasViewLocation(export async function saveCanvasDocument(documentId: string,- canvas: Canvas+ canvas: 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-pptx/components/ribbon/home-tab.tsx b/apps/web/src/features/block-pptx/components/ribbon/home-tab.tsxindex ee89968c1f..1fa04e4724 100644--- a/apps/web/src/features/block-pptx/components/ribbon/home-tab.tsx+++ b/apps/web/src/features/block-pptx/components/ribbon/home-tab.tsx@@ -454,30 +454,28 @@ export function HomeTab() {</div>)}</RibbonPopover>- <>- <RibbonPopover- label="Layout"- icon={<span>Layout</span>}- disabled={ro()}- >- {(close) => (- <div class="flex max-h-[60vh] w-56 flex-col overflow-y-auto">- <For each={env.deck()?.layouts ?? []}>- {(layout) => (- <PopoverItem- label={layout.name}- active={layout.name === env.slide()?.layout}- onClick={() => {- close();- void c.setLayout(layout.name);- }}- />- )}- </For>- </div>- )}- </RibbonPopover>- </>+ <RibbonPopover+ label="Layout"+ icon={<span>Layout</span>}+ disabled={ro()}+ >+ {(close) => (+ <div class="flex max-h-[60vh] w-56 flex-col overflow-y-auto">+ <For each={env.deck()?.layouts ?? []}>+ {(layout) => (+ <PopoverItem+ label={layout.name}+ active={layout.name === env.slide()?.layout}+ onClick={() => {+ close();+ void c.setLayout(layout.name);+ }}+ />+ )}+ </For>+ </div>+ )}+ </RibbonPopover><SectionMenu /><RibbonButtonlabel="Duplicate slide"diff --git a/apps/web/src/features/block-pptx/components/ribbon/table-tabs.tsx b/apps/web/src/features/block-pptx/components/ribbon/table-tabs.tsxindex 99eb301722..6faccfae03 100644--- a/apps/web/src/features/block-pptx/components/ribbon/table-tabs.tsx+++ b/apps/web/src/features/block-pptx/components/ribbon/table-tabs.tsx@@ -144,80 +144,76 @@ export function TableDesignTab(props: TableTabProps) {</RibbonGroup></Show><RibbonGroup label="Cells">- <>- <RibbonPopover- label="Shading"- icon={<PaintBucket class="size-3.5" />}- disabled={ro()}- testId="pptx-cell-shading"- >- {(close) => (+ <RibbonPopover+ label="Shading"+ icon={<PaintBucket class="size-3.5" />}+ disabled={ro()}+ testId="pptx-cell-shading"+ >+ {(close) => (+ <ColorPicker+ themeGrid={env.themeGrid()}+ standard={env.standardColors}+ noneLabel="No fill"+ onPick={(v) => {+ close();+ void c.fillCells(v);+ }}+ />+ )}+ </RibbonPopover>+ <RibbonPopover+ label="Borders"+ icon={<BorderIcon edges="all" />}+ disabled={ro()}+ testId="pptx-cell-borders"+ >+ {(close) => (+ <div class="flex w-56 flex-col">+ <For each={BORDER_EDGES}>+ {([edges, label]) => (+ <PopoverItem+ label={label}+ icon={<BorderIcon edges={edges} />}+ onClick={() => {+ close();+ void c.borderCells(edges);+ }}+ />+ )}+ </For>+ <PopoverItem+ label="No border"+ icon={<BorderIcon edges="none" />}+ onClick={() => {+ close();+ void c.borderCells('all', true);+ }}+ />+ <PopoverLabel>Pen</PopoverLabel><ColorPickerthemeGrid={env.themeGrid()}standard={env.standardColors}- noneLabel="No fill"onPick={(v) => {- close();- void c.fillCells(v);+ if (v) c.setBorderPen({ color: v });}}/>- )}- </RibbonPopover>- </>- <>- <RibbonPopover- label="Borders"- icon={<BorderIcon edges="all" />}- disabled={ro()}- testId="pptx-cell-borders"- >- {(close) => (- <div class="flex w-56 flex-col">- <For each={BORDER_EDGES}>- {([edges, label]) => (- <PopoverItem- label={label}- icon={<BorderIcon edges={edges} />}- onClick={() => {- close();- void c.borderCells(edges);- }}- />+ <div class="flex flex-wrap gap-1 px-1 pt-1">+ <For each={[0.5, 1, 1.5, 2.25, 3, 4.5]}>+ {(w) => (+ <button+ type="button"+ class="rounded-md border border-edge-muted px-1.5 py-0.5 text-xs hover:bg-ink/5"+ onClick={() => c.setBorderPen({ width: w })}+ >+ {w} pt+ </button>)}</For>- <PopoverItem- label="No border"- icon={<BorderIcon edges="none" />}- onClick={() => {- close();- void c.borderCells('all', true);- }}- />- <PopoverLabel>Pen</PopoverLabel>- <ColorPicker- themeGrid={env.themeGrid()}- standard={env.standardColors}- onPick={(v) => {- if (v) c.setBorderPen({ color: v });- }}- />- <div class="flex flex-wrap gap-1 px-1 pt-1">- <For each={[0.5, 1, 1.5, 2.25, 3, 4.5]}>- {(w) => (- <button- type="button"- class="rounded-md border border-edge-muted px-1.5 py-0.5 text-xs hover:bg-ink/5"- onClick={() => c.setBorderPen({ width: w })}- >- {w} pt- </button>- )}- </For>- </div></div>- )}- </RibbonPopover>- </>+ </div>+ )}+ </RibbonPopover></RibbonGroup></>);@@ -374,61 +370,57 @@ export function TableLayoutTab(props: TableTabProps) {Insert right</RibbonTextButton></RibbonGroup>- <>- <RibbonGroup label="Merge">- <RibbonTextButton- label="Merge cells"- disabled={ro() || !c.canMerge()}- data-testid="pptx-merge-cells"- onClick={() => void c.mergeCells()}- >- Merge cells- </RibbonTextButton>- <RibbonTextButton- label="Split cells"- disabled={ro() || !c.canSplit()}- onClick={() => void c.splitCells()}- >- Split cells- </RibbonTextButton>- </RibbonGroup>- </>- <>- <RibbonGroup label="Cell size">- <NumberField- label="Row height"- unit="pt"- value={c.cellSize()?.h}- min={4}- max={2000}- disabled={ro()}- onCommit={(h) => void c.setCellSize({ h })}- />- <NumberField- label="Column width"- unit="pt"- value={c.cellSize()?.w}- min={4}- max={2000}- disabled={ro()}- onCommit={(w) => void c.setCellSize({ w })}- />- <RibbonTextButton- label="Distribute rows"- disabled={ro()}- onClick={() => void c.distributeRows()}- >- Distribute rows- </RibbonTextButton>- <RibbonTextButton- label="Distribute columns"- disabled={ro()}- onClick={() => void c.distributeColumns()}- >- Distribute columns- </RibbonTextButton>- </RibbonGroup>- </>+ <RibbonGroup label="Merge">+ <RibbonTextButton+ label="Merge cells"+ disabled={ro() || !c.canMerge()}+ data-testid="pptx-merge-cells"+ onClick={() => void c.mergeCells()}+ >+ Merge cells+ </RibbonTextButton>+ <RibbonTextButton+ label="Split cells"+ disabled={ro() || !c.canSplit()}+ onClick={() => void c.splitCells()}+ >+ Split cells+ </RibbonTextButton>+ </RibbonGroup>+ <RibbonGroup label="Cell size">+ <NumberField+ label="Row height"+ unit="pt"+ value={c.cellSize()?.h}+ min={4}+ max={2000}+ disabled={ro()}+ onCommit={(h) => void c.setCellSize({ h })}+ />+ <NumberField+ label="Column width"+ unit="pt"+ value={c.cellSize()?.w}+ min={4}+ max={2000}+ disabled={ro()}+ onCommit={(w) => void c.setCellSize({ w })}+ />+ <RibbonTextButton+ label="Distribute rows"+ disabled={ro()}+ onClick={() => void c.distributeRows()}+ >+ Distribute rows+ </RibbonTextButton>+ <RibbonTextButton+ label="Distribute columns"+ disabled={ro()}+ onClick={() => void c.distributeColumns()}+ >+ Distribute columns+ </RibbonTextButton>+ </RibbonGroup><RibbonGroup label="Alignment"><RibbonButtonlabel="Align left"diff --git a/apps/web/src/features/drive-view/views/CanvasDetail.tsx b/apps/web/src/features/drive-view/views/CanvasDetail.tsxindex 4099cf107e..2d5425ca9f 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 { useCanvasDocument } from '@block-canvas/context/canvas-document-context';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import {getPermissions,@@ -9,7 +8,7 @@ import {} from '@core/component/SharePermissions';import { downloadFile } from '@filesystem/download';import { useSearchParams } from '@solidjs/router';-import type { JSX } from 'solid-js';+import type { Accessor, JSX } from 'solid-js';import { FileDetailLayout, FileDetailLoadGate } from '../components/FileDetail';import { downloadFileOperation } from '../components/file-detail-operations';import {@@ -25,16 +24,16 @@ function CanvasDetailContent(props: {data: CanvasDocumentData;children?: (context: CanvasDetailContext) => JSX.Element;content: JSX.Element;+ savedFile: Accessor<Blob | undefined>;}) {const analytics = useAnalytics();- const [savedFile] = useCanvasDocument().state.signals.currentSavedFile;const downloadName = documentDownloadName(props.data.documentMetadata,'Unknown Filename');const operations = [downloadFileOperation(() => {- downloadFile(savedFile() ?? props.data.file, downloadName);+ downloadFile(props.savedFile() ?? props.data.file, downloadName);analytics.track('download', { blockType: 'canvas' });}),];@@ -81,11 +80,12 @@ export function CanvasDetailDocument(props: {portalScope="split"locationParams={searchParams}>- {(content) => (+ {(content, state) => (<CanvasDetailContentdata={props.data}children={props.children}content={content}+ savedFile={state.savedFile}/>)}</CanvasDocument>diff --git a/apps/web/src/features/entity/extractors/entity-timestamp.tsx b/apps/web/src/features/entity/extractors/entity-timestamp.tsxindex 679d2bbdcf..a7c5824ba8 100644--- a/apps/web/src/features/entity/extractors/entity-timestamp.tsx+++ b/apps/web/src/features/entity/extractors/entity-timestamp.tsx@@ -20,10 +20,7 @@ export function EntityTimestamp(props: {? props.entity.scheduledSendTime: undefined;return (- <Show- when={scheduledSendTime()}- fallback={<>{formatTimestamp(timestamp())}</>}- >+ <Show when={scheduledSendTime()} fallback={formatTimestamp(timestamp())}>{(sendTime) => <ScheduledBadge sendTime={sendTime()} />}</Show>);diff --git a/apps/web/src/features/theme/components/ColorPickerPopover.tsx b/apps/web/src/features/theme/components/ColorPickerPopover.tsxindex c7224a5d09..42b298b727 100644--- a/apps/web/src/features/theme/components/ColorPickerPopover.tsx+++ b/apps/web/src/features/theme/components/ColorPickerPopover.tsx@@ -1,14 +1,13 @@import { Popover } from '@kobalte/core/popover';import { Slider } from '@kobalte/core/slider';-import { Tabs } from '@kobalte/core/tabs';-import { cn, Layer } from '@ui';+import { cn, Input, Layer, Select } from '@ui';+import { inputClasses } from '@ui/components/Input';import Color from 'colorjs.io';import {batch,createEffect,createMemo,createSignal,- For,type JSX,onCleanup,onMount,@@ -115,7 +114,8 @@ function ColorField(props: {return (<divref={ref}- class="relative h-40 flex-1 cursor-crosshair touch-none overflow-hidden rounded-md"+ data-color-field+ class="relative h-40 w-full shrink-0 cursor-crosshair touch-none overflow-hidden rounded-md"onPointerDown={(e) => {setDragging(true);apply(e);@@ -139,11 +139,6 @@ function ColorField(props: {);}-// Vertical hue gradient, 0° at the top → 360° at the bottom. Pairs with the-// slider's `inverted` flag so the thumb (value 0 at top) tracks the gradient.-const HUE_GRADIENT =- 'linear-gradient(to bottom, oklch(0.7 0.2 0deg), oklch(0.7 0.2 60deg), oklch(0.7 0.2 120deg), oklch(0.7 0.2 180deg), oklch(0.7 0.2 240deg), oklch(0.7 0.2 300deg), oklch(0.7 0.2 360deg))';-const HORIZONTAL_HUE_GRADIENT ='linear-gradient(to right, hsl(0 100% 50%), hsl(60 100% 50%), hsl(120 100% 50%), hsl(180 100% 50%), hsl(240 100% 50%), hsl(300 100% 50%), hsl(360 100% 50%))';@@ -189,15 +184,11 @@ function ChannelSlider(props: {);}-/** Vertical hue slider (0 → 360), backed by Kobalte's generic Slider so pointer- * dragging and keyboard control come for free; we only style the rail/thumb.- * `inverted` keeps 0° at the top (matching the prior hand-rolled slider). */+/** Keyboard-accessible horizontal hue slider. */function HueSlider(props: { h: () => number; onH: (n: number) => void }) {return (<Slider- class="relative flex h-40 w-3 shrink-0 touch-none select-none"- orientation="vertical"- inverted+ class="relative flex h-3 w-full shrink-0 touch-none select-none"minValue={0}maxValue={360}step={1}@@ -207,12 +198,10 @@ function HueSlider(props: { h: () => number; onH: (n: number) => void }) {><Slider.Trackclass="relative h-full w-full rounded-full"- style={{ background: HUE_GRADIENT }}+ style={{ background: HORIZONTAL_HUE_GRADIENT }}>- {/* Kobalte positions the thumb on the main (vertical) axis via `bottom` +- its own transform; we only center it horizontally and paint it. */}<Slider.Thumb- class="absolute left-1/2 -ml-[7px] size-3.5 rounded-full border-2 border-[white] shadow-[0_1px_3px_oklch(0_0_0/0.4)] outline-none"+ class="absolute top-1/2 -mt-[7px] size-3.5 rounded-full border-2 border-[white] shadow-[0_1px_3px_oklch(0_0_0/0.4)] outline-none"style={{ 'background-color': `oklch(0.7 0.2 ${props.h()}deg)` }}><Slider.Input />@@ -237,12 +226,18 @@ export function ColorPickerPopover(props: {onH: (n: number) => void;onAlpha?: (n: number) => void;ariaLabel: string;+ formats?: ['hex', ...('rgb' | 'hsl')[]];title?: string;subtitle?: string;/** Width passed to the default trigger swatch (full-width by default). */triggerWidth?: string;/** Custom trigger content (replaces the default swatch). */trigger?: JSX.Element;+ /** Optional preset controls below the custom color controls. */+ children?: JSX.Element;+ class?: string;+ triggerClass?: string;+ onOpenChange?: (open: boolean) => void;}) {const pickerColor = createMemo(() =>sanitizeOklch({@@ -369,9 +364,16 @@ export function ColorPickerPopover(props: {};return (- <Popover placement="bottom-end" gutter={8}>+ <Popover+ placement="bottom-end"+ gutter={8}+ onOpenChange={props.onOpenChange}+ ><Popover.Trigger- class="block appearance-none border-none bg-transparent p-0"+ class={cn(+ 'block appearance-none border-none bg-transparent p-0',+ props.triggerClass+ )}aria-label={props.ariaLabel}><Show@@ -389,7 +391,10 @@ export function ColorPickerPopover(props: {<Popover.Content class="z-modal"><Popover.Arrow class="fill-surface" /><div- class="flex w-[34rem] max-w-[calc(100vw-2rem)] flex-col gap-4 rounded-xl glass bg-menu-glass p-4"+ class={cn(+ 'flex max-h-[min(calc(100vh-2rem),var(--kb-popper-content-available-height))] w-[34rem] max-w-[calc(100vw-2rem)] flex-col overflow-y-auto gap-4 rounded-xl border border-edge glass bg-menu-glass p-4',+ props.class+ )}role="dialog"aria-label={props.ariaLabel}>@@ -410,7 +415,7 @@ export function ColorPickerPopover(props: {</div></Show>- <div class="flex gap-4">+ <div class="flex shrink-0 flex-col gap-4"><ColorFieldl={lightness}c={chroma}@@ -450,24 +455,6 @@ export function ColorPickerPopover(props: {</span></Slider>- <Tabs- value={format()}- onChange={(value) => setFormat(value as ColorFormat)}- >- <Tabs.List class="grid grid-cols-3 overflow-hidden rounded-md border border-edge-muted bg-inset p-0.5">- <For each={['hex', 'rgb', 'hsl'] as const}>- {(value) => (- <Tabs.Trigger- value={value}- class="rounded-sm px-3 py-1.5 text-xs uppercase text-ink-muted outline-none data-selected:bg-surface data-selected:text-ink data-selected:shadow-sm"- >- {value}- </Tabs.Trigger>- )}- </For>- </Tabs.List>- </Tabs>-<Show when={format() === 'rgb'}><div class="flex flex-col gap-3 rounded-md bg-inset p-3"><ChannelSlider@@ -545,16 +532,41 @@ export function ColorPickerPopover(props: {</div></Show>- <input- class={cn(- 'h-10 rounded-md border border-edge-muted bg-transparent px-3 text-center font-mono text-sm text-ink outline-none focus:border-accent',- colorInvalid() && 'border-failure text-failure'- )}- value={colorText()}- onInput={(e) => setColorTextValue(e.currentTarget.value)}- spellcheck={false}- aria-label={`${format().toUpperCase()} color`}- />+ <div class="flex items-center gap-2">+ <Select<ColorFormat>+ options={props.formats ?? ['hex', 'rgb', 'hsl']}+ disabled={props.formats?.length === 1}+ value={format()}+ onChange={(value) => value && setFormat(value)}+ >+ <Select.Trigger+ aria-label="Color format"+ class={inputClasses({+ size: 'md',+ class: 'w-20 shrink-0 text-xs uppercase',+ })}+ >+ <Select.Value<ColorFormat>>+ {(state) => state.selectedOption()}+ </Select.Value>+ <Show when={props.formats?.length !== 1}>+ <Select.Icon />+ </Show>+ </Select.Trigger>+ <Select.Content>+ <Select.Listbox />+ </Select.Content>+ </Select>+ <Input+ class="text-center font-mono text-xs"+ aria-invalid={colorInvalid()}+ value={colorText()}+ onInput={(e) => setColorTextValue(e.currentTarget.value)}+ spellcheck={false}+ aria-label={`${format().toUpperCase()} color`}+ />+ </div>+ {props.children}</div></Popover.Content></Layer>diff --git a/apps/web/src/lib/core/component/DocumentPreview.tsx b/apps/web/src/lib/core/component/DocumentPreview.tsxindex a276b26423..0dba02c5f5 100644--- a/apps/web/src/lib/core/component/DocumentPreview.tsx+++ b/apps/web/src/lib/core/component/DocumentPreview.tsx@@ -81,52 +81,16 @@ import { Dynamic } from 'solid-js/web';import { formatDate } from '../util/date';import NotFound from './AccessErrorViews/NotFound';import Unauthorized from './AccessErrorViews/Unauthorized';+import {+ DocumentPreviewIconSkeleton,+ DocumentPreviewSkeleton,+} from './DocumentPreviewSkeleton';import { useItemPreviewData } from './ItemPreview';import {TaskPropertiesPreview,TaskPropertiesPreviewProvider,} from './TaskPropertiesPreview';-/**- * Container for displaying mentions with optional collapsing- */-function MentionContainer(props: {- icon: JSX.Element;- text: JSX.Element;- collapsed?: boolean;-}) {- return (- <span class="pointer-events-auto">- <span class="relative top-[0.125em] size-[1em] inline-flex mx-1">- {props.icon}- </span>- <Show when={!props.collapsed}>- <span class="underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2 mr-1">- {props.text}- </span>- </Show>- </span>- );-}--/**- * Simple spinner component for loading states- */-function Spinner() {- return (- <div class="animate-spin">- <LoadingSpinner />- </div>- );-}--/**- * Loading indicator for mentions- */-function Loading() {- return <MentionContainer icon={<Spinner />} text="Loading" />;-}-/*** Returns the appropriate icon component based on the icon name* @param icon - Icon identifier string@@ -835,9 +799,7 @@ export function DocumentPreviewContent(props: DocumentPreviewContentProps) {<Switch>{/* Loading state */}<Match when={item().loading}>- <div class="p-3 flex items-center justify-center">- <Loading />- </div>+ <DocumentPreviewSkeleton /></Match>{/* Accessible preview */}@@ -870,7 +832,7 @@ export function DocumentPreviewContent(props: DocumentPreviewContentProps) {><Suspensefallback={- <LoadingSpinner class="size-4 animate-spin text-ink-muted" />+ <DocumentPreviewIconSkeleton label="Loading task status" />}><TaskPropertiesPreview@@ -1085,14 +1047,16 @@ export function PopupPreview(depth={2}class="rounded-xl shadow-lg shadow-drop-shadow">- <DocumentPreviewContent- delete={props.delete}- collapseInfo={props.collapseInfo}- documentInfo={props.documentInfo}- previewInfo={props.previewInfo}- snapshotInfo={props.snapshotInfo}- useFallbackData={props.useFallbackData}- />+ <Suspense fallback={<DocumentPreviewSkeleton />}>+ <DocumentPreviewContent+ delete={props.delete}+ collapseInfo={props.collapseInfo}+ documentInfo={props.documentInfo}+ previewInfo={props.previewInfo}+ snapshotInfo={props.snapshotInfo}+ useFallbackData={props.useFallbackData}+ />+ </Suspense></Card></div>);diff --git a/apps/web/src/lib/core/component/DocumentPreviewSkeleton.tsx b/apps/web/src/lib/core/component/DocumentPreviewSkeleton.tsxnew file mode 100644index 0000000000..7a05b9f6c3--- /dev/null+++ b/apps/web/src/lib/core/component/DocumentPreviewSkeleton.tsx@@ -0,0 +1,34 @@+/** Shared by preview cards and their async boundaries; no document data required. */+export function DocumentPreviewIconSkeleton(props: { label?: string }) {+ return (+ <span+ role={props.label ? 'img' : undefined}+ aria-label={props.label}+ aria-hidden={props.label ? undefined : true}+ class="block size-4 shrink-0 rounded-full bg-skeleton motion-safe:animate-pulse"+ />+ );+}++export function DocumentPreviewSkeleton() {+ return (+ <div+ role="status"+ aria-label="Loading document preview"+ class="w-full px-3 py-2.5"+ >+ <div+ aria-hidden="true"+ class="grid grid-cols-[1rem_minmax(0,1fr)] items-start gap-x-2"+ >+ <div class="pt-0.5">+ <DocumentPreviewIconSkeleton />+ </div>+ <div class="flex min-w-0 flex-col gap-2 py-1 motion-safe:animate-pulse">+ <div class="h-3.5 w-3/4 rounded bg-skeleton" />+ <div class="h-3.5 w-1/2 rounded bg-skeleton" />+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/src/lib/core/component/InlineTaskProperties.tsx b/apps/web/src/lib/core/component/InlineTaskProperties.tsxindex e6a7ccbf4c..6a1537bf07 100644--- a/apps/web/src/lib/core/component/InlineTaskProperties.tsx+++ b/apps/web/src/lib/core/component/InlineTaskProperties.tsx@@ -59,20 +59,28 @@ function InlineTaskPropertyValues(props: { properties: Accessor<Property[]> }) {});return (<Show when={statusOptionId() || priorityOptionId() || firstAssigneeId()}>- <span class="inline-flex items-center gap-1 mx-1 align-middle relative top-[-0.05em]">+ <span+ data-inline-task-properties+ class="inline-flex items-center gap-[0.25em] mx-[0.25em] align-middle relative top-[-0.05em]"+ ><Show when={statusOptionId()}>- {(id) => <PropertyValueIcon optionId={id()} class="size-3" />}+ {(id) => (+ <PropertyValueIcon optionId={id()} class="size-[0.75em] shrink-0" />+ )}</Show><Show when={priorityOptionId()}>- {(id) => <PropertyValueIcon optionId={id()} class="size-3" />}+ {(id) => (+ <PropertyValueIcon optionId={id()} class="size-[0.75em] shrink-0" />+ )}</Show><Show when={firstAssigneeId()}>{(id) => (- <span class="inline-flex ml-0.5 size-3.25">+ <span class="inline-flex ml-[0.125em] size-[0.8125em] shrink-0"><UserIconid={id()}isDeleted={false}size="fill"+ class="[&>span]:text-[50cqw]"suppressClickshowTooltip={false}/>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsxindex 31dfa509bc..daf7961f2e 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx@@ -641,7 +641,14 @@ const Video: TypedRenderableEntity<VideoNode> = {const Paragraph: TypedRenderableElement<ParagraphNode> = {guard: (node: LexicalNode): node is ParagraphNode =>node.__type === 'paragraph',- render: (props) => <p class={props.theme.paragraph}>{props.children}</p>,+ render: (props) => (+ <p+ class={props.theme.paragraph}+ style={{ 'text-align': props.node.getFormatType() || undefined }}+ >+ {props.children}+ </p>+ ),};const Heading: TypedRenderableElement<HeadingNode> = {@@ -652,6 +659,7 @@ const Heading: TypedRenderableElement<HeadingNode> = {<Dynamiccomponent={tag}class={props.theme.heading?.[tag]}+ style={{ 'text-align': props.node.getFormatType() || undefined }}children={props.children}/>);@@ -710,14 +718,26 @@ const ListItem: TypedRenderableElement<ListItemNode> = {.filter(Boolean).join(' ');- return <li class={classes}>{props.children}</li>;+ return (+ <li+ class={classes}+ style={{ 'text-align': props.node.getFormatType() || undefined }}+ >+ {props.children}+ </li>+ );},};const Quote: TypedRenderableElement<QuoteNode> = {guard: (node: LexicalNode): node is QuoteNode => node.__type === 'quote',render: (props) => (- <blockquote class={props.theme.quote}>{props.children}</blockquote>+ <blockquote+ class={props.theme.quote}+ style={{ 'text-align': props.node.getFormatType() || undefined }}+ >+ {props.children}+ </blockquote>),};@@ -1067,6 +1087,24 @@ const context = createContext<{lazy: Accessor<boolean>;}>({ editor: null, theme: () => baseTheme, lazy: () => true });+/** Render a saved Lexical tree directly, preserving formats absent from Markdown. */+export function StaticLexical(props: { serializedState: string }) {+ const inherited = useContext(context);+ const editor =+ inherited.editor ?? newStaticRenderingEditor({ theme: inherited.theme() });+ const tree = createMemo(() => {+ const state = editor.parseEditorState(props.serializedState);+ return state.read(() =>+ Document({+ rootNode: $getRoot(),+ theme: inherited.theme(),+ lazy: false,+ })+ );+ });+ return <>{tree()}</>;+}+export function StaticMarkdown(props: {markdown: string;parentEditor?: LexicalEditor;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsxindex f3397b6917..9f5bc4e466 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx@@ -97,11 +97,11 @@ function MentionContainer(props: {}) {return (<span class="pointer-events-auto">- <span class="relative top-[0.125em] size-[1em] inline-flex mx-1">+ <span class="relative top-[0.125em] size-[1em] inline-flex mx-[0.25em]">{props.icon}</span><Show when={!props.collapsed}>- <span class="underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">+ <span class="underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-[0.125em]">{props.text}</span></Show>@@ -721,7 +721,7 @@ function DocumentMentionInner(props: DocumentMentionDecoratorProps) {trigger={<span class="relative"><span- class="size-full py-0.5 cursor-default rounded-xs hover:bg-hover focus:bg-active"+ class="size-full py-[0.125em] cursor-default rounded-xs hover:bg-hover focus:bg-active"classList={{'bg-active text-ink': isSelectedAsNode(),}}diff --git a/apps/web/src/lib/core/component/TaskPropertiesPreview.tsx b/apps/web/src/lib/core/component/TaskPropertiesPreview.tsxindex 6838f2fbbd..0076c8a3a0 100644--- a/apps/web/src/lib/core/component/TaskPropertiesPreview.tsx+++ b/apps/web/src/lib/core/component/TaskPropertiesPreview.tsx@@ -27,6 +27,7 @@ import {Show,useContext,} from 'solid-js';+import { DocumentPreviewIconSkeleton } from './DocumentPreviewSkeleton';const TASK_PREVIEW_PROPERTIES = [SYSTEM_PROPERTY_IDS.STATUS,@@ -189,15 +190,18 @@ function TaskPropertiesPreviewContent(when={!props.isLoading && previewProperties().length > 0}fallback={<Show when={props.mode === 'status'}>- <CircleIcon- class="size-4 text-ink-muted"- role="img"- aria-label={- props.isLoading- ? 'Loading task status'- : 'Task status unavailable'+ <Show+ when={props.isLoading}+ fallback={+ <CircleIcon+ class="size-4 text-ink-muted"+ role="img"+ aria-label="Task status unavailable"+ />}- />+ >+ <DocumentPreviewIconSkeleton label="Loading task status" />+ </Show></Show>}>diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex cc1fa4b2e8..a9236d6a2f 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -91,6 +91,13 @@ 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,+});+/*** Imperative snapshot. Env/`default` override wins. Otherwise PostHog,* or `false` if flags have not loaded or the key is unknown.diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.tsindex 5171d30206..3b642ff612 100644--- a/apps/web/src/lib/core/hotkey/tokens.ts+++ b/apps/web/src/lib/core/hotkey/tokens.ts@@ -205,6 +205,7 @@ export const TOKENS = {paste: 'canvas.paste',zoomIn: 'canvas.zoomIn',zoomOut: 'canvas.zoomOut',+ zoomFit: 'canvas.zoomFit',undo: 'canvas.undo',redo: 'canvas.redo',cancel: 'canvas.cancel',diff --git a/bun.lock b/bun.lockindex 53ceb76131..dd790338a1 100644--- a/bun.lock+++ b/bun.lock@@ -71,6 +71,7 @@"@ironcalc/wasm": "workspace:*","@kobalte/core": "^0.13.11","@leeoniya/ufuzzy": "^1.0.19",+ "@lexical/extension": "0.45.0","@lexical/history": "0.45.0","@lexical/html": "0.45.0","@lexical/link": "0.45.0",@@ -88,6 +89,7 @@"@lukemorales/query-key-factory": "^1.3.4","@macro-inc/collaboration": "workspace:*","@macro-inc/email-renderer": "workspace:*",+ "@macro-inc/graphics": "workspace:*","@macro-inc/lexical-core": "workspace:*","@macro-inc/machine": "workspace:*","@macro-inc/observability": "workspace:*",@@ -270,6 +272,30 @@"vitest": "5.0.1",},},+ "packages/graphics": {+ "name": "@macro-inc/graphics",+ "version": "0.1.0",+ "dependencies": {+ "fractional-indexing": "4.0.0",+ "loro-crdt": "catalog:",+ "perfect-freehand": "1.2.3",+ },+ "devDependencies": {+ "@biomejs/biome": "2.4.12",+ "@types/node": "^24.8.0",+ "jsdom": "^26.1.0",+ "solid-js": "^1.9.7",+ "typescript": "^5.9.3",+ "vite-plugin-solid": "^2.11.8",+ "vitest": "5.0.1",+ },+ "peerDependencies": {+ "solid-js": "^1.9.7",+ },+ "optionalPeers": [+ "solid-js",+ ],+ },"packages/lexical-core": {"name": "@macro-inc/lexical-core","version": "0.2.2",@@ -1232,6 +1258,8 @@"@macro-inc/email-renderer": ["@macro-inc/email-renderer@workspace:packages/email-renderer"],+ "@macro-inc/graphics": ["@macro-inc/graphics@workspace:packages/graphics"],+"@macro-inc/lexical-core": ["@macro-inc/lexical-core@workspace:packages/lexical-core"],"@macro-inc/machine": ["@macro-inc/machine@workspace:packages/machine"],@@ -2468,6 +2496,8 @@"frac": ["[email protected]", "", {}, "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA=="],+ "fractional-indexing": ["[email protected]", "", {}, "sha512-Nr2P1Yyaj2sy1Qdt/wI3GcByxrUdbSKg5+cGvw8f18hT2SkQt6V72iOjBpk7IO3UkzBsdlGRs2a4z6dLrJprgw=="],+"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA=="],@@ -3146,6 +3176,8 @@"pend": ["[email protected]", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],+ "perfect-freehand": ["[email protected]", "", {}, "sha512-bHZSfqDHGNlPpgH2yxXgPHlQSPpEbo+qg7li0M78J9vNAi2yjwLeA4x79BEQhX44lEWpCLSFCeRZwpw0niiXPA=="],+"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],"picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],@@ -3872,6 +3904,8 @@"@macro-inc/collaboration/@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.12", "@biomejs/cli-darwin-x64": "2.4.12", "@biomejs/cli-linux-arm64": "2.4.12", "@biomejs/cli-linux-arm64-musl": "2.4.12", "@biomejs/cli-linux-x64": "2.4.12", "@biomejs/cli-linux-x64-musl": "2.4.12", "@biomejs/cli-win32-arm64": "2.4.12", "@biomejs/cli-win32-x64": "2.4.12" }, "bin": { "biome": "bin/biome" } }, "sha512-Rro7adQl3NLq/zJCIL98eElXKI8eEiBtoeu5TbXF/U3qbjuSc7Jb5rjUbeHHcquDWeSf3HnGP7XI5qGrlRk/pA=="],+ "@macro-inc/graphics/@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.12", "@biomejs/cli-darwin-x64": "2.4.12", "@biomejs/cli-linux-arm64": "2.4.12", "@biomejs/cli-linux-arm64-musl": "2.4.12", "@biomejs/cli-linux-x64": "2.4.12", "@biomejs/cli-linux-x64-musl": "2.4.12", "@biomejs/cli-win32-arm64": "2.4.12", "@biomejs/cli-win32-x64": "2.4.12" }, "bin": { "biome": "bin/biome" } }, "sha512-Rro7adQl3NLq/zJCIL98eElXKI8eEiBtoeu5TbXF/U3qbjuSc7Jb5rjUbeHHcquDWeSf3HnGP7XI5qGrlRk/pA=="],+"@macro-inc/lexical-core/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg=="],"@macro-inc/lexical-core/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="],@@ -4336,6 +4370,22 @@"@macro-inc/collaboration/@biomejs/biome/@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-yMckRzTyZ83hkk8iDFWswqSdU8tvZxspJKnYNh7JZr/zhZNOlzH13k4ecboU6MurKExCe2HUkH75pGI/O2JwGA=="],+ "@macro-inc/graphics/@biomejs/biome/@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BnMU4Pc3ciEVteVpZ0BK33MLr7X57F5w1dwDLDn+/iy/yTrA4Q/N2yftidFtsA4vrDh0FMXDpacNV/Tl3fbmng=="],++ "@macro-inc/graphics/@biomejs/biome/@biomejs/cli-darwin-x64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-x9uJ0bI1rJsWICp3VH8w/5PnAVD3A7SqzDpbrfoUQX1QyWrK5jSU4fRLo/wSgGeplCivbxBRKmt5Xq4/nWvq8A=="],++ "@macro-inc/graphics/@biomejs/biome/@biomejs/cli-linux-arm64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-tOwuCuZZtKi1jVzbk/5nXmIsziOB6yqN8c9r9QM0EJYPU6DpQWf11uBOSCfFKKM4H3d9ZoarvlgMfbcuD051Pw=="],++ "@macro-inc/graphics/@biomejs/biome/@biomejs/cli-linux-arm64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-FhfpkAAlKL6kwvcVap0Hgp4AhZmtd3YImg0kK1jd7C/aSoh4SfsB2f++yG1rU0lr8Y5MCFJrcSkmssiL9Xnnig=="],++ "@macro-inc/graphics/@biomejs/biome/@biomejs/cli-linux-x64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-8pFeAnLU9QdW9jCIslB/v82bI0lhBmz2ZAKc8pVMFPO0t0wAHsoEkrUQUbMkIorTRIjbqyNZHA3lEXavsPWYSw=="],++ "@macro-inc/graphics/@biomejs/biome/@biomejs/cli-linux-x64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-dwTIgZrGutzhkQCuvHynCkyW6hJxUuyZqKKO0YNfaS2GUoRO+tOvxXZqZB6SkWAOdfZTzwaw8IEdUnIkHKHoew=="],++ "@macro-inc/graphics/@biomejs/biome/@biomejs/cli-win32-arm64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-B0DLnx0vA9ya/3v7XyCaP+/lCpnbWbMOfUFFve+xb5OxyYvdHaS55YsSddr228Y+JAFk58agCuZTsqNiw2a6ig=="],++ "@macro-inc/graphics/@biomejs/biome/@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-yMckRzTyZ83hkk8iDFWswqSdU8tvZxspJKnYNh7JZr/zhZNOlzH13k4ecboU6MurKExCe2HUkH75pGI/O2JwGA=="],+"@macro-inc/lexical-core/@types/node/undici-types": ["[email protected]", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],"@macro-inc/machine/@biomejs/biome/@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BnMU4Pc3ciEVteVpZ0BK33MLr7X57F5w1dwDLDn+/iy/yTrA4Q/N2yftidFtsA4vrDh0FMXDpacNV/Tl3fbmng=="],diff --git a/docs/CANVAS_ARCHITECTURE.md b/docs/CANVAS_ARCHITECTURE.mdnew file mode 100644index 0000000000..137d36d953--- /dev/null+++ b/docs/CANVAS_ARCHITECTURE.md@@ -0,0 +1,44 @@+# Canvas architecture++Canvas Next is the Macro host for a reusable graphics engine. The host owns+product UI and services; `@macro-inc/graphics` owns the portable scene and editing+model.++## Layers++| Layer | Responsibility |+| --- | --- |+| Canvas Next | Toolbars, inspectors, Lexical, assets, permissions, persistence, migration, and Macro embeds |+| Graphics core | Immutable document tree, affine geometry, queries, commands, selection, and local history |+| Browser adapter | Pointer, keyboard, clipboard, drag/drop, and capture behavior |+| Solid adapter | Read-only rendering and editor overlays with stable component identity |+| Loro adapter | Optional CRDT mapping, collaborative undo, and ephemeral presence |++## State boundaries++- The document stores stable IDs, ordered containment, local transforms, typed+ shape data, appearance, and durable references.+- The editor session stores selection, active tool, gesture previews, and history.+- The view stores camera, hover, focus, and other local-only state.+- Gestures preview transient state and commit one validated command when complete.++Graphics treats rich text as opaque content and assets as stable references. It+must not depend on Macro services, Lexical, the DOM, Solid, object URLs, or theme+variables. Canvas adapters resolve those concerns at the edge.++Saved Canvas Next documents use a versioned JSON boundary. The Loro backend and+two-peer harness prove the collaboration mapping, but production SyncService+integration and conflict-policy approval remain separate work.++## Principles++- Keep one authoritative representation for structure and transforms.+- Preserve world pose when moving items through the scene tree.+- Validate commands atomically and keep derived indexes out of saved data.+- Add capabilities through typed definitions and explicit adapters.+- Keep application migration and compatibility logic outside graphics core.++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),+and [collaboration notes](../packages/graphics/src/loro/README.md).diff --git a/docs/CANVAS_LEGACY_BRIDGE.md b/docs/CANVAS_LEGACY_BRIDGE.mdnew file mode 100644index 0000000000..c498006d7c--- /dev/null+++ b/docs/CANVAS_LEGACY_BRIDGE.md@@ -0,0 +1,38 @@+# 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+`@macro-inc/graphics`, because it understands old schemas, Lexical payloads,+Macro entities, and product rollout policy.++## Contract++- Import legacy JSON through a versioned, validated boundary.+- Preserve stable IDs, effective paint order, geometry, bindings, text, media,+ and unknown source data whenever possible.+- Return explicit diagnostics for unsupported or lossy conversions.+- Never silently overwrite a legacy document that cannot round-trip safely.+- Keep the original payload available until compatibility is established.++The first supported slice should cover common shapes, groups, free connectors,+bound connectors, text, images, videos, and Macro entity references. Rich-text+details, unusual transforms, unknown node kinds, and legacy-only behaviors require+fixtures and an explicit fallback policy.++## Color policy++Saved artwork colors are durable literal values. Theme tokens belong to Canvas UI+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++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.++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).diff --git a/docs/GRAPHICS_API.md b/docs/GRAPHICS_API.mdnew file mode 100644index 0000000000..e9f1e09200--- /dev/null+++ b/docs/GRAPHICS_API.md@@ -0,0 +1,38 @@+# Graphics API++`@macro-inc/graphics` provides the reusable scene, editing, input, rendering, and+optional collaboration layers used by Canvas Next.++## Entry points++| Import | Purpose |+| --- | --- |+| `@macro-inc/graphics` | Document model, editor, commands, geometry, queries, and shape definitions |+| `@macro-inc/graphics/browser` | Browser input, clipboard, and gesture adapters |+| `@macro-inc/graphics/solid` | Solid renderers and scene projections |+| `@macro-inc/graphics/loro` | Optional collaborative document and presence backend |++The document is an immutable, normalized tree with stable IDs, sibling order,+local affine transforms, typed item data, and durable references. The editor owns+validated commits, selection, gesture state, and local history. Cameras and other+view state remain outside the document.++Create documents through the public constructors, pass commands through the+editor, and read geometry through scene queries. Browser gestures may preview+changes, but should produce one final command. Renderers consume read-only+projections and must not become a second source of truth.++## Extending graphics++New shape kinds provide typed data, runtime validation, bounds, hit testing,+resize behavior, equality, and rendering. Add browser gestures or collaboration+mapping only when the feature needs them. Keep feature registration explicit and+centrally compiled.++Host applications provide text measurement and editing, asset resolution,+navigation, permissions, storage, and service integration. Graphics stores opaque+text and stable asset/entity references; it does not import application services.++See the [package README](../packages/graphics/README.md),+[scene foundation](GRAPHICS_SCENE_FOUNDATION.md), and+[Canvas architecture](CANVAS_ARCHITECTURE.md).diff --git a/docs/GRAPHICS_PARITY.md b/docs/GRAPHICS_PARITY.mdnew file mode 100644index 0000000000..e5d5eea3a5--- /dev/null+++ b/docs/GRAPHICS_PARITY.md@@ -0,0 +1,42 @@+# 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+older JSON at the host boundary, and writes the current versioned format.++## Current coverage++| Area | Status |+| --- | --- |+| Scene and transforms | Tree structure, grouping, ordering, rotation, resize, alignment, and distribution are implemented |+| Everyday editing | Selection, marquee, move, duplicate, clipboard, nudge, undo/redo, and context actions are implemented |+| Content | Shapes, pencil, rich text and labels, connectors, images, video, Macro entity cards, and document embeds are implemented |+| Presentation | Solid rendering, overlays, fit/pan/zoom, inspectors, and shared controls are implemented |+| Persistence | Versioned JSON loading, migration, and saving are connected at the Canvas host boundary |+| Collaboration | Loro mapping and two-peer tests exist; production transport, recovery, and rollout are not complete |++## Ownership++Graphics owns reusable document structure, geometry, commands, queries, shape+contracts, and optional browser/Solid/Loro adapters. Canvas owns tools, shortcuts,+Lexical, colors and defaults, assets, Macro content, permissions, persistence,+migration, sharing, and product rollout.++## Remaining priorities++1. Finish and validate the bidirectional legacy bridge with explicit diagnostics.+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,+ and libraries as separate checkpoints.+5. Measure mixed-content scenes before adding broad indexing or culling systems.++Do not block production integration on every optional parity feature, and do not+copy the legacy or Excalidraw data model into the new transform tree. Each new+renderer must preserve shared paint order, reverse hit order, and stable mounted+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).diff --git a/docs/GRAPHICS_SCENE_FOUNDATION.md b/docs/GRAPHICS_SCENE_FOUNDATION.mdnew file mode 100644index 0000000000..b82977ad90--- /dev/null+++ b/docs/GRAPHICS_SCENE_FOUNDATION.md@@ -0,0 +1,43 @@+# Graphics scene foundation++The graphics scene is a normalized containment tree with stable IDs. A surface is+the coordinate-space root; groups establish nested coordinate spaces; drawable+items provide typed geometry and appearance.++## Structure and coordinates++- Each non-root item has one authoritative parent and sibling order.+- Every spatial item has one local affine matrix; world transforms are composed+ through ancestors.+- Position, rotation, and scale are views of that matrix, not parallel saved+ fields.+- References such as connector endpoints are graph edges, separate from+ containment.+- Derived child lists, world transforms, bounds, and indexes are never persisted.++Validation rejects missing parents, cycles, unreachable items, invalid geometry,+non-finite transforms, and illegal containment before an atomic commit. Reparent,+group, and ungroup operations preserve world pose. Deleting a container removes+its subtree as one operation.++## Queries and editing++Scene queries own traversal, paint order, coordinate conversion, bounds, and hit+testing. Selection stores IDs and normalizes to selected roots so descendants are+not transformed twice. Handles and guides render in a viewport overlay.++Typed shape definitions own validation, local bounds, hit testing, resizing, and+equality. The editor owns transactions and history; browser adapters normalize+input; Solid renderers consume read-only projections. A gesture previews temporary+overrides and commits once, while cancellation discards the preview.++## Collaboration boundary++The in-memory scene model is independent of its backend. The optional Loro adapter+maps the same logical tree to collaborative storage and uses native local undo.+Production use still requires approved conflict behavior for concurrent reparent,+delete, ordering, and pose edits.++See the [graphics README](../packages/graphics/README.md),+[Loro notes](../packages/graphics/src/loro/README.md), and+[architecture overview](CANVAS_ARCHITECTURE.md).diff --git a/package.json b/package.jsonindex f06833b524..1a8474aa61 100644--- a/package.json+++ b/package.json@@ -70,6 +70,7 @@"packages/email-renderer","packages/collaboration","packages/machine",+ "packages/graphics","packages/loro-mirror","packages/lexical-core","services/ai-editing-worker",diff --git a/packages/graphics/README.md b/packages/graphics/README.mdnew file mode 100644index 0000000000..828dfaeddb--- /dev/null+++ b/packages/graphics/README.md@@ -0,0 +1,462 @@+# Graphics++Experimental graphics editor with a framework-independent scene tree.++For a short implementation-based reference, start with the+[Graphics API guide](../../docs/GRAPHICS_API.md).++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.+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.++- `@macro-inc/graphics`: document, affine math, scene queries, selection, editing,+ validation and local history. No DOM, Solid, app or Loro imports.+- `@macro-inc/graphics/browser`: pointer capture, keyboard and wheel input.+- `@macro-inc/graphics/solid`: read-only reactive projection and keyed renderers.+- `@macro-inc/graphics/loro`: optional Loro backend and presence APIs. The+ in-memory peer transport lives in test support only.+- `@macro-inc/graphics/loro/solid`: optional awareness rendering and smoothing.++## Scene contract++Documents have one surface root and a normalized node map. Shapes+and groups have one authoritative `placement: { parentId, sortKey }` and a local+affine `transform: [a,b,c,d,e,f]`. Rectangles and ellipses own local width/height and appearance. Pencil owns raw+local `[x, y, pressure]` samples and `simulatePressure`; ink is derived.+Groups own no intrinsic geometry; their bounds come from descendants. Child lists+and paint order are derived from case-sensitive fractional string keys allocated+by [fractional-indexing](https://github.com/rocicorp/fractional-indexing).+Use `sortKeysBetween(lower, upper, count)` to create keys; null means an open end.+Keys must be unique among siblings; different parents may reuse keys. Comparison+uses code-unit ordering, never locale-sensitive sorting. Rendering and reverse+hit testing consume the same depth-first scene order.+Flat scenes are ordinary trees with shapes directly under the surface. Additional+typed kinds are text, connector, image, video and document; their feature contracts+are documented below. Shape labels are owned by rectangle, ellipse or connector+geometry.++Matrices use column vectors: x'=a*x+c*y+e, y'=b*x+d*y+f. World transforms compose+parent * local. Positive rotation is clockwise; angles are radians. Core queries+own coordinate conversion, inverse transforms, transformed corners, polygon+intersection and topmost hits. Invalid roots, cycles, missing/leaf parents,+nonfinite or noninvertible local/world transforms and invalid dimensions are rejected+before an atomic document commit.++`createScene` accepts only current typed nodes. Schema versions, legacy formats and+migrations belong to durable host boundaries such as Canvas Next.++## Editing++The editor composes the selection feature through its explicit `SelectionHost`+contract. Selection, box previews and transform overrides are session state.+Creation, move, rotation, resize, grouping, ungrouping, reparenting and subtree+deletion commit once, with bounded 100-entry local undo/redo. Navigation and+selection never enter history. Invalid operations make no partial changes.++Local history stores reversible item deltas: each entry references only the items+added, removed or replaced, plus changed root/surface metadata. Unchanged immutable+items and geometry are shared across commits; moving a pencil stroke retains its+existing samples. Undo/redo applies the whole delta atomically and restores the+original item references. No document snapshots are retained by the stacks.+Validation still checks scene-wide containment, ordering and connector invariants.+The optional backend owns its own history; Loro continues using its UndoManager.++`fitScene(viewport)` centers the full scene's world bounds and zooms in or out+until the first axis fills the current viewport with 100 screen pixels per side.+It respects camera zoom limits and reduces padding in small embedded viewports.+The host supplies its actual current dimensions; selection and current camera+offset do not influence the fit.++Group/reparent/ungroup preserve world transforms. Selected ancestors suppress+descendants as edit targets, preventing double movement/deletion. Mixed-parent+moves and pivoted rotation operate in world space, then convert back into each+parent's coordinates. `selectionFrame` is pure derived state shared by the Solid+overlay and the resize operation. One shape uses its full local-to-world frame;+a group or multiple roots always use a dashed world-axis-aligned box, regardless+of their rotation. Single shapes retain their local oriented solid outline.+Click-drag anywhere inside the selected box moves its selected roots, including+empty space and unfilled interiors. Shift and deep-select modifiers still pick+individual shapes. This does not change hit testing for unselected shapes.++Editors accept `snapUnit` in their options, with `getSnapUnit()` and+`setSnapUnit(unit)` for local configuration. Any positive finite scene-unit+interval is supported, including fractions; `undefined` disables snapping.+It is independent of camera zoom, document serialization and backend choice.+Changing the unit cancels active drawing/transform previews without adding history.+`CommandContext.snapUnit` and the pure `snapValue`, `snapPoint`, and+`snapTranslation` helpers let contributed commands use the same policy.++Rectangle/ellipse drawing and free connector endpoints snap positions. Moves,+nudges, duplicates and pasted fragments snap their common world-bounds anchor,+preserving internal spacing, pointer grab offsets and untouched axes. Resizing+snaps physical dimensions along the selection's axes, accounting for ancestor+scale. Proportional resizing snaps its controlling dimension while preserving+aspect ratio; center resizing keeps its center. Image boundaries, connector+bindings and angle/axis constraints take priority over the grid. Freehand samples,+rotation, equal distribution and exact alignment retain their own semantics.+Snapping does not round existing documents on load or remote updates.++The Solid surface's dot grid is camera-aware presentation: scene-unit intervals+1, 4, 16, 64, 256, etc. appear progressively as zoom increases. Fine dots fade in+from invisible at 4 screen pixels apart to full strength at 36; coarser dots stay+steady. At 800% individual canvas pixels are marked subtly at 12.5% opacity.+Three screen-space SVG patterns use fixed 1 px marks and crisp edges to avoid+resampling gradient tiles at fractional zoom. Each surface has unique pattern+IDs, and pattern count is independent of viewport size or dot count. All levels+share the scene origin and the caller's `gridColor`. The pure `dotGridLevels(scale)`+helper exposes those same intervals and opacities so hosts can choose a matching+snap unit. The surface itself does not change snap policy or document data.++Hold Shift during rotation to snap a single shape/group's world angle to 30° increments.+Hold Shift during movement to constrain the world-space delta to its dominant+horizontal or vertical axis, including nested selections and Option-drag duplicates.+Rectangle/ellipse drawing accepts `DrawingModifiers.proportional` to create a square+or circle; the browser maps Shift to it. The original pointer endpoint is retained,+so pressing/releasing Shift updates the preview immediately. Image-surface drawing+reduces both dimensions together when a constrained shape reaches the image edge.+Shift-click still toggles selection on release; crossing 3 screen pixels begins+a move instead. Shift-drag on empty canvas remains additive marquee selection.+Multiple selections snap the rotation delta while preserving relative angles.+The rotation circle sits 16 screen pixels outside a single shape's oriented top+edge, or above the world-aligned bounds for groups and multiple selections, with+no connecting stem. Single-shape resize adjusts local dimensions and placement while+keeping the opposite corner or edge midpoint fixed. Hold Shift to preserve the+original aspect ratio. Hold Alt/Option to resize from the original center;+Shift+Alt/Option combines both. Modifiers update even without pointer movement.++Invisible targets along each full edge also resize single shapes, multiple selections and groups.+Selected rectangles also have inset circular radius controls. `radius-nw/ne/se/sw`+gestures adjust the existing uniform `appearance.cornerRadius` in local shape units,+in whole-pixel steps independent of scene snapping, with a half-short-side clamp,+ephemeral preview, cancellation, and one+history commit. Geometry and pose stay unchanged. The controls follow affine parent+transforms while their visual size stays fixed on screen.+During a radius drag, the active handle shows the whole-pixel value as white text+on the filled selection-color badge.+Each target spans 10 screen pixels across the edge at any zoom. Visible corner+handles take priority where they overlap the edge targets.+Handles stay square to the screen. Top/bottom edges use `ns-resize`; side edges use+`ew-resize`. Corners use `nwse-resize` or `nesw-resize` according to their world-space+quadrant relative to the selection center, including rotated or flipped shapes.+The chosen cursor stays visible during the drag preview.+Active gestures follow their pointer at the window level until release, even if+pointer capture is lost or the pointer leaves the canvas. Escape, pointer cancellation,+focus loss and disposal still discard previews; capture loss alone does not.+Left/right changes width; top/bottom changes height. Single-shape handles follow+the selection frame's axes. Perpendicular pointer motion is+ignored. Alt/Option anchors the center. Shift preserves proportions and centers+changes on the perpendicular axis, including when shrinking.++Shared corner and edge drags can stretch axes independently only when every+selected node and descendant has axes parallel to the frame (quarter turns are+compatible). Otherwise the entire gesture scales proportionally, keeping the+opposite anchor fixed and the content fitted to the box without adding shear.+Existing affine shear is preserved; shared resizing of such selections is uniform.++Nonuniform shared resizing uses `stretchShapes` to move leaf centers and resize+geometry, retaining group frames and placements. Crossing the opposite edge+reflects the leaf axes as well as their positions, so the contents truly flip.+Uniform resizing transforms selected roots once. Stroke width/radius stay local+dimensions during geometry resizing and scale with uniform root transforms.+Shapes opting into `regenerateOnScale` (pencil) instead absorb the added scale+into samples and compensate in their local pose, preserving nominal brush width.+Single and shared resizing continue through zero and invert each crossed axis.+Only a tiny minimum magnitude (1e-6 of the starting extent) keeps transforms+invertible at the exact crossing. Shift proportions and Alt/Option center anchors+apply on both sides of zero. Every gesture previews, cancels and commits once.++Grouping initially requires a common parent. Noncontiguous siblings become one+contiguous group at their earliest selected sibling position, which can change+stacking relative to unselected siblings. Ungroup splices children back in order.+Reparent takes a position: `'front'` (default), `'back'`, `{ before: siblingId }`+or `{ after: siblingId }`. It allocates a new key for the moved node. Grouping+retains child keys and places the group at the backmost selected key. Ungrouping+allocates new keys only for children released into the parent's order.++`reorderNodes(document, ids, 'front' | 'back' | 'forward' | 'backward')` and+`editor.reorderSelection(operation)` preserve selected nodes' relative order and+operate independently within each parent. Forward/backward move selected runs+past one unselected sibling; front/back move them to the ends. Only moved nodes+receive new keys; other siblings are never renumbered. Each command is one undo+step, with no history entry for a no-op. Groups remain contiguous subtrees.++These keys support stable local edits and serialization, not concurrent allocation+on their own. Duplicate sibling keys are rejected at the document boundary.+Concurrent inserts can generate the same key; the Loro adapter must resolve or+replace this allocation with ordered-tree positions before shared documents are+enabled. An isolated Loro experiment now exercises these cases; its mapping and conflict+policy are documented separately below.++Solid renders drawable IDs in tree paint order with computed world matrices.+Grouping/reparenting/reordering preserves keyed component identity. The surface+isolates its content stack from the app, each item wrapper isolates its renderer,+and editor overlays live above content. Renderers may layer their internal+children, but must keep document content inside their item wrapper; portals are+reserved for explicitly coordinated editor UI. Selection polygons,+a solid oriented box for a single shape, a dashed axis-aligned box for groups and+multiple selections, corner handles, invisible edge targets and rotation handles are drawn in a viewport overlay, so their+size is independent of ancestor scale/rotation. The shared box and handles hide+during transform previews; individual outlines remain visible. Selected shapes (including+selected groups' leaves) also get a one-screen-pixel selection-color trace along their+geometry: the pencil's streamlined centerline, rounded rectangle perimeter, or ellipse.+In groups or multiple selections, rounded rectangles and ellipses show only that+geometry trace inside the shared selection box, without individual rectangular boxes.+These non-interactive SVG traces use non-scaling strokes in the viewport overlay.+The Select tool previews the same trace on hover, using the exact pointer-down+target policy (3 screen px tolerance, click-through, group/deep selection, and+selected box interiors). Hover stays local to the browser/Solid adapter, repicks+after camera/document/modifier changes, and hides while dragging, panning or drawing.+It never enters core session state, history, persistence or collaboration awareness.+The scene tree does not require+a matching DOM tree.++## Boundaries and verification++One surface per document, a centrally compiled typed shape registry, linear scene+queries are deliberate prototype limits. Text,+connectors and embedded item contracts are implemented. Frames/clipping, layout,+multi-surface documents, per-host core registries and runtime plugin loading are not.+Affine reflection/shear compose correctly, but have no dedicated UI controls.+SyncService integration remains separate work. The two-peer Loro experiment uses+native local undo; never apply local item-delta undo to a shared document.++The [scene foundation specification](../../docs/GRAPHICS_SCENE_FOUNDATION.md)+describes the intended longer-term boundary and collaboration questions.+Run `bun run test` and `bun run type-check` here. Tests cover tree invariants,+transform math, document reset, pose preservation, nested editing, history, selection,+input routing and stable Solid mounts. The no-DOM compilation/import checks+enforce the pure TypeScript core boundary.++## Pencil++`shapes/pencil.ts` wraps `perfect-freehand` with private brush settings. Documents+store the raw local centerline and normalized pressure values, not SVG paths,+brush presets, timestamps, or generated bounds. Mouse strokes use spacing-based+pressure simulation; pen strokes retain hardware pressure. Resize scales samples+and regenerates the ink, including simulated pressure, without changing nominal+stroke width. Reflections and nested placement remain scene transforms.++Rendering, hit testing and selection bounds share the generated ink polygon.+The selected pencil's centerline highlight comes from the same brush calculation;+it does not trace the raw samples or the outer ink polygon.+Click tolerance is measured in world space after ancestor transforms; marquee+uses polygon/box intersection, so empty loops and unused bounds do not hit.+Immutable core geometries cache derived ink. The Solid projection exposes both+a reconciled store for fine-grained UI reads and a reactive immutable snapshot+for rendering and geometry queries. Pan, hover, selection, move and rotation+previews reuse cached ink; geometry or stroke-width changes regenerate it.+The keyed renderer emits one filled SVG path. Fill/radius have no pencil+meaning; stroke color, width and opacity control its ink.++Browser coalesced pointer samples are processed as a batch. Preview and commit+use the same brush endpoint policy to avoid a release-time change in shape.+One stroke creates one history entry; cancellation creates none. A tap creates+a dot. Samples are deeply frozen and limited to 16,384 per stroke; further samples+are ignored at this prototype limit. Point editing, erasing, straight segments,+compact point encoding and spatial indexing remain later work.++## Adding a shape++Shape registration is explicit and compile-time. There is no mutable global+registry or runtime plugin loading. Rectangle, ellipse and pencil follow the same path:++1. Add a pure module under `src/core/shapes/` exporting its geometry type and+ `ShapeDefinition<'kind'>`. Add the geometry type to `ShapeGeometryMap` in+ `model.ts`, then add the definition to the mapped registry in+ `shapes/registry.ts`. TypeScript checks the kind/definition pairing.+2. Implement geometry validation, deep freezing, local bounds, point hit testing,+ box intersection, resize and geometry equality. Bounds may have a nonzero local+ origin (pencil ink extends around its samples). `resize` scales geometry about+ the local origin without changing identity/placement/transform; the selection+ feature applies translation and reflection. A brush may regenerate its outline+ rather than making painted bounds fit the target box exactly. Opt into+ `regenerateOnScale` when uniform group scaling must also rebuild geometry.+3. Point picking receives a **local point**, the complete **world transform**,+ and a tolerance in **world units** (`3 / camera.scale`). Measure outline+ distance in world space to preserve screen tolerance through nested affine+ transforms. Marquee intersection uses the actual shape, regardless of fill.+4. Add a Solid component under `src/solid/shapes/` with+ `ShapeViewProps<'kind'>`, and register it in `defaultRenderers` in+ `solid/shape-renderers.tsx`. It receives a reactive item, effective scale and+ optional preview state. Hosts can supply typed overrides via `renderers`;+ image markup retains its rectangle renderer. The core never imports these.+ Register the geometry-only selection indicator in the typed `outlines` map in+ `solid/selection-outline.tsx`; it must use `non-scaling-stroke` and local geometry.+5. Add a typed acquisition gesture to `core/drawing.ts`, separate from the shape+ definition. Boxes collect two corners; pencil collects samples. Browser input+ calls `beginShape`, batched `updateDrawing`, `commitShape`, `cancelShape`;+ `getDrawingPreview(appearance)` produces the typed temporary shape.+ Rectangle aliases remain for the image host. Selection and rendering consume+ definitions and typed previews without shape-specific gesture branches.+6. Cover curve/interior picking, zoom tolerance, box intersection, invalid geometry,+ transforms and history, and verify the actual component and controls in-browser.++Ellipse performs analytic curve picking after transforming to principal axes;+marquee queries transform the box into ellipse-normalized coordinates. Neither+uses the ellipse's bounding rectangle as its hit area. Selection handles still+use the local bounding rectangle, as they do for other bounded shapes.++This checkpoint proves typed shape modules, not a general-purpose extension API:+text and connector gestures now have explicit feature contracts; layout, per-host+core registry composition and dynamic plugins remain future work. Schema versioning and+import/export boundaries can be introduced when real persistence is needed.++## Typed commands and everyday editing++`GraphicsCommand<Payload>` is a pure contribution with `id` and+`apply({ document, selection }, payload)`. Return a proposed document and optional+selection. `editor.execute(command, payload)` validates the proposal and makes one+history step; returning the original document is a no-op. The command receives no+Solid, browser, persistence or collaboration objects. Inject ID factories in the+payload for operations that allocate nodes.++Built-ins: `selectAllCommand`, `nudgeCommand`, `duplicateCommand`, `pasteCommand`,+`styleCommand`, `alignCommand`, and `distributeCommand`. `copyFragment` extracts+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).++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;+`resolveAppearance` supplies defaults. Width/radius use local units and scale with+the node transform. The Loro adapter writes each style field independently so local+undo of one property preserves a peer's edit to another.++The Solid renderer calculates one world-space offset for ordinary move previews+and applies CSS translation only to moving wrappers and outlines. Selected shapes+(including group descendants) retain their keyed mounts, geometry, and flat paint+order. Content and unselected shapes do not receive pointer updates. Connectors+retain their live geometry path so bindings track moving ends.+Resize/rotation and committed document changes use the regular projection. Shape+renderer `item` props are live views: read their fields in reactive scopes, as with+Solid props, rather than relying on the outer object's identity changing. Nested+geometry and appearance retain their immutable identities for core caches.++`beginTransform` optionally takes an ID factory to preview subtree duplication.+Its session-only preview document includes new nodes; the durable document remains+unchanged until a moved gesture commits. Cancellation discards the preview and+restores the previous selection. Solid keeps original keyed mounts intact.++## Loro adapter++The in-memory peer harness gives tests two real Loro replicas with independent+selection, camera and local undo. See [the adapter notes](src/loro/README.md) for+its ordered tree mapping, geometry conflict policy, limitations and validation cases.++The optional `@macro-inc/graphics/loro/solid` wrapper adds colored peer cursors,+selection outlines and ghosts of pending drawing/move/resize/rotation gestures.+Awareness uses a separate ephemeral channel: it never enters the document, local+selection, hit testing or undo. Disconnect clears remote overlays; reconnect sends+fresh presence. The core and ordinary browser/Solid surfaces do not depend on it.++### Rich text++`text` is an explicit shape kind. `TextGeometry.content` is a host-defined opaque+string; geometry also stores measured width/height, typography and auto-width.+Core checks only that content is a string of at most 2,000,000 UTF-16 code units+and preserves it verbatim, including empty strings. The host owns format validation+and decides whether a completed edit sets content, deletes a text item or clears a+label. `setTextCommand` stores content as one history entry; `setShapeLabelCommand`+clears a label only when the host omits it. Existing transforms, picking, ordering+and clipboard work unchanged.++Pass `{measureText}` to the editor for actual font metrics. The default browser+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+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,+display and measurement, and owns the matching markup styles. Only the active item+mounts an editable editor. The optional Loro adapter continues storing the whole+string without parsing it; no content migration is needed.++The shared host supports mentions in both text and labels. Mention decorators+scale with typography; active editing keeps the native caret without an extra+box outline. Backend mention tracking/notifications remain disabled in Canvas Next.++Single-text side edges change wrapping width; other grips scale font and box+proportionally. Completed content is one LWW string in the optional Loro adapter,+independent of pose. This is the chosen collaboration granularity, not a character+CRDT. GraphicsSurface accepts overlays, hidden selection and suspended input so+host editing stays separate from geometric tools.++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.++Rectangles, ellipses and connectors accept `geometry.label?: ShapeLabel`, containing+portable rich content, font family/size, and measured height. Box label width is+derived from the padded shape interior. Connector labels store a measured width+and sit at the route midpoint. `setShapeLabelCommand` edits/clears only the label.+`shapeLabelLayout` supplies a shared local transform for rendering, editing, and+picking. Box labels wrap and fit uniformly inside their owner. Shape resizing uses+the injected measurer to update label height; headless hosts without one retain the+stored height and should remeasure before displaying changed wrapping. Labels are+part of shape geometry in the core; fragments preserve their serialized strings.+The Loro adapter stores label content and layout separately from pose, allowing+label creation or editing to merge with moving its owner.+`textTargetAt` is a text-gesture query that includes unfilled shape interiors;+ordinary shape picking adds only the label's visible layout box.++## Connectors and references++`ShapeItem<'connector'>` stores two local endpoints, route (`straight`, `stepped`,+`smooth`), and start/end heads (`none`, `arrow`, `arrow-filled`, `circle`,+`circle-small`). Each endpoint has a fallback `point`, optional outgoing `direction`,+and an optional `{ targetId, anchor }` reference. Anchors are `center`, `top`,+`right`, `bottom`, `left`. References are independent of scene containment;+connectors remain ordinary keyed shape components in document paint order.++`core/connectors.ts` resolves references through the target's current world matrix+and geometry, including uncommitted transform overrides. Side ports stay at edge+midpoints. A center port automatically intersects the target outline toward the+other endpoint (exact ellipse and rounded rectangle outlines; bounds for other+shapes). Groups are not attachment targets; their eligible shape children are.+Connectors cannot target pencil strokes, other connectors or themselves. Missing+or ineligible targets use stored fallback coordinates, so older pencil bindings+still load without following the ink. No route cache or Solid state is persisted+in geometry.++`connector-routing.ts` ports the original Canvas route math: straight segments,+36-unit rectilinear leads with rounded 10-unit corners, cubic smooth curves and the+same arrow/dot styles. Rotated target normals preserve an outward lead. Picking+follows the sampled rendered path and head geometry, with screen tolerance supplied+by the host. It does not select the empty path bounding box.++`createConnectorInteraction` owns a disposable draft and preview scene. The browser+endpoint adapter captures the gesture; `GraphicsSurface.attachControls` owns that+adapter's viewport lifecycle. The app owns tools, defaults, inspector and hover-only+screen-sized endpoint circles. `connectorTargetAt` is the shared hover/start/drop+policy: only the frontmost hovered shape exposes ports; nearby edge points win,+and the interior core activates the center. Only the active port gets a larger+blue halo. Releasing submits `setConnectorCommand` as one history+entry. Escape cancels; Shift snaps free endpoints to 45 degrees. Both endpoints can+be reattached independently. Moving a connector body moves free endpoints while+bound endpoints remain on their targets, matching legacy Canvas.++Copy/paste and duplicate remap references when the targets are copied too. External+references detach at their current visible endpoints. Deleting a target detaches+surviving connectors in the same history transaction; undo restores the references.+Reparenting keeps world positions through the existing tree math. The existing Loro+adapter transports connector geometry and references without core dependencies on+collaboration. Connector labels share the existing label/text path and Loro mapping.+Endpoint drafts are local only; connector-specific remote gesture awareness remains+follow-up work.++### Embedded items++`image` and `video` store box dimensions, a name, and a stable `MediaSource`+(document ID, static-file ID, or safe HTTP(S)/root-relative URL). `document` stores+box dimensions, document ID, file type and a fallback name. Definitions participate+in the same transform, selection, connector, clipboard, grouping and Loro paths as+other shapes. `insertShapesCommand` inserts an ordered batch in one undo step.+Default Solid renderers show placeholders; hosts provide asset and preview views.+No upload, storage-service, player or application preview dependency enters core.diff --git a/packages/graphics/biome.jsonc b/packages/graphics/biome.jsoncnew file mode 100644index 0000000000..89452894fd--- /dev/null+++ b/packages/graphics/biome.jsonc@@ -0,0 +1,9 @@+{+ "$schema": "https://biomejs.dev/schemas/2.4.12/schema.json",+ "root": true,+ "extends": ["../../biome.base.jsonc"],+ "vcs": { "root": "../.." },+ "files": {+ "includes": ["**/*.{ts,tsx,js,jsx,json}", "!**/*.d.ts", "!**/node_modules"]+ }+}diff --git a/packages/graphics/package.json b/packages/graphics/package.jsonnew file mode 100644index 0000000000..dde15f1fa8--- /dev/null+++ b/packages/graphics/package.json@@ -0,0 +1,40 @@+{+ "name": "@macro-inc/graphics",+ "version": "0.1.0",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/core/index.ts",+ "./browser": "./src/browser/index.ts",+ "./solid": "./src/solid/index.tsx",+ "./loro": "./src/loro/index.ts",+ "./loro/solid": "./src/loro/solid/index.tsx"+ },+ "scripts": {+ "test": "vitest run",+ "type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.core.json",+ "lint": "biome check ."+ },+ "peerDependencies": {+ "solid-js": "^1.9.7"+ },+ "peerDependenciesMeta": {+ "solid-js": {+ "optional": true+ }+ },+ "devDependencies": {+ "@biomejs/biome": "2.4.12",+ "@types/node": "^24.8.0",+ "jsdom": "^26.1.0",+ "solid-js": "^1.9.7",+ "typescript": "^5.9.3",+ "vite-plugin-solid": "^2.11.8",+ "vitest": "5.0.1"+ },+ "dependencies": {+ "fractional-indexing": "4.0.0",+ "loro-crdt": "catalog:",+ "perfect-freehand": "1.2.3"+ }+}diff --git a/packages/graphics/src/browser/connectors.ts b/packages/graphics/src/browser/connectors.tsnew file mode 100644index 0000000000..9f9a423bbb--- /dev/null+++ b/packages/graphics/src/browser/connectors.ts@@ -0,0 +1,172 @@+import { screenToWorld } from '../core/camera';+import type { ConnectorStyle } from '../core/connector-commands';+import type { createConnectorInteraction } from '../core/connector-interaction';+import type { GraphicsEditor } from '../core/editor';+import type { Appearance } from '../core/model';++/** Endpoint capture is independent of shape drawing and document history. */+export function attachConnectorControls(+ element: HTMLElement,+ editor: GraphicsEditor,+ options: {+ interaction: ReturnType<typeof createConnectorInteraction>;+ active(): boolean;+ appearance(): Appearance;+ style(): ConnectorStyle;+ onCommit(): void;+ createId?: () => string;+ }+) {+ const op = options.interaction;+ let pointer: number | undefined,+ space = false;+ let last: { clientX: number; clientY: number; shiftKey: boolean } | undefined;+ const worldPoint = (event: { clientX: number; clientY: number }) => {+ const rect = element.getBoundingClientRect();+ return screenToWorld(editor.getCamera(), {+ x: event.clientX - rect.left,+ y: event.clientY - rect.top,+ });+ };+ const update = () => {+ if (last)+ op.update(worldPoint(last), 14 / editor.getCamera().scale, last.shiftKey);+ };+ const cleanupPointer = () => {+ if (pointer !== undefined && element.hasPointerCapture(pointer))+ element.releasePointerCapture(pointer);+ pointer = undefined;+ last = undefined;+ window.removeEventListener('pointermove', move, true);+ window.removeEventListener('pointerup', up, true);+ window.removeEventListener('pointercancel', cancel, true);+ };+ const cancel = () => {+ cleanupPointer();+ op.cancel();+ };+ const move = (event: PointerEvent) => {+ if (event.pointerId !== pointer) return;+ last = {+ clientX: event.clientX,+ clientY: event.clientY,+ shiftKey: event.shiftKey,+ };+ update();+ event.preventDefault();+ };+ const hover = (event: PointerEvent) => {+ if (pointer !== undefined) return;+ if (options.active() && !space && !event.buttons)+ op.hover(worldPoint(event), 14 / editor.getCamera().scale);+ else op.clearHover();+ };+ const leave = () => op.clearHover();+ const up = (event: PointerEvent) => {+ if (event.pointerId !== pointer) return;+ last = {+ clientX: event.clientX,+ clientY: event.clientY,+ shiftKey: event.shiftKey,+ };+ update();+ cleanupPointer();+ if (op.commit(3 / editor.getCamera().scale)) options.onCommit();+ else if (options.active() && !space)+ op.hover(worldPoint(event), 14 / editor.getCamera().scale);+ event.preventDefault();+ event.stopPropagation();+ };+ const down = (event: PointerEvent) => {+ if (+ event.button !== 0 ||+ space ||+ !(event.target instanceof Element) ||+ event.target.closest('[contenteditable],input,textarea')+ )+ return;+ const handle = event.target.closest('[data-graphics-connector-end]');+ if (!options.active() && !handle) return;+ const id = handle?.getAttribute('data-graphics-connector-id'),+ end = handle?.getAttribute('data-graphics-connector-end');+ editor.cancelShape();+ editor.cancelTransform();+ if (id && (end === 'start' || end === 'end')) {+ editor.select(id);+ if (!op.edit(id, end)) return;+ op.hover(worldPoint(event), 14 / editor.getCamera().scale);+ } else {+ editor.select();+ op.begin(+ (options.createId ?? (() => crypto.randomUUID()))(),+ worldPoint(event),+ options.appearance(),+ options.style(),+ 14 / editor.getCamera().scale+ );+ }+ pointer = event.pointerId;+ last = {+ clientX: event.clientX,+ clientY: event.clientY,+ shiftKey: event.shiftKey,+ };+ element.focus({ preventScroll: true });+ element.setPointerCapture(pointer);+ window.addEventListener('pointermove', move, true);+ window.addEventListener('pointerup', up, true);+ window.addEventListener('pointercancel', cancel, true);+ event.preventDefault();+ event.stopPropagation();+ };+ const keyDown = (event: KeyboardEvent) => {+ if (+ event.target instanceof Element &&+ event.target.closest('[contenteditable],input,textarea')+ )+ return;+ if (event.code === 'Space') {+ space = true;+ op.clearHover();+ }+ if (event.key === 'Escape' && pointer !== undefined) {+ cancel();+ event.preventDefault();+ event.stopPropagation();+ }+ if (event.key === 'Shift' && last) {+ last = { ...last, shiftKey: true };+ update();+ }+ };+ const keyUp = (event: KeyboardEvent) => {+ if (event.code === 'Space') space = false;+ if (event.key === 'Shift' && last) {+ last = { ...last, shiftKey: false };+ update();+ }+ };+ const blur = () => {+ space = false;+ cancel();+ };+ element.addEventListener('pointerdown', down, true);+ element.addEventListener('pointermove', hover);+ element.addEventListener('pointerleave', leave);+ element.addEventListener('keydown', keyDown, true);+ window.addEventListener('keyup', keyUp);+ window.addEventListener('blur', blur);+ const unsubscribe = editor.subscribeDocument(cancel),+ camera = editor.subscribeCamera(cancel);+ return () => {+ cancel();+ unsubscribe();+ camera();+ element.removeEventListener('pointerdown', down, true);+ element.removeEventListener('pointermove', hover);+ element.removeEventListener('pointerleave', leave);+ element.removeEventListener('keydown', keyDown, true);+ window.removeEventListener('keyup', keyUp);+ window.removeEventListener('blur', blur);+ };+}diff --git a/packages/graphics/src/browser/index.ts b/packages/graphics/src/browser/index.tsnew file mode 100644index 0000000000..437bacca2b--- /dev/null+++ b/packages/graphics/src/browser/index.ts@@ -0,0 +1,472 @@+import { screenToWorld } from '../core/camera';+import type { DrawingKind } from '../core/drawing';+import type { GraphicsEditor } from '../core/editor';+import type { Appearance, Point } from '../core/model';+import { isRadiusHandle } from '../core/radius';+import {+ isResizeHandle,+ type ResizeHandle,+ resizeHandles,+} from '../core/resize';+import {+ type SelectionFrame,+ selectionContainsPoint,+ selectionFrame,+} from '../core/selection-frame';+import { isShapeKind } from '../core/shapes/registry';+import { selectionTarget } from './selection-target';++const WHEEL_ZOOM_RATE = 0.002;+const MAX_WHEEL_ZOOM_EXPONENT = 0.2;++export function resizeCursor(handle: ResizeHandle, frame?: SelectionFrame) {+ if (handle === 'n' || handle === 's') return 'ns-resize';+ if (handle === 'e' || handle === 'w') return 'ew-resize';+ const corner = frame?.corners[resizeHandles.indexOf(handle)];+ // Local corner names survive rotation and reflection; use their world quadrant.+ const descending =+ frame && corner+ ? (corner.x - frame.center.x) * (corner.y - frame.center.y) >= 0+ : handle === 'nw' || handle === 'se';+ return descending ? 'nwse-resize' : 'nesw-resize';+}++export type GraphicsHover = Readonly<{+ point: Point;+ deep: boolean;+ additive: boolean;+ handle: boolean;+}>;+export type GraphicsInputOptions = {+ tool?: () => 'pan' | DrawingKind | 'select';+ editing?: boolean;+ suspended?: () => boolean;+ /** Host-owned controls may keep their pointer events without starting a gesture. */+ ignoreTarget?: (target: EventTarget | null) => boolean;+ duplicateOnAltDrag?: boolean;+ onShapeCreated?: (id: string) => void;+ navigation?: 'free' | 'centered-image';+ createId?: () => string;+ appearance?: () => Appearance;+ /** Local viewport position and picking modifiers; never document/awareness state. */+ onHover?: (hover: GraphicsHover | undefined) => void;+};++/** Attach camera controls to a focusable viewport. No document-global keyboard shortcuts. */+export function attachCameraControls(+ element: HTMLElement,+ editor: GraphicsEditor,+ options: GraphicsInputOptions = {}+): () => void {+ let space = false;+ let drag:+ | {+ id: number;+ x: number;+ y: number;+ mode: 'pan' | 'shape' | 'transform' | 'box' | 'select';+ cursor?: string;+ }+ | undefined;+ let pendingSelection:+ | {+ id: string;+ point: Point;+ toggle: boolean;+ duplicate?: () => string;+ }+ | undefined;+ const originalCursor = element.style.cursor;+ let hoverPointer: PointerEvent | undefined;+ const clearHover = () => {+ hoverPointer = undefined;+ options.onHover?.(undefined);+ };+ const updateHover = (+ modifiers: Pick<PointerEvent, 'altKey' | 'metaKey' | 'ctrlKey' | 'shiftKey'>+ ) => {+ const event = hoverPointer;+ if (+ !event ||+ drag ||+ space ||+ event.buttons ||+ event.pointerType === 'touch'+ ) {+ options.onHover?.(undefined);+ return;+ }+ const rect = element.getBoundingClientRect();+ options.onHover?.({+ point: { x: event.clientX - rect.left, y: event.clientY - rect.top },+ deep: options.duplicateOnAltDrag+ ? modifiers.metaKey || modifiers.ctrlKey+ : modifiers.altKey,+ additive: modifiers.shiftKey,+ handle:+ event.target instanceof Element &&+ !!event.target.closest('[data-graphics-handle]'),+ });+ };+ const pointerHover = (event: PointerEvent) => {+ hoverPointer = event;+ updateHover(event);+ };++ const updateCursor = () => {+ element.style.cursor =+ drag?.mode === 'pan'+ ? 'grabbing'+ : drag?.mode === 'transform'+ ? (drag.cursor ?? 'move')+ : space || options.tool?.() === 'pan'+ ? 'grab'+ : isShapeKind(options.tool?.())+ ? 'crosshair'+ : originalCursor;+ };+ const cancel = () => {+ clearHover();+ const id = drag?.id;+ drag = undefined;+ pendingSelection = undefined;+ window.removeEventListener('pointermove', pointerMove, true);+ window.removeEventListener('pointerup', pointerUp, true);+ window.removeEventListener('pointercancel', pointerEnd, true);+ editor.cancelShape();+ editor.cancelTransform();+ space = false;+ if (id !== undefined && element.hasPointerCapture(id))+ element.releasePointerCapture(id);+ updateCursor();+ };+ const worldPoint = (event: Pick<PointerEvent, 'clientX' | 'clientY'>) => {+ const rect = element.getBoundingClientRect();+ return screenToWorld(editor.getCamera(), {+ x: event.clientX - rect.left,+ y: event.clientY - rect.top,+ });+ };+ const sample = (event: PointerEvent) => ({+ ...worldPoint(event),+ ...(event.pointerType === 'pen' && Number.isFinite(event.pressure)+ ? { pressure: event.pressure }+ : {}),+ });+ const updateDrawing = (event: PointerEvent) => {+ const coalesced = event.getCoalescedEvents?.() ?? [];+ editor.updateDrawing((coalesced.length ? coalesced : [event]).map(sample), {+ proportional: event.shiftKey,+ });+ };+ const transformModifiers = (+ event: Pick<PointerEvent, 'shiftKey' | 'altKey'>+ ) => ({+ proportional: event.shiftKey,+ fromCenter: event.altKey,+ snapRotation: event.shiftKey,+ constrainAxis: event.shiftKey,+ });+ const updateModifierPreview = (event: KeyboardEvent) => {+ if (!drag || (event.key !== 'Shift' && event.key !== 'Alt')) return;+ if (drag.mode === 'transform') {+ event.preventDefault();+ editor.updateTransform(+ worldPoint({ clientX: drag.x, clientY: drag.y }),+ transformModifiers(event)+ );+ } else if (+ drag.mode === 'shape' &&+ editor.getDrawingKind() !== 'pencil' &&+ event.key === 'Shift'+ ) {+ event.preventDefault();+ editor.updateDrawing([], { proportional: event.shiftKey });+ }+ };+ const pointerDown = (event: PointerEvent) => {+ if (+ options.suspended?.() ||+ options.ignoreTarget?.(event.target) ||+ (event.target instanceof Element &&+ event.target.closest('[contenteditable="true"]'))+ )+ return;+ if (+ event.target !== element &&+ !(+ event.target instanceof Element &&+ event.target.closest(+ '[data-graphics-item], [data-graphics-handle], [data-graphics-selection-bounds]'+ )+ )+ )+ return;+ element.focus({ preventScroll: true });+ clearHover();+ if (drag) return;+ const pan =+ options.navigation !== 'centered-image' &&+ (event.button === 1 ||+ (event.button === 0 && (space || options.tool?.() === 'pan')));+ const tool = options.tool?.();+ const drawing = event.button === 0 && !pan && isShapeKind(tool);+ const selecting =+ event.button === 0 && !pan && options.tool?.() === 'select';+ let transforming = false;+ let boxing = false;+ let cursor: string | undefined;+ if (selecting) {+ const target = event.target instanceof Element ? event.target : undefined;+ const handle = target+ ?.closest('[data-graphics-handle]')+ ?.getAttribute('data-graphics-handle');+ const transformHandle =+ isResizeHandle(handle) || isRadiusHandle(handle) || handle === 'rotate'+ ? handle+ : undefined;+ const point = worldPoint(event);+ const deep = options.duplicateOnAltDrag+ ? event.metaKey || event.ctrlKey+ : event.altKey;+ const frame = selectionFrame(+ editor.document,+ editor.getSession().selectedIds+ );+ const id = selectionTarget(+ editor.document,+ editor.getSession().selectedIds,+ point,+ {+ deep,+ additive: event.shiftKey,+ handle: !!transformHandle,+ tolerance: 3 / editor.getCamera().scale,+ }+ );+ cursor =+ transformHandle === 'rotate' || isRadiusHandle(transformHandle)+ ? 'grabbing'+ : transformHandle+ ? resizeCursor(transformHandle, frame)+ : 'move';+ const shiftTarget =+ id ??+ (!deep && frame && selectionContainsPoint(frame, point)+ ? editor.getSession().selectedIds[0]+ : undefined);+ if (shiftTarget && event.shiftKey && !transformHandle) {+ // Defer Shift-click toggling until release so Shift-drag can move instead.+ pendingSelection = {+ id: shiftTarget,+ point,+ toggle: !!id,+ duplicate:+ options.duplicateOnAltDrag && event.altKey+ ? (options.createId ?? (() => crypto.randomUUID()))+ : undefined,+ };+ } else if (id)+ transforming = editor.beginTransform(+ id,+ worldPoint(event),+ transformHandle,+ options.duplicateOnAltDrag && event.altKey && !transformHandle+ ? (options.createId ?? (() => crypto.randomUUID()))+ : undefined+ );+ else boxing = editor.beginBoxSelection(worldPoint(event), event.shiftKey);+ }+ if (!pan && !drawing && !transforming && !boxing && !pendingSelection)+ return;+ if (drawing && isShapeKind(tool) && !editor.beginShape(tool, sample(event)))+ return;+ event.preventDefault();+ element.setPointerCapture(event.pointerId);+ drag = {+ id: event.pointerId,+ x: event.clientX,+ y: event.clientY,+ mode: pan+ ? 'pan'+ : pendingSelection+ ? 'select'+ : transforming+ ? 'transform'+ : boxing+ ? 'box'+ : 'shape',+ cursor,+ };+ // Capture can be lost before pointerup. Keep ownership of this pointer until+ // release or an actual cancellation, even over another widget or viewport.+ window.addEventListener('pointermove', pointerMove, true);+ window.addEventListener('pointerup', pointerUp, true);+ window.addEventListener('pointercancel', pointerEnd, true);+ updateCursor();+ };+ const pointerMove = (event: PointerEvent) => {+ if (!drag || drag.id !== event.pointerId) return;+ if (drag.mode === 'select') {+ const pending = pendingSelection;+ if (+ !pending ||+ Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 3+ )+ return;+ if (!editor.getSession().selectedIds.includes(pending.id))+ editor.toggleSelection(pending.id);+ if (+ !editor.beginTransform(+ pending.id,+ pending.point,+ undefined,+ pending.duplicate+ )+ ) {+ cancel();+ return;+ }+ pendingSelection = undefined;+ drag = { ...drag, mode: 'transform' };+ updateCursor();+ }+ if (drag.mode === 'shape') updateDrawing(event);+ else if (drag.mode === 'box') editor.updateBoxSelection(worldPoint(event));+ else if (drag.mode === 'transform')+ editor.updateTransform(worldPoint(event), transformModifiers(event));+ else editor.panBy({ x: event.clientX - drag.x, y: event.clientY - drag.y });+ drag = { ...drag, x: event.clientX, y: event.clientY };+ };+ const pointerEnd = (event: PointerEvent) => {+ if (drag?.id === event.pointerId) cancel();+ };+ const pointerUp = (event: PointerEvent) => {+ if (drag?.id !== event.pointerId) return;+ if (drag.mode === 'select') pointerMove(event);+ if (!drag) return;+ if (drag.mode === 'select' && pendingSelection?.toggle)+ editor.toggleSelection(pendingSelection.id);+ if (drag.mode === 'box') {+ editor.updateBoxSelection(worldPoint(event));+ editor.commitBoxSelection();+ }+ if (drag.mode === 'transform') {+ editor.updateTransform(worldPoint(event), transformModifiers(event));+ editor.commitTransform();+ }+ if (drag.mode === 'shape') {+ updateDrawing(event);+ const id = options.createId?.() ?? crypto.randomUUID();+ const committed = editor.commitShape(+ id,+ options.appearance?.() ?? { fill: 'transparent', stroke: '#e53935' },+ 3 / editor.getCamera().scale+ );+ if (committed) options.onShapeCreated?.(id);+ }+ cancel();+ };+ const keyDown = (event: KeyboardEvent) => {+ if (options.suspended?.()) return;+ if (event.target !== element) return;+ updateModifierPreview(event);+ if (event.code === 'Space' && options.navigation !== 'centered-image') {+ event.preventDefault();+ space = true;+ updateCursor();+ }+ if (event.key === 'Escape') {+ const active = !!drag;+ cancel();+ if (!active) editor.select();+ }+ if (options.editing && !event.repeat) {+ const key = event.key.toLowerCase();+ if ((event.ctrlKey || event.metaKey) && (key === 'z' || key === 'y')) {+ event.preventDefault();+ cancel();+ if (key === 'y' || event.shiftKey) editor.redo();+ else editor.undo();+ } else if (event.key === 'Delete' || event.key === 'Backspace') {+ event.preventDefault();+ cancel();+ editor.deleteSelection();+ }+ }+ };+ const keyUp = (event: KeyboardEvent) => {+ if (event.target === element) updateModifierPreview(event);+ if (event.code === 'Space') {+ space = false;+ updateCursor();+ }+ };+ const wheel = (event: WheelEvent) => {+ if (options.suspended?.()) return;+ event.preventDefault();+ if (drag) return;+ const rect = element.getBoundingClientRect();+ const unit =+ event.deltaMode === 1+ ? 16+ : event.deltaMode === 2+ ? element.clientHeight+ : 1;+ if (options.navigation === 'centered-image') {+ const exponent = Math.max(-1, Math.min(1, -event.deltaY * unit * 0.01));+ editor.centerImage(+ { width: element.clientWidth, height: element.clientHeight },+ editor.getCamera().scale * Math.exp(exponent)+ );+ } else if (event.ctrlKey || event.metaKey) {+ // Keep fine trackpad deltas continuous and bound coarse wheel/page jumps.+ const exponent = Math.max(+ -MAX_WHEEL_ZOOM_EXPONENT,+ Math.min(+ MAX_WHEEL_ZOOM_EXPONENT,+ -event.deltaY * unit * WHEEL_ZOOM_RATE+ )+ );+ editor.zoomAt(+ { x: event.clientX - rect.left, y: event.clientY - rect.top },+ editor.getCamera().scale * Math.exp(exponent)+ );+ } else {+ editor.panBy({ x: -event.deltaX * unit, y: -event.deltaY * unit });+ }+ };+ element.addEventListener('pointerdown', pointerDown);+ element.addEventListener('pointermove', pointerHover);+ element.addEventListener('pointerup', pointerHover);+ element.addEventListener('pointerleave', clearHover);+ element.addEventListener('keydown', keyDown);+ element.addEventListener('keyup', keyUp);+ element.addEventListener('blur', cancel);+ element.addEventListener('wheel', wheel, { passive: false });+ window.addEventListener('blur', cancel);+ window.addEventListener('keydown', updateHover);+ window.addEventListener('keyup', updateHover);+ return () => {+ cancel();+ element.removeEventListener('pointerdown', pointerDown);+ element.removeEventListener('pointermove', pointerHover);+ element.removeEventListener('pointerup', pointerHover);+ element.removeEventListener('pointerleave', clearHover);+ element.removeEventListener('keydown', keyDown);+ element.removeEventListener('keyup', keyUp);+ element.removeEventListener('blur', cancel);+ element.removeEventListener('wheel', wheel);+ window.removeEventListener('blur', cancel);+ window.removeEventListener('keydown', updateHover);+ window.removeEventListener('keyup', updateHover);+ element.style.cursor = originalCursor;+ };+}++export { attachConnectorControls } from './connectors';+export {+ createTextMeasurer,+ textFonts,+ textLayoutStyle,+} from './rich-text';diff --git a/packages/graphics/src/browser/rich-text.css b/packages/graphics/src/browser/rich-text.cssnew file mode 100644index 0000000000..317aaf6e62--- /dev/null+++ b/packages/graphics/src/browser/rich-text.css@@ -0,0 +1 @@+.graphics-rich-text { box-sizing: border-box; line-height: 1.35; white-space: pre-wrap; overflow-wrap: anywhere; tab-size: 4; }diff --git a/packages/graphics/src/browser/rich-text.ts b/packages/graphics/src/browser/rich-text.tsnew file mode 100644index 0000000000..0d9c651e13--- /dev/null+++ b/packages/graphics/src/browser/rich-text.ts@@ -0,0 +1,39 @@+import type { TextFont, TextGeometry, TextMeasurer } from '../core/shapes/text';+export const textFonts: Readonly<Record<TextFont, string>> = {+ sans: 'Arial, Helvetica, sans-serif',+ serif: 'Georgia, serif',+ mono: 'ui-monospace, SFMono-Regular, Menlo, monospace',+};+export const textLayoutStyle = (geometry: TextGeometry) => ({+ 'font-family': textFonts[geometry.fontFamily],+ 'font-size': `${geometry.fontSize}px`,+ width: geometry.autoWidth ? 'max-content' : `${geometry.width}px`,+ 'min-width': '1px',+});+/** Plain-string measurement matching the default TextView. Hosts with encoded+ * content supply their own measurer and contentView. */+export function createTextMeasurer() {+ const element = document.createElement('div');+ element.className = 'graphics-rich-text';+ Object.assign(element.style, {+ position: 'fixed',+ left: '-100000px',+ top: '0',+ visibility: 'hidden',+ pointerEvents: 'none',+ });+ element.setAttribute('aria-hidden', 'true');+ document.body.append(element);+ const measure: TextMeasurer = (geometry) => {+ const style = textLayoutStyle(geometry);+ for (const [key, value] of Object.entries(style))+ element.style.setProperty(key, value);+ element.textContent = geometry.content;+ const rect = element.getBoundingClientRect();+ return {+ width: geometry.autoWidth ? Math.max(1, rect.width) : geometry.width,+ height: Math.max(geometry.fontSize * 1.35, rect.height),+ };+ };+ return { measure, dispose: () => element.remove() };+}diff --git a/packages/graphics/src/browser/selection-target.ts b/packages/graphics/src/browser/selection-target.tsnew file mode 100644index 0000000000..8e40628757--- /dev/null+++ b/packages/graphics/src/browser/selection-target.ts@@ -0,0 +1,32 @@+import type { GraphicsDocument, Point } from '../core/model';+import { hitTest } from '../core/scene';+import {+ selectionContainsPoint,+ selectionFrame,+} from '../core/selection-frame';++/** Hover and pointer-down share the same selection policy, including box interiors. */+export function selectionTarget(+ document: GraphicsDocument,+ selectedIds: readonly string[],+ point: Point,+ options: {+ deep: boolean;+ additive: boolean;+ handle: boolean;+ tolerance: number;+ }+) {+ const frame = selectionFrame(document, selectedIds);+ return options.handle ||+ (!options.additive &&+ !options.deep &&+ !(+ selectedIds.length === 1 &&+ document.items[selectedIds[0]!]?.type === 'connector'+ ) &&+ frame &&+ selectionContainsPoint(frame, point))+ ? selectedIds[0]+ : hitTest(document, point, options.deep, options.tolerance);+}diff --git a/packages/graphics/src/core/affine.ts b/packages/graphics/src/core/affine.tsnew file mode 100644index 0000000000..73b40ac028--- /dev/null+++ b/packages/graphics/src/core/affine.ts@@ -0,0 +1,102 @@+import type { Bounds, Point } from './model';++/** Column vectors: x'=a*x+c*y+e, y'=b*x+d*y+f. Positive rotation is clockwise. */+export type Matrix = readonly [number, number, number, number, number, number];+export const IDENTITY: Matrix = Object.freeze([1, 0, 0, 1, 0, 0]);+export const translation = (x: number, y: number): Matrix => [1, 0, 0, 1, x, y];+export const scaling = (x: number, y = x): Matrix => [x, 0, 0, y, 0, 0];+export const rotation = (radians: number): Matrix => [+ Math.cos(radians),+ Math.sin(radians),+ -Math.sin(radians),+ Math.cos(radians),+ 0,+ 0,+];+/** Apply right first, then left. */+export function multiply(l: Matrix, r: Matrix): Matrix {+ return [+ l[0] * r[0] + l[2] * r[1],+ l[1] * r[0] + l[3] * r[1],+ l[0] * r[2] + l[2] * r[3],+ l[1] * r[2] + l[3] * r[3],+ l[0] * r[4] + l[2] * r[5] + l[4],+ l[1] * r[4] + l[3] * r[5] + l[5],+ ];+}+export function inverse(m: Matrix): Matrix {+ const determinant = m[0] * m[3] - m[1] * m[2];+ const magnitude = Math.max(+ Math.abs(m[0]),+ Math.abs(m[1]),+ Math.abs(m[2]),+ Math.abs(m[3])+ );+ if (+ !m.every(Number.isFinite) ||+ !Number.isFinite(determinant) ||+ magnitude === 0 ||+ Math.abs(determinant) <= 1e-12 * magnitude * magnitude+ )+ throw new Error('Noninvertible transform');+ const result: Matrix = [+ m[3] / determinant,+ -m[1] / determinant,+ -m[2] / determinant,+ m[0] / determinant,+ (m[2] * m[5] - m[3] * m[4]) / determinant,+ (m[1] * m[4] - m[0] * m[5]) / determinant,+ ];+ if (!result.every(Number.isFinite))+ throw new Error('Noninvertible transform');+ return result;+}+export const transformPoint = (m: Matrix, p: Point): Point => ({+ x: m[0] * p.x + m[2] * p.y + m[4],+ y: m[1] * p.x + m[3] * p.y + m[5],+});+export const transformVector = (m: Matrix, p: Point): Point => ({+ x: m[0] * p.x + m[2] * p.y,+ y: m[1] * p.x + m[3] * p.y,+});+export const around = (pivot: Point, matrix: Matrix): Matrix =>+ multiply(+ translation(pivot.x, pivot.y),+ multiply(matrix, translation(-pivot.x, -pivot.y))+ );+export const corners = (b: Bounds): readonly Point[] => [+ { x: b.x, y: b.y },+ { x: b.x + b.width, y: b.y },+ { x: b.x + b.width, y: b.y + b.height },+ { x: b.x, y: b.y + b.height },+];+export function enclosing(points: readonly Point[]): Bounds {+ if (!points.length) return { x: 0, y: 0, width: 0, height: 0 };+ const xs = points.map((p) => p.x),+ ys = points.map((p) => p.y);+ const x = Math.min(...xs),+ y = Math.min(...ys);+ return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y };+}+/** Separating-axis test for convex polygons (including boundary contact). */+export function intersects(a: readonly Point[], b: readonly Point[]): boolean {+ for (const polygon of [a, b]) {+ for (let i = 0; i < polygon.length; i++) {+ const p = polygon[i],+ q = polygon[(i + 1) % polygon.length];+ if (!p || !q) continue;+ const axis = { x: p.y - q.y, y: q.x - p.x };+ const pa = a.map((v) => v.x * axis.x + v.y * axis.y),+ pb = b.map((v) => v.x * axis.x + v.y * axis.y);+ if (+ Math.max(...pa) < Math.min(...pb) - 1e-9 ||+ Math.max(...pb) < Math.min(...pa) - 1e-9+ )+ return false;+ }+ }+ return true;+}+export const sameMatrix = (a: Matrix, b: Matrix) =>+ a.every((v, i) => Math.abs(v - (b[i] ?? 0)) < 1e-9);+export const cssMatrix = (m: Matrix) => `matrix(${m.join(',')})`;diff --git a/packages/graphics/src/core/appearance.ts b/packages/graphics/src/core/appearance.tsnew file mode 100644index 0000000000..3d28fc5f2d--- /dev/null+++ b/packages/graphics/src/core/appearance.ts@@ -0,0 +1,47 @@+import type { Appearance } from './model';++export const resolveAppearance = (appearance: Appearance) => ({+ ...appearance,+ strokeWidth: appearance.strokeWidth ?? 2,+ strokeStyle: appearance.strokeStyle ?? 'solid',+ opacity: appearance.opacity ?? 1,+ cornerRadius: appearance.cornerRadius ?? 0,+});++export function validAppearance(value: unknown): value is Appearance {+ if (+ !value ||+ typeof value !== 'object' ||+ !('fill' in value) ||+ typeof value.fill !== 'string' ||+ !('stroke' in value) ||+ typeof value.stroke !== 'string'+ )+ return false;+ for (const key of ['strokeWidth', 'opacity', 'cornerRadius'] as const) {+ if (!(key in value)) continue;+ const number = value[key as keyof typeof value];+ if (number === undefined) continue;+ if (+ typeof number !== 'number' ||+ !Number.isFinite(number) ||+ number < 0 ||+ (key === 'opacity' && number > 1)+ )+ return false;+ }+ if (+ 'strokeStyle' in value &&+ value.strokeStyle !== undefined &&+ !['solid', 'dashed', 'dotted'].includes(value.strokeStyle as string)+ )+ return false;+ return true;+}++export function strokeDasharray(appearance: Appearance): string | undefined {+ const { strokeWidth, strokeStyle } = resolveAppearance(appearance);+ if (strokeStyle === 'dashed') return `${strokeWidth * 4} ${strokeWidth * 3}`;+ if (strokeStyle === 'dotted') return `0 ${strokeWidth * 2.5}`;+ return undefined;+}diff --git a/packages/graphics/src/core/backend.ts b/packages/graphics/src/core/backend.tsnew file mode 100644index 0000000000..57e1aeba54--- /dev/null+++ b/packages/graphics/src/core/backend.ts@@ -0,0 +1,13 @@+import type { GraphicsDocument } from './model';++/** An authoritative document/history owner. The editor only proposes commits. */+export interface GraphicsBackend {+ getDocument(): GraphicsDocument;+ getHistory(): { canUndo: boolean; canRedo: boolean };+ commit(document: GraphicsDocument): void;+ undo(): void;+ redo(): void;+ subscribe(+ listener: (source: 'local' | 'remote' | 'history') => void+ ): () => void;+}diff --git a/packages/graphics/src/core/camera.ts b/packages/graphics/src/core/camera.tsnew file mode 100644index 0000000000..89b28d1d5a--- /dev/null+++ b/packages/graphics/src/core/camera.ts@@ -0,0 +1,64 @@+import type { Camera, Point } from './model';++export const MIN_SCALE = 0.01;+export const MAX_SCALE = 8;+export const INITIAL_CAMERA: Camera = Object.freeze({ x: 0, y: 0, scale: 1 });++export function fitImageCamera(+ image: { width: number; height: number },+ viewport: { width: number; height: number }+): Camera {+ if (+ ![image.width, image.height, viewport.width, viewport.height].every(+ (value) => Number.isFinite(value) && value > 0+ )+ )+ return INITIAL_CAMERA;+ const scale = Math.max(+ MIN_SCALE,+ Math.min(+ 1,+ (viewport.width - Math.min(48, viewport.width / 4)) / image.width,+ (viewport.height - Math.min(48, viewport.height / 4)) / image.height+ )+ );+ return {+ x: (viewport.width - image.width * scale) / 2,+ y: (viewport.height - image.height * scale) / 2,+ scale,+ };+}++export function worldToScreen(camera: Camera, point: Point): Point {+ return {+ x: point.x * camera.scale + camera.x,+ y: point.y * camera.scale + camera.y,+ };+}++export function screenToWorld(camera: Camera, point: Point): Point {+ return {+ x: (point.x - camera.x) / camera.scale,+ y: (point.y - camera.y) / camera.scale,+ };+}++export function zoomAt(+ camera: Camera,+ anchor: Point,+ requestedScale: number+): Camera {+ if (+ !Number.isFinite(requestedScale) ||+ !Number.isFinite(anchor.x) ||+ !Number.isFinite(anchor.y)+ )+ return camera;+ const scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, requestedScale));+ const world = screenToWorld(camera, anchor);+ return {+ x: anchor.x - world.x * scale,+ y: anchor.y - world.y * scale,+ scale,+ };+}diff --git a/packages/graphics/src/core/commands.ts b/packages/graphics/src/core/commands.tsnew file mode 100644index 0000000000..75e987a81e--- /dev/null+++ b/packages/graphics/src/core/commands.ts@@ -0,0 +1,212 @@+import { enclosing, inverse, multiply, translation } from './affine';+import { resolveAppearance } from './appearance';+import {+ duplicateNodes,+ type GraphicsFragment,+ type IdFactory,+ pasteFragment,+} from './fragments';+import { layoutBounds, layoutRoots } from './layout';+import type { Appearance, GraphicsDocument, Point } from './model';+import { children, nodeBoundsPoints, roots, worldMatrix } from './scene';+import { isShape } from './shapes/registry';+import type { TextMeasurer } from './shapes/text';+import { snapTranslation } from './snapping';+import { selectedShapeIds } from './style-selection';++export type CommandContext = Readonly<{+ document: GraphicsDocument;+ selection: readonly string[];+ snapUnit?: number;+ measureText?: TextMeasurer;+}>;+export type CommandResult = Readonly<{+ document: GraphicsDocument;+ selection?: readonly string[];+}>;+/** Typed, pure contribution; the editor owns validation, notification and history. */+export type GraphicsCommand<Payload> = Readonly<{+ id: string;+ apply(context: CommandContext, payload: Payload): CommandResult;+}>;+function move(+ document: GraphicsDocument,+ offsets: ReadonlyMap<string, Point>+): GraphicsDocument {+ const items = { ...document.items };+ let changed = false;+ for (const [id, delta] of offsets) {+ if (![delta.x, delta.y].every(Number.isFinite))+ throw new Error('Invalid translation');+ if (Math.abs(delta.x) < 1e-9 && Math.abs(delta.y) < 1e-9) continue;+ const node = items[id];+ if (!node || node.type === 'surface') continue;+ items[id] = {+ ...node,+ transform: multiply(+ inverse(worldMatrix(document, node.placement.parentId)),+ multiply(translation(delta.x, delta.y), worldMatrix(document, id))+ ),+ };+ changed = true;+ }+ return changed ? { ...document, items } : document;+}+export const selectAllCommand: GraphicsCommand<void> = {+ id: 'select-all',+ apply: ({ document }) => ({ document, selection: children(document) }),+};+export const nudgeCommand: GraphicsCommand<Point> = {+ id: 'nudge',+ apply: ({ document, selection, snapUnit }, delta) => {+ const selected = roots(document, selection);+ const bounds = enclosing(+ selected.flatMap((id) => nodeBoundsPoints(document, id))+ );+ const snapped = snapTranslation(bounds, delta, snapUnit);+ return {+ document: move(document, new Map(selected.map((id) => [id, snapped]))),+ };+ },+};+export const duplicateCommand: GraphicsCommand<{+ createId: IdFactory;+ offset?: Point;+}> = {+ id: 'duplicate',+ apply: (+ { document, selection, snapUnit },+ { createId, offset = { x: 24, y: 24 } }+ ) => {+ const bounds = enclosing(+ roots(document, selection).flatMap((id) => nodeBoundsPoints(document, id))+ );+ return duplicateNodes(+ document,+ selection,+ createId,+ snapTranslation(bounds, offset, snapUnit)+ );+ },+};+export const pasteCommand: GraphicsCommand<{+ fragment: GraphicsFragment;+ createId: IdFactory;+ offset?: Point;+}> = {+ id: 'paste',+ apply: (+ { document, snapUnit },+ { fragment, createId, offset = { x: 24, y: 24 } }+ ) => {+ const bounds = enclosing(+ children(fragment.scene).flatMap((id) =>+ nodeBoundsPoints(fragment.scene, id)+ )+ );+ return pasteFragment(+ document,+ fragment,+ createId,+ snapTranslation(bounds, offset, snapUnit)+ );+ },+};+export const styleCommand: GraphicsCommand<Partial<Appearance>> = {+ id: 'style',+ apply: ({ document, selection }, patch) => {+ const items = { ...document.items };+ let changed = false;+ for (const id of selectedShapeIds(document, selection)) {+ const node = items[id];+ if (!isShape(node)) continue;+ const before = resolveAppearance(node.appearance);+ const after = resolveAppearance({ ...node.appearance, ...patch });+ if (+ Object.keys(after).every(+ (key) =>+ before[key as keyof typeof before] ===+ after[key as keyof typeof after]+ )+ )+ continue;+ items[id] = { ...node, appearance: after };+ changed = true;+ }+ return { document: changed ? { ...document, items } : document };+ },+};+export type Alignment =+ | 'left'+ | 'center'+ | 'right'+ | 'top'+ | 'middle'+ | 'bottom';+export const alignCommand: GraphicsCommand<Alignment> = {+ id: 'align',+ apply: ({ document, selection }, alignment) => {+ const ids = layoutRoots(document, selection);+ if (ids.length < 2) return { document };+ const all = enclosing(+ ids.flatMap((id) => {+ const b = layoutBounds(document, id);+ return [+ { x: b.x, y: b.y },+ { x: b.x + b.width, y: b.y + b.height },+ ];+ })+ );+ const offsets = new Map(+ ids.map((id) => {+ const b = layoutBounds(document, id);+ const deltas: Record<Alignment, Point> = {+ left: { x: all.x - b.x, y: 0 },+ center: { x: all.x + all.width / 2 - b.x - b.width / 2, y: 0 },+ right: { x: all.x + all.width - b.x - b.width, y: 0 },+ top: { x: 0, y: all.y - b.y },+ middle: { x: 0, y: all.y + all.height / 2 - b.y - b.height / 2 },+ bottom: { x: 0, y: all.y + all.height - b.y - b.height },+ };+ return [id, deltas[alignment]] as const;+ })+ );+ return { document: move(document, offsets) };+ },+};+/** Equal gaps between world bounds, keeping the two outer items fixed. */+export const distributeCommand: GraphicsCommand<'horizontal' | 'vertical'> = {+ id: 'distribute',+ apply: ({ document, selection }, axis) => {+ const horizontal = axis === 'horizontal';+ const entries = layoutRoots(document, selection).map((id) => ({+ id,+ b: layoutBounds(document, id),+ }));+ const start = (b: (typeof entries)[number]['b']) =>+ horizontal ? b.x : b.y;+ const size = (b: (typeof entries)[number]['b']) =>+ horizontal ? b.width : b.height;+ entries.sort((a, b) => start(a.b) - start(b.b) || a.id.localeCompare(b.id));+ if (entries.length < 3) return { document };+ const first = entries[0]!.b,+ last = entries[entries.length - 1]!.b;+ const gap =+ (start(last) ++ size(last) -+ start(first) -+ entries.reduce((n, e) => n + size(e.b), 0)) /+ (entries.length - 1);+ let position = start(first);+ const offsets = new Map<string, Point>();+ for (const entry of entries) {+ const delta = position - start(entry.b);+ offsets.set(+ entry.id,+ horizontal ? { x: delta, y: 0 } : { x: 0, y: delta }+ );+ position += size(entry.b) + gap;+ }+ return { document: move(document, offsets) };+ },+};diff --git a/packages/graphics/src/core/connector-commands.ts b/packages/graphics/src/core/connector-commands.tsnew file mode 100644index 0000000000..9965d0009d--- /dev/null+++ b/packages/graphics/src/core/connector-commands.ts@@ -0,0 +1,50 @@+import type { GraphicsCommand } from './commands';+import { resolveConnector } from './connectors';+import type { ShapeItem } from './model';+import {+ type ConnectorGeometry,+ connectorDefinition,+} from './shapes/connector';+import { selectedShapeIds } from './style-selection';++export const setConnectorCommand: GraphicsCommand<ShapeItem<'connector'>> = {+ id: 'set-connector',+ apply: ({ document }, item) => {+ const previous = document.items[item.id];+ if (previous && previous.type !== 'connector')+ throw new Error('Connector id belongs to another node');+ if (!connectorDefinition.validateGeometry(item.geometry))+ throw new Error('Invalid connector geometry');+ if (+ previous?.type === 'connector' &&+ connectorDefinition.sameGeometry(previous, item)+ )+ return { document, selection: [item.id] };+ const next = { ...document, items: { ...document.items, [item.id]: item } };+ // Remember the final visible endpoints as fallbacks without storing a route cache.+ next.items[item.id] = resolveConnector(next, item);+ return { document: next, selection: [item.id] };+ },+};+export type ConnectorStyle = Pick<+ ConnectorGeometry,+ 'route' | 'startHead' | 'endHead'+>;+export const connectorStyleCommand: GraphicsCommand<Partial<ConnectorStyle>> = {+ id: 'connector-style',+ apply: ({ document, selection }, patch) => {+ const items = { ...document.items };+ let changed = false;+ for (const id of selectedShapeIds(document, selection)) {+ const item = items[id];+ if (item?.type !== 'connector') continue;+ const next = { ...item, geometry: { ...item.geometry, ...patch } };+ if (connectorDefinition.sameGeometry(item, next)) continue;+ if (!connectorDefinition.validateGeometry(next.geometry))+ throw new Error('Invalid connector style');+ items[id] = next;+ changed = true;+ }+ return { document: changed ? { ...document, items } : document };+ },+};diff --git a/packages/graphics/src/core/connector-interaction.ts b/packages/graphics/src/core/connector-interaction.tsnew file mode 100644index 0000000000..f0c0b2d48a--- /dev/null+++ b/packages/graphics/src/core/connector-interaction.ts@@ -0,0 +1,158 @@+import { IDENTITY, inverse, transformPoint } from './affine';+import type { ConnectorStyle } from './connector-commands';+import {+ type ConnectorPort,+ type ConnectorTarget,+ connectorTargetAt,+ resolveConnector,+} from './connectors';+import type { Appearance, GraphicsDocument, Point, ShapeItem } from './model';+import { keysAt } from './ordering';+import { children, worldMatrix } from './scene';+import type { ConnectorEndpoint } from './shapes/connector';+import { snapPoint, snapValue } from './snapping';++export type ConnectorGesture = Readonly<{+ item: ShapeItem<'connector'>;+ endpoint: 'start' | 'end';+ dropTarget?: ConnectorPort;+ creating: boolean;+}>;+export function createConnectorInteraction(host: {+ getDocument(): GraphicsDocument;+ getSnapUnit?(): number | undefined;+ commit(item: ShapeItem<'connector'>): void;+ onChange(): void;+}) {+ let gesture: ConnectorGesture | undefined;+ let target: ConnectorTarget | undefined;+ const emit = () => host.onChange();+ const cancel = () => {+ gesture = undefined;+ target = undefined;+ emit();+ };+ const previewDocument = (): GraphicsDocument => {+ const doc = host.getDocument();+ return gesture+ ? { ...doc, items: { ...doc.items, [gesture.item.id]: gesture.item } }+ : doc;+ };+ function update(point: Point, tolerance: number, shift = false) {+ if (!gesture || ![point.x, point.y].every(Number.isFinite)) return;+ const document = previewDocument(),+ item = gesture.item,+ other = gesture.endpoint === 'start' ? 'end' : 'start';+ const world = worldMatrix(document, item.id);+ target = connectorTargetAt(document, point, tolerance);+ const port = target?.active;+ const fixed = transformPoint(+ world,+ resolveConnector(document, item).geometry[other].point+ );+ const unit = host.getSnapUnit?.();+ if (shift && !port) {+ const dx = point.x - fixed.x,+ dy = point.y - fixed.y,+ distance = Math.hypot(dx, dy);+ const angle =+ (Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * Math.PI) / 4;+ const x = Math.cos(angle),+ y = Math.sin(angle);+ // Snap the dominant axis while retaining the exact 45-degree constraint.+ const component = Math.max(Math.abs(x), Math.abs(y));+ const length = snapValue(distance * component, unit) / component;+ point = { x: fixed.x + x * length, y: fixed.y + y * length };+ } else if (!port) point = snapPoint(point, unit);+ const end: ConnectorEndpoint = {+ point: transformPoint(inverse(world), port?.point ?? point),+ ...(port+ ? { binding: { targetId: port.targetId, anchor: port.anchor } }+ : {}),+ };+ gesture = {+ ...gesture,+ dropTarget: port,+ item: {+ ...item,+ geometry: { ...item.geometry, [gesture.endpoint]: end },+ },+ };+ emit();+ }+ return {+ getState: () => gesture,+ getTarget: () => target,+ hover(point: Point, tolerance: number) {+ target = connectorTargetAt(previewDocument(), point, tolerance);+ emit();+ },+ clearHover() {+ if (!target) return;+ target = undefined;+ emit();+ },+ getPreviewDocument: previewDocument,+ cancel,+ update,+ begin(+ id: string,+ point: Point,+ appearance: Appearance,+ style: ConnectorStyle,+ tolerance: number+ ) {+ const doc = host.getDocument();+ if (doc.items[id]) throw new Error('Duplicate connector id');+ target = connectorTargetAt(doc, point, tolerance);+ const port = target?.active;+ const start: ConnectorEndpoint = {+ point: port?.point ?? snapPoint(point, host.getSnapUnit?.()),+ ...(port+ ? { binding: { targetId: port.targetId, anchor: port.anchor } }+ : {}),+ };+ gesture = {+ creating: true,+ endpoint: 'end',+ dropTarget: port,+ item: {+ id,+ type: 'connector',+ placement: {+ parentId: doc.rootId,+ sortKey: keysAt(doc, children(doc), children(doc).length, 1)[0]!,+ },+ transform: IDENTITY,+ appearance: { ...appearance, fill: 'transparent' },+ geometry: { ...style, start, end: start },+ },+ };+ emit();+ },+ edit(id: string, endpoint: 'start' | 'end') {+ const item = host.getDocument().items[id];+ if (item?.type !== 'connector') return false;+ gesture = { item, endpoint, creating: false };+ emit();+ return true;+ },+ commit(minLength = 0) {+ const current = gesture;+ if (!current) return false;+ const doc = previewDocument(),+ item = resolveConnector(doc, current.item);+ const world = worldMatrix(doc, item.id),+ start = transformPoint(world, item.geometry.start.point),+ end = transformPoint(world, item.geometry.end.point);+ cancel();+ if (+ current.creating &&+ Math.hypot(end.x - start.x, end.y - start.y) < minLength+ )+ return false;+ host.commit(item);+ return true;+ },+ };+}diff --git a/packages/graphics/src/core/connectors.ts b/packages/graphics/src/core/connectors.tsnew file mode 100644index 0000000000..0b5c8c08e5--- /dev/null+++ b/packages/graphics/src/core/connectors.ts@@ -0,0 +1,319 @@+import {+ corners,+ IDENTITY,+ inverse,+ type Matrix,+ transformPoint,+} from './affine';+import type {+ Bounds,+ GraphicsDocument,+ GraphicsItem,+ Point,+ ShapeItem,+} from './model';+import { drawableIds, type SceneOverrides, worldMatrix } from './scene';+import { segmentDistance } from './shapes/box-geometry';+import {+ type ConnectorAnchor,+ type ConnectorBinding,+ type ConnectorEndpoint,+ connectorAnchors,+} from './shapes/connector';+import { sub, unit } from './shapes/connector-routing';+import { isShape, shapeDefinition } from './shapes/registry';++export const canBindConnector = (+ item: GraphicsItem | undefined+): item is Exclude<ShapeItem, ShapeItem<'connector' | 'pencil'>> =>+ isShape(item) && item.type !== 'connector' && item.type !== 'pencil';+const fractions: Record<ConnectorAnchor, Point> = {+ center: { x: 0.5, y: 0.5 },+ top: { x: 0.5, y: 0 },+ right: { x: 1, y: 0.5 },+ bottom: { x: 0.5, y: 1 },+ left: { x: 0, y: 0.5 },+};+const normals: Record<ConnectorAnchor, Point> = {+ center: { x: 1, y: 0 },+ top: { x: 0, y: -1 },+ right: { x: 1, y: 0 },+ bottom: { x: 0, y: 1 },+ left: { x: -1, y: 0 },+};+const anchorPoint = (b: Bounds, anchor: ConnectorAnchor): Point => ({+ x: b.x + fractions[anchor].x * b.width,+ y: b.y + fractions[anchor].y * b.height,+});+const vector = (m: Matrix, p: Point): Point =>+ unit({ x: m[0] * p.x + m[2] * p.y, y: m[1] * p.x + m[3] * p.y });+const normal = (world: Matrix, n: Point): Point => {+ const m = inverse(world);+ return unit({ x: m[0] * n.x + m[1] * n.y, y: m[2] * n.x + m[3] * n.y });+};+function boundary(+ item: Exclude<ShapeItem, ShapeItem<'connector'>>,+ toward: Point+) {+ const b = shapeDefinition(item.type).bounds(item),+ center = anchorPoint(b, 'center');+ let delta = sub(toward, center);+ if (Math.hypot(delta.x, delta.y) < 1e-8) delta = { x: 1, y: 0 };+ const rx = b.width / 2,+ ry = b.height / 2;+ if (item.type === 'ellipse') {+ const t = 1 / Math.hypot(delta.x / rx, delta.y / ry);+ const d = { x: delta.x * t, y: delta.y * t };+ return {+ point: { x: center.x + d.x, y: center.y + d.y },+ direction: unit({ x: d.x / (rx * rx), y: d.y / (ry * ry) }),+ };+ }+ let t = Math.min(rx / Math.abs(delta.x), ry / Math.abs(delta.y));+ const radius =+ item.type === 'rectangle'+ ? Math.min(item.appearance.cornerRadius ?? 0, rx, ry)+ : 0;+ if (radius) {+ let lo = 0,+ hi = t;+ for (let i = 0; i < 40; i++) {+ const m = (lo + hi) / 2;+ const x = Math.max(0, Math.abs(delta.x * m) - rx + radius),+ y = Math.max(0, Math.abs(delta.y * m) - ry + radius);+ if (Math.hypot(x, y) > radius) hi = m;+ else lo = m;+ }+ t = lo;+ }+ const dx = delta.x * t,+ dy = delta.y * t;+ const nx = Math.max(0, Math.abs(dx) - rx + radius),+ ny = Math.max(0, Math.abs(dy) - ry + radius);+ const direction =+ radius && (nx || ny)+ ? unit({ x: Math.sign(dx) * nx, y: Math.sign(dy) * ny })+ : Math.abs(dx / rx) > Math.abs(dy / ry)+ ? { x: Math.sign(dx), y: 0 }+ : { x: 0, y: Math.sign(dy) };+ return { point: { x: center.x + dx, y: center.y + dy }, direction };+}+function boundTarget(+ document: GraphicsDocument,+ end: ConnectorEndpoint,+ overrides: SceneOverrides+) {+ const binding = end.binding;+ if (!binding) return;+ const item = overrides[binding.targetId] ?? document.items[binding.targetId];+ if (!canBindConnector(item)) return;+ const world = worldMatrix(document, item.id, overrides),+ bounds = shapeDefinition(item.type).bounds(item);+ return {+ item,+ world,+ binding,+ point: transformPoint(world, anchorPoint(bounds, binding.anchor)),+ };+}+/** Resolve references into the connector's local frame. The document stays untouched. */+export function resolveConnector(+ document: GraphicsDocument,+ item: ShapeItem<'connector'>,+ overrides: SceneOverrides = {}+): ShapeItem<'connector'> {+ const world = worldMatrix(document, item.id, overrides),+ local = inverse(world),+ g = item.geometry;+ const start = boundTarget(document, g.start, overrides),+ end = boundTarget(document, g.end, overrides);+ const a = start?.point ?? transformPoint(world, g.start.point),+ b = end?.point ?? transformPoint(world, g.end.point);+ const resolve = (+ endpoint: ConnectorEndpoint,+ target: typeof start,+ other: Point+ ): ConnectorEndpoint => {+ if (!target) return endpoint;+ const { binding, item, world } = target;+ const resolved =+ binding.anchor === 'center'+ ? boundary(item, transformPoint(inverse(world), other))+ : {+ point: anchorPoint(+ shapeDefinition(item.type).bounds(item),+ binding.anchor+ ),+ direction: normals[binding.anchor],+ };+ return {+ ...endpoint,+ point: transformPoint(local, transformPoint(world, resolved.point)),+ direction: vector(local, normal(world, resolved.direction)),+ };+ };+ return {+ ...item,+ geometry: {+ ...g,+ start: resolve(g.start, start, b),+ end: resolve(g.end, end, a),+ },+ };+}+export type ConnectorPort = ConnectorBinding & Readonly<{ point: Point }>;+export type ConnectorTarget = Readonly<{+ targetId: string;+ ports: readonly ConnectorPort[];+ active?: ConnectorPort;+}>;+export function connectorPorts(+ document: GraphicsDocument,+ overrides: SceneOverrides = {}+): readonly ConnectorPort[] {+ return drawableIds(document).flatMap((id) => {+ const item = overrides[id] ?? document.items[id];+ if (!canBindConnector(item) || item.appearance.opacity === 0) return [];+ const bounds = shapeDefinition(item.type).bounds(item),+ world = worldMatrix(document, id, overrides);+ return connectorAnchors.map((anchor) => ({+ targetId: id,+ anchor,+ point: transformPoint(world, anchorPoint(bounds, anchor)),+ }));+ });+}+export function connectorDropTarget(+ document: GraphicsDocument,+ point: Point,+ tolerance: number+): ConnectorPort | undefined {+ return connectorTargetAt(document, point, tolerance)?.active;+}++/** Hover, starting an endpoint, and dropping it share one target policy. */+export function connectorTargetAt(+ document: GraphicsDocument,+ point: Point,+ tolerance: number+): ConnectorTarget | undefined {+ for (const id of [...drawableIds(document)].reverse()) {+ const item = document.items[id];+ if (!canBindConnector(item) || item.appearance.opacity === 0) continue;+ const definition = shapeDefinition(item.type),+ bounds = definition.bounds(item);+ const world = worldMatrix(document, id),+ local = transformPoint(inverse(world), point);+ const ports = connectorAnchors.map((anchor) => ({+ targetId: id,+ anchor,+ point: transformPoint(world, anchorPoint(bounds, anchor)),+ }));+ let active: ConnectorPort | undefined,+ distance = tolerance;+ for (const port of ports) {+ const d = Math.hypot(point.x - port.point.x, point.y - port.point.y);+ if (d <= distance) {+ active = port;+ distance = d;+ }+ }+ let inside: boolean, core: boolean;+ if (item.type === 'rectangle' || item.type === 'ellipse') {+ // Geometry-only probes: unfilled shapes are targets too, and labels must+ // not turn the shape's entire interior into an outline hit.+ const probe = {+ ...item,+ geometry: { width: item.geometry.width, height: item.geometry.height },+ appearance: {+ ...item.appearance,+ fill: 'black',+ stroke: 'transparent',+ strokeWidth: 0,+ },+ };+ inside = definition.hitTest(probe, local, {+ worldTransform: world,+ tolerance: 0,+ });+ core =+ inside &&+ !definition.hitTest(+ {+ ...probe,+ appearance: {+ ...probe.appearance,+ fill: 'transparent',+ stroke: 'black',+ strokeWidth: Number.EPSILON,+ },+ },+ local,+ { worldTransform: world, tolerance }+ );+ } else {+ inside =+ local.x >= bounds.x &&+ local.x <= bounds.x + bounds.width &&+ local.y >= bounds.y &&+ local.y <= bounds.y + bounds.height;+ const outline = corners(bounds).map((p) => transformPoint(world, p));+ core =+ inside &&+ outline.every(+ (p, i) => segmentDistance(point, p, outline[(i + 1) % 4]!) > tolerance+ );+ }+ if (inside || active)+ return {+ targetId: id,+ ports,+ active: active ?? (core ? ports[0] : undefined),+ };+ }+}+/** Detach removed/external references at their current visible position. */+export function retainConnectorBindings(+ document: GraphicsDocument,+ item: ShapeItem<'connector'>,+ retained: ReadonlySet<string>+): ShapeItem<'connector'> {+ const resolved = resolveConnector(document, item);+ const retain = (end: ConnectorEndpoint, visible: ConnectorEndpoint) =>+ end.binding && !retained.has(end.binding.targetId)+ ? {+ point: visible.point,+ ...(visible.direction ? { direction: visible.direction } : {}),+ }+ : end;+ return {+ ...item,+ geometry: {+ ...item.geometry,+ start: retain(item.geometry.start, resolved.geometry.start),+ end: retain(item.geometry.end, resolved.geometry.end),+ },+ };+}++/** Bound connector ink stays in world units, independent of its own or group scale.+ * Endpoints must already be resolved against their targets. */+export function connectorWorldView(+ item: ShapeItem<'connector'>,+ world: Matrix+): ShapeItem<'connector'> {+ const endpoint = (end: ConnectorEndpoint): ConnectorEndpoint => ({+ ...end,+ point: transformPoint(world, end.point),+ direction: end.direction ? vector(world, end.direction) : undefined,+ });+ return {+ ...item,+ transform: IDENTITY,+ geometry: {+ ...item.geometry,+ start: endpoint(item.geometry.start),+ end: endpoint(item.geometry.end),+ },+ };+}diff --git a/packages/graphics/src/core/dot-grid.ts b/packages/graphics/src/core/dot-grid.tsnew file mode 100644index 0000000000..b3915cebfe--- /dev/null+++ b/packages/graphics/src/core/dot-grid.ts@@ -0,0 +1,13 @@+/** Fine dots emerge gently as they spread out; coarser dots stay steady.+ * Three overlapping powers of four cover every readable level. The coarsest+ * is always opaque, so dropping a redundant coarser level cannot cause a pop.+ */+export function dotGridLevels(scale: number) {+ const smallest =+ 4 ** Math.max(0, Math.floor(Math.log(16 / scale) / Math.log(4)));+ return [smallest, smallest * 4, smallest * 16].map((unit) => ({+ unit,+ spacing: unit * scale,+ opacity: Math.max(0, Math.min(1, (unit * scale - 4) / 32)),+ }));+}diff --git a/packages/graphics/src/core/drawing.ts b/packages/graphics/src/core/drawing.tsnew file mode 100644index 0000000000..23491bca66--- /dev/null+++ b/packages/graphics/src/core/drawing.ts@@ -0,0 +1,144 @@+import { translation } from './affine';+import type {+ Appearance,+ Bounds,+ ImageSurface,+ Placement,+ Point,+ ShapeItem,+ ShapeKind,+} from './model';+import { boxGeometry } from './shapes/box-geometry';+import {+ MAX_PENCIL_POINTS,+ type PencilPoint,+ pencilDefinition,+} from './shapes/pencil';++/** Browser-independent input; absent pressure selects mouse pressure simulation. */+export type DrawingKind = Extract<+ ShapeKind,+ 'rectangle' | 'ellipse' | 'pencil'+>;+export type DrawingSample = Point & Readonly<{ pressure?: number }>;+export type DrawingModifiers = Readonly<{ proportional?: boolean }>;+type Gesture = {+ origin: Point;+ surface?: ImageSurface;+} & (+ | { kind: 'rectangle' | 'ellipse'; end: Point; proportional: boolean }+ | { kind: 'pencil'; points: PencilPoint[]; simulatePressure: boolean }+);++/** Drawing tools own acquisition; shape definitions own finalized geometry. */+export function createDrawing() {+ let gesture: Gesture | undefined;+ let kind: DrawingKind = 'rectangle';+ const pressure = (value?: number) =>+ Number.isFinite(value) ? Math.max(0, Math.min(1, value!)) : 0.5;+ function update(+ samples: readonly DrawingSample[],+ modifiers: DrawingModifiers = {}+ ) {+ if (!gesture) return;+ if (gesture.kind !== 'pencil')+ gesture.proportional = !!modifiers.proportional;+ for (const sample of samples) {+ if (![sample.x, sample.y].every(Number.isFinite)) continue;+ if (gesture.kind !== 'pencil') {+ gesture.end = { x: sample.x, y: sample.y };+ continue;+ }+ const point: PencilPoint = [+ sample.x - gesture.origin.x,+ sample.y - gesture.origin.y,+ pressure(sample.pressure),+ ];+ const last = gesture.points[gesture.points.length - 1]!;+ if (point[0] === last[0] && point[1] === last[1]) continue;+ if (gesture.points.length < MAX_PENCIL_POINTS) gesture.points.push(point);+ }+ }+ function bounds(): Bounds | undefined {+ if (!gesture) return;+ const { origin } = gesture;+ if (gesture.kind === 'pencil') {+ const xs = gesture.points.map((p) => p[0]),+ ys = gesture.points.map((p) => p[1]);+ const x = Math.min(...xs),+ y = Math.min(...ys);+ return {+ x: origin.x + x,+ y: origin.y + y,+ width: Math.max(...xs) - x,+ height: Math.max(...ys) - y,+ };+ }+ let dx = gesture.end.x - origin.x,+ dy = gesture.end.y - origin.y;+ if (gesture.proportional) {+ const surface = gesture.surface;+ const size = Math.min(+ Math.max(Math.abs(dx), Math.abs(dy)),+ surface ? (dx < 0 ? origin.x : surface.width - origin.x) : Infinity,+ surface ? (dy < 0 ? origin.y : surface.height - origin.y) : Infinity+ );+ dx = (dx < 0 ? -1 : 1) * size;+ dy = (dy < 0 ? -1 : 1) * size;+ }+ return {+ x: origin.x + Math.min(0, dx),+ y: origin.y + Math.min(0, dy),+ width: Math.abs(dx),+ height: Math.abs(dy),+ };+ }+ return {+ begin(next: DrawingKind, sample: DrawingSample, surface?: ImageSurface) {+ kind = next;+ const origin = { x: sample.x, y: sample.y };+ gesture =+ next === 'pencil'+ ? {+ kind: next,+ origin,+ points: [[0, 0, pressure(sample.pressure)]],+ simulatePressure: sample.pressure === undefined,+ }+ : { kind: next, origin, end: origin, proportional: false, surface };+ },+ update,+ bounds,+ kind: () => kind,+ cancel: () => {+ gesture = undefined;+ },+ item(+ id: string,+ placement: Placement,+ appearance: Appearance,+ minSize = 0+ ): ShapeItem | undefined {+ const box = bounds();+ if (!gesture || !box) return;+ const common = { id, placement, appearance };+ if (gesture.kind === 'pencil')+ return {+ ...common,+ type: 'pencil',+ transform: translation(gesture.origin.x, gesture.origin.y),+ geometry: pencilDefinition.freezeGeometry({+ points: gesture.points,+ simulatePressure: gesture.simulatePressure,+ }),+ };+ if (box.width <= minSize || box.height <= minSize) return;+ return {+ ...common,+ type: gesture.kind,+ transform: translation(box.x, box.y),+ geometry: boxGeometry(box),+ };+ },+ };+}diff --git a/packages/graphics/src/core/editor.ts b/packages/graphics/src/core/editor.tsnew file mode 100644index 0000000000..3283e7c1e8--- /dev/null+++ b/packages/graphics/src/core/editor.ts@@ -0,0 +1,490 @@+import type { GraphicsBackend } from './backend';+import {+ fitImageCamera,+ INITIAL_CAMERA,+ MAX_SCALE,+ MIN_SCALE,+ zoomAt,+} from './camera';+import { type GraphicsCommand, styleCommand } from './commands';+import {+ createDrawing,+ type DrawingKind,+ type DrawingModifiers,+ type DrawingSample,+} from './drawing';+import {+ applyDocumentDelta,+ type DocumentDelta,+ documentDelta,+} from './history';+import { type LayerOperation, reorderNodes } from './layering';+import type {+ Appearance,+ Bounds,+ Camera,+ GraphicsDocument,+ GraphicsItem,+ ImageSurface,+ Point,+} from './model';+import { keysAt, type LayerPosition } from './ordering';+import {+ children,+ createScene,+ drawableIds,+ freezeDocument,+ groupNodes,+ hitTest,+ reparent,+ ungroupNode,+ worldBounds,+} from './scene';+import { createSelection, type SelectionState } from './selection';+import type { TextMeasurer } from './shapes/text';+import { snapPoint, validateSnapUnit } from './snapping';++export type EditingSession = SelectionState &+ Readonly<{+ canUndo: boolean;+ canRedo: boolean;+ snapUnit?: number;+ }>;++export type GraphicsEditorOptions = Readonly<{+ measureText?: TextMeasurer;+ /** Any positive finite scene-unit interval; omitted disables snapping. */+ snapUnit?: number;+}>;+export type GraphicsEditor = ReturnType<typeof createGraphicsEditor>;++/** One document and camera per instance. The caller owns disposal. */+export function createGraphicsEditor(+ seed: readonly GraphicsItem[] | GraphicsDocument = [],+ options: GraphicsEditorOptions = {}+) {+ return createEditor(seed, undefined, options);+}++/** The caller owns the backend lifetime; disposal only detaches this editor. */+export function createGraphicsEditorFromBackend(+ backend: GraphicsBackend,+ options: GraphicsEditorOptions = {}+) {+ return createEditor(backend.getDocument(), backend, options);+}++function createEditor(+ seed: readonly GraphicsItem[] | GraphicsDocument,+ backend?: GraphicsBackend,+ options: GraphicsEditorOptions = {}+) {+ validateSnapUnit(options.snapUnit);+ let snapUnit = options.snapUnit;+ let document: GraphicsDocument = Array.isArray(seed)+ ? createScene(seed)+ : freezeDocument(seed as GraphicsDocument);+ let camera = INITIAL_CAMERA;+ let disposed = false;+ const listeners = new Set<(camera: Camera) => void>();+ const documentListeners = new Set<(document: GraphicsDocument) => void>();+ const previewListeners = new Set<(preview: Bounds | undefined) => void>();+ const undoStack: DocumentDelta[] = [];+ const redoStack: DocumentDelta[] = [];+ const sessionListeners = new Set<(session: EditingSession) => void>();+ const getSession = (): EditingSession =>+ Object.freeze({+ ...selection.getState(),+ snapUnit,+ canUndo: backend ? backend.getHistory().canUndo : undoStack.length > 0,+ canRedo: backend ? backend.getHistory().canRedo : redoStack.length > 0,+ });+ const emitSession = () => {+ const session = getSession();+ for (const listener of sessionListeners) listener(session);+ };+ const selection = createSelection({+ measureText: options.measureText,+ getSnapUnit: () => snapUnit,+ getDocument: () => document,+ commitDocument,+ cancelDrawing: cancelShape,+ onChange: emitSession,+ });+ const { select, cancelTransform } = selection;+ function commitDocument(next: GraphicsDocument) {+ next = freezeDocument(next);+ if (backend) {+ backend.commit(next);+ return;+ }+ const delta = documentDelta(document, next);+ if (!delta) return;+ undoStack.push(delta);+ if (undoStack.length > 100) undoStack.shift();+ redoStack.length = 0;+ publishDocument(next);+ emitSession();+ }+ function travel(+ from: DocumentDelta[],+ to: DocumentDelta[],+ direction: 'before' | 'after'+ ) {+ if (disposed) return;+ cancelShape();+ cancelTransform();+ const delta = from.pop();+ if (delta) {+ to.push(delta);+ publishDocument(applyDocumentDelta(document, delta, direction));+ }+ emitSession();+ }+ const drawing = createDrawing();+ let preview: Bounds | undefined;++ const detachBackend = backend?.subscribe((source) => {+ // Until intent rebasing is implemented, remote commits cancel local previews.+ if (source === 'remote') cancelShape();+ publishDocument(backend.getDocument());+ emitSession();+ });++ function setPreview(next: Bounds | undefined) {+ preview = next ? Object.freeze(next) : undefined;+ for (const listener of previewListeners) listener(preview);+ }+ function cancelShape() {+ drawing.cancel();+ setPreview(undefined);+ }+ function publishDocument(next: GraphicsDocument) {+ selection.reconcile(next);+ document = Object.freeze(next);+ for (const listener of documentListeners) listener(document);+ }+ /** Replace disposable working data and clear selection, previews and history. */+ function resetDocument(next: GraphicsDocument) {+ if (disposed) return;+ if (backend)+ throw new Error('Reset shared scenes by recreating their backend');+ const validated = freezeDocument(next);+ select();+ undoStack.length = 0;+ redoStack.length = 0;+ publishDocument(validated);+ emitSession();+ }+ function clampPoint(point: Point): Point {+ const surface = document.surface;+ return surface+ ? {+ x: Math.max(0, Math.min(surface.width, point.x)),+ y: Math.max(0, Math.min(surface.height, point.y)),+ }+ : point;+ }+ function updateShape(point: DrawingSample, modifiers: DrawingModifiers = {}) {+ updateDrawing([point], modifiers);+ }+ function updateDrawing(+ samples: readonly DrawingSample[],+ modifiers: DrawingModifiers = {}+ ) {+ if (disposed) return;+ drawing.update(+ samples.map((sample) => ({+ ...sample,+ ...clampPoint(+ drawing.kind() === 'pencil' ? sample : snapPoint(sample, snapUnit)+ ),+ })),+ modifiers+ );+ setPreview(drawing.bounds());+ }+ function getDrawingPreview(appearance: Appearance) {+ return drawing.item(+ 'preview',+ { parentId: document.rootId, sortKey: 'a0' },+ appearance+ );+ }++ function publish(next: Camera) {+ if (disposed || ![next.x, next.y, next.scale].every(Number.isFinite))+ return;+ if (+ next.x === camera.x &&+ next.y === camera.y &&+ next.scale === camera.scale+ )+ return;+ camera = Object.freeze(next);+ cancelShape();+ cancelTransform();+ for (const listener of listeners) listener(camera);+ }++ function beginShape(kind: DrawingKind, point: DrawingSample) {+ if (disposed || !Number.isFinite(point.x) || !Number.isFinite(point.y))+ return false;+ const surface = document.surface;+ if (+ surface &&+ (point.x < 0 ||+ point.y < 0 ||+ point.x > surface.width ||+ point.y > surface.height)+ )+ return false;+ select();+ drawing.begin(+ kind,+ kind === 'pencil' ? point : clampPoint(snapPoint(point, snapUnit)),+ document.surface+ );+ setPreview(drawing.bounds());+ return true;+ }+ function commitShape(id: string, appearance: Appearance, minSize = 0) {+ if (disposed) return false;+ const item = drawing.item(+ id,+ {+ parentId: document.rootId,+ sortKey: keysAt(+ document,+ children(document),+ children(document).length,+ 1+ )[0]!,+ },+ appearance,+ minSize+ );+ cancelShape();+ if (!item) return false;+ if (Object.hasOwn(document.items, id))+ throw new Error(`Duplicate graphics item: ${id}`);+ commitDocument({+ ...document,+ items: Object.freeze({ ...document.items, [id]: item }),+ });+ return true;+ }++ function execute<Payload>(+ command: GraphicsCommand<Payload>,+ payload: Payload+ ) {+ if (disposed) return;+ // Commands replace any pending gesture and always form one history step.+ cancelShape();+ cancelTransform();+ const result = command.apply(+ {+ document,+ selection: selection.getState().selectedIds,+ snapUnit,+ measureText: options.measureText,+ },+ payload+ );+ if (result.document !== document) commitDocument(result.document);+ if (result.selection) selection.selectMany(result.selection);+ }++ return {+ get document() {+ return document;+ },+ getSession,+ getSnapUnit: () => snapUnit,+ setSnapUnit(unit: number | undefined) {+ validateSnapUnit(unit);+ if (disposed || unit === snapUnit) return;+ snapUnit = unit;+ cancelShape();+ cancelTransform();+ },+ resetDocument,+ subscribeSession(listener: (session: EditingSession) => void) {+ if (disposed) return () => {};+ sessionListeners.add(listener);+ return () => {+ sessionListeners.delete(listener);+ };+ },+ select,+ hitTest: (point: Point, deep = false) =>+ hitTest(document, point, deep, 3 / camera.scale),+ groupSelection(id: string) {+ if (disposed) return;+ commitDocument(+ groupNodes(document, selection.getState().selectedIds, id)+ );+ select(id);+ },+ ungroupSelection() {+ if (disposed) return;+ const id = selection.getState().selectedId;+ if (id) commitDocument(ungroupNode(document, id));+ },+ reparent(id: string, parentId: string, position: LayerPosition = 'front') {+ if (disposed) return;+ const next = reparent(document, id, parentId, position);+ if (next !== document) commitDocument(next);+ },+ reorderSelection(operation: LayerOperation) {+ if (disposed) return;+ const next = reorderNodes(+ document,+ selection.getState().selectedIds,+ operation+ );+ if (next !== document) commitDocument(next);+ },+ toggleSelection: selection.toggle,+ beginBoxSelection: selection.beginBox,+ updateBoxSelection: selection.updateBox,+ commitBoxSelection: selection.commitBox,+ beginTransform: selection.beginTransform,+ updateTransform: selection.updateTransform,+ cancelTransform,+ commitTransform: selection.commitTransform,+ deleteSelection: selection.deleteSelection,+ execute,+ setSelectionAppearance: (appearance: Partial<Appearance>) =>+ execute(styleCommand, appearance),+ undo: () => {+ if (disposed) return;+ if (!backend) return travel(undoStack, redoStack, 'before');+ cancelShape();+ cancelTransform();+ backend.undo();+ },+ redo: () => {+ if (disposed) return;+ if (!backend) return travel(redoStack, undoStack, 'after');+ cancelShape();+ cancelTransform();+ backend.redo();+ },+ getPreview: () => preview,+ getDrawingPreview,+ updateDrawing,+ subscribeDocument(listener: (document: GraphicsDocument) => void) {+ if (disposed) return () => {};+ documentListeners.add(listener);+ return () => {+ documentListeners.delete(listener);+ };+ },+ subscribePreview(listener: (preview: Bounds | undefined) => void) {+ if (disposed) return () => {};+ previewListeners.add(listener);+ return () => {+ previewListeners.delete(listener);+ };+ },+ setImageSurface(surface: ImageSurface) {+ resetDocument({ ...createScene(), surface });+ },+ fitScene(viewport: { width: number; height: number }) {+ const bounds = worldBounds(document, document.rootId);+ if (+ bounds.width <= 0 ||+ bounds.height <= 0 ||+ ![viewport.width, viewport.height].every(+ (size) => Number.isFinite(size) && size > 0+ )+ )+ return;+ // Screen-space margins; leave usable room even in a small embedded view.+ const padding = Math.min(100, viewport.width / 4, viewport.height / 4);+ const scale = Math.max(+ MIN_SCALE,+ Math.min(+ MAX_SCALE,+ (viewport.width - padding * 2) / bounds.width,+ (viewport.height - padding * 2) / bounds.height+ )+ );+ publish({+ scale,+ x: (viewport.width - bounds.width * scale) / 2 - bounds.x * scale,+ y: (viewport.height - bounds.height * scale) / 2 - bounds.y * scale,+ });+ },+ fitImage(viewport: { width: number; height: number }) {+ if (document.surface) publish(fitImageCamera(document.surface, viewport));+ },+ centerImage(+ viewport: { width: number; height: number },+ scale = camera.scale+ ) {+ const surface = document.surface;+ if (+ !surface ||+ ![viewport.width, viewport.height, scale].every(Number.isFinite)+ )+ return;+ const boundedScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale));+ publish({+ x: (viewport.width - surface.width * boundedScale) / 2,+ y: (viewport.height - surface.height * boundedScale) / 2,+ scale: boundedScale,+ });+ },+ beginShape,+ updateShape,+ cancelShape,+ commitShape,+ getDrawingKind: drawing.kind,+ // Convenience operations for the rectangle-only image markup host.+ beginRectangle: (point: Point) => beginShape('rectangle', point),+ updateRectangle: updateShape,+ cancelRectangle: cancelShape,+ commitRectangle: commitShape,+ clearRectangles() {+ if (disposed || !drawableIds(document).length) return;+ select();+ commitDocument({+ ...document,+ items: { [document.rootId]: { id: document.rootId, type: 'surface' } },+ });+ },+ getCamera: () => camera,+ subscribeCamera(listener: (camera: Camera) => void) {+ if (disposed) return () => {};+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ panBy(delta: Point) {+ publish({ ...camera, x: camera.x + delta.x, y: camera.y + delta.y });+ },+ zoomAt(anchor: Point, scale: number) {+ publish(zoomAt(camera, anchor, scale));+ },+ resetCamera() {+ publish(INITIAL_CAMERA);+ },+ dispose() {+ disposed = true;+ detachBackend?.();+ listeners.clear();+ documentListeners.clear();+ previewListeners.clear();+ sessionListeners.clear();+ undoStack.length = 0;+ redoStack.length = 0;+ selection.dispose();+ drawing.cancel();+ preview = undefined;+ },+ };+}diff --git a/packages/graphics/src/core/fragments.ts b/packages/graphics/src/core/fragments.tsnew file mode 100644index 0000000000..693a833099--- /dev/null+++ b/packages/graphics/src/core/fragments.ts@@ -0,0 +1,212 @@+import { inverse, multiply, translation } from './affine';+import { retainConnectorBindings } from './connectors';+import type { GraphicsDocument, GraphicsItem, Point } from './model';+import { keysAt, sortKeysBetween } from './ordering';+import {+ children,+ freezeDocument,+ paintOrder,+ roots,+ worldMatrix,+} from './scene';+import type { ConnectorEndpoint } from './shapes/connector';++/** A standalone scene whose selected roots have world-space transforms. */+export type GraphicsFragment = Readonly<{+ kind: 'macro-graphics-fragment';+ scene: GraphicsDocument;+}>;+export type IdFactory = () => string;++export function copyFragment(+ document: GraphicsDocument,+ selection: readonly string[]+): GraphicsFragment | undefined {+ const targets = new Set(roots(document, selection));+ const ordered = paintOrder(document).filter((id) => targets.has(id));+ if (!ordered.length) return;+ const scene: GraphicsDocument = {+ rootId: document.rootId,+ items: { [document.rootId]: { id: document.rootId, type: 'surface' } },+ };+ const items: Record<string, GraphicsItem> = Object.assign(+ Object.create(null),+ scene.items+ );+ const keys = sortKeysBetween(null, null, ordered.length);+ const visit = (id: string, rootIndex?: number) => {+ const node = document.items[id]!;+ if (node.type === 'surface') return;+ items[id] =+ rootIndex === undefined+ ? node+ : {+ ...node,+ placement: { parentId: scene.rootId, sortKey: keys[rootIndex]! },+ transform: worldMatrix(document, id),+ };+ children(document, id).forEach((child) => visit(child));+ };+ ordered.forEach(visit);+ const retained = new Set(Object.keys(items));+ for (const id of retained) {+ const source = document.items[id];+ const copied = items[id];+ if (source?.type === 'connector' && copied?.type === 'connector')+ items[id] = {+ ...copied,+ geometry: retainConnectorBindings(document, source, retained).geometry,+ };+ }+ return {+ kind: 'macro-graphics-fragment',+ scene: freezeDocument({ ...scene, items }),+ };+}++export function parseFragment(text: string): GraphicsFragment | undefined {+ // Clipboard input is untrusted and deliberately bounded. No document migration.+ if (text.length > 2_000_000) return;+ try {+ const value = JSON.parse(text);+ if (+ value?.kind !== 'macro-graphics-fragment' ||+ !value.scene?.items ||+ Object.keys(value.scene.items).length > 5000+ )+ return;+ const scene = freezeDocument(value.scene);+ if (scene.surface || !children(scene).length) return;+ return { kind: 'macro-graphics-fragment', scene };+ } catch {+ return;+ }+}++export function pasteFragment(+ document: GraphicsDocument,+ fragment: GraphicsFragment,+ createId: IdFactory,+ offset: Point = { x: 24, y: 24 },+ parentId = document.rootId+) {+ const source = freezeDocument(fragment.scene);+ const parent = document.items[parentId];+ if (!parent || (parent.type !== 'group' && parent.type !== 'surface'))+ throw new Error('Invalid paste parent');+ const ids = paintOrder(source);+ const remap = new Map<string, string>();+ const allocated = new Set(Object.keys(document.items));+ for (const id of ids) {+ const next = createId();+ if (!next || allocated.has(next)) throw new Error('Duplicate graphics ID');+ allocated.add(next);+ remap.set(id, next);+ }+ const top = children(source);+ const keys = keysAt(+ document,+ children(document, parentId),+ children(document, parentId).length,+ top.length+ );+ const items: Record<string, GraphicsItem> = Object.assign(+ Object.create(null),+ document.items+ );+ for (const id of ids) {+ const node = source.items[id]!;+ if (node.type === 'surface') continue;+ const index = top.indexOf(id);+ const newId = remap.get(id)!;+ const mapped =+ node.type === 'connector'+ ? {+ ...node,+ geometry: {+ ...node.geometry,+ start: remapEndpoint(node.geometry.start, remap),+ end: remapEndpoint(node.geometry.end, remap),+ },+ }+ : node;+ items[newId] = {+ ...mapped,+ id: newId,+ placement: {+ parentId: index < 0 ? remap.get(node.placement.parentId)! : parentId,+ sortKey: index < 0 ? node.placement.sortKey : keys[index]!,+ },+ transform:+ index < 0+ ? node.transform+ : multiply(+ inverse(worldMatrix(document, parentId)),+ multiply(translation(offset.x, offset.y), node.transform)+ ),+ };+ }+ return {+ document: freezeDocument({ ...document, items }),+ selection: top.map((id) => remap.get(id)!),+ idMap: remap,+ };+}++function remapEndpoint(+ end: ConnectorEndpoint,+ ids: ReadonlyMap<string, string>+): ConnectorEndpoint {+ return end.binding && ids.has(end.binding.targetId)+ ? {+ ...end,+ binding: { ...end.binding, targetId: ids.get(end.binding.targetId)! },+ }+ : {+ point: end.point,+ ...(end.direction ? { direction: end.direction } : {}),+ };+}+/** Duplicate each selected subtree in its existing parent, above its siblings. */+export function duplicateNodes(+ document: GraphicsDocument,+ selection: readonly string[],+ createId: IdFactory,+ offset: Point = { x: 24, y: 24 }+) {+ const parents = new Map<string, string[]>();+ for (const id of roots(document, selection)) {+ const node = document.items[id]!;+ if (node.type === 'surface') continue;+ const ids = parents.get(node.placement.parentId) ?? [];+ ids.push(id);+ parents.set(node.placement.parentId, ids);+ }+ let next = document;+ const selected: string[] = [];+ const remapped = new Map<string, string>();+ for (const [parentId, ids] of parents) {+ const fragment = copyFragment(document, ids)!;+ const result = pasteFragment(next, fragment, createId, offset, parentId);+ next = result.document;+ for (const [source, copy] of result.idMap) remapped.set(source, copy);+ selected.push(...result.selection);+ }+ const items = { ...next.items },+ retained = new Set(remapped.keys());+ for (const [sourceId, copyId] of remapped) {+ const source = document.items[sourceId],+ copy = items[copyId];+ if (source?.type !== 'connector' || copy?.type !== 'connector') continue;+ const g = retainConnectorBindings(document, source, retained).geometry;+ items[copyId] = {+ ...copy,+ geometry: {+ ...g,+ start: remapEndpoint(g.start, remapped),+ end: remapEndpoint(g.end, remapped),+ },+ };+ }+ return { document: freezeDocument({ ...next, items }), selection: selected };+}diff --git a/packages/graphics/src/core/history.ts b/packages/graphics/src/core/history.tsnew file mode 100644index 0000000000..7874e5cc8a--- /dev/null+++ b/packages/graphics/src/core/history.ts@@ -0,0 +1,61 @@+import type { GraphicsDocument, GraphicsItem } from './model';++type Change<T> = Readonly<{ before: T; after: T }>;++/** Local-only history. Entries retain changed immutable items, never documents. */+export type DocumentDelta = Readonly<{+ items: readonly Readonly<{ id: string } & Change<GraphicsItem | undefined>>[];+ rootId?: Change<string>;+ surface?: Change<GraphicsDocument['surface']>;+}>;++/** Both documents must have passed freezeDocument before recording history. */+export function documentDelta(+ before: GraphicsDocument,+ after: GraphicsDocument+): DocumentDelta | undefined {+ const items: DocumentDelta['items'][number][] = [];+ for (const id of Object.keys(before.items)) {+ if (before.items[id] !== after.items[id])+ items.push({ id, before: before.items[id], after: after.items[id] });+ }+ for (const id of Object.keys(after.items)) {+ if (!Object.hasOwn(before.items, id))+ items.push({ id, before: undefined, after: after.items[id] });+ }+ const rootId =+ before.rootId !== after.rootId+ ? { before: before.rootId, after: after.rootId }+ : undefined;+ const surface =+ before.surface?.id !== after.surface?.id ||+ before.surface?.width !== after.surface?.width ||+ before.surface?.height !== after.surface?.height+ ? { before: before.surface, after: after.surface }+ : undefined;+ if (!items.length && !rootId && !surface) return;+ return { items, rootId, surface };+}++/** Apply an entire committed transaction atomically, retaining item identities. */+export function applyDocumentDelta(+ document: GraphicsDocument,+ delta: DocumentDelta,+ direction: 'before' | 'after'+): GraphicsDocument {+ const items: Record<string, GraphicsItem> = Object.assign(+ Object.create(null),+ document.items+ );+ for (const change of delta.items) {+ const item = change[direction];+ if (item) items[change.id] = item;+ else delete items[change.id];+ }+ const surface = delta.surface ? delta.surface[direction] : document.surface;+ return Object.freeze({+ rootId: delta.rootId ? delta.rootId[direction] : document.rootId,+ items: Object.freeze(items),+ ...(surface ? { surface } : {}),+ });+}diff --git a/packages/graphics/src/core/index.ts b/packages/graphics/src/core/index.tsnew file mode 100644index 0000000000..0ee4424678--- /dev/null+++ b/packages/graphics/src/core/index.ts@@ -0,0 +1,124 @@+export * from './affine';+export { resolveAppearance } from './appearance';+export type { GraphicsBackend } from './backend';+export {+ fitImageCamera,+ INITIAL_CAMERA,+ MAX_SCALE,+ MIN_SCALE,+ screenToWorld,+ worldToScreen,+ zoomAt,+} from './camera';+export * from './commands';+export * from './connector-commands';+export {+ type ConnectorGesture,+ createConnectorInteraction,+} from './connector-interaction';+export * from './connectors';+export { dotGridLevels } from './dot-grid';+export type { DrawingKind, DrawingModifiers, DrawingSample } from './drawing';+export {+ createGraphicsEditor,+ createGraphicsEditorFromBackend,+ type EditingSession,+ type GraphicsEditor,+ type GraphicsEditorOptions,+} from './editor';+export * from './fragments';+export * from './insert';+export { type LayerOperation, reorderNodes } from './layering';+export { fullyConnected, layoutBounds, layoutRoots } from './layout';+export type {+ Appearance,+ Bounds,+ Camera,+ EllipseItem,+ GraphicsDocument,+ GraphicsItem,+ GroupItem,+ ImageSurface,+ PencilItem,+ Placement,+ Point,+ RectangleItem,+ ShapeGeometryMap,+ ShapeItem,+ ShapeKind,+ SurfaceItem,+} from './model';+export {+ isSortKey,+ type LayerPosition,+ type SortKey,+ sortKeysBetween,+} from './ordering';+export * from './radius';+export * from './rich-text';+export * from './scene';+export type { TransformHandle, TransformModifiers } from './selection';+export {+ createSelection,+ type ResizeCorner,+ type ResizeEdge,+ type ResizeHandle,+ type ResizeModifiers,+ type SelectionHost,+ type SelectionState,+} from './selection';+export {+ type SelectionFrame,+ selectionContainsPoint,+ selectionFrame,+} from './selection-frame';+export {+ type ConnectorAnchor,+ type ConnectorBinding,+ type ConnectorEndpoint,+ type ConnectorGeometry,+ connectorAnchors,+ connectorDefinition,+} from './shapes/connector';+export {+ type ConnectorHead,+ type ConnectorRoute,+ connectorHead,+ connectorPath,+} from './shapes/connector-routing';+export type { HitTestContext, ShapeDefinition } from './shapes/definition';+export { ellipseDefinition } from './shapes/ellipse';+export * from './shapes/embedded';+export {+ canLabel,+ type LabelShape,+ measureShapeLabel,+ type ShapeLabel,+ shapeLabelLayout,+ shapeLabelText,+ withShapeLabel,+} from './shapes/label';+export {+ type PencilGeometry,+ type PencilPoint,+ pencilDefinition,+} from './shapes/pencil';+export { rectangleDefinition } from './shapes/rectangle';+export {+ isShape,+ isShapeKind,+ shapeDefinition,+ shapeDefinitions,+ shapeKinds,+} from './shapes/registry';+export {+ type TextFont,+ type TextGeometry,+ type TextMeasurer,+ textDefinition,+} from './shapes/text';+export { snapPoint, snapTranslation, snapValue } from './snapping';+export { regenerateScaledShapes, stretchShapes } from './stretch';+export { selectedShapeIds } from './style-selection';+export * from './text-commands';+export { textTargetAt } from './text-target';diff --git a/packages/graphics/src/core/insert.ts b/packages/graphics/src/core/insert.tsnew file mode 100644index 0000000000..d4bf5ccbfb--- /dev/null+++ b/packages/graphics/src/core/insert.ts@@ -0,0 +1,43 @@+import { translation } from './affine';+import type { GraphicsCommand } from './commands';+import type { Point, ShapeItem } from './model';+import { sortKeysBetween } from './ordering';+import { children } from './scene';+import { snapPoint } from './snapping';++type NewShape = {+ [K in ShapeItem['type']]: Pick<+ ShapeItem<K>,+ 'id' | 'type' | 'geometry' | 'appearance'+ >;+}[ShapeItem['type']];+/** Insert a batch as one history entry, assigning durable sibling order in core. */+export const insertShapesCommand: GraphicsCommand<+ readonly { item: NewShape; point: Point }[]+> = {+ id: 'insert-shapes',+ apply: ({ document, snapUnit }, entries) => {+ if (!entries.length) return { document };+ const siblings = children(document),+ last = document.items[siblings[siblings.length - 1]!];+ const keys = sortKeysBetween(+ last && last.type !== 'surface' ? last.placement.sortKey : null,+ null,+ entries.length+ );+ const items = { ...document.items };+ entries.forEach(({ item, point }, index) => {+ if (items[item.id]) throw new Error('Shape id already exists');+ const position = snapPoint(point, snapUnit);+ items[item.id] = {+ ...item,+ placement: { parentId: document.rootId, sortKey: keys[index]! },+ transform: translation(position.x, position.y),+ };+ });+ return {+ document: { ...document, items },+ selection: entries.map(({ item }) => item.id),+ };+ },+};diff --git a/packages/graphics/src/core/layering.ts b/packages/graphics/src/core/layering.tsnew file mode 100644index 0000000000..c4a4357f15--- /dev/null+++ b/packages/graphics/src/core/layering.ts@@ -0,0 +1,66 @@+import type { GraphicsDocument, GraphicsItem } from './model';+import { children, keysAt } from './ordering';+import { freezeDocument, roots } from './scene';++export type LayerOperation = 'front' | 'back' | 'forward' | 'backward';++/** Reorder selected roots within each parent, retaining their relative order. */+export function reorderNodes(+ doc: GraphicsDocument,+ ids: readonly string[],+ operation: LayerOperation+): GraphicsDocument {+ const selected = new Set(roots(doc, ids));+ const parents = new Set<string>();+ for (const id of selected) {+ const node = doc.items[id];+ if (node && node.type !== 'surface') parents.add(node.placement.parentId);+ }+ const changes: Record<string, GraphicsItem> = Object.create(null);+ for (const parentId of parents) {+ const before = children(doc, parentId);+ let after = [...before];+ if (operation === 'front' || operation === 'back') {+ const moving = before.filter((id) => selected.has(id));+ const staying = before.filter((id) => !selected.has(id));+ after =+ operation === 'front'+ ? [...staying, ...moving]+ : [...moving, ...staying];+ } else if (operation === 'forward') {+ for (let i = after.length - 2; i >= 0; i--) {+ if (selected.has(after[i]!) && !selected.has(after[i + 1]!))+ [after[i], after[i + 1]] = [after[i + 1]!, after[i]!];+ }+ } else {+ for (let i = 1; i < after.length; i++) {+ if (selected.has(after[i]!) && !selected.has(after[i - 1]!))+ [after[i], after[i - 1]] = [after[i - 1]!, after[i]!];+ }+ }+ const moved = new Set(+ after.filter((id, index) => selected.has(id) && before[index] !== id)+ );+ // Allocate between stationary neighbors, touching only moved nodes.+ for (let start = 0; start < after.length; start++) {+ if (!moved.has(after[start]!)) continue;+ let end = start + 1;+ while (end < after.length && moved.has(after[end]!)) end++;+ const surrounding = [...after.slice(0, start), ...after.slice(end)];+ const keys = keysAt(doc, surrounding, start, end - start);+ for (let i = start; i < end; i++) {+ const id = after[i]!,+ node = doc.items[id];+ if (node && node.type !== 'surface')+ changes[id] = {+ ...node,+ placement: { ...node.placement, sortKey: keys[i - start]! },+ };+ }+ start = end - 1;+ }+ }+ return Object.keys(changes).length+ ? freezeDocument({ ...doc, items: { ...doc.items, ...changes } })+ : doc;+}diff --git a/packages/graphics/src/core/layout.ts b/packages/graphics/src/core/layout.tsnew file mode 100644index 0000000000..4a4b258b63--- /dev/null+++ b/packages/graphics/src/core/layout.ts@@ -0,0 +1,40 @@+import { enclosing } from './affine';+import type { GraphicsDocument } from './model';+import { children, nodeBoundsPoints, roots } from './scene';+import { isShape } from './shapes/registry';++export function fullyConnected(doc: GraphicsDocument, id: string): boolean {+ const item = doc.items[id];+ return (+ item?.type === 'connector' &&+ !!item.geometry.start.binding &&+ !!item.geometry.end.binding &&+ isShape(doc.items[item.geometry.start.binding.targetId]) &&+ isShape(doc.items[item.geometry.end.binding.targetId])+ );+}+function layoutCorners(+ doc: GraphicsDocument,+ id: string+): ReturnType<typeof nodeBoundsPoints> {+ if (fullyConnected(doc, id)) return [];+ return isShape(doc.items[id])+ ? nodeBoundsPoints(doc, id)+ : children(doc, id).flatMap((child) => layoutCorners(doc, child));+}+export function layoutBounds(doc: GraphicsDocument, id: string) {+ return enclosing(layoutCorners(doc, id));+}+function hasLayoutShape(doc: GraphicsDocument, id: string): boolean {+ if (fullyConnected(doc, id)) return false;+ return (+ isShape(doc.items[id]) ||+ children(doc, id).some((child) => hasLayoutShape(doc, child))+ );+}+export function layoutRoots(+ doc: GraphicsDocument,+ selection: readonly string[]+) {+ return roots(doc, selection).filter((id) => hasLayoutShape(doc, id));+}diff --git a/packages/graphics/src/core/model.ts b/packages/graphics/src/core/model.tsnew file mode 100644index 0000000000..8af3cdabbe--- /dev/null+++ b/packages/graphics/src/core/model.ts@@ -0,0 +1,67 @@+import type { Matrix } from './affine';+import type { SortKey } from './ordering';+import type { ConnectorGeometry } from './shapes/connector';+import type { EllipseGeometry } from './shapes/ellipse';+import type { DocumentGeometry, MediaGeometry } from './shapes/embedded';+import type { PencilGeometry } from './shapes/pencil';+import type { RectangleGeometry } from './shapes/rectangle';+import type { TextGeometry } from './shapes/text';++export type Point = Readonly<{ x: number; y: number }>;+export type Camera = Readonly<{ x: number; y: number; scale: number }>;+export type Bounds = Readonly<{+ x: number;+ y: number;+ width: number;+ height: number;+}>;+export type Placement = Readonly<{ parentId: string; sortKey: SortKey }>;+type SpatialNode = Readonly<{+ id: string;+ placement: Placement;+ transform: Matrix;+}>;+/** Compile-time composition point; no declaration merging or global mutation. */+export type ShapeGeometryMap = {+ connector: ConnectorGeometry;+ rectangle: RectangleGeometry;+ ellipse: EllipseGeometry;+ pencil: PencilGeometry;+ text: TextGeometry;+ image: MediaGeometry;+ video: MediaGeometry;+ document: DocumentGeometry;+};+export type ShapeKind = keyof ShapeGeometryMap;+export type Appearance = Readonly<{+ fill: string;+ stroke: string;+ strokeWidth?: number;+ strokeStyle?: 'solid' | 'dashed' | 'dotted';+ opacity?: number;+ cornerRadius?: number;+}>;+export type ShapeItem<K extends ShapeKind = ShapeKind> = {+ [P in K]: SpatialNode &+ Readonly<{+ type: P;+ geometry: ShapeGeometryMap[P];+ appearance: Appearance;+ }>;+}[K];+export type RectangleItem = ShapeItem<'rectangle'>;+export type EllipseItem = ShapeItem<'ellipse'>;+export type PencilItem = ShapeItem<'pencil'>;+export type GroupItem = SpatialNode & Readonly<{ type: 'group' }>;+export type SurfaceItem = Readonly<{ id: string; type: 'surface' }>;+export type GraphicsItem = ShapeItem | GroupItem | SurfaceItem;+export type ImageSurface = Readonly<{+ id: string;+ width: number;+ height: number;+}>;+export type GraphicsDocument = Readonly<{+ rootId: string;+ items: Readonly<Record<string, GraphicsItem>>;+ surface?: ImageSurface;+}>;diff --git a/packages/graphics/src/core/ordering.ts b/packages/graphics/src/core/ordering.tsnew file mode 100644index 0000000000..bba0eeeb48--- /dev/null+++ b/packages/graphics/src/core/ordering.ts@@ -0,0 +1,117 @@+import { generateKeyBetween, generateNKeysBetween } from 'fractional-indexing';+import type { GraphicsDocument } from './model';++/** Persisted, case-sensitive fractional index. Allocate through these helpers. */+export type SortKey = string;+export type LayerPosition =+ | 'back'+ | 'front'+ | Readonly<{ before: string }>+ | Readonly<{ after: string }>;++export function isSortKey(value: unknown): value is SortKey {+ if (typeof value !== 'string' || !/^[A-Za-z][0-9A-Za-z]+$/.test(value))+ return false;+ try {+ generateKeyBetween(value, null);+ return true;+ } catch {+ return false;+ }+}++export function sortKeysBetween(+ lower: SortKey | null,+ upper: SortKey | null,+ count: number+): readonly SortKey[] {+ if (+ !Number.isSafeInteger(count) ||+ count < 0 ||+ (lower !== null && !isSortKey(lower)) ||+ (upper !== null && !isSortKey(upper)) ||+ (lower !== null && upper !== null && lower >= upper)+ )+ throw new Error('Invalid sort key interval');+ return generateNKeysBetween(lower, upper, count);+}++const childIndexes = new WeakMap<+ GraphicsDocument['items'],+ ReadonlyMap<string, readonly string[]>+>();+const noChildren: readonly string[] = Object.freeze([]);++export function children(+ doc: GraphicsDocument,+ parentId = doc.rootId+): readonly string[] {+ // Only immutable snapshots can be indexed. Mutable editor/host projections+ // must continue reading their nodes so changes and reactive dependencies survive.+ let index = childIndexes.get(doc.items);+ if (!index) {+ const groups = new Map<string, string[]>();+ for (const node of Object.values(doc.items)) {+ if (node.type === 'surface') continue;+ let siblings = groups.get(node.placement.parentId);+ if (!siblings) {+ siblings = [];+ groups.set(node.placement.parentId, siblings);+ }+ siblings.push(node.id);+ }+ for (const siblings of groups.values()) {+ siblings.sort((a, b) => {+ const left = nodeSortKey(doc, a)!,+ right = nodeSortKey(doc, b)!;+ return left < right+ ? -1+ : left > right+ ? 1+ : a < b+ ? -1+ : a > b+ ? 1+ : 0;+ });+ Object.freeze(siblings);+ }+ index = groups;+ if (Object.isFrozen(doc.items)) childIndexes.set(doc.items, index);+ }+ return index.get(parentId) ?? noChildren;+}++export function nodeSortKey(+ doc: GraphicsDocument,+ id?: string+): SortKey | null {+ const node = id === undefined ? undefined : doc.items[id];+ return node && node.type !== 'surface' ? node.placement.sortKey : null;+}++export function insertionIndex(+ siblings: readonly string[],+ position: LayerPosition+): number {+ if (position === 'front') return siblings.length;+ if (position === 'back') return 0;+ const index = siblings.indexOf(+ 'before' in position ? position.before : position.after+ );+ if (index < 0) throw new Error('Layer anchor must be an unselected sibling');+ return index + ('after' in position ? 1 : 0);+}++export function keysAt(+ doc: GraphicsDocument,+ siblings: readonly string[],+ index: number,+ count: number+): readonly SortKey[] {+ return sortKeysBetween(+ nodeSortKey(doc, siblings[index - 1]),+ nodeSortKey(doc, siblings[index]),+ count+ );+}diff --git a/packages/graphics/src/core/radius.ts b/packages/graphics/src/core/radius.tsnew file mode 100644index 0000000000..ca9e9fc588--- /dev/null+++ b/packages/graphics/src/core/radius.ts@@ -0,0 +1,69 @@+import { inverse, type Matrix, transformPoint } from './affine';+import type { Point, RectangleItem } from './model';++export const radiusHandles = [+ 'radius-nw',+ 'radius-ne',+ 'radius-se',+ 'radius-sw',+] as const;+export type RadiusHandle = (typeof radiusHandles)[number];+export const isRadiusHandle = (+ value: string | undefined | null+): value is RadiusHandle => radiusHandles.some((handle) => handle === value);++export const rectangleRadius = (item: RectangleItem) =>+ Math.min(+ item.appearance.cornerRadius ?? 0,+ item.geometry.width / 2,+ item.geometry.height / 2+ );++export function radiusHandlePoint(+ item: RectangleItem,+ handle: RadiusHandle,+ inset: Point = { x: 0, y: 0 }+): Point {+ const radius = rectangleRadius(item);+ const x = Math.min(item.geometry.width / 2, Math.max(radius, inset.x));+ const y = Math.min(item.geometry.height / 2, Math.max(radius, inset.y));+ return {+ x: handle.endsWith('w') ? x : item.geometry.width - x,+ y:+ handle === 'radius-nw' || handle === 'radius-ne'+ ? y+ : item.geometry.height - y,+ };+}++/** Radius uses whole local pixels, independent of the scene's snapping policy. */+export function dragRectangleRadius(+ item: RectangleItem,+ world: Matrix,+ handle: RadiusHandle,+ origin: Point,+ point: Point+): RectangleItem {+ const fromWorld = inverse(world);+ const start = transformPoint(fromWorld, origin);+ const end = transformPoint(fromWorld, point);+ const dx = (end.x - start.x) * (handle.endsWith('w') ? 1 : -1);+ const dy =+ (end.y - start.y) *+ (handle === 'radius-nw' || handle === 'radius-ne' ? 1 : -1);+ // Clicking a handle must not round an existing fractional or oversized value.+ if (Math.abs(dx + dy) < 1e-9) return item;+ const cornerRadius = Math.max(+ 0,+ Math.min(+ Math.floor(Math.min(item.geometry.width, item.geometry.height) / 2),+ Math.round(rectangleRadius(item) + (dx + dy) / 2)+ )+ );+ return cornerRadius === (item.appearance.cornerRadius ?? 0)+ ? item+ : {+ ...item,+ appearance: Object.freeze({ ...item.appearance, cornerRadius }),+ };+}diff --git a/packages/graphics/src/core/resize.ts b/packages/graphics/src/core/resize.tsnew file mode 100644index 0000000000..3b8a80eda1--- /dev/null+++ b/packages/graphics/src/core/resize.ts@@ -0,0 +1,126 @@+import { around, type Matrix, scaling } from './affine';+import type { Bounds, Point } from './model';+import { snapValue } from './snapping';++export type ResizeCorner = 'nw' | 'ne' | 'sw' | 'se';+export type ResizeEdge = 'n' | 'e' | 's' | 'w';+export type ResizeHandle = ResizeCorner | ResizeEdge;+export const resizeHandles: readonly ResizeHandle[] = [+ 'nw',+ 'ne',+ 'se',+ 'sw',+ 'n',+ 'e',+ 's',+ 'w',+];+export const isResizeHandle = (value: unknown): value is ResizeHandle =>+ resizeHandles.some((handle) => handle === value);+export const isResizeEdge = (handle: ResizeHandle): handle is ResizeEdge =>+ handle.length === 1;+export type ResizeModifiers = Readonly<{+ proportional?: boolean;+ fromCenter?: boolean;+}>;++/** Resize in the shape's local axes, always relative to the gesture's start.+ * Pointer delta preserves an off-center handle grab. Modifier changes recompute+ * from the original bounds so toggling them never accumulates drift.+ */+export function resizeBox(+ bounds: Bounds,+ handle: ResizeHandle,+ delta: Point,+ modifiers: ResizeModifiers & {+ proportionalFit?: 'project';+ /** Snap intervals along the frame's axes, accounting for its world scale. */+ snap?: Point;+ }+): Readonly<{+ bounds: Bounds;+ transform: Matrix;+ scaleX: number;+ scaleY: number;+}> {+ const divisor = modifiers.fromCenter ? 2 : 1;+ const horizontal = handle.includes('w') || handle.includes('e');+ const vertical = handle.includes('n') || handle.includes('s');+ const signX = handle.endsWith('w') ? -1 : 1;+ const signY = handle.startsWith('n') ? -1 : 1;+ const extentX = bounds.width / divisor;+ const extentY = bounds.height / divisor;+ const anchor = modifiers.fromCenter+ ? { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 }+ : {+ x:+ bounds.x ++ (!horizontal ? bounds.width / 2 : signX < 0 ? bounds.width : 0),+ y:+ bounds.y ++ (!vertical ? bounds.height / 2 : signY < 0 ? bounds.height : 0),+ };+ let sx = horizontal ? 1 + (signX * delta.x) / extentX : 1;+ let sy = vertical ? 1 + (signY * delta.y) / extentY : 1;+ if (modifiers.proportional) {+ let factor = !vertical+ ? Math.abs(sx)+ : !horizontal+ ? Math.abs(sy)+ : modifiers.proportionalFit === 'project'+ ? // Closest point on the aspect-ratio diagonal. Short text boxes must+ // not amplify a small vertical pointer movement into a huge scale.+ (Math.abs(sx) * extentX ** 2 + Math.abs(sy) * extentY ** 2) /+ (extentX ** 2 + extentY ** 2)+ : Math.max(Math.abs(sx), Math.abs(sy));+ if (modifiers.snap && (delta.x !== 0 || delta.y !== 0)) {+ const useX = horizontal && (!vertical || Math.abs(sx) >= Math.abs(sy));+ const size = useX ? bounds.width : bounds.height;+ const unit = useX ? modifiers.snap.x : modifiers.snap.y;+ factor = Math.max(unit, snapValue(size * factor, unit)) / size;+ }+ sx = (sx < 0 ? -1 : 1) * factor;+ sy = (sy < 0 ? -1 : 1) * factor;+ } else if (modifiers.snap) {+ const snapScale = (scale: number, size: number, unit: number) =>+ ((scale < 0 ? -1 : 1) *+ Math.max(unit, snapValue(Math.abs(scale) * size, unit))) /+ size;+ if (horizontal && delta.x !== 0)+ sx = snapScale(sx, bounds.width, modifiers.snap.x);+ if (vertical && delta.y !== 0)+ sy = snapScale(sy, bounds.height, modifiers.snap.y);+ }+ // Retain the sign through the opposite edge. Only exact collapse needs a tiny+ // nonzero extent so the scene's transforms stay invertible during the gesture.+ sx = (sx < 0 ? -1 : 1) * Math.max(1e-6, Math.abs(sx));+ sy = (sy < 0 ? -1 : 1) * Math.max(1e-6, Math.abs(sy));+ const dx = signX * extentX * sx;+ const dy = signY * extentY * sy;+ const width = Math.abs(dx) * divisor;+ const height = Math.abs(dy) * divisor;+ return {+ transform: around(anchor, scaling(sx, sy)),+ scaleX: sx,+ scaleY: sy,+ bounds: {+ x:+ modifiers.fromCenter || !horizontal+ ? anchor.x - width / 2+ : Math.min(anchor.x, anchor.x + dx),+ y:+ modifiers.fromCenter || !vertical+ ? anchor.y - height / 2+ : Math.min(anchor.y, anchor.y + dy),+ width,+ height,+ },+ };+}++export const resizeBounds = (+ bounds: Bounds,+ handle: ResizeHandle,+ delta: Point,+ modifiers: ResizeModifiers+) => resizeBox(bounds, handle, delta, modifiers).bounds;diff --git a/packages/graphics/src/core/rich-text.ts b/packages/graphics/src/core/rich-text.tsnew file mode 100644index 0000000000..d49be5877a--- /dev/null+++ b/packages/graphics/src/core/rich-text.ts@@ -0,0 +1,8 @@+/** Host-defined text content. Graphics stores this string verbatim and never+ * interprets its format; the host owns validation, editing and rendering. */+export type RichText = string;++/** Bound stored payloads without imposing an editor schema or empty-text policy. */+export function validRichText(value: unknown): value is RichText {+ return typeof value === 'string' && value.length <= 2_000_000;+}diff --git a/packages/graphics/src/core/scene.ts b/packages/graphics/src/core/scene.tsnew file mode 100644index 0000000000..5f357fdfd1--- /dev/null+++ b/packages/graphics/src/core/scene.ts@@ -0,0 +1,550 @@+import {+ corners,+ enclosing,+ IDENTITY,+ inverse,+ type Matrix,+ multiply,+ transformPoint,+} from './affine';+import { resolveAppearance, validAppearance } from './appearance';+import {+ connectorWorldView,+ resolveConnector,+ retainConnectorBindings,+} from './connectors';+import type {+ Bounds,+ GraphicsDocument,+ GraphicsItem,+ Point,+ ShapeKind,+} from './model';+import {+ children,+ insertionIndex,+ isSortKey,+ keysAt,+ type LayerPosition,+} from './ordering';+import { isShape, shapeDefinition } from './shapes/registry';++export type SceneOverrides = Readonly<Record<string, GraphicsItem>>;+export { children } from './ordering';++const paintOrders = new WeakMap<GraphicsDocument['items'], readonly string[]>();+export function paintOrder(doc: GraphicsDocument): readonly string[] {+ const cached = paintOrders.get(doc.items);+ if (cached) return cached;+ const result: string[] = [];+ const visit = (id: string) => {+ for (const child of children(doc, id)) {+ result.push(child);+ if (!isShape(doc.items[child])) visit(child);+ }+ };+ visit(doc.rootId);+ // Bound connectors cannot be obscured by either endpoint, even when those+ // endpoints live in different groups or have just been reordered.+ const positions = new Map(result.map((id, index) => [id, index]));+ const above = new Map<number, string[]>();+ const deferred = new Set<string>();+ result.forEach((id, index) => {+ const item = doc.items[id];+ if (item?.type !== 'connector') return;+ const targets = [+ item.geometry.start.binding,+ item.geometry.end.binding,+ ].flatMap((binding) =>+ binding && isShape(doc.items[binding.targetId])+ ? [positions.get(binding.targetId)!]+ : []+ );+ if (!targets.length) return;+ const rank = Math.max(index, ...targets);+ const bucket = above.get(rank) ?? [];+ bucket.push(id);+ above.set(rank, bucket);+ deferred.add(id);+ });+ const ordered = deferred.size+ ? result.flatMap((id, index) => [+ ...(deferred.has(id) ? [] : [id]),+ ...(above.get(index) ?? []),+ ])+ : result;+ Object.freeze(ordered);+ if (Object.isFrozen(doc.items)) paintOrders.set(doc.items, ordered);+ return ordered;+}+export const drawableIds = (doc: GraphicsDocument) =>+ paintOrder(doc).filter((id) => isShape(doc.items[id]));+export function worldMatrix(+ doc: GraphicsDocument,+ id: string,+ overrides: SceneOverrides = {}+): Matrix {+ const node = Object.hasOwn(overrides, id) ? overrides[id] : doc.items[id];+ if (!node) throw new Error(`Missing node: ${id}`);+ return node.type === 'surface'+ ? IDENTITY+ : multiply(+ worldMatrix(doc, node.placement.parentId, overrides),+ node.transform+ );+}+/** Geometry projection for scene-dependent features such as bound connectors. */+export function resolvedShape(+ doc: GraphicsDocument,+ id: string,+ overrides: SceneOverrides = {}+) {+ const node = overrides[id] ?? doc.items[id];+ if (!isShape(node)) return;+ return node.type === 'connector'+ ? resolveConnector(doc, node, overrides)+ : node;+}+/** Geometry and frame shared by drawing, selection bounds, and picking. */+export function shapeProjection(+ doc: GraphicsDocument,+ id: string,+ overrides: SceneOverrides = {}+) {+ const item = resolvedShape(doc, id, overrides);+ const transform = worldMatrix(doc, id, overrides);+ if (+ item?.type === 'connector' &&+ (item.geometry.start.binding || item.geometry.end.binding)+ ) {+ return { item: connectorWorldView(item, transform), transform: IDENTITY };+ }+ return { item, transform };+}+export function nodeCorners(+ doc: GraphicsDocument,+ id: string,+ overrides: SceneOverrides = {}+): readonly Point[] {+ return projectedBoundsPoints(doc, id, overrides, false);+}+/** World-space points enclosing actual geometry. Unlike nodeCorners, these+ * need not be the transformed corners of the shape's local resize box. */+export function nodeBoundsPoints(+ doc: GraphicsDocument,+ id: string,+ overrides: SceneOverrides = {}+): readonly Point[] {+ return projectedBoundsPoints(doc, id, overrides, true);+}+function projectedBoundsPoints(+ doc: GraphicsDocument,+ id: string,+ overrides: SceneOverrides,+ tight: boolean+): readonly Point[] {+ const node = Object.hasOwn(overrides, id) ? overrides[id] : doc.items[id];+ if (!node) return [];+ if (isShape(node)) {+ const { item, transform } = shapeProjection(doc, id, overrides);+ const definition = shapeDefinition(node.type);+ if (tight && definition.transformedBounds)+ return corners(definition.transformedBounds(item!, transform));+ return corners(definition.bounds(item!)).map((p) =>+ transformPoint(transform, p)+ );+ }+ return children(doc, id).flatMap((child) =>+ projectedBoundsPoints(doc, child, overrides, tight)+ );+}+export const worldBounds = (+ doc: GraphicsDocument,+ id: string,+ overrides: SceneOverrides = {}+) => enclosing(nodeBoundsPoints(doc, id, overrides));+export function roots(+ doc: GraphicsDocument,+ ids: readonly string[]+): readonly string[] {+ const selected = new Set(ids);+ return [...selected].filter((id) => {+ let node = doc.items[id];+ if (!node || node.type === 'surface') return false;+ while (node && node.type !== 'surface') {+ if (selected.has(node.placement.parentId)) return false;+ node = doc.items[node.placement.parentId];+ }+ return true;+ });+}+export function outermost(doc: GraphicsDocument, id: string): string {+ let node = doc.items[id];+ while (+ node &&+ node.type !== 'surface' &&+ node.placement.parentId !== doc.rootId+ ) {+ id = node.placement.parentId;+ node = doc.items[id];+ }+ return id;+}+const hitIndexes = new WeakMap<+ GraphicsDocument,+ ReturnType<typeof buildHitIndex>+>();+function buildHitIndex(doc: GraphicsDocument) {+ return drawableIds(doc).map((id) => {+ const projection = shapeProjection(doc, id);+ const item = projection.item!;+ const worldTransform = projection.transform;+ const bounds = worldBounds(doc, id);+ const stroke = resolveAppearance(item.appearance).strokeWidth / 2;+ const padding =+ stroke *+ Math.max(+ Math.hypot(worldTransform[0], worldTransform[2]),+ Math.hypot(worldTransform[1], worldTransform[3])+ );+ return {+ id,+ item,+ worldTransform,+ local: inverse(worldTransform),+ bounds,+ padding,+ };+ });+}+export function hitTest(+ doc: GraphicsDocument,+ point: Point,+ deep = false,+ tolerance = 0+): string | undefined {+ let index = hitIndexes.get(doc);+ if (!index) {+ index = buildHitIndex(doc);+ if (Object.isFrozen(doc) && Object.isFrozen(doc.items))+ hitIndexes.set(doc, index);+ }+ for (let i = index.length - 1; i >= 0; i--) {+ const { id, item, worldTransform, local, bounds, padding } = index[i]!;+ const margin = padding + tolerance;+ if (+ point.x < bounds.x - margin ||+ point.y < bounds.y - margin ||+ point.x > bounds.x + bounds.width + margin ||+ point.y > bounds.y + bounds.height + margin+ )+ continue;+ if (+ shapeDefinition(item.type).hitTest(item, transformPoint(local, point), {+ worldTransform,+ tolerance,+ })+ )+ return deep ? id : outermost(doc, id);+ }+}+export function boxHits(doc: GraphicsDocument, box: Bounds): readonly string[] {+ return [+ ...new Set(+ drawableIds(doc)+ .filter((id) => {+ const { item: node, transform } = shapeProjection(doc, id);+ return (+ isShape(node) &&+ shapeDefinition(node.type).intersectsBox(node, transform, box)+ );+ })+ .map((id) => outermost(doc, id))+ ),+ ];+}+// Only trust objects frozen here, not caller-owned shallow Object.freeze values.+// Weak collections do not retain discarded documents or history entries.+const frozenDocuments = new WeakSet<GraphicsDocument>();+const frozenItems = new WeakSet<GraphicsItem>();+const frozenGeometries = new WeakMap<object, ShapeKind>();++function deepFreeze<T>(value: T): T {+ if (value && typeof value === 'object') {+ for (const child of Object.values(value)) deepFreeze(child);+ Object.freeze(value);+ }+ return value;+}++function cloneGeometryValue<T>(value: T, ancestors = new WeakSet<object>()): T {+ if (!value || typeof value !== 'object') return value;+ if (ancestors.has(value)) throw new Error('Cyclic geometry value');+ const prototype = Object.getPrototypeOf(value);+ if (+ !Array.isArray(value) &&+ prototype !== Object.prototype &&+ prototype !== null+ )+ throw new Error('Invalid geometry value');+ ancestors.add(value);+ const clone = (Array.isArray(value) ? [] : {}) as Record<string, unknown>;+ for (const [key, child] of Object.entries(value))+ clone[key] = cloneGeometryValue(child, ancestors);+ ancestors.delete(value);+ return clone as T;+}++export function freezeDocument(doc: GraphicsDocument): GraphicsDocument {+ if (frozenDocuments.has(doc)) return doc;+ if (doc.items[doc.rootId]?.type !== 'surface')+ throw new Error('Invalid scene root');+ const items: Record<string, GraphicsItem> = Object.create(null);+ const siblingKeys = new Map<string, Set<string>>();+ for (const [id, node] of Object.entries(doc.items)) {+ if (+ !node ||+ (node.type !== 'surface' && node.type !== 'group' && !isShape(node))+ )+ throw new Error('Invalid node type');+ if (id !== node.id) throw new Error('Node identity mismatch');+ if (node.type === 'surface') {+ if (id !== doc.rootId)+ throw new Error('Only one surface root per document is supported');+ const frozen = frozenItems.has(node) ? node : Object.freeze({ ...node });+ frozenItems.add(frozen);+ Object.defineProperty(items, id, {+ value: frozen,+ enumerable: true,+ });+ continue;+ }+ if (+ !Array.isArray(node.transform) ||+ node.transform.length !== 6 ||+ !node.transform.every(Number.isFinite)+ )+ throw new Error('Invalid transform');+ if (isShape(node) && !validAppearance(node.appearance))+ throw new Error('Invalid appearance');+ inverse(node.transform);+ if (!isSortKey(node.placement.sortKey))+ throw new Error('Invalid sibling order');+ const used = siblingKeys.get(node.placement.parentId) ?? new Set<string>();+ if (used.has(node.placement.sortKey))+ throw new Error('Duplicate sibling sort key');+ used.add(node.placement.sortKey);+ siblingKeys.set(node.placement.parentId, used);+ const parent = doc.items[node.placement.parentId];+ if (!parent || isShape(parent)) throw new Error('Invalid parent');+ const seen = new Set([id]);+ let ancestor: GraphicsItem | undefined = parent;+ while (ancestor && ancestor.type !== 'surface') {+ if (seen.has(ancestor.id)) throw new Error('Containment cycle');+ seen.add(ancestor.id);+ ancestor = doc.items[ancestor.placement.parentId];+ }+ if (ancestor?.id !== doc.rootId) throw new Error('Unreachable node');+ if (+ isShape(node) &&+ frozenGeometries.get(node.geometry) !== node.type &&+ !shapeDefinition(node.type).validateGeometry(node.geometry)+ )+ throw new Error(`Invalid ${node.type} geometry`);+ if (node.type === 'connector') {+ for (const end of [node.geometry.start, node.geometry.end]) {+ if (!end.binding) continue;+ const target = doc.items[end.binding.targetId];+ if (+ end.binding.targetId === id ||+ (target && (!isShape(target) || target.type === 'connector'))+ )+ throw new Error('Invalid connector target');+ }+ }+ // The registry preserves the validated node kind/geometry correlation.+ const frozen = (+ frozenItems.has(node)+ ? node+ : Object.freeze({+ ...node,+ placement: Object.freeze({ ...node.placement }),+ transform: Object.freeze([...node.transform]) as Matrix,+ ...(isShape(node)+ ? {+ geometry:+ frozenGeometries.get(node.geometry) === node.type+ ? node.geometry+ : deepFreeze(+ shapeDefinition(node.type).freezeGeometry(+ cloneGeometryValue(node.geometry)+ )+ ),+ appearance: Object.freeze({ ...node.appearance }),+ }+ : {}),+ })+ ) as typeof node;+ frozenItems.add(frozen);+ if (isShape(frozen)) frozenGeometries.set(frozen.geometry, frozen.type);+ Object.defineProperty(items, id, { value: frozen, enumerable: true });+ }+ if (+ doc.surface &&+ ![doc.surface.width, doc.surface.height].every(+ (v) => Number.isFinite(v) && v > 0+ )+ )+ throw new Error('Invalid image dimensions');+ const result: GraphicsDocument = Object.freeze({+ ...doc,+ items: Object.freeze(items),+ ...(doc.surface ? { surface: Object.freeze({ ...doc.surface }) } : {}),+ });+ for (const id of Object.keys(items)) inverse(worldMatrix(result, id));+ frozenDocuments.add(result);+ return result;+}+export function createScene(+ seed: readonly GraphicsItem[] = []+): GraphicsDocument {+ const rootId = 'scene-root';+ const items: Record<string, GraphicsItem> = {+ [rootId]: { id: rootId, type: 'surface' },+ };+ for (const node of seed) {+ if (Object.hasOwn(items, node.id)) throw new Error('Duplicate node ID');+ Object.defineProperty(items, node.id, { value: node, enumerable: true });+ }+ return freezeDocument({ rootId, items });+}+export function deleteSubtrees(+ doc: GraphicsDocument,+ ids: readonly string[]+): GraphicsDocument {+ const removed = new Set<string>();+ const visit = (id: string) => {+ removed.add(id);+ for (const child of children(doc, id)) visit(child);+ };+ for (const id of roots(doc, ids)) visit(id);+ const retained = new Set(+ Object.keys(doc.items).filter((id) => !removed.has(id))+ );+ return freezeDocument({+ ...doc,+ items: Object.fromEntries(+ Object.entries(doc.items)+ .filter(([id]) => retained.has(id))+ .map(([id, item]) => [+ id,+ item.type === 'connector'+ ? retainConnectorBindings(doc, item, retained)+ : item,+ ])+ ),+ });+}+export function reparent(+ doc: GraphicsDocument,+ id: string,+ parentId: string,+ position: LayerPosition = 'front'+): GraphicsDocument {+ const node = doc.items[id];+ if (!node || node.type === 'surface')+ throw new Error('Cannot reparent root or missing node');+ const siblings = children(doc, parentId).filter((key) => key !== id);+ const index = insertionIndex(siblings, position);+ if (+ node.placement.parentId === parentId &&+ children(doc, parentId).indexOf(id) === index+ )+ return doc;+ const sortKey = keysAt(doc, siblings, index, 1)[0]!;+ const transform = multiply(+ inverse(worldMatrix(doc, parentId)),+ worldMatrix(doc, id)+ );+ return freezeDocument({+ ...doc,+ items: {+ ...doc.items,+ [id]: { ...node, placement: { parentId, sortKey }, transform },+ },+ });+}+export function groupNodes(+ doc: GraphicsDocument,+ ids: readonly string[],+ id: string+): GraphicsDocument {+ const selected = roots(doc, ids),+ first = doc.items[selected[0] ?? ''];+ if (!first || first.type === 'surface' || Object.hasOwn(doc.items, id))+ throw new Error('Invalid group');+ const parentId = first.placement.parentId;+ if (+ selected.some((key) => {+ const n = doc.items[key];+ return !n || n.type === 'surface' || n.placement.parentId !== parentId;+ })+ )+ throw new Error('Group nodes must share a parent');+ const ordered = children(doc, parentId).filter((key) =>+ selected.includes(key)+ );+ const items: Record<string, GraphicsItem> = Object.assign(+ Object.create(null),+ doc.items+ );+ items[id] = {+ id,+ type: 'group',+ placement: { parentId, sortKey: first.placement.sortKey },+ transform: IDENTITY,+ };+ for (const key of ordered) {+ const n = items[key];+ if (n && n.type !== 'surface')+ items[key] = { ...n, placement: { ...n.placement, parentId: id } };+ }+ const backmost = doc.items[ordered[0]!];+ if (backmost && backmost.type !== 'surface')+ items[id] = {+ ...items[id],+ placement: { parentId, sortKey: backmost.placement.sortKey },+ };+ return freezeDocument({ ...doc, items });+}+export function ungroupNode(+ doc: GraphicsDocument,+ id: string+): GraphicsDocument {+ const group = doc.items[id];+ if (group?.type !== 'group') throw new Error('Not a group');+ const parentId = group.placement.parentId;+ const siblings = children(doc, parentId);+ const descendants = children(doc, id);+ const keys = keysAt(+ doc,+ siblings.filter((key) => key !== id),+ siblings.indexOf(id),+ descendants.length+ );+ const items: Record<string, GraphicsItem> = Object.assign(+ Object.create(null),+ doc.items+ );+ descendants.forEach((child, index) => {+ const node = items[child];+ if (node && node.type !== 'surface')+ items[child] = {+ ...node,+ placement: { parentId, sortKey: keys[index]! },+ transform: multiply(group.transform, node.transform),+ };+ });+ delete items[id];+ return freezeDocument({ ...doc, items });+}diff --git a/packages/graphics/src/core/selection-frame.ts b/packages/graphics/src/core/selection-frame.tsnew file mode 100644index 0000000000..38009097b8--- /dev/null+++ b/packages/graphics/src/core/selection-frame.ts@@ -0,0 +1,98 @@+import {+ corners,+ enclosing,+ IDENTITY,+ inverse,+ type Matrix,+ multiply,+ transformPoint,+} from './affine';+import type { Bounds, GraphicsDocument, Point } from './model';+import {+ children,+ nodeBoundsPoints,+ roots,+ type SceneOverrides,+ shapeProjection,+ worldMatrix,+} from './scene';+import { isShape, shapeDefinition } from './shapes/registry';++/** The same coordinate frame drives selection chrome and resize math. Bounds+ * are in frame space; corners and center are in world space. This is derived+ * editor state, never document data.+ */+export type SelectionFrame = Readonly<{+ bounds: Bounds;+ transform: Matrix;+ angle: number;+ corners: readonly Point[];+ center: Point;+ canDeform: boolean;+}>;++export function selectionFrame(+ document: GraphicsDocument,+ selection: readonly string[],+ overrides: SceneOverrides = {}+): SelectionFrame | undefined {+ const selected = roots(document, selection);+ const firstId = selected[0];+ if (!firstId) return undefined;+ const first = overrides[firstId] ?? document.items[firstId];+ const projection = shapeProjection(document, firstId, overrides);+ const world = projection.transform;+ const singleShape = selected.length === 1 && isShape(first);+ // A single leaf retains its full affine frame, including existing ancestor+ // scale/shear. Groups and multiple roots always use a world-aligned box.+ const angle = singleShape ? Math.atan2(world[1], world[0]) : 0;+ const transform = singleShape ? world : IDENTITY;+ const fromWorld = inverse(transform);+ const points = selected.flatMap((id) =>+ nodeBoundsPoints(document, id, overrides)+ );+ if (!points.length) return undefined;+ const bounds = singleShape+ ? shapeDefinition(first.type).bounds(projection.item!)+ : enclosing(points.map((point) => transformPoint(fromWorld, point)));+ const compatible = (id: string): boolean => {+ const item = overrides[id] ?? document.items[id];+ if (isShape(item) && shapeDefinition(item.type).canDeform === false)+ return false;+ const matrix = multiply(fromWorld, worldMatrix(document, id, overrides));+ const x = Math.hypot(matrix[0], matrix[1]);+ const y = Math.hypot(matrix[2], matrix[3]);+ // Parallel or quarter-turn axes can stretch without introducing shear.+ // Check both axes: a sheared ancestor cannot be classified by angle alone.+ const aligned =+ (Math.abs(matrix[1]) <= x * 1e-8 && Math.abs(matrix[2]) <= y * 1e-8) ||+ (Math.abs(matrix[0]) <= x * 1e-8 && Math.abs(matrix[3]) <= y * 1e-8);+ return aligned && children(document, id).every(compatible);+ };+ return {+ bounds,+ transform,+ angle,+ corners: corners(bounds).map((point) => transformPoint(transform, point)),+ center: transformPoint(transform, {+ x: bounds.x + bounds.width / 2,+ y: bounds.y + bounds.height / 2,+ }),+ canDeform: singleShape || selected.every(compatible),+ };+}++/** Selection interiors can move the selected roots without picking a leaf. */+export function selectionContainsPoint(+ frame: SelectionFrame,+ point: Point+): boolean {+ const local = transformPoint(inverse(frame.transform), point);+ const b = frame.bounds;+ return (+ local.x >= b.x &&+ local.x <= b.x + b.width &&+ local.y >= b.y &&+ local.y <= b.y + b.height+ );+}diff --git a/packages/graphics/src/core/selection.ts b/packages/graphics/src/core/selection.tsnew file mode 100644index 0000000000..0ae08bdc69--- /dev/null+++ b/packages/graphics/src/core/selection.ts@@ -0,0 +1,523 @@+import {+ around,+ corners,+ enclosing,+ inverse,+ multiply,+ rotation,+ sameMatrix,+ scaling,+ transformPoint,+ translation,+} from './affine';+import { duplicateNodes, type IdFactory } from './fragments';+import type { Bounds, GraphicsDocument, GraphicsItem, Point } from './model';+import {+ dragRectangleRadius,+ isRadiusHandle,+ type RadiusHandle,+} from './radius';+import { type ResizeHandle, type ResizeModifiers, resizeBox } from './resize';+import {+ boxHits,+ deleteSubtrees,+ nodeBoundsPoints,+ resolvedShape,+ roots,+ type SceneOverrides,+ worldBounds,+ worldMatrix,+} from './scene';+import { type SelectionFrame, selectionFrame } from './selection-frame';+import { isShape, shapeDefinition, shapePayload } from './shapes/registry';+import type { TextMeasurer } from './shapes/text';+import { snapTranslation } from './snapping';+import { regenerateScaledShapes, stretchShapes } from './stretch';++export type {+ ResizeCorner,+ ResizeEdge,+ ResizeHandle,+ ResizeModifiers,+} from './resize';+export type TransformHandle = ResizeHandle | RadiusHandle | 'rotate';+export type TransformModifiers = ResizeModifiers &+ Readonly<{ snapRotation?: boolean; constrainAxis?: boolean }>;+export type SelectionState = Readonly<{+ selectedId?: string;+ selectedIds: readonly string[];+ box?: Bounds;+ transform?: Readonly<{+ id: string;+ kind: 'move' | 'resize' | 'scale' | 'rotate' | 'radius';+ handle?: TransformHandle;+ geometry: Bounds;+ geometries: Readonly<Record<string, Bounds>>;+ nodes: SceneOverrides;+ document?: GraphicsDocument;+ }>;+}>;+export type SelectionHost = Readonly<{+ measureText?: TextMeasurer;+ getSnapUnit?: () => number | undefined;+ getDocument: () => GraphicsDocument;+ commitDocument: (document: GraphicsDocument) => void;+ cancelDrawing: () => void;+ onChange: () => void;+}>;++export function createSelection(host: SelectionHost) {+ let disposed = false;+ let selectedIds: readonly string[] = Object.freeze([]);+ let box:+ | {+ origin: Point;+ bounds: Bounds;+ previous: readonly string[];+ additive: boolean;+ }+ | undefined;+ let gesture:+ | {+ id: string;+ origin: Point;+ handle?: TransformHandle;+ base: GraphicsDocument;+ targets: readonly string[];+ frame: SelectionFrame;+ pivot: Point;+ nodes: SceneOverrides;+ originalSelection?: readonly string[];+ }+ | undefined;+ const emit = () => host.onChange();+ const getState = (): SelectionState => {+ const geometries: Record<string, Bounds> = Object.create(null);+ if (gesture)+ for (const id of gesture.targets)+ geometries[id] = worldBounds(gesture.base, id, gesture.nodes);+ return Object.freeze({+ selectedId: selectedIds.length === 1 ? selectedIds[0] : undefined,+ selectedIds,+ box: box?.bounds,+ transform: gesture+ ? Object.freeze({+ id: gesture.id,+ handle: gesture.handle,+ kind: isRadiusHandle(gesture.handle)+ ? 'radius'+ : gesture.handle === 'rotate'+ ? 'rotate'+ : gesture.handle+ ? gesture.targets.length > 1 ||+ gesture.base.items[gesture.id]?.type === 'group'+ ? 'scale'+ : 'resize'+ : 'move',+ geometry:+ geometries[gesture.id] ??+ worldBounds(gesture.base, gesture.id, gesture.nodes),+ geometries: Object.freeze(geometries),+ nodes: gesture.nodes,+ document: gesture.originalSelection ? gesture.base : undefined,+ })+ : undefined,+ });+ };+ function cancelTransform() {+ if (disposed) return;+ if (gesture?.originalSelection) selectedIds = gesture.originalSelection;+ gesture = undefined;+ if (box) selectedIds = box.previous;+ box = undefined;+ emit();+ }+ function select(id?: string) {+ if (disposed) return;+ host.cancelDrawing();+ gesture = undefined;+ box = undefined;+ selectedIds = Object.freeze(+ id &&+ host.getDocument().items[id]?.type &&+ host.getDocument().items[id]?.type !== 'surface'+ ? [id]+ : []+ );+ emit();+ }+ function updateTransform(point: Point, modifiers: TransformModifiers = {}) {+ if (disposed || !gesture || ![point.x, point.y].every(Number.isFinite))+ return;+ const { base, origin, handle, pivot, targets, id, frame } = gesture;+ const node = resolvedShape(base, id) ?? base.items[id];+ const nodes: Record<string, GraphicsItem> = Object.create(null);+ const unit = host.getSnapUnit?.();+ if (isRadiusHandle(handle)) {+ if (node?.type !== 'rectangle') return;+ nodes[id] = dragRectangleRadius(+ node,+ worldMatrix(base, id),+ handle,+ origin,+ point+ );+ } else if (+ handle &&+ handle !== 'rotate' &&+ (targets.length > 1 || node?.type === 'group')+ ) {+ const { bounds } = frame;+ if (bounds.width <= 0 || bounds.height <= 0) return;+ const fromWorld = inverse(frame.transform);+ const start = transformPoint(fromWorld, origin);+ const end = transformPoint(fromWorld, point);+ // Different child axes force uniform scaling for the entire selection,+ // including edge drags. This keeps the dragged box and content in sync.+ const proportional = modifiers.proportional || !frame.canDeform;+ const resized = resizeBox(+ bounds,+ handle,+ {+ x: end.x - start.x,+ y: end.y - start.y,+ },+ {+ ...modifiers,+ proportional,+ snap: unit === undefined ? undefined : { x: unit, y: unit },+ }+ );+ const delta = multiply(+ frame.transform,+ multiply(resized.transform, fromWorld)+ );+ if (!proportional) {+ Object.assign(+ nodes,+ stretchShapes(base, targets, delta, host.measureText, handle)+ );+ } else {+ for (const key of targets) {+ const item = base.items[key];+ if (!item || item.type === 'surface') continue;+ nodes[key] = {+ ...item,+ transform: multiply(+ inverse(worldMatrix(base, item.placement.parentId)),+ multiply(delta, worldMatrix(base, key))+ ),+ };+ }+ regenerateScaledShapes(base, targets, nodes);+ }+ } else if (handle && handle !== 'rotate') {+ if (!isShape(node)) return;+ const definition = shapeDefinition(node.type);+ const localBounds = definition.bounds(node);+ const world = worldMatrix(base, id);+ const surface = base.surface;+ const endWorld = surface+ ? {+ x: Math.max(0, Math.min(surface.width, point.x)),+ y: Math.max(0, Math.min(surface.height, point.y)),+ }+ : point;+ const end = transformPoint(inverse(world), endWorld),+ start = transformPoint(inverse(world), origin);+ const delta = { x: end.x - start.x, y: end.y - start.y };+ const resizeModifiers = {+ ...modifiers,+ ...(node.type === 'text' && handle !== 'e' && handle !== 'w'+ ? { proportional: true, proportionalFit: 'project' as const }+ : {}),+ };+ let resized = resizeBox(localBounds, handle, delta, {+ ...resizeModifiers,+ snap:+ unit === undefined+ ? undefined+ : {+ x: unit / Math.hypot(world[0], world[1]),+ y: unit / Math.hypot(world[2], world[3]),+ },+ });+ if (surface && unit !== undefined) {+ const matrix = multiply(world, resized.transform);+ const outside = corners(localBounds).some((point) => {+ const { x, y } = transformPoint(matrix, point);+ return x < 0 || y < 0 || x > surface.width || y > surface.height;+ });+ // The bounded surface takes priority over a grid step past its edge.+ if (outside)+ resized = resizeBox(localBounds, handle, delta, resizeModifiers);+ }+ const { width, height } = resized.bounds;+ nodes[id] = {+ ...definition.resize(+ node,+ { x: 0, y: 0, width, height },+ { handle, measureText: host.measureText }+ ),+ transform: multiply(+ node.transform,+ multiply(+ resized.transform,+ scaling(1 / Math.abs(resized.scaleX), 1 / Math.abs(resized.scaleY))+ )+ ),+ };+ } else {+ let dx = point.x - origin.x,+ dy = point.y - origin.y;+ const horizontal = Math.abs(dx) >= Math.abs(dy);+ if (!handle && unit !== undefined) {+ // A single shape's frame is local; moving always snaps in world space.+ const anchor =+ targets.length === 1 && isShape(base.items[targets[0]!])+ ? worldBounds(base, targets[0]!)+ : frame.bounds;+ const snapped = snapTranslation(anchor, { x: dx, y: dy }, unit);+ dx = snapped.x;+ dy = snapped.y;+ }+ if (!handle && base.surface) {+ const bounds = enclosing(+ targets.flatMap((key) => nodeBoundsPoints(base, key))+ );+ dx = Math.max(+ -bounds.x,+ Math.min(base.surface.width - bounds.x - bounds.width, dx)+ );+ dy = Math.max(+ -bounds.y,+ Math.min(base.surface.height - bounds.y - bounds.height, dy)+ );+ }+ if (!handle && modifiers.constrainAxis) {+ if (horizontal) dy = 0;+ else dx = 0;+ }+ let delta = translation(dx, dy);+ if (handle === 'rotate') {+ let angle =+ Math.atan2(point.y - pivot.y, point.x - pivot.x) -+ Math.atan2(origin.y - pivot.y, origin.x - pivot.x);+ if (modifiers.snapRotation) {+ const world = worldMatrix(base, id);+ const initialAngle =+ targets.length === 1 ? Math.atan2(world[1], world[0]) : 0;+ const step = Math.PI / 6;+ angle =+ Math.round((initialAngle + angle) / step) * step - initialAngle;+ }+ delta = around(pivot, rotation(angle));+ }+ for (const key of targets) {+ const item = base.items[key];+ if (!item || item.type === 'surface') continue;+ nodes[key] = {+ ...item,+ transform: multiply(+ inverse(worldMatrix(base, item.placement.parentId)),+ multiply(delta, worldMatrix(base, key))+ ),+ };+ }+ }+ for (const [id, node] of Object.entries(nodes)) {+ if (node.type === 'surface') continue;+ const original = base.items[id];+ // Moving and rotating retain the validated, deeply frozen geometry.+ // Cloning it here would invalidate derived ink on every pointer update.+ const unchangedGeometry =+ isShape(node) &&+ isShape(original) &&+ node.type === original.type &&+ node.geometry === original.geometry;+ const transform = Object.freeze([+ ...node.transform,+ ]) as typeof node.transform;+ nodes[id] =+ isShape(node) && !unchangedGeometry+ ? Object.freeze({+ ...node,+ ...shapePayload(node.type, node.geometry),+ transform,+ })+ : Object.freeze({ ...node, transform });+ }+ gesture = { ...gesture, nodes: Object.freeze(nodes) };+ emit();+ }+ return {+ getState,+ select,+ selectMany(ids: readonly string[]) {+ cancelTransform();+ host.cancelDrawing();+ selectedIds = Object.freeze(roots(host.getDocument(), ids));+ emit();+ },+ cancelTransform,+ updateTransform,+ toggle(id: string) {+ if (+ disposed ||+ !Object.hasOwn(host.getDocument().items, id) ||+ id === host.getDocument().rootId+ )+ return;+ cancelTransform();+ host.cancelDrawing();+ selectedIds = Object.freeze(+ selectedIds.includes(id)+ ? selectedIds.filter((key) => key !== id)+ : [...selectedIds, id]+ );+ emit();+ },+ beginBox(point: Point, additive = false) {+ if (disposed || ![point.x, point.y].every(Number.isFinite)) return false;+ cancelTransform();+ host.cancelDrawing();+ box = {+ origin: { ...point },+ bounds: Object.freeze({ ...point, width: 0, height: 0 }),+ previous: selectedIds,+ additive,+ };+ if (!additive) selectedIds = Object.freeze([]);+ emit();+ return true;+ },+ updateBox(point: Point) {+ if (disposed || !box || ![point.x, point.y].every(Number.isFinite))+ return;+ const bounds = Object.freeze({+ x: Math.min(box.origin.x, point.x),+ y: Math.min(box.origin.y, point.y),+ width: Math.abs(point.x - box.origin.x),+ height: Math.abs(point.y - box.origin.y),+ });+ box = { ...box, bounds };+ const hits =+ bounds.width > 0 && bounds.height > 0+ ? boxHits(host.getDocument(), bounds)+ : [];+ selectedIds = Object.freeze([+ ...new Set([...(box.additive ? box.previous : []), ...hits]),+ ]);+ emit();+ },+ commitBox() {+ if (!disposed) {+ box = undefined;+ emit();+ }+ },+ beginTransform(+ id: string,+ point: Point,+ handle?: TransformHandle,+ duplicateId?: IdFactory+ ) {+ let base = host.getDocument(),+ node = base.items[id];+ if (+ disposed ||+ !node ||+ node.type === 'surface' ||+ ![point.x, point.y].every(Number.isFinite)+ )+ return false;+ if (+ isRadiusHandle(handle) &&+ (node.type !== 'rectangle' ||+ (selectedIds.includes(id) && selectedIds.length !== 1))+ )+ return false;+ if (!selectedIds.includes(id)) select(id);+ else {+ cancelTransform();+ host.cancelDrawing();+ }+ let originalSelection: readonly string[] | undefined;+ if (duplicateId && !handle) {+ originalSelection = selectedIds;+ const cloned = duplicateNodes(base, selectedIds, duplicateId, {+ x: 0,+ y: 0,+ });+ base = cloned.document;+ selectedIds = Object.freeze(cloned.selection);+ id = selectedIds[0]!;+ }+ const targets = roots(base, selectedIds);+ const frame = selectionFrame(base, targets);+ if (!frame) return false;+ gesture = {+ id,+ origin: { ...point },+ originalSelection,+ handle,+ base,+ targets,+ frame,+ pivot: frame.center,+ nodes: Object.freeze({}),+ };+ emit();+ return true;+ },+ commitTransform() {+ if (disposed || !gesture) return false;+ const { base, nodes, originalSelection } = gesture;+ gesture = undefined;+ const changed = Object.entries(nodes).some(([id, node]) => {+ const old = base.items[id];+ if (!old || old.type === 'surface' || node.type === 'surface')+ return false;+ return (+ !sameMatrix(old.transform, node.transform) ||+ (isShape(old) &&+ isShape(node) &&+ (!shapeDefinition(node.type).sameGeometry(old, node) ||+ (old.appearance.cornerRadius ?? 0) !==+ (node.appearance.cornerRadius ?? 0)))+ );+ });+ if (!changed) {+ if (originalSelection) selectedIds = originalSelection;+ emit();+ return false;+ }+ host.commitDocument({ ...base, items: { ...base.items, ...nodes } });+ return true;+ },+ deleteSelection() {+ if (disposed || !selectedIds.length) return;+ host.cancelDrawing();+ const next = deleteSubtrees(host.getDocument(), selectedIds);+ selectedIds = Object.freeze([]);+ gesture = undefined;+ box = undefined;+ host.commitDocument(next);+ },+ reconcile(document: GraphicsDocument) {+ if (disposed) return;+ if (gesture?.originalSelection) selectedIds = gesture.originalSelection;+ gesture = undefined;+ box = undefined;+ selectedIds = Object.freeze(+ selectedIds.filter((id) => Object.hasOwn(document.items, id))+ );+ },+ dispose() {+ disposed = true;+ selectedIds = Object.freeze([]);+ gesture = undefined;+ box = undefined;+ },+ };+}diff --git a/packages/graphics/src/core/shapes/box-geometry.ts b/packages/graphics/src/core/shapes/box-geometry.tsnew file mode 100644index 0000000000..da0d06475b--- /dev/null+++ b/packages/graphics/src/core/shapes/box-geometry.ts@@ -0,0 +1,41 @@+import type { Bounds, Point } from '../model';++export type BoxGeometry = Readonly<{ width: number; height: number }>;+export const boxGeometry = ({ width, height }: Bounds): BoxGeometry => ({+ width,+ height,+});+export const validBoxGeometry = (value: unknown): value is BoxGeometry =>+ typeof value === 'object' &&+ value !== null &&+ 'width' in value &&+ typeof value.width === 'number' &&+ Number.isFinite(value.width) &&+ value.width > 0 &&+ 'height' in value &&+ typeof value.height === 'number' &&+ Number.isFinite(value.height) &&+ value.height > 0;+export const sameBoxGeometry = (a: BoxGeometry, b: BoxGeometry) =>+ Math.abs(a.width - b.width) < 1e-9 && Math.abs(a.height - b.height) < 1e-9;+export function segmentDistance(+ point: Point,+ start: Point,+ end: Point+): number {+ const dx = end.x - start.x,+ dy = end.y - start.y;+ const lengthSquared = dx * dx + dy * dy;+ const t =+ lengthSquared === 0+ ? 0+ : Math.max(+ 0,+ Math.min(+ 1,+ ((point.x - start.x) * dx + (point.y - start.y) * dy) /+ lengthSquared+ )+ );+ return Math.hypot(point.x - start.x - t * dx, point.y - start.y - t * dy);+}diff --git a/packages/graphics/src/core/shapes/connector-routing.ts b/packages/graphics/src/core/shapes/connector-routing.tsnew file mode 100644index 0000000000..0129627de7--- /dev/null+++ b/packages/graphics/src/core/shapes/connector-routing.ts@@ -0,0 +1,264 @@+import { enclosing } from '../affine';+import type { Point } from '../model';++export type ConnectorRoute = 'straight' | 'stepped' | 'smooth';+export type ConnectorHead =+ | 'none'+ | 'arrow'+ | 'arrow-filled'+ | 'circle'+ | 'circle-small';+export type RouteEnd = Readonly<{ point: Point; direction?: Point }>;+export type CurveSegment = Readonly<{+ from: Point;+ to: Point;+ controls?: readonly [Point, Point];+}>;+export const add = (a: Point, b: Point): Point => ({+ x: a.x + b.x,+ y: a.y + b.y,+});+export const sub = (a: Point, b: Point): Point => ({+ x: a.x - b.x,+ y: a.y - b.y,+});+export const times = (p: Point, k: number): Point => ({+ x: p.x * k,+ y: p.y * k,+});+export const length = (p: Point) => Math.hypot(p.x, p.y);+export const unit = (p: Point): Point =>+ length(p) > 1e-9 ? times(p, 1 / length(p)) : { x: 1, y: 0 };+const mid = (a: Point, b: Point) => times(add(a, b), 0.5);+const horizontal = (p: Point) => Math.abs(p.x) > Math.abs(p.y) + 1e-6;+const cardinal = (p: Point): Point =>+ horizontal(p)+ ? { x: Math.sign(p.x) || 1, y: 0 }+ : { x: 0, y: Math.sign(p.y) || 1 };+const cross = (a: Point, b: Point) => a.x * b.y - a.y * b.x;++/** Ported from the original Canvas getRectilinearPoints: same 36-unit leads,+ * facing / parallel / perpendicular cases, and forward-ray intersection. */+function orthogonal(a: Point, b: Point, aDir: Point, bDir: Point): Point[] {+ const aNext = add(a, times(aDir, 36)),+ bNext = add(b, times(bDir, 36));+ const dot = aDir.x * bDir.x + aDir.y * bDir.y,+ h = horizontal(aDir);+ if (Math.abs(dot) < 1e-6) {+ const delta = sub(b, a),+ denominator = cross(aDir, bDir);+ const t = cross(delta, bDir) / denominator,+ u = cross(delta, aDir) / denominator;+ if (t >= 0 && u >= 0) return [a, add(a, times(aDir, t)), b];+ return [+ a,+ aNext,+ h ? { x: aNext.x, y: bNext.y } : { x: bNext.x, y: aNext.y },+ bNext,+ b,+ ];+ }+ const delta = sub(bNext, aNext),+ aligned = h+ ? Math.sign(aDir.x) === Math.sign(delta.x)+ : Math.sign(aDir.y) === Math.sign(delta.y);+ if (dot < 0) {+ if (aligned) {+ const m = mid(a, b);+ return [+ a,+ h ? { x: m.x, y: a.y } : { x: a.x, y: m.y },+ h ? { x: m.x, y: b.y } : { x: b.x, y: m.y },+ b,+ ];+ }+ const m = mid(aNext, bNext);+ return [+ a,+ aNext,+ h ? { x: aNext.x, y: m.y } : { x: m.x, y: aNext.y },+ h ? { x: bNext.x, y: m.y } : { x: m.x, y: bNext.y },+ bNext,+ b,+ ];+ }+ return aligned+ ? [a, h ? { x: bNext.x, y: a.y } : { x: a.x, y: bNext.y }, bNext, b]+ : [a, aNext, h ? { x: aNext.x, y: b.y } : { x: b.x, y: aNext.y }, bNext, b];+}+function steppedPoints(a: Point, b: Point, from: Point, to: Point) {+ const af = cardinal(from),+ bt = cardinal(to);+ // Preserve normal leads on rotated/nested shapes before joining the rectilinear route.+ const rotated = length(sub(from, af)) > 1e-6 || length(sub(to, bt)) > 1e-6;+ const points = rotated+ ? [+ a,+ ...orthogonal(add(a, times(from, 36)), add(b, times(to, 36)), af, bt),+ b,+ ]+ : orthogonal(a, b, af, bt);+ const merged: Point[] = [points[0]!];+ for (let i = 1; i < points.length - 1; i++)+ if (length(sub(points[i]!, merged[merged.length - 1]!)) > 5)+ merged.push(points[i]!);+ // Retain the true endpoint even when it is within the old merge threshold.+ merged.push(b);+ return merged;+}+function rounded(points: readonly Point[]): CurveSegment[] {+ const segments: CurveSegment[] = [];+ let current = points[0]!;+ for (let i = 1; i < points.length - 1; i++) {+ const corner = points[i]!,+ v1 = sub(corner, points[i - 1]!),+ v2 = sub(points[i + 1]!, corner);+ const radius = Math.min(10, length(v1) / 2, length(v2) / 2);+ const start = sub(corner, times(unit(v1), radius)),+ end = add(corner, times(unit(v2), radius));+ segments.push(+ { from: current, to: start },+ {+ from: start,+ to: end,+ controls: [+ add(start, times(unit(v1), radius * 0.55)),+ sub(end, times(unit(v2), radius * 0.55)),+ ],+ }+ );+ current = end;+ }+ segments.push({ from: current, to: points[points.length - 1]! });+ return segments;+}+const pair = (p: Point) => `${p.x} ${p.y}`;+export function connectorPath(+ start: RouteEnd,+ end: RouteEnd,+ route: ConnectorRoute+) {+ const a = start.point,+ b = end.point,+ delta = sub(b, a),+ forward = unit(delta);+ const from =+ route === 'straight' ? forward : unit(start.direction ?? cardinal(forward));+ const to =+ route === 'straight'+ ? times(forward, -1)+ : unit(end.direction ?? times(cardinal(forward), -1));+ const strength = Math.max(1, Math.min(200, length(delta) / 2));+ const segments: readonly CurveSegment[] =+ route === 'straight'+ ? [{ from: a, to: b }]+ : route === 'smooth'+ ? [+ {+ from: a,+ to: b,+ controls: [+ add(a, times(from, strength)),+ add(b, times(to, strength)),+ ],+ },+ ]+ : rounded(steppedPoints(a, b, from, to));+ const path = `M ${pair(a)} ${segments.map((s) => (s.controls ? `C ${pair(s.controls[0])} ${pair(s.controls[1])} ${pair(s.to)}` : `L ${pair(s.to)}`)).join(' ')}`;+ const bounds = enclosing(+ segments.flatMap((segment) => {+ if (!segment.controls) return [segment.from, segment.to];+ const [c1, c2] = segment.controls;+ const times = new Set([0, 1]);+ for (const axis of ['x', 'y'] as const) {+ const p0 = segment.from[axis],+ p1 = c1[axis],+ p2 = c2[axis],+ p3 = segment.to[axis];+ const a = -p0 + 3 * p1 - 3 * p2 + p3;+ const b = 2 * (p0 - 2 * p1 + p2);+ const c = p1 - p0;+ const roots =+ Math.abs(a) < 1e-12+ ? Math.abs(b) < 1e-12+ ? []+ : [-c / b]+ : b * b - 4 * a * c < 0+ ? []+ : [+ (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a),+ (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a),+ ];+ roots.forEach((t) => {+ if (t > 0 && t < 1) times.add(t);+ });+ }+ return [...times].map((t) => {+ const u = 1 - t;+ return {+ x:+ u ** 3 * segment.from.x ++ 3 * u * u * t * c1.x ++ 3 * u * t * t * c2.x ++ t ** 3 * segment.to.x,+ y:+ u ** 3 * segment.from.y ++ 3 * u * u * t * c1.y ++ 3 * u * t * t * c2.y ++ t ** 3 * segment.to.y,+ };+ });+ })+ );+ const points: Point[] = [a];+ for (const s of segments) {+ if (!s.controls) {+ points.push(s.to);+ continue;+ }+ const [c1, c2] = s.controls;+ const steps = Math.max(+ 8,+ Math.min(+ 256,+ Math.ceil(+ (length(sub(c1, s.from)) ++ length(sub(c2, c1)) ++ length(sub(s.to, c2))) /+ 4+ )+ )+ );+ for (let i = 1; i <= steps; i++) {+ const t = i / steps,+ u = 1 - t;+ points.push(+ add(+ add(times(s.from, u ** 3), times(c1, 3 * u * u * t)),+ add(times(c2, 3 * u * t * t), times(s.to, t ** 3))+ )+ );+ }+ }+ return { path, points, bounds, from, to, segments };+}+export function connectorHead(+ point: Point,+ direction: Point,+ style: ConnectorHead+) {+ const d = unit(direction),+ perpendicular = { x: -d.y, y: d.x };+ const angle = style === 'arrow-filled' ? Math.PI / 6 : Math.PI / 4;+ const back = add(point, times(d, 12 * Math.cos(angle))),+ offset = times(perpendicular, 12 * Math.sin(angle));+ const vertices = [add(back, offset), point, sub(back, offset)];+ return {+ vertices,+ path:+ style === 'arrow' || style === 'arrow-filled'+ ? `M ${pair(vertices[0]!)} L ${pair(point)} L ${pair(vertices[2]!)}${style === 'arrow-filled' ? ' Z' : ''}`+ : '',+ radius: style === 'circle' ? 6 : style === 'circle-small' ? 3 : 0,+ };+}diff --git a/packages/graphics/src/core/shapes/connector.ts b/packages/graphics/src/core/shapes/connector.tsnew file mode 100644index 0000000000..c143a43b95--- /dev/null+++ b/packages/graphics/src/core/shapes/connector.ts@@ -0,0 +1,369 @@+import { corners, enclosing, intersects, transformPoint } from '../affine';+import type { Point, ShapeItem } from '../model';+import { segmentDistance } from './box-geometry';+import {+ type ConnectorHead,+ type ConnectorRoute,+ connectorHead,+ connectorPath,+} from './connector-routing';+import type { ShapeDefinition } from './definition';+import {+ hitShapeLabel,+ type ShapeLabel,+ shapeLabelLayout,+ validShapeLabel,+} from './label';++export const connectorAnchors = [+ 'center',+ 'top',+ 'right',+ 'bottom',+ 'left',+] as const;+export type ConnectorAnchor = (typeof connectorAnchors)[number];+export type ConnectorBinding = Readonly<{+ targetId: string;+ anchor: ConnectorAnchor;+}>;+export type ConnectorEndpoint = Readonly<{+ /** Local coordinate, also the fallback if the referenced node is unavailable. */+ point: Point;+ binding?: ConnectorBinding;+ /** Optional local outgoing tangent; bound endpoints derive this from the target. */+ direction?: Point;+}>;+export type ConnectorGeometry = Readonly<{+ label?: ShapeLabel;+ start: ConnectorEndpoint;+ end: ConnectorEndpoint;+ route: ConnectorRoute;+ startHead: ConnectorHead;+ endHead: ConnectorHead;+}>;+const validPoint = (p: unknown): p is Point =>+ !!p &&+ typeof p === 'object' &&+ 'x' in p &&+ 'y' in p &&+ typeof p.x === 'number' &&+ typeof p.y === 'number' &&+ Number.isFinite(p.x) &&+ Number.isFinite(p.y);+const validEnd = (value: unknown): value is ConnectorEndpoint => {+ if (+ !value ||+ typeof value !== 'object' ||+ !('point' in value) ||+ !validPoint(value.point)+ )+ return false;+ if (+ 'direction' in value &&+ value.direction !== undefined &&+ !validPoint(value.direction)+ )+ return false;+ if (!('binding' in value) || value.binding === undefined) return true;+ const b = value.binding;+ return (+ !!b &&+ typeof b === 'object' &&+ 'targetId' in b &&+ typeof b.targetId === 'string' &&+ !!b.targetId &&+ 'anchor' in b &&+ connectorAnchors.includes(b.anchor as ConnectorAnchor)+ );+};+const headPoints = (point: Point, direction: Point, style: ConnectorHead) => {+ const head = connectorHead(point, direction, style);+ return head.radius+ ? Array.from({ length: 32 }, (_, i) => ({+ x: point.x + Math.cos((i * Math.PI) / 16) * head.radius,+ y: point.y + Math.sin((i * Math.PI) / 16) * head.radius,+ }))+ : head.vertices;+};+const freezeEnd = (end: ConnectorEndpoint): ConnectorEndpoint =>+ Object.freeze({+ ...end,+ point: Object.freeze({ ...end.point }),+ ...(end.binding ? { binding: Object.freeze({ ...end.binding }) } : {}),+ ...(end.direction+ ? { direction: Object.freeze({ ...end.direction }) }+ : {}),+ });+const connectorBounds = (+ item: ShapeItem<'connector'>,+ includeLabel: boolean+) => {+ const g = item.geometry,+ route = connectorPath(g.start, g.end, g.route);+ const points = [...corners(route.bounds)];+ for (const [end, style, direction] of [+ [g.start, g.startHead, route.from],+ [g.end, g.endHead, route.to],+ ] as const) {+ if (style === 'none') continue;+ const head = connectorHead(end.point, direction, style);+ if (head.radius)+ points.push(+ ...corners({+ x: end.point.x - head.radius,+ y: end.point.y - head.radius,+ width: head.radius * 2,+ height: head.radius * 2,+ })+ );+ else points.push(...head.vertices);+ }+ const label = includeLabel ? shapeLabelLayout(item) : undefined;+ if (label)+ points.push(+ ...corners({+ x: 0,+ y: 0,+ width: label.geometry.width,+ height: label.geometry.height,+ }).map((p) => transformPoint(label.transform, p))+ );+ const bounds = enclosing(points);+ return {+ ...bounds,+ width: Math.max(0.001, bounds.width),+ height: Math.max(0.001, bounds.height),+ };+};+export const connectorDefinition: ShapeDefinition<'connector'> = {+ type: 'connector',+ label: 'Connector',+ validateGeometry(value): value is ConnectorGeometry {+ if (!value || typeof value !== 'object') return false;+ const g = value as Record<string, unknown>,+ heads = ['none', 'arrow', 'arrow-filled', 'circle', 'circle-small'];+ return (+ (g.label === undefined || validShapeLabel(g.label)) &&+ validEnd(g.start) &&+ validEnd(g.end) &&+ ['straight', 'stepped', 'smooth'].includes(String(g.route)) &&+ heads.includes(String(g.startHead)) &&+ heads.includes(String(g.endHead))+ );+ },+ freezeGeometry: (g) =>+ Object.freeze({+ ...g,+ start: freezeEnd(g.start),+ end: freezeEnd(g.end),+ ...(g.label ? { label: Object.freeze({ ...g.label }) } : {}),+ }),+ sameGeometry: (a, b) =>+ JSON.stringify(a.geometry) === JSON.stringify(b.geometry),+ bounds: (item) => connectorBounds(item, true),+ hitTest: (item, point, context) => {+ if (item.appearance.opacity === 0) return false;+ if (hitShapeLabel(item, point)) return true;+ if (+ item.appearance.stroke === 'transparent' ||+ item.appearance.strokeWidth === 0+ )+ return false;+ const g = item.geometry,+ path = connectorPath(g.start, g.end, g.route),+ p = transformPoint(context.worldTransform, point);+ const points = path.points.map((p) =>+ transformPoint(context.worldTransform, p)+ );+ const scale = Math.max(+ Math.hypot(context.worldTransform[0], context.worldTransform[1]),+ Math.hypot(context.worldTransform[2], context.worldTransform[3])+ );+ const tolerance =+ context.tolerance + ((item.appearance.strokeWidth ?? 2) * scale) / 2;+ if (+ points.some(+ (p1, i) => i > 0 && segmentDistance(p, points[i - 1]!, p1) <= tolerance+ )+ )+ return true;+ return (+ [+ ['start', path.from],+ ['end', path.to],+ ] as const+ ).some(([key, direction]) => {+ const style = key === 'start' ? g.startHead : g.endHead;+ if (style === 'none') return false;+ const vertices = headPoints(g[key].point, direction, style).map((v) =>+ transformPoint(context.worldTransform, v)+ );+ const filled = style !== 'arrow';+ if (filled && intersects([p], vertices)) return true;+ return vertices.some(+ (v, i) =>+ (filled || i > 0) &&+ segmentDistance(+ p,+ vertices[(i + vertices.length - 1) % vertices.length]!,+ v+ ) <= tolerance+ );+ });+ },+ intersectsBox: (item, world, box) => {+ const label = shapeLabelLayout(item);+ if (+ label &&+ intersects(+ corners({+ x: 0,+ y: 0,+ width: label.geometry.width,+ height: label.geometry.height,+ }).map((p) =>+ transformPoint(world, transformPoint(label.transform, p))+ ),+ corners(box)+ )+ )+ return true;+ const g = item.geometry,+ path = connectorPath(g.start, g.end, g.route),+ bounds = corners(box);+ const points = path.points.map((p) => transformPoint(world, p));+ if (points.some((p, i) => i > 0 && intersects([points[i - 1]!, p], bounds)))+ return true;+ return (+ [+ ['start', path.from, g.startHead],+ ['end', path.to, g.endHead],+ ] as const+ ).some(([key, direction, style]) => {+ if (style === 'none') return false;+ const vertices = headPoints(g[key].point, direction, style).map((p) =>+ transformPoint(world, p)+ );+ return style !== 'arrow'+ ? intersects(vertices, bounds)+ : vertices.some(+ (v, i) => i > 0 && intersects([vertices[i - 1]!, v], bounds)+ );+ });+ },+ resize: (item, size, context) => {+ const visible = connectorBounds(item, true),+ geometry = connectorBounds(item, false),+ sx = size.width / visible.width,+ sy = size.height / visible.height,+ midpoint = {+ x: (item.geometry.start.point.x + item.geometry.end.point.x) / 2,+ y: (item.geometry.start.point.y + item.geometry.end.point.y) / 2,+ },+ minimum = connectorBounds(+ {+ ...item,+ geometry: {+ ...item.geometry,+ start: { ...item.geometry.start, point: midpoint },+ end: { ...item.geometry.end, point: midpoint },+ },+ },+ true+ ),+ target = {+ width: Math.max(size.width, minimum.width),+ height: Math.max(size.height, minimum.height),+ },+ scaled = {+ left: size.x + visible.x * sx,+ right: size.x + (visible.x + visible.width) * sx,+ top: size.y + visible.y * sy,+ bottom: size.y + (visible.y + visible.height) * sy,+ },+ handle = context?.handle,+ targetOrigin = {+ x:+ target.width === size.width || handle?.includes('e')+ ? scaled.left+ : handle?.includes('w')+ ? scaled.right - target.width+ : (scaled.left + scaled.right - target.width) / 2,+ y:+ target.height === size.height || handle?.includes('s')+ ? scaled.top+ : handle?.includes('n')+ ? scaled.bottom - target.height+ : (scaled.top + scaled.bottom - target.height) / 2,+ };+ const flatX =+ Math.abs(item.geometry.end.point.x - item.geometry.start.point.x) < 1e-9;+ const flatY =+ Math.abs(item.geometry.end.point.y - item.geometry.start.point.y) < 1e-9;+ const expandFlatX = flatX && size.width > visible.width + 1e-9;+ const expandFlatY = flatY && size.height > visible.height + 1e-9;+ const resize = (e: ConnectorEndpoint, end: boolean) => ({+ ...e,+ point: {+ x: expandFlatX+ ? targetOrigin.x + (end ? target.width : 0)+ : flatX+ ? targetOrigin.x + target.width / 2+ : targetOrigin.x ++ ((e.point.x - geometry.x) * target.width) / geometry.width,+ y: expandFlatY+ ? targetOrigin.y + (end ? target.height : 0)+ : flatY+ ? targetOrigin.y + target.height / 2+ : targetOrigin.y ++ ((e.point.y - geometry.y) * target.height) / geometry.height,+ },+ });+ let start = resize(item.geometry.start, false),+ end = resize(item.geometry.end, true);+ // Labels and heads stay screen-legible instead of scaling with the route.+ // Refine the endpoint span against their fixed visible extents.+ for (let i = 0; i < 8; i++) {+ const candidate = {+ ...item,+ geometry: { ...item.geometry, start, end },+ };+ const actual = connectorBounds(candidate, true);+ if (+ Math.abs(actual.x - targetOrigin.x) < 1e-6 &&+ Math.abs(actual.y - targetOrigin.y) < 1e-6 &&+ Math.abs(actual.width - target.width) < 1e-6 &&+ Math.abs(actual.height - target.height) < 1e-6+ )+ return candidate;+ const adjust = (endpoint: ConnectorEndpoint) => ({+ ...endpoint,+ point: {+ x:+ flatX && !expandFlatX+ ? endpoint.point.x ++ (targetOrigin.x ++ target.width / 2 -+ (actual.x + actual.width / 2))+ : targetOrigin.x ++ ((endpoint.point.x - actual.x) * target.width) / actual.width,+ y:+ flatY && !expandFlatY+ ? endpoint.point.y ++ (targetOrigin.y ++ target.height / 2 -+ (actual.y + actual.height / 2))+ : targetOrigin.y ++ ((endpoint.point.y - actual.y) * target.height) / actual.height,+ },+ });+ start = adjust(start);+ end = adjust(end);+ }+ return {+ ...item,+ geometry: { ...item.geometry, start, end },+ };+ },+};diff --git a/packages/graphics/src/core/shapes/definition.ts b/packages/graphics/src/core/shapes/definition.tsnew file mode 100644index 0000000000..17eb73b923--- /dev/null+++ b/packages/graphics/src/core/shapes/definition.ts@@ -0,0 +1,48 @@+import type { Matrix } from '../affine';+import type {+ Bounds,+ Point,+ ShapeGeometryMap,+ ShapeItem,+ ShapeKind,+} from '../model';+import type { ResizeHandle } from '../resize';+import type { TextMeasurer } from './text';++export type HitTestContext = Readonly<{+ worldTransform: Matrix;+ tolerance: number;+}>;+/** Pure geometry contract. The host owns transforms, transactions and selection. */+export type ShapeDefinition<K extends ShapeKind> = Readonly<{+ type: K;+ label: string;+ /** False keeps mixed selections uniform, preserving typographic proportions. */+ canDeform?: boolean;+ /** Regenerate ink instead of magnifying its brush during group scaling. */+ regenerateOnScale?: boolean;+ validateGeometry(value: unknown): value is ShapeGeometryMap[K];+ freezeGeometry(geometry: ShapeGeometryMap[K]): ShapeGeometryMap[K];+ bounds(item: ShapeItem<K>): Bounds;+ /** Tight axis-aligned geometry bounds after a transform. Defaults to the+ * transformed local box; curved shapes can provide their actual extrema. */+ transformedBounds?(item: ShapeItem<K>, transform: Matrix): Bounds;+ hitTest(+ item: ShapeItem<K>,+ localPoint: Point,+ context: HitTestContext+ ): boolean;+ intersectsBox(+ item: ShapeItem<K>,+ worldTransform: Matrix,+ box: Bounds+ ): boolean;+ /** Resize about the local origin. The caller supplies positive bounds sizes+ * and handles translation/reflection. Brush-based shapes regenerate their ink. */+ resize(+ item: ShapeItem<K>,+ size: Bounds,+ context?: { handle?: ResizeHandle; measureText?: TextMeasurer }+ ): ShapeItem<K>;+ sameGeometry(a: ShapeItem<K>, b: ShapeItem<K>): boolean;+}>;diff --git a/packages/graphics/src/core/shapes/ellipse.ts b/packages/graphics/src/core/shapes/ellipse.tsnew file mode 100644index 0000000000..ffc0f804eb--- /dev/null+++ b/packages/graphics/src/core/shapes/ellipse.ts@@ -0,0 +1,144 @@+import {+ corners,+ IDENTITY,+ inverse,+ type Matrix,+ transformPoint,+} from '../affine';+import { resolveAppearance } from '../appearance';+import type { Point } from '../model';+import { segmentDistance } from './box-geometry';+import type { ShapeDefinition } from './definition';+import {+ freezeLabeledGeometry,+ hitShapeLabel,+ type LabeledGeometry,+ resizeLabeledShape,+ sameLabeledGeometry,+ validLabeledGeometry,+} from './label';++export type EllipseGeometry = LabeledGeometry;+const normalized = (g: EllipseGeometry, p: Point): Point => ({+ x: p.x / (g.width / 2) - 1,+ y: p.y / (g.height / 2) - 1,+});++/** Distance to an affine ellipse, measured in world units (including shear).+ * Principal axes turn it into an axis-aligned ellipse. The closest boundary point+ * solves q_i = axis_i² * p_i / (lambda + axis_i²), constrained to the ellipse.+ */+function outlineDistance(+ g: EllipseGeometry,+ world: Matrix,+ local: Point+): number {+ const rx = g.width / 2,+ ry = g.height / 2;+ const ux = world[0] * rx,+ uy = world[1] * rx;+ const vx = world[2] * ry,+ vy = world[3] * ry;+ const xx = ux * ux + vx * vx,+ yy = uy * uy + vy * vy,+ xy = ux * uy + vx * vy;+ const majorSquared = (xx + yy + Math.hypot(xx - yy, 2 * xy)) / 2;+ const major = Math.sqrt(majorSquared);+ const minor = Math.abs(ux * vy - uy * vx) / major;+ const angle = Math.atan2(2 * xy, xx - yy) / 2;+ const c = Math.cos(angle),+ s = Math.sin(angle);+ const dx = world[0] * (local.x - rx) + world[2] * (local.y - ry);+ const dy = world[1] * (local.x - rx) + world[3] * (local.y - ry);+ const x = Math.abs(c * dx + s * dy) / major;+ const y = Math.abs(-s * dx + c * dy) / major;+ const b = minor / major,+ b2 = b * b;+ if (y < 1e-14) {+ const qx = x < 1 - b2 ? x / (1 - b2) : 1;+ const qy = b * Math.sqrt(Math.max(0, 1 - qx * qx));+ return Math.hypot(x - qx, y - qy) * major;+ }+ let low = -b2,+ high = Math.hypot(x, b * y);+ for (let i = 0; i < 80; i++) {+ const lambda = (low + high) / 2;+ if ((x / (lambda + 1)) ** 2 + ((b * y) / (lambda + b2)) ** 2 > 1)+ low = lambda;+ else high = lambda;+ }+ const lambda = (low + high) / 2;+ return Math.hypot(x - x / (lambda + 1), y - (b2 * y) / (lambda + b2)) * major;+}+export const ellipseDefinition: ShapeDefinition<'ellipse'> = {+ type: 'ellipse',+ label: 'Ellipse',+ validateGeometry: validLabeledGeometry,+ freezeGeometry: freezeLabeledGeometry,+ bounds: (item) => ({+ x: 0,+ y: 0,+ width: item.geometry.width,+ height: item.geometry.height,+ }),+ transformedBounds: (item, transform) => {+ const rx = item.geometry.width / 2,+ ry = item.geometry.height / 2;+ const center = transformPoint(transform, { x: rx, y: ry });+ // Each transformed coordinate is A cos(t) + B sin(t), whose amplitude+ // is hypot(A, B). This also handles shear, reflection and ancestor scale.+ const x = Math.hypot(transform[0] * rx, transform[2] * ry);+ const y = Math.hypot(transform[1] * rx, transform[3] * ry);+ return {+ x: center.x - x,+ y: center.y - y,+ width: 2 * x,+ height: 2 * y,+ };+ },+ resize: (item, size, context) =>+ resizeLabeledShape(item, size, context?.measureText),+ sameGeometry: (a, b) => sameLabeledGeometry(a.geometry, b.geometry),+ hitTest: (item, p, context) => {+ const style = resolveAppearance(item.appearance);+ if (style.opacity === 0) return false;+ if (hitShapeLabel(item, p)) return true;+ const unit = normalized(item.geometry, p);+ if (+ item.appearance.fill !== 'transparent' &&+ Math.hypot(unit.x, unit.y) <= 1+ )+ return true;+ if (style.stroke === 'transparent' || style.strokeWidth === 0) return false;+ return (+ outlineDistance(item.geometry, IDENTITY, p) <= style.strokeWidth / 2 ||+ outlineDistance(item.geometry, context.worldTransform, p) <=+ context.tolerance + 1e-10+ );+ },+ intersectsBox: (item, world, box) => {+ const center = transformPoint(world, {+ x: item.geometry.width / 2,+ y: item.geometry.height / 2,+ });+ if (+ center.x >= box.x &&+ center.x <= box.x + box.width &&+ center.y >= box.y &&+ center.y <= box.y + box.height+ )+ return true;+ const inverseWorld = inverse(world);+ const polygon = corners(box).map((p) =>+ normalized(item.geometry, transformPoint(inverseWorld, p))+ );+ return polygon.some(+ (p, i) =>+ segmentDistance(+ { x: 0, y: 0 },+ p,+ polygon[(i + 1) % polygon.length]!+ ) <= 1+ );+ },+};diff --git a/packages/graphics/src/core/shapes/embedded.ts b/packages/graphics/src/core/shapes/embedded.tsnew file mode 100644index 0000000000..b4e0bdeff5--- /dev/null+++ b/packages/graphics/src/core/shapes/embedded.ts@@ -0,0 +1,104 @@+import { corners, intersects, transformPoint } from '../affine';+import type { ShapeGeometryMap, ShapeItem } from '../model';+import { type BoxGeometry, validBoxGeometry } from './box-geometry';+import type { ShapeDefinition } from './definition';++/** Stable references only. Signed URLs, upload progress and players belong to hosts. */+export type MediaSource =+ | Readonly<{ type: 'document' | 'static'; id: string }>+ | Readonly<{ type: 'url'; url: string }>;+export type MediaGeometry = BoxGeometry &+ Readonly<{ source: MediaSource; name: string }>;+export type DocumentGeometry = BoxGeometry &+ Readonly<{+ documentId: string;+ name: string;+ fileType: string;+ /** Host-owned entity kind for references that are not stored documents. */+ entityType?: string;+ /** Opaque host navigation state retained from imported references. */+ subpath?: string;+ display?: 'preview' | 'embed';+ }>;+const record = (v: unknown): v is Record<string, unknown> =>+ !!v && typeof v === 'object';+export const validMediaSource = (v: unknown): v is MediaSource =>+ record(v) &&+ (((v.type === 'document' || v.type === 'static') &&+ typeof v.id === 'string' &&+ !!v.id.trim()) ||+ (v.type === 'url' &&+ typeof v.url === 'string' &&+ /^(https?:\/\/|\/(?!\/))[^\s]+$/i.test(v.url)));+function definition<K extends 'image' | 'video' | 'document'>(+ type: K,+ label: string,+ validate: (v: unknown) => v is ShapeGeometryMap[K]+): ShapeDefinition<K> {+ const bounds = (item: ShapeItem<K>) => ({+ x: 0,+ y: 0,+ width: item.geometry.width,+ height: item.geometry.height,+ });+ return {+ type,+ label,+ validateGeometry: validate,+ freezeGeometry: (g) =>+ Object.freeze({+ ...g,+ ...('source' in g ? { source: Object.freeze({ ...g.source }) } : {}),+ }) as ShapeGeometryMap[K],+ bounds,+ sameGeometry: (a, b) =>+ JSON.stringify(a.geometry) === JSON.stringify(b.geometry),+ hitTest: (item, p) =>+ (item.appearance.opacity ?? 1) > 0 &&+ p.x >= 0 &&+ p.y >= 0 &&+ p.x <= item.geometry.width &&+ p.y <= item.geometry.height,+ intersectsBox: (item, world, box) =>+ intersects(+ corners(bounds(item)).map((p) => transformPoint(world, p)),+ corners(box)+ ),+ resize: (item, size) => ({+ ...item,+ geometry: { ...item.geometry, width: size.width, height: size.height },+ }),+ };+}+const validMedia = (v: unknown): v is MediaGeometry =>+ validBoxGeometry(v) &&+ 'source' in v &&+ validMediaSource(v.source) &&+ 'name' in v &&+ typeof v.name === 'string';+export const imageDefinition = definition('image', 'Image', validMedia);+export const videoDefinition = definition('video', 'Video', validMedia);+export const documentDefinition = definition(+ 'document',+ 'Document',+ (v): v is DocumentGeometry =>+ validBoxGeometry(v) &&+ 'documentId' in v &&+ typeof v.documentId === 'string' &&+ !!v.documentId.trim() &&+ 'fileType' in v &&+ typeof v.fileType === 'string' &&+ !!v.fileType.trim() &&+ (!('entityType' in v) ||+ v.entityType === undefined ||+ (typeof v.entityType === 'string' && !!v.entityType.trim())) &&+ (!('subpath' in v) ||+ v.subpath === undefined ||+ typeof v.subpath === 'string') &&+ (!('display' in v) ||+ v.display === undefined ||+ v.display === 'preview' ||+ v.display === 'embed') &&+ 'name' in v &&+ typeof v.name === 'string'+);diff --git a/packages/graphics/src/core/shapes/label.ts b/packages/graphics/src/core/shapes/label.tsnew file mode 100644index 0000000000..7ea3fd9e7b--- /dev/null+++ b/packages/graphics/src/core/shapes/label.ts@@ -0,0 +1,215 @@+import {+ inverse,+ multiply,+ scaling,+ transformPoint,+ translation,+} from '../affine';+import type { GraphicsItem, Point, ShapeItem } from '../model';+import {+ type BoxGeometry,+ sameBoxGeometry,+ validBoxGeometry,+} from './box-geometry';+import { connectorPath } from './connector-routing';+import { type TextGeometry, type TextMeasurer, textDefinition } from './text';++/** A shape-owned annotation, not an independently selectable scene node. */+export type ShapeLabel = Pick<+ TextGeometry,+ 'content' | 'fontSize' | 'fontFamily' | 'height'+> &+ Readonly<{+ /** Measured text width for connectors; box labels use the interior. */+ width?: number;+ }>;+export type LabeledGeometry = BoxGeometry & Readonly<{ label?: ShapeLabel }>;+export type LabelShape = ShapeItem<'rectangle' | 'ellipse' | 'connector'>;+export const canLabel = (item: GraphicsItem | undefined): item is LabelShape =>+ item?.type === 'rectangle' ||+ item?.type === 'ellipse' ||+ item?.type === 'connector';+const innerSize = (item: ShapeItem<'rectangle' | 'ellipse'>) => {+ const ratio = item.type === 'ellipse' ? Math.SQRT1_2 : 1;+ return {+ width: Math.max(1, item.geometry.width * ratio - 24),+ height: Math.max(1, item.geometry.height * ratio - 24),+ };+};+export function labelTextGeometry(+ item: LabelShape,+ label: ShapeLabel+): TextGeometry {+ return {+ ...label,+ autoWidth: false,+ width:+ item.type === 'connector'+ ? (label.width ?? 240)+ : Math.max(label.fontSize * 2, innerSize(item).width),+ };+}+export function measureShapeLabel(+ item: LabelShape,+ label: ShapeLabel,+ measure?: TextMeasurer+): ShapeLabel {+ if (item.type === 'connector') {+ const size = measure?.({+ ...labelTextGeometry(item, label),+ autoWidth: true,+ });+ return {+ ...label,+ width: size?.width ?? label.width ?? 240,+ height: size?.height ?? label.height,+ };+ }+ return {+ ...label,+ height: measure?.(labelTextGeometry(item, label)).height ?? label.height,+ };+}+/** Same local layout feeds rendering, the editing overlay, and painted picking.+ * Small shapes fit the wrapped label uniformly; glyphs are never stretched. */+export function shapeLabelLayout(item: LabelShape) {+ const label = item.geometry.label;+ if (!label) return;+ const geometry = labelTextGeometry(item, label);+ if (item.type === 'connector') {+ const { start, end, route } = item.geometry;+ const points = connectorPath(start, end, route).points;+ const lengths = points+ .slice(1)+ .map((p, i) => Math.hypot(p.x - points[i]!.x, p.y - points[i]!.y));+ let remaining = lengths.reduce((sum, length) => sum + length, 0) / 2;+ let center = start.point;+ for (let i = 0; i < lengths.length; i++) {+ const length = lengths[i]!;+ if (remaining <= length) {+ const a = points[i]!,+ b = points[i + 1]!,+ t = length ? remaining / length : 0;+ center = { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };+ break;+ }+ remaining -= length;+ }+ return {+ geometry,+ transform: translation(+ center.x - geometry.width / 2,+ center.y - geometry.height / 2+ ),+ };+ }+ const inner = innerSize(item);+ const scale = Math.min(+ 1,+ inner.width / geometry.width,+ inner.height / geometry.height+ );+ return {+ geometry,+ transform: multiply(+ translation(+ (item.geometry.width - geometry.width * scale) / 2,+ (item.geometry.height - geometry.height * scale) / 2+ ),+ scaling(scale, scale)+ ),+ };+}+/** An ephemeral text projection lets hosts reuse their text editor. Never persist it. */+export function shapeLabelText(+ item: LabelShape+): ShapeItem<'text'> | undefined {+ const layout = shapeLabelLayout(item);+ if (!layout) return;+ return {+ ...item,+ type: 'text',+ geometry: layout.geometry,+ transform: multiply(item.transform, layout.transform),+ appearance: {+ ...item.appearance,+ stroke:+ item.appearance.stroke === 'transparent'+ ? 'currentColor'+ : item.appearance.stroke,+ },+ };+}+export function hitShapeLabel(item: LabelShape, point: Point): boolean {+ const layout = shapeLabelLayout(item);+ if (!layout) return false;+ const p = transformPoint(inverse(layout.transform), point);+ return (+ p.x >= 0 &&+ p.y >= 0 &&+ p.x <= layout.geometry.width &&+ p.y <= layout.geometry.height+ );+}+export function validShapeLabel(value: unknown): value is ShapeLabel {+ return (+ !!value &&+ typeof value === 'object' &&+ textDefinition.validateGeometry({ width: 1, ...value, autoWidth: false })+ );+}+export function validLabeledGeometry(value: unknown): value is LabeledGeometry {+ return (+ validBoxGeometry(value) &&+ (!('label' in value) ||+ value.label === undefined ||+ validShapeLabel(value.label))+ );+}+export function freezeLabeledGeometry(+ geometry: LabeledGeometry+): LabeledGeometry {+ return Object.freeze({+ ...geometry,+ width: geometry.width,+ height: geometry.height,+ ...(geometry.label+ ? {+ label: Object.freeze({+ ...geometry.label,+ content: geometry.label.content,+ }),+ }+ : {}),+ });+}+export function sameLabeledGeometry(a: LabeledGeometry, b: LabeledGeometry) {+ return sameBoxGeometry(a, b) && JSON.stringify(a) === JSON.stringify(b);+}+export function resizeLabeledShape<+ T extends ShapeItem<'rectangle' | 'ellipse'>,+>(item: T, size: BoxGeometry, measure?: TextMeasurer): T {+ const resized = {+ ...item,+ geometry: { ...item.geometry, width: size.width, height: size.height },+ };+ const label = item.geometry.label;+ return label+ ? {+ ...resized,+ geometry: {+ ...resized.geometry,+ label: measureShapeLabel(resized, label, measure),+ },+ }+ : resized;+}++/** Replace a label while preserving the owner's geometry and discriminant. */+export function withShapeLabel<T extends LabelShape>(+ item: T,+ label?: ShapeLabel+): T {+ const { label: _previous, ...geometry } = item.geometry;+ return { ...item, geometry: { ...geometry, ...(label ? { label } : {}) } };+}diff --git a/packages/graphics/src/core/shapes/pencil.ts b/packages/graphics/src/core/shapes/pencil.tsnew file mode 100644index 0000000000..0631351a1b--- /dev/null+++ b/packages/graphics/src/core/shapes/pencil.ts@@ -0,0 +1,295 @@+import {+ getStrokeOutlinePoints,+ getStrokePoints,+ type StrokeOptions,+} from 'perfect-freehand';+import { corners, enclosing, transformPoint } from '../affine';+import { resolveAppearance } from '../appearance';+import type { Bounds, PencilItem, Point } from '../model';+import { segmentDistance } from './box-geometry';+import type { ShapeDefinition } from './definition';++export type PencilPoint = readonly [x: number, y: number, pressure: number];+export type PencilGeometry = Readonly<{+ points: readonly PencilPoint[];+ simulatePressure: boolean;+}>;+export const MAX_PENCIL_POINTS = 16384;+type Ink = {+ outline: Point[];+ path: string;+ centerline: string;+ bounds: Bounds;+};+const cache = new WeakMap<PencilGeometry, { size: number; ink: Ink }>();++/** Document samples remain raw. Brush policy and generated ink stay internal.+ * Rebuild after resizing so mouse pressure follows the new point spacing. */+export function pencilInk(item: PencilItem) {+ const size = resolveAppearance(item.appearance).strokeWidth;+ const cached = cache.get(item.geometry);+ if (cached?.size === size) return cached.ink;+ const options: StrokeOptions = {+ size: Math.max(size, 0.01),+ thinning: 0.5,+ smoothing: 0.65,+ streamline: 0.6,+ simulatePressure: item.geometry.simulatePressure,+ easing: (pressure) => Math.sin((pressure * Math.PI) / 2),+ last: true,+ };+ const strokePoints = getStrokePoints(+ item.geometry.points.map((p) => [...p]),+ options+ );+ const outline = getStrokeOutlinePoints(strokePoints, options).map(+ ([x, y]) => ({ x, y })+ );+ // The same polygon is painted and picked, including self-overlapping strokes.+ const path = outline.length+ ? `M${outline.map((p) => `${p.x},${p.y}`).join('L')}Z`+ : '';+ // Use the brush's streamlined centerline, not the unsmoothed input samples.+ // A tap gets a zero-length segment, painted as a dot with round caps.+ const centerline =+ item.geometry.points.length === 1+ ? `M${item.geometry.points[0]![0]},${item.geometry.points[0]![1]}l0,0`+ : `M${strokePoints.map(({ point }) => point.join(',')).join('L')}`;+ const ink = { outline, path, centerline, bounds: enclosing(outline) };+ // Mutable Solid-store projections must keep their dependency reads; only plain+ // immutable core geometries can safely be cached by identity.+ if (Object.isFrozen(item.geometry)) cache.set(item.geometry, { size, ink });+ return ink;+}++/** SVG's default nonzero winding rule, including ink crossing over itself. */+function contains(polygon: readonly Point[], point: Point) {+ let winding = 0;+ polygon.forEach((a, i) => {+ const b = polygon[(i + 1) % polygon.length]!;+ const side = (b.x - a.x) * (point.y - a.y) - (point.x - a.x) * (b.y - a.y);+ if (a.y <= point.y && b.y > point.y && side > 0) winding++;+ if (a.y > point.y && b.y <= point.y && side < 0) winding--;+ });+ return winding !== 0;+}++function segmentIntersectsBox(a: Point, b: Point, box: Bounds) {+ let low = 0,+ high = 1;+ for (const [start, delta, min, max] of [+ [a.x, b.x - a.x, box.x, box.x + box.width],+ [a.y, b.y - a.y, box.y, box.y + box.height],+ ] as const) {+ if (delta === 0) {+ if (start < min || start > max) return false;+ } else {+ const t1 = (min - start) / delta,+ t2 = (max - start) / delta;+ low = Math.max(low, Math.min(t1, t2));+ high = Math.min(high, Math.max(t1, t2));+ if (low > high) return false;+ }+ }+ return true;+}++export const pencilDefinition: ShapeDefinition<'pencil'> = {+ type: 'pencil',+ label: 'Pencil',+ regenerateOnScale: true,+ validateGeometry: (value): value is PencilGeometry => {+ if (!value || typeof value !== 'object') return false;+ const geometry = value as Partial<PencilGeometry>;+ return (+ typeof geometry.simulatePressure === 'boolean' &&+ Array.isArray(geometry.points) &&+ geometry.points.length > 0 &&+ geometry.points.length <= MAX_PENCIL_POINTS &&+ geometry.points.every(+ (p) =>+ Array.isArray(p) &&+ p.length === 3 &&+ p.every(Number.isFinite) &&+ p[2] >= 0 &&+ p[2] <= 1+ )+ );+ },+ freezeGeometry: (geometry) =>+ Object.freeze({+ ...geometry,+ simulatePressure: geometry.simulatePressure,+ points: Object.freeze(+ geometry.points.map((point) => Object.freeze([...point]) as PencilPoint)+ ),+ }),+ bounds: (item) => pencilInk(item).bounds,+ resize: (item, size, context) => {+ const visible = pencilInk(item).bounds;+ if (!context?.handle) {+ const sx = size.width / visible.width,+ sy = size.height / visible.height;+ return {+ ...item,+ geometry: pencilDefinition.freezeGeometry({+ ...item.geometry,+ points: item.geometry.points.map(([x, y, pressure]) => [+ x * sx,+ y * sy,+ pressure,+ ]),+ }),+ };+ }+ const xs = item.geometry.points.map(([x]) => x),+ ys = item.geometry.points.map(([, y]) => y),+ minX = Math.min(...xs),+ maxX = Math.max(...xs),+ minY = Math.min(...ys),+ maxY = Math.max(...ys),+ flatX = maxX - minX < 1e-9,+ flatY = maxY - minY < 1e-9,+ margins = {+ left: minX - visible.x,+ right: visible.x + visible.width - maxX,+ top: minY - visible.y,+ bottom: visible.y + visible.height - maxY,+ },+ sx = size.width / visible.width,+ sy = size.height / visible.height,+ scaled = {+ left: size.x + visible.x * sx,+ right: size.x + (visible.x + visible.width) * sx,+ top: size.y + visible.y * sy,+ bottom: size.y + (visible.y + visible.height) * sy,+ },+ target = {+ width: flatX+ ? visible.width+ : Math.max(size.width, margins.left + margins.right + 0.001),+ height: flatY+ ? visible.height+ : Math.max(size.height, margins.top + margins.bottom + 0.001),+ },+ handle = context.handle,+ targetOrigin = {+ x:+ target.width === size.width || handle?.includes('e')+ ? scaled.left+ : handle?.includes('w')+ ? scaled.right - target.width+ : (scaled.left + scaled.right - target.width) / 2,+ y:+ target.height === size.height || handle?.includes('s')+ ? scaled.top+ : handle?.includes('n')+ ? scaled.bottom - target.height+ : (scaled.top + scaled.bottom - target.height) / 2,+ },+ targetSamples = {+ left: targetOrigin.x + margins.left,+ right: targetOrigin.x + target.width - margins.right,+ top: targetOrigin.y + margins.top,+ bottom: targetOrigin.y + target.height - margins.bottom,+ };+ let points = item.geometry.points.map(+ ([x, y, pressure]) =>+ [+ flatX+ ? x ++ (targetOrigin.x ++ target.width / 2 -+ (visible.x + visible.width / 2))+ : targetSamples.left ++ ((x - minX) * (targetSamples.right - targetSamples.left)) /+ (maxX - minX),+ flatY+ ? y ++ (targetOrigin.y ++ target.height / 2 -+ (visible.y + visible.height / 2))+ : targetSamples.top ++ ((y - minY) * (targetSamples.bottom - targetSamples.top)) /+ (maxY - minY),+ pressure,+ ] as PencilPoint+ );+ let candidate = {+ ...item,+ geometry: pencilDefinition.freezeGeometry({+ ...item.geometry,+ points,+ }),+ };+ // Perfect Freehand's pressure and smoothing can change the brush margins+ // after a nonuniform stretch. Refine against the generated outline so the+ // visible ink, rather than only its input samples, reaches the requested+ // bounds while the caller keeps the opposite resize edge anchored.+ for (let i = 0; i < 4; i++) {+ const actual = pencilInk(candidate).bounds;+ if (+ (Math.abs(actual.x - targetOrigin.x) < 0.1 &&+ Math.abs(actual.y - targetOrigin.y) < 0.1 &&+ Math.abs(actual.width - target.width) < 0.1 &&+ Math.abs(actual.height - target.height) < 0.1) ||+ i === 3+ )+ return candidate;+ points = points.map(([x, y, pressure]) => [+ flatX+ ? x ++ (targetOrigin.x + target.width / 2 - (actual.x + actual.width / 2))+ : targetOrigin.x + ((x - actual.x) * target.width) / actual.width,+ flatY+ ? y ++ (targetOrigin.y ++ target.height / 2 -+ (actual.y + actual.height / 2))+ : targetOrigin.y + ((y - actual.y) * target.height) / actual.height,+ pressure,+ ]);+ candidate = {+ ...item,+ geometry: pencilDefinition.freezeGeometry({+ ...item.geometry,+ points,+ }),+ };+ }+ return candidate;+ },+ sameGeometry: (a, b) =>+ JSON.stringify(a.geometry) === JSON.stringify(b.geometry),+ hitTest: (item, point, context) => {+ const style = resolveAppearance(item.appearance);+ if (+ style.opacity === 0 ||+ style.stroke === 'transparent' ||+ style.strokeWidth === 0+ )+ return false;+ const { outline } = pencilInk(item);+ if (contains(outline, point)) return true;+ const worldPoint = transformPoint(context.worldTransform, point);+ const polygon = outline.map((p) =>+ transformPoint(context.worldTransform, p)+ );+ return polygon.some(+ (p, i) =>+ segmentDistance(worldPoint, p, polygon[(i + 1) % polygon.length]!) <=+ context.tolerance+ );+ },+ intersectsBox: (item, world, box) => {+ const polygon = pencilInk(item).outline.map((p) =>+ transformPoint(world, p)+ );+ return (+ corners(box).some((point) => contains(polygon, point)) ||+ polygon.some((p, i) =>+ segmentIntersectsBox(p, polygon[(i + 1) % polygon.length]!, box)+ )+ );+ },+};diff --git a/packages/graphics/src/core/shapes/rectangle.ts b/packages/graphics/src/core/shapes/rectangle.tsnew file mode 100644index 0000000000..997f9570ce--- /dev/null+++ b/packages/graphics/src/core/shapes/rectangle.ts@@ -0,0 +1,78 @@+import { corners, intersects, transformPoint } from '../affine';+import { resolveAppearance } from '../appearance';+import { segmentDistance } from './box-geometry';+import type { ShapeDefinition } from './definition';+import {+ freezeLabeledGeometry,+ hitShapeLabel,+ type LabeledGeometry,+ resizeLabeledShape,+ sameLabeledGeometry,+ validLabeledGeometry,+} from './label';++export type RectangleGeometry = LabeledGeometry;+export const rectangleDefinition: ShapeDefinition<'rectangle'> = {+ type: 'rectangle',+ label: 'Rectangle',+ validateGeometry: validLabeledGeometry,+ freezeGeometry: freezeLabeledGeometry,+ bounds: (item) => ({+ x: 0,+ y: 0,+ width: item.geometry.width,+ height: item.geometry.height,+ }),+ resize: (item, size, context) =>+ resizeLabeledShape(item, size, context?.measureText),+ sameGeometry: (a, b) => sameLabeledGeometry(a.geometry, b.geometry),+ hitTest: (item, p, { worldTransform, tolerance }) => {+ const style = resolveAppearance(item.appearance);+ if (style.opacity === 0) return false;+ if (hitShapeLabel(item, p)) return true;+ const { width, height } = item.geometry;+ const radius = Math.min(style.cornerRadius, width / 2, height / 2);+ const dx = Math.abs(p.x - width / 2) - width / 2 + radius;+ const dy = Math.abs(p.y - height / 2) - height / 2 + radius;+ const distance =+ Math.hypot(Math.max(dx, 0), Math.max(dy, 0)) ++ Math.min(Math.max(dx, dy), 0) -+ radius;+ if (style.fill !== 'transparent' && distance <= 0) return true;+ if (style.stroke === 'transparent' || style.strokeWidth === 0) return false;+ if (Math.abs(distance) <= style.strokeWidth / 2) return true;+ const point = transformPoint(worldTransform, p);+ const outline =+ radius === 0+ ? corners(rectangleDefinition.bounds(item)).map((p) =>+ transformPoint(worldTransform, p)+ )+ : Array.from({ length: 260 }, (_, i) => {+ const corner = Math.floor(i / 65),+ angle =+ -Math.PI / 2 ++ (corner * Math.PI) / 2 ++ (((i % 65) / 64) * Math.PI) / 2;+ return transformPoint(worldTransform, {+ x:+ (corner < 2 ? width - radius : radius) ++ radius * Math.cos(angle),+ y:+ (corner === 0 || corner === 3 ? radius : height - radius) ++ radius * Math.sin(angle),+ });+ });+ return outline.some(+ (start, i) =>+ segmentDistance(point, start, outline[(i + 1) % outline.length]!) <=+ tolerance+ );+ },+ intersectsBox: (item, world, box) =>+ intersects(+ corners(rectangleDefinition.bounds(item)).map((p) =>+ transformPoint(world, p)+ ),+ corners(box)+ ),+};diff --git a/packages/graphics/src/core/shapes/registry.ts b/packages/graphics/src/core/shapes/registry.tsnew file mode 100644index 0000000000..2a010107d8--- /dev/null+++ b/packages/graphics/src/core/shapes/registry.ts@@ -0,0 +1,49 @@+import type { GraphicsItem, ShapeItem, ShapeKind } from '../model';+import { connectorDefinition } from './connector';+import type { ShapeDefinition } from './definition';+import { ellipseDefinition } from './ellipse';+import {+ documentDefinition,+ imageDefinition,+ videoDefinition,+} from './embedded';+import { pencilDefinition } from './pencil';+import { rectangleDefinition } from './rectangle';+import { textDefinition } from './text';++/** Explicit compile-time registration; kind and definition must agree. */+export const shapeDefinitions: {+ readonly [K in ShapeKind]: ShapeDefinition<K>;+} = Object.freeze({+ connector: connectorDefinition,+ rectangle: rectangleDefinition,+ ellipse: ellipseDefinition,+ pencil: pencilDefinition,+ text: textDefinition,+ image: imageDefinition,+ video: videoDefinition,+ document: documentDefinition,+});+export const shapeKinds = Object.freeze(+ Object.keys(shapeDefinitions) as ShapeKind[]+);+export const isShapeKind = (value: unknown): value is ShapeKind =>+ typeof value === 'string' && Object.hasOwn(shapeDefinitions, value);+export const isShape = (item: GraphicsItem | undefined): item is ShapeItem =>+ !!item && isShapeKind(item.type);+export function shapeDefinition<K extends ShapeKind>(+ kind: K+): ShapeDefinition<K> {+ // The mapped registry enforces this key/item correlation at registration.+ return shapeDefinitions[kind] as ShapeDefinition<K>;+}++/** Validate the kind/geometry correlation at wire and clipboard boundaries. */+export function shapePayload<K extends ShapeKind>(kind: K, geometry: unknown) {+ const definition = shapeDefinition(kind);+ if (!definition.validateGeometry(geometry))+ throw new Error(`Invalid ${kind} geometry`);+ return { type: kind, geometry: definition.freezeGeometry(geometry) } as {+ [P in K]: Pick<ShapeItem<P>, 'type' | 'geometry'>;+ }[K];+}diff --git a/packages/graphics/src/core/shapes/text.ts b/packages/graphics/src/core/shapes/text.tsnew file mode 100644index 0000000000..d2ac060b11--- /dev/null+++ b/packages/graphics/src/core/shapes/text.ts@@ -0,0 +1,83 @@+import { corners, intersects, transformPoint } from '../affine';+import type { Bounds } from '../model';+import { type RichText, validRichText } from '../rich-text';+import { validBoxGeometry } from './box-geometry';+import type { ShapeDefinition } from './definition';+export type TextFont = 'sans' | 'serif' | 'mono';+export type TextGeometry = Readonly<{+ width: number;+ height: number;+ autoWidth: boolean;+ fontSize: number;+ fontFamily: TextFont;+ content: RichText;+}>;+/** The host measures with its actual fonts; the core never calls browser layout. */+export type TextMeasurer = (+ geometry: TextGeometry+) => Pick<Bounds, 'width' | 'height'>;+export const textDefinition: ShapeDefinition<'text'> = {+ type: 'text',+ label: 'Text',+ canDeform: false,+ validateGeometry(value): value is TextGeometry {+ if (!validBoxGeometry(value)) return false;+ const v = value as Record<string, unknown>;+ return (+ typeof v.autoWidth === 'boolean' &&+ typeof v.fontSize === 'number' &&+ Number.isFinite(v.fontSize) &&+ v.fontSize > 0 &&+ v.fontSize <= 10000 &&+ ['sans', 'serif', 'mono'].includes(String(v.fontFamily)) &&+ validRichText(v.content)+ );+ },+ freezeGeometry: (geometry) => Object.freeze({ ...geometry }),+ bounds: (item) => ({+ x: 0,+ y: 0,+ width: item.geometry.width,+ height: item.geometry.height,+ }),+ sameGeometry: (a, b) =>+ JSON.stringify(a.geometry) === JSON.stringify(b.geometry),+ hitTest: (item, p) =>+ (item.appearance.opacity ?? 1) > 0 &&+ p.x >= 0 &&+ p.y >= 0 &&+ p.x <= item.geometry.width &&+ p.y <= item.geometry.height,+ intersectsBox: (item, world, box) =>+ intersects(+ corners(textDefinition.bounds(item)).map((p) => transformPoint(world, p)),+ corners(box)+ ),+ resize: (item, size, context) => {+ const reflow = context?.handle === 'e' || context?.handle === 'w';+ const geometry: TextGeometry = {+ ...item.geometry,+ width: Math.max(1, size.width),+ height: Math.max(1, size.height),+ autoWidth: reflow ? false : item.geometry.autoWidth,+ fontSize: reflow+ ? item.geometry.fontSize+ : Math.max(+ 0.1,+ Math.min(+ 10000,+ (item.geometry.fontSize * size.height) / item.geometry.height+ )+ ),+ };+ return {+ ...item,+ // Corner scaling preserves the layout; remeasuring at fractional font+ // sizes can change wrapping and make the dragged corner jump. Only a+ // width edit needs new layout from the host.+ geometry: reflow+ ? { ...geometry, ...context?.measureText?.(geometry) }+ : geometry,+ };+ },+};diff --git a/packages/graphics/src/core/snapping.ts b/packages/graphics/src/core/snapping.tsnew file mode 100644index 0000000000..f1c2ba1d66--- /dev/null+++ b/packages/graphics/src/core/snapping.ts@@ -0,0 +1,32 @@+import type { Point } from './model';++/** Snapping is local editor policy, expressed in scene units, not screen pixels. */+export function validateSnapUnit(unit: number | undefined) {+ if (unit !== undefined && (!Number.isFinite(unit) || unit <= 0))+ throw new Error('Snap unit must be a positive finite number');+}++export function snapValue(value: number, unit?: number): number {+ validateSnapUnit(unit);+ if (unit === undefined) return value;+ const snapped = Math.round(value / unit) * unit;+ // Very small units can be below the representable precision of the coordinate.+ return Number.isFinite(snapped) ? snapped || 0 : value;+}++export function snapPoint(point: Point, unit?: number): Point {+ return { x: snapValue(point.x, unit), y: snapValue(point.y, unit) };+}++/** Snap a moving anchor, preserving pointer grab offset and untouched axes. */+export function snapTranslation(+ anchor: Point,+ delta: Point,+ unit?: number+): Point {+ if (unit === undefined) return delta;+ return {+ x: delta.x === 0 ? 0 : snapValue(anchor.x + delta.x, unit) - anchor.x,+ y: delta.y === 0 ? 0 : snapValue(anchor.y + delta.y, unit) - anchor.y,+ };+}diff --git a/packages/graphics/src/core/stretch.ts b/packages/graphics/src/core/stretch.tsnew file mode 100644index 0000000000..02de83ad7d--- /dev/null+++ b/packages/graphics/src/core/stretch.ts@@ -0,0 +1,155 @@+import {+ inverse,+ type Matrix,+ multiply,+ scaling,+ transformPoint,+ transformVector,+} from './affine';+import type { Bounds, GraphicsDocument, GraphicsItem, Point } from './model';+import type { ResizeHandle } from './resize';+import { resolvedShape, worldMatrix } from './scene';+import { isShape, shapeDefinition } from './shapes/registry';+import type { TextMeasurer } from './shapes/text';+import { selectedShapeIds } from './style-selection';++function oppositeAnchor(bounds: Bounds, handle: ResizeHandle): Point {+ const right = bounds.x + bounds.width,+ bottom = bounds.y + bounds.height;+ switch (handle) {+ case 'e':+ case 's':+ case 'se':+ return { x: bounds.x, y: bounds.y };+ case 'w':+ case 'sw':+ return { x: right, y: bounds.y };+ case 'n':+ case 'ne':+ return { x: bounds.x, y: bottom };+ case 'nw':+ return { x: right, y: bottom };+ }+}++function localResizeHandle(handle: ResizeHandle, world: Matrix): ResizeHandle {+ const direction = transformVector(inverse(world), {+ x: handle.includes('e') ? 1 : handle.includes('w') ? -1 : 0,+ y: handle.includes('s') ? 1 : handle.includes('n') ? -1 : 0,+ });+ const threshold =+ Math.max(Math.abs(direction.x), Math.abs(direction.y)) * 1e-8;+ const vertical =+ Math.abs(direction.y) <= threshold ? '' : direction.y < 0 ? 'n' : 's';+ const horizontal =+ Math.abs(direction.x) <= threshold ? '' : direction.x < 0 ? 'w' : 'e';+ return `${vertical}${horizontal}` as ResizeHandle;+}++/** Selected groups may scale their frame; ink opts to absorb that scale into+ * samples and cancel the added magnification in its local pose. */+export function regenerateScaledShapes(+ document: GraphicsDocument,+ selected: readonly string[],+ nodes: Record<string, GraphicsItem>+) {+ for (const id of selectedShapeIds(document, selected)) {+ const item = resolvedShape(document, id);+ if (!isShape(item)) continue;+ const definition = shapeDefinition(item.type);+ if (!definition.regenerateOnScale) continue;+ const before = worldMatrix(document, id);+ const after = worldMatrix(document, id, nodes);+ const sx =+ Math.hypot(after[0], after[1]) / Math.hypot(before[0], before[1]);+ const sy =+ Math.hypot(after[2], after[3]) / Math.hypot(before[2], before[3]);+ const bounds = definition.bounds(item);+ nodes[id] = {+ ...definition.resize(item, {+ x: 0,+ y: 0,+ width: bounds.width * sx,+ height: bounds.height * sy,+ }),+ transform: multiply(+ inverse(worldMatrix(document, item.placement.parentId, nodes)),+ multiply(after, scaling(1 / sx, 1 / sy))+ ),+ };+ }+}++/** Nonuniform selection resize, retaining leaf axes and reflecting them on flips.+ * Move centers with the selection transform and resize along the leaf's axes.+ * Group frames stay intact; solve each leaf's new pose in its own parent frame.+ * The selection frame permits nonuniform resizing only when all descendant axes+ * align with its axes (including quarter turns), so the result fits that frame+ * exactly. Incompatible axes take the uniform selected-root transform path.+ */+export function stretchShapes(+ document: GraphicsDocument,+ selected: readonly string[],+ delta: Matrix,+ measureText?: TextMeasurer,+ handle?: ResizeHandle+): Record<string, GraphicsItem> {+ const nodes: Record<string, GraphicsItem> = Object.create(null);+ for (const id of selectedShapeIds(document, selected)) {+ const item = resolvedShape(document, id);+ if (!isShape(item)) continue;+ const world = worldMatrix(document, id);+ const stretched = multiply(delta, world);+ const sx =+ Math.hypot(stretched[0], stretched[1]) / Math.hypot(world[0], world[1]);+ const sy =+ Math.hypot(stretched[2], stretched[3]) / Math.hypot(world[2], world[3]);+ const definition = shapeDefinition(item.type);+ const bounds = definition.bounds(item);+ const localHandle = handle ? localResizeHandle(handle, world) : undefined;+ const center = transformPoint(stretched, {+ x: bounds.x + bounds.width / 2,+ y: bounds.y + bounds.height / 2,+ });+ const resized = definition.resize(+ item,+ {+ x: 0,+ y: 0,+ width: bounds.width * sx,+ height: bounds.height * sy,+ },+ { measureText, handle: localHandle }+ );+ const nextBounds = definition.bounds(resized);+ const nextAnchor = localHandle+ ? oppositeAnchor(nextBounds, localHandle)+ : {+ x: nextBounds.x + nextBounds.width / 2,+ y: nextBounds.y + nextBounds.height / 2,+ };+ const worldAnchor = localHandle+ ? transformPoint(stretched, oppositeAnchor(bounds, localHandle))+ : center;+ const a = stretched[0] / sx,+ b = stretched[1] / sx;+ const c = stretched[2] / sy,+ d = stretched[3] / sy;+ const nextWorld: Matrix = [+ a,+ b,+ c,+ d,+ worldAnchor.x - a * nextAnchor.x - c * nextAnchor.y,+ worldAnchor.y - b * nextAnchor.x - d * nextAnchor.y,+ ];+ nodes[id] = {+ ...resized,+ transform: multiply(+ inverse(worldMatrix(document, item.placement.parentId)),+ nextWorld+ ),+ };+ }+ return nodes;+}diff --git a/packages/graphics/src/core/style-selection.ts b/packages/graphics/src/core/style-selection.tsnew file mode 100644index 0000000000..31d4cdb033--- /dev/null+++ b/packages/graphics/src/core/style-selection.ts@@ -0,0 +1,17 @@+import type { GraphicsDocument } from './model';+import { children, roots } from './scene';+import { isShape } from './shapes/registry';++/** Groups have no inherited style. Styling a group explicitly edits its leaves. */+export function selectedShapeIds(+ document: GraphicsDocument,+ selection: readonly string[]+): readonly string[] {+ const result: string[] = [];+ const visit = (id: string) => {+ if (isShape(document.items[id])) result.push(id);+ else for (const child of children(document, id)) visit(child);+ };+ roots(document, selection).forEach(visit);+ return result;+}diff --git a/packages/graphics/src/core/text-commands.ts b/packages/graphics/src/core/text-commands.tsnew file mode 100644index 0000000000..0bca96b2b2--- /dev/null+++ b/packages/graphics/src/core/text-commands.ts@@ -0,0 +1,55 @@+import type { GraphicsCommand } from './commands';+import type { ShapeItem } from './model';+import {+ canLabel,+ type ShapeLabel,+ validShapeLabel,+ withShapeLabel,+} from './shapes/label';+import { textDefinition } from './shapes/text';+/** One completed text edit is one document operation; keystrokes stay in the host. */+export const setTextCommand: GraphicsCommand<ShapeItem<'text'>> = {+ id: 'set-text',+ apply: ({ document }, item) => {+ const before = document.items[item.id];+ if (before && before.type !== 'text')+ throw new Error('Text id belongs to another shape');+ if (!textDefinition.validateGeometry(item.geometry))+ throw new Error('Invalid text geometry');+ if (before?.type === 'text' && textDefinition.sameGeometry(before, item))+ return { document };+ const items = { ...document.items };+ items[item.id] =+ before?.type === 'text' ? { ...before, geometry: item.geometry } : item;+ return {+ document: { ...document, items },+ selection: [item.id],+ };+ },+};++/** Clearing a label retains its owning shape and its place in the scene. */+export const setShapeLabelCommand: GraphicsCommand<{+ id: string;+ label?: ShapeLabel;+}> = {+ id: 'set-shape-label',+ apply: ({ document }, { id, label }) => {+ const item = document.items[id];+ if (!canLabel(item)) return { document };+ if (label && !validShapeLabel(label))+ throw new Error('Invalid shape label');+ if (JSON.stringify(item.geometry.label) === JSON.stringify(label))+ return { document };+ return {+ document: {+ ...document,+ items: {+ ...document.items,+ [id]: withShapeLabel(item, label),+ },+ },+ selection: [id],+ };+ },+};diff --git a/packages/graphics/src/core/text-target.ts b/packages/graphics/src/core/text-target.tsnew file mode 100644index 0000000000..352a3273a8--- /dev/null+++ b/packages/graphics/src/core/text-target.ts@@ -0,0 +1,30 @@+import { inverse, transformPoint } from './affine';+import type { GraphicsDocument, Point } from './model';+import { drawableIds, shapeProjection } from './scene';+import { canLabel } from './shapes/label';+import { shapeDefinition } from './shapes/registry';++/** Text gestures may enter an unfilled shape's interior. Normal selection still+ * uses painted picking. Frontmost painted non-text shapes block text behind them. */+export function textTargetAt(+ document: GraphicsDocument,+ point: Point+): string | undefined {+ for (const id of drawableIds(document).reverse()) {+ const { item, transform: world } = shapeProjection(document, id);+ if (!item || item.appearance.opacity === 0) continue;+ const local = transformPoint(inverse(world), point);+ const definition = shapeDefinition(item.type);+ const target = item.type === 'text' || canLabel(item);+ const testItem = canLabel(item)+ ? { ...item, appearance: { ...item.appearance, fill: 'black' } }+ : item;+ if (+ definition.hitTest(testItem, local, {+ worldTransform: world,+ tolerance: item.type === 'connector' ? 3 : 0,+ })+ )+ return target ? id : undefined;+ }+}diff --git a/packages/graphics/src/loro/README.md b/packages/graphics/src/loro/README.mdnew file mode 100644index 0000000000..715f7ffd35--- /dev/null+++ b/packages/graphics/src/loro/README.md@@ -0,0 +1,175 @@+# Two-peer scene experiment++Status reviewed 2026-09-28. See the [main progress plan](../../../../docs/GRAPHICS_PARITY.md).+Automated mapping coverage now includes pencil, rich text/labels, connectors and+media/document references. Full Canvas Next integration is deferred while the+[legacy bridge and colors](../../../../docs/CANVAS_LEGACY_BRIDGE.md) take priority.++`@macro-inc/graphics/loro` is an experimental adapter with an in-memory transport+harness used by tests. It uses the workspace Loro version (1.16.3). No SyncService,+network requests, local storage, or server changes are involved.++The root graphics export stays framework/DOM/Loro-free. `GraphicsBackend` is the+small document/history contract; `createGraphicsEditorFromBackend` proposes local+commits and renders backend snapshots. Loro is authoritative. The editor does not+also maintain snapshot undo for these documents. The owner disposes each editor+before its backend. Memory-backed hosts keep their original behavior.++## Representation++- A LoroTree owns containment and sibling ordering. Node data retains the stable+ graphics ID and immutable kind. The surface is the implicit root of the forest.+- Each node has one coherent `pose` register: local matrix, geometry, coordinate+ parent ID, and a captured world matrix. Fill and stroke are separate registers,+ so moving and restyling the same shape can merge independently.+- Ordered Loro children project to unique core sort keys. These keys are derived,+ not CRDT fields; concurrent key collisions are handled by Loro's ordered tree.+ Core commands become moves of affected tree nodes, not full-list replacements.+- A gesture makes one commit and one undo step. Selection, camera, active tool and+ previews remain local editor state. A separate ephemeral channel broadcasts+ read-only cursor, selection and pending-gesture snapshots while connected.+- Incoming changes cancel local transform/drawing previews. Intent rebasing is+ deliberately deferred. Imported changes do not echo back into the transport.++## Conflict policy under evaluation++Loro resolves competing values of the same pose register. Independent style fields+merge separately. Its tree resolves competing parents and prevents cycles.++A winning tree parent can differ from the coordinate parent recorded by the winning+pose. In that case the projection uses the pose's captured world matrix, expressed+relative to the actual parent. This keeps both replicas valid and avoids interpreting+an old local matrix in the wrong coordinate space. It is a derived interpretation:+no repair operations or reconciliation loop are emitted.++**This is a policy to evaluate, not a settled production schema.** Such a node stays+anchored in world space through subsequent parent transforms until it receives a+new pose edit. Adapter diagnostics report these nodes. Captured world pose is the+winning edit's pose, not a guarantee that both concurrent geometric intentions+survive. Concurrent edits to one pose choose one coherent result.++The native Loro UndoManager records only local operations, with merging disabled+and a 100-step bound. Independent remote properties survive undo. Undo of a field+that another peer subsequently overwrote can restore the pre-local value; redo can+restore the remote value. Undoing a deletion restores pre-delete node data, even+when another peer edited that node concurrently. The tests explicitly capture+these behaviors. Snapshot undo+is never applied to a shared document. Deleting a group while another peer extracts+a child lets the extracted child survive; opposite reparents converge without cycles.++## Test transport++The automated collaboration tests give Alice and Bob independent editors backed by+an in-memory transport. Tests can pause delivery, flush queued updates, reconnect,+and add artificial latency. Disposing the harness clears editors, histories,+queued messages and timers so packets cannot leak between cases.++## Awareness boundary++`createGraphicsPresence` observes the editor through its existing subscriptions.+It uses Loro's `EphemeralStore`, independently of the document and UndoManager.+Its packets contain identity/color, a world-space cursor, selected root IDs, the+document clock and an optional pending action. Transform previews flatten selected+descendants into world-space shape outlines; drawing and marquee previews have+their own payloads. Neither sending nor receiving presence issues editor commands.++`@macro-inc/graphics/loro/solid` exports `CollaborativeGraphicsSurface`, composing+the unchanged `GraphicsSurface` with a sibling overlay and cursor listener.+Remote selections and ghosts use the receiving camera, have no editing handles+and ignore pointer events. Committed shape components retain their identity.+The core, shared browser input and ordinary Solid surface have no awareness hooks+or imports. Non-collaborative hosts keep their existing imports and behavior.++Cursor and preview publication uses a 40 ms trailing debounce with a 100 ms maximum+wait, so continuous movement still sends updates. Capture and encoding happen only+when sending. Selection changes, cursor departure, release and cancellation flush+immediately. The in-memory test transport coalesces the latest packet per peer and+can add artificial latency. Presence is excluded from the durable queued/delivered counters. Disconnect hides remote+presence and discards pending presence packets; reconnect publishes fresh state.+Sync now while offline exchanges only document updates. Monotonic packet sequences+reject duplicate/reordered presence. Heartbeats refresh idle selections every 10+seconds; states expire after 30 seconds without an update, checked on Loro's+15-second cleanup interval. Reset/unmount disposes listeners and timers.++Ghosts are displayed only when their captured document clock matches the receiver's+clock. A commit therefore suppresses a delayed, obsolete gesture until fresh+presence arrives. Selection IDs still resolve against the current committed scene.+The current ghost contract carries rectangle/ellipse dimensions and pencil samples,+using default renderers. It does not carry complete text, connector, media or document+geometry; do not assume every registered shape can render a valid ghost. A full+Canvas Next peer lab needs typed preview coverage or deliberate bounds-only previews+for these kinds, plus connector endpoint-draft awareness. Authenticated peer identity,+payload validation and real network presence transport remain integration work.++The cursor is a colored pointer with a rounded name-only badge, shown only while+the peer's cursor is on the canvas. Pending ghosts replace redundant transform+selection outlines. The receiver springs cursor, ghost geometry and marquee bounds+between packets using one animation loop, with no writes back to presence. The+critically damped closed-form solver stays stable after background tab pauses;+affine transforms interpolate translation, angle, scale and shear separately,+unwrapping angles across ±π instead of interpolating raw matrix entries. New+elements appear at their first reported position. Completion, cancellation,+invalid document clocks and peer removal clear ghosts immediately. Reduced-motion+preferences bypass interpolation; settled/unmounted overlays stop their frame loop.++Tests cover independent and conflicting property edits/undo, concurrent inserts and+ordering, grouping/ungrouping, opposite reparents, parent/pose mismatch, group deletion+versus extraction, remote preview cancellation, delayed/offline transport, duplicates+and reversed deliveries. Node tests use Loro's Node WASM entry; the web app uses the+existing Vite WASM configuration and browser entry.++Awareness tests cover nested and drawing previews, camera mapping, selection and+cursor isolation from document/history, unchanged committed DOM mounts, stale+previews, reordered packets, coalescing, offline/reconnect behavior and disposal/expiry.+Motion tests cover bounded debounce, mid-flight retargeting, shortest-arc rotation,+stable ghost DOM, settling, reduced motion and animation cleanup.++Production integration still needs an accepted geometry/history conflict policy,+an explicit choice to retain cancellation or implement intent rebasing, mixed-content+editor validation, shared collaboration runtime integration, durable initialization,+permissions, reconnect/storage tests and deployment. Asset/text mappings now exist;+their production acceptance is separate from basic mapping tests. This transport is+only an in-memory test harness; do not turn it into another production sync engine.++References: [Loro ordered trees](https://www.loro.dev/docs/tutorial/tree),+[Loro undo](https://www.loro.dev/docs/advanced/undo),+[Loro ephemeral state](https://www.loro.dev/docs/tutorial/ephemeral). See tests for the actual behavior+of the pinned workspace version rather than treating these docs as test evidence.++### Pencil mapping++Pencil geometry travels as one immutable sample-array value in the existing pose+merge unit; transform and geometry still win together. Live drawing is ephemeral+awareness only, with the finalized stroke committed once. The adapter validates+kind/geometry pairs through the core shape registry. As with other poses, moving+a stroke currently resends its geometry; compact encoding and reducing those+payloads are future transport optimizations, not core document requirements.++### Text and embedded items++Text items and shape labels store the exact host-defined content string as one+`textContent` LoroMap value. Concurrent edits select one complete string through+last-write-wins; no LoroText, per-node CRDT, or character merging is involved.+The text register is separate from pose and appearance; label layout is also+separate, so a move cannot discard a new label. Typing drafts remain local and+finished edits become one backend transaction. Tests cover conflicting strings,+text-versus-move, new labels versus moves, and local undo preserving remote moves.++Image, video and document references use the existing shape geometry mapping.+Their source bytes, resolved URLs, loading state and playback are host concerns.++### Next integration gates++Use the actual Canvas view, rich-text measurer and content/asset renderers with two+injected Loro editors. Exercise concurrent whole-string edits, text editing versus+remote movement, local text/scene undo, reference deletion, selection/gesture+awareness and mixed-content layering/focus. Keep embedded document editing under+its own existing permissions/sync; the outer scene shares only the embed reference+and display geometry. No character CRDT, durable seed or second network engine is+needed for this checkpoint.++For the later durable host, reuse the existing collaboration infrastructure and+the [spreadsheet session](../../../../apps/web/src/features/block-spreadsheet/queries/spreadsheet-session.ts)+as a reference for WAL/snapshot recovery and disposal. First audit canvas document+initialization, content routing, authorization and legacy readers; the lab does not+prove that enabling SyncService requires no server changes.diff --git a/packages/graphics/src/loro/backend.ts b/packages/graphics/src/loro/backend.tsnew file mode 100644index 0000000000..11fcbdd58b--- /dev/null+++ b/packages/graphics/src/loro/backend.ts@@ -0,0 +1,118 @@+import { LoroDoc, type LoroTree, type PeerID, UndoManager } from 'loro-crdt';+import type { GraphicsBackend } from '../core/backend';+import type { GraphicsDocument } from '../core/model';+import { freezeDocument } from '../core/scene';+import { type NodeData, readScene, writeScene } from './scene-mapping';++type Schema = { scene: LoroTree<NodeData> };+type Source = Parameters<Parameters<GraphicsBackend['subscribe']>[0]>[0];++export function createLoroSeed(seed: GraphicsDocument): Uint8Array {+ const validated = freezeDocument(seed);+ const doc = new LoroDoc<Schema>();+ doc.setPeerId('0');+ const tree = doc.getTree('scene');+ tree.enableFractionalIndex(0);+ writeScene(+ tree,+ {+ rootId: seed.rootId,+ items: { [seed.rootId]: { id: seed.rootId, type: 'surface' } },+ },+ validated+ );+ doc.commit();+ const snapshot = doc.export({ mode: 'snapshot' });+ tree.free();+ doc.free();+ return snapshot;+}++/** Experimental Loro owner; no browser, network, storage or Solid dependencies. */+export function createLoroGraphicsBackend(+ snapshot: Uint8Array,+ peerId: PeerID,+ rootId: string+) {+ const doc = new LoroDoc<Schema>();+ doc.import(snapshot);+ doc.setPeerId(peerId);+ const tree = doc.getTree('scene');+ tree.enableFractionalIndex(0);+ const history = new UndoManager(doc, { mergeInterval: 0, maxUndoSteps: 100 });+ let projection = readScene(tree, rootId);+ let disposed = false;+ const listeners = new Set<(source: Source) => void>();+ const updates = new Set<(bytes: Uint8Array) => void>();+ const refresh = (source: Source) => {+ projection = readScene(tree, rootId);+ for (const listener of listeners) listener(source);+ };+ const local = (source: Source, action: () => void) => {+ if (disposed) return;+ const from = doc.oplogVersion();+ action();+ doc.commit();+ const bytes = doc.export({ mode: 'update', from });+ from.free();+ refresh(source);+ for (const listener of updates) listener(bytes);+ };+ return {+ getDocument: () => projection.document,+ getClock() {+ const version = doc.version();+ const clock = Object.fromEntries(version.toJSON());+ version.free();+ return clock;+ },+ getFrameConflicts: () => projection.frameConflicts,+ getHistory: () => ({+ canUndo: !disposed && history.canUndo(),+ canRedo: !disposed && history.canRedo(),+ }),+ commit(next: GraphicsDocument) {+ const validated = freezeDocument(next);+ local('local', () => writeScene(tree, projection.document, validated));+ },+ undo() {+ if (!disposed && history.canUndo())+ local('history', () => {+ history.undo();+ });+ },+ redo() {+ if (!disposed && history.canRedo())+ local('history', () => {+ history.redo();+ });+ },+ subscribe(listener: (source: Source) => void) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ subscribeUpdates(listener: (bytes: Uint8Array) => void) {+ updates.add(listener);+ return () => {+ updates.delete(listener);+ };+ },+ receive(bytes: Uint8Array) {+ if (disposed) return;+ doc.import(bytes);+ refresh('remote');+ },+ dispose() {+ if (disposed) return;+ disposed = true;+ listeners.clear();+ updates.clear();+ history.free();+ tree.free();+ doc.free();+ },+ };+}+export type LoroGraphicsBackend = ReturnType<typeof createLoroGraphicsBackend>;diff --git a/packages/graphics/src/loro/index.ts b/packages/graphics/src/loro/index.tsnew file mode 100644index 0000000000..a1547f2503--- /dev/null+++ b/packages/graphics/src/loro/index.ts@@ -0,0 +1,15 @@+export {+ createLoroGraphicsBackend,+ createLoroSeed,+ type LoroGraphicsBackend,+} from './backend';+export {+ createGraphicsPresence,+ type GraphicsPresence,+ type PresencePacket,+} from './presence';+export {+ currentPresencePreview,+ type PeerPresence,+ type PresenceClock,+} from './presence-state';diff --git a/packages/graphics/src/loro/presence-state.ts b/packages/graphics/src/loro/presence-state.tsnew file mode 100644index 0000000000..eecead5606--- /dev/null+++ b/packages/graphics/src/loro/presence-state.ts@@ -0,0 +1,133 @@+import type { Matrix } from '../core/affine';+import { resolveAppearance } from '../core/appearance';+import type { GraphicsEditor } from '../core/editor';+import type { Bounds, Point, ShapeItem, ShapeKind } from '../core/model';+import { drawableIds, roots, worldMatrix } from '../core/scene';+import { isShape, shapeDefinition } from '../core/shapes/registry';++export type PresenceClock = Record<string, number>;+type WireMatrix = [number, number, number, number, number, number];+export type PresenceShape = {+ id: string;+ kind: ShapeKind;+ width: number;+ height: number;+ world: WireMatrix;+ pencil?: { points: [number, number, number][]; simulatePressure: boolean };+ strokeWidth?: number;+ cornerRadius?: number;+};+export type ActionPreview = {+ kind: 'draw' | 'move' | 'resize' | 'scale' | 'rotate' | 'radius' | 'marquee';+ shapes: PresenceShape[];+ box: Bounds | null;+};+export type PeerPresence = {+ id: string;+ name: string;+ color: string;+ cursor: Point | null;+ selectedIds: string[];+ clock: PresenceClock;+ preview: ActionPreview | null;+};+export type PresenceIdentity = Pick<PeerPresence, 'id' | 'name' | 'color'>;+const wireMatrix = (matrix: Matrix): WireMatrix => [...matrix];++function presenceShape(node: ShapeItem, world: Matrix): PresenceShape {+ const bounds = shapeDefinition(node.type).bounds(node);+ return {+ id: node.id,+ kind: node.type,+ width: bounds.width,+ height: bounds.height,+ world: wireMatrix(world),+ ...(node.type === 'rectangle'+ ? { cornerRadius: node.appearance.cornerRadius ?? 0 }+ : {}),+ ...(node.type === 'pencil'+ ? {+ pencil: {+ points: node.geometry.points.map((p) => [...p]),+ simulatePressure: node.geometry.simulatePressure,+ },+ strokeWidth: resolveAppearance(node.appearance).strokeWidth,+ }+ : {}),+ };+}++/** Read-only capture: committed data and local gestures never receive remote state. */+export function capturePresence(+ editor: GraphicsEditor,+ identity: PresenceIdentity,+ clock: PresenceClock,+ cursor: Point | null+): PeerPresence {+ const doc = editor.getSession().transform?.document ?? editor.document;+ const session = editor.getSession();+ const selectedIds = [...roots(doc, session.selectedIds)];+ let preview: ActionPreview | null = null;+ const drawing = editor.getDrawingPreview({+ fill: 'transparent',+ stroke: identity.color,+ });+ if (session.transform) {+ const overrides = session.transform.nodes;+ const targets = new Set(selectedIds);+ const shapes: PresenceShape[] = [];+ for (const id of drawableIds(doc)) {+ let ancestor = doc.items[id];+ while (+ ancestor &&+ ancestor.type !== 'surface' &&+ !targets.has(ancestor.id)+ )+ ancestor = doc.items[ancestor.placement.parentId];+ if (!ancestor || !targets.has(ancestor.id)) continue;+ const node = overrides[id] ?? doc.items[id];+ if (isShape(node))+ shapes.push(presenceShape(node, worldMatrix(doc, id, overrides)));+ }+ preview = {+ kind: session.transform.kind,+ shapes,+ box: null,+ };+ } else if (drawing) {+ preview = {+ kind: 'draw',+ shapes: [+ presenceShape(+ { ...drawing, id: `draft-${identity.id}` },+ drawing.transform+ ),+ ],+ box: null,+ };+ } else if (session.box) {+ preview = {+ kind: 'marquee',+ shapes: [],+ box: { ...session.box },+ };+ }+ return {+ ...identity,+ cursor: cursor ? { ...cursor } : null,+ selectedIds,+ clock,+ preview,+ };+}++/** A delayed gesture is invalid as soon as either replica has another commit. */+export function currentPresencePreview(+ state: PeerPresence,+ clock: PresenceClock+): ActionPreview | null {+ const keys = new Set([...Object.keys(state.clock), ...Object.keys(clock)]);+ return [...keys].every((key) => (state.clock[key] ?? 0) === (clock[key] ?? 0))+ ? state.preview+ : null;+}diff --git a/packages/graphics/src/loro/presence.ts b/packages/graphics/src/loro/presence.tsnew file mode 100644index 0000000000..debd8d9d10--- /dev/null+++ b/packages/graphics/src/loro/presence.ts@@ -0,0 +1,143 @@+import { EphemeralStore } from 'loro-crdt';+import type { GraphicsEditor } from '../core/editor';+import type { Point } from '../core/model';+import {+ capturePresence,+ type PeerPresence,+ type PresenceClock,+ type PresenceIdentity,+} from './presence-state';++export type PresencePacket = {+ from: string;+ sequence: number;+ bytes: Uint8Array;+};+export const PRESENCE_TIMEOUT = 30_000;+export const PRESENCE_DEBOUNCE = 40;+export const PRESENCE_MAX_WAIT = 100;+const HEARTBEAT_INTERVAL = 10_000;++/** Ephemeral channel adapter. It only observes the core and never issues edits. */+export function createGraphicsPresence(+ editor: GraphicsEditor,+ identity: PresenceIdentity,+ clock: () => PresenceClock+) {+ const store = new EphemeralStore<Record<string, PeerPresence>>(+ PRESENCE_TIMEOUT+ );+ const listeners = new Set<() => void>();+ const outgoing = new Set<(packet: PresencePacket) => void>();+ const sequences = new Map<string, number>();+ let sequence = 0;+ let cursor: Point | null = null;+ let online = true;+ let disposed = false;+ let debounceTimer: ReturnType<typeof setTimeout> | undefined;+ let deadlineTimer: ReturnType<typeof setTimeout> | undefined;+ const clearPending = () => {+ clearTimeout(debounceTimer);+ clearTimeout(deadlineTimer);+ debounceTimer = deadlineTimer = undefined;+ };+ const notify = () => {+ for (const listener of listeners) listener();+ };+ const publish = () => {+ clearPending();+ if (disposed || !online) return;+ store.set(identity.id, capturePresence(editor, identity, clock(), cursor));+ const packet = {+ from: identity.id,+ sequence: ++sequence,+ bytes: store.encode(identity.id),+ };+ for (const listener of outgoing) listener(packet);+ };+ // Capture/encode only when sending, not on every pointer or preview event.+ const schedule = () => {+ if (disposed || !online) return;+ clearTimeout(debounceTimer);+ debounceTimer = setTimeout(publish, PRESENCE_DEBOUNCE);+ deadlineTimer ??= setTimeout(publish, PRESENCE_MAX_WAIT);+ };+ const observeGesture = () => {+ const session = editor.getSession();+ if (session.transform || session.box || editor.getPreview()) schedule();+ else publish(); // Selection changes, cancellation and release are immediate.+ };+ const detach = [+ editor.subscribeSession(observeGesture),+ editor.subscribePreview(observeGesture),+ editor.subscribeDocument(publish),+ store.subscribe((event) => {+ if (event.by !== 'local') notify();+ }),+ ];+ const heartbeat = setInterval(publish, HEARTBEAT_INTERVAL);+ return {+ identity,+ getClock: clock,+ getRemote: () =>+ online && !disposed+ ? Object.values(store.getAllStates()).filter(+ (value): value is PeerPresence =>+ !!value && value.id !== identity.id+ )+ : [],+ subscribe(listener: () => void) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ subscribeUpdates(listener: (packet: PresencePacket) => void) {+ outgoing.add(listener);+ return () => {+ outgoing.delete(listener);+ };+ },+ publish,+ setCursor(point: Point | null) {+ if (disposed) return;+ if (point && ![point.x, point.y].every(Number.isFinite)) return;+ if (!point && !cursor) return;+ cursor = point;+ if (point) schedule();+ else publish();+ },+ receive(packet: PresencePacket) {+ if (+ disposed ||+ !online ||+ packet.from === identity.id ||+ packet.sequence <= (sequences.get(packet.from) ?? 0)+ )+ return;+ sequences.set(packet.from, packet.sequence);+ store.apply(packet.bytes);+ },+ setOnline(value: boolean) {+ if (disposed) return;+ online = value;+ clearPending();+ if (!online)+ for (const id of store.keys()) if (id !== identity.id) store.delete(id);+ notify();+ if (online) publish();+ },+ dispose() {+ if (disposed) return;+ disposed = true;+ clearPending();+ clearInterval(heartbeat);+ detach.forEach((unsubscribe) => unsubscribe());+ store.destroy();+ store.inner.free();+ outgoing.clear();+ listeners.clear();+ },+ };+}+export type GraphicsPresence = ReturnType<typeof createGraphicsPresence>;diff --git a/packages/graphics/src/loro/scene-mapping.ts b/packages/graphics/src/loro/scene-mapping.tsnew file mode 100644index 0000000000..6f74d17247--- /dev/null+++ b/packages/graphics/src/loro/scene-mapping.ts@@ -0,0 +1,260 @@+import type { LoroTree, LoroTreeNode } from 'loro-crdt';+import {+ IDENTITY,+ inverse,+ type Matrix,+ multiply,+ sameMatrix,+} from '../core/affine';+import { resolveAppearance } from '../core/appearance';+import type {+ GraphicsDocument,+ GraphicsItem,+ ShapeGeometryMap,+ ShapeKind,+} from '../core/model';+import { sortKeysBetween } from '../core/ordering';+import {+ children,+ freezeDocument,+ paintOrder,+ roots,+ worldMatrix,+} from '../core/scene';+import { canLabel, type ShapeLabel } from '../core/shapes/label';+import { isShape, shapePayload } from '../core/shapes/registry';++/** Experimental merge unit: geometry and its coordinate frame always win together. */+export type NodeData = {+ id: string;+ kind: ShapeKind | 'group';+ pose: {+ parentId: string;+ transform: Matrix;+ world: Matrix;+ geometry: ShapeGeometryMap[ShapeKind] | null;+ };+ /** One LWW string, deliberately not a LoroText or nested CRDT tree. */+ textContent: string | null;+ labelStyle: Omit<ShapeLabel, 'content'> | null;+ fill: string;+ stroke: string;+ strokeWidth: number;+ strokeStyle?: 'solid' | 'dashed' | 'dotted';+ opacity: number;+ cornerRadius: number;+};++export function readScene(tree: LoroTree<NodeData>, rootId: string) {+ const items: Record<string, GraphicsItem> = {+ [rootId]: { id: rootId, type: 'surface' },+ };+ const frameConflicts: string[] = [];+ function visit(+ nodes: LoroTreeNode<NodeData>[],+ parentId: string,+ parentWorld: Matrix+ ) {+ // Loro owns durable ordering. These keys are a disposable core projection.+ const keys = sortKeysBetween(null, null, nodes.length);+ nodes.forEach((node, index) => {+ const id = node.data.get('id'),+ kind = node.data.get('kind'),+ pose = node.data.get('pose');+ if (!id || !kind || !pose || Object.hasOwn(items, id))+ throw new Error('Invalid shared scene node');+ const matchingFrame = pose.parentId === parentId;+ const transform = matchingFrame+ ? pose.transform+ : multiply(inverse(parentWorld), pose.world);+ if (!matchingFrame) frameConflicts.push(id);+ const spatial = {+ id,+ transform,+ placement: { parentId, sortKey: keys[index]! },+ };+ if (kind === 'group') items[id] = { ...spatial, type: 'group' };+ else {+ const fill = node.data.get('fill'),+ stroke = node.data.get('stroke');+ if (!pose.geometry || fill === undefined || stroke === undefined)+ throw new Error('Invalid shared shape');+ items[id] = {+ ...spatial,+ ...shapePayload(+ kind,+ restoreText(+ kind,+ pose.geometry,+ node.data.get('textContent') ?? null,+ node.data.get('labelStyle') ?? null+ )+ ),+ appearance: {+ fill,+ stroke,+ strokeWidth: node.data.get('strokeWidth') ?? 2,+ strokeStyle: node.data.get('strokeStyle') ?? 'solid',+ opacity: node.data.get('opacity') ?? 1,+ cornerRadius: node.data.get('cornerRadius') ?? 0,+ },+ };+ }+ visit(node.children() ?? [], id, multiply(parentWorld, transform));+ });+ }+ visit(tree.roots() as LoroTreeNode<NodeData>[], rootId, IDENTITY);+ return { document: freezeDocument({ rootId, items }), frameConflicts };+}++function textContent(node: GraphicsItem | undefined): string | null {+ if (node?.type === 'text') return node.geometry.content;+ return canLabel(node) ? (node.geometry.label?.content ?? null) : null;+}+/** Pose and text use separate map registers, so a move cannot overwrite typing. */+function poseGeometry(node: GraphicsItem | undefined) {+ if (!isShape(node)) return null;+ if (node.type === 'text') return { ...node.geometry, content: '' };+ if (canLabel(node)) {+ const { label: _label, ...box } = node.geometry;+ return box;+ }+ return node.geometry;+}+function restoreText(+ kind: ShapeKind,+ geometry: ShapeGeometryMap[ShapeKind],+ content: string | null,+ labelStyle: NodeData['labelStyle']+) {+ if (kind === 'text') return { ...geometry, content };+ if (kind === 'rectangle' || kind === 'ellipse' || kind === 'connector')+ return content !== null && labelStyle+ ? { ...geometry, label: { ...labelStyle, content } }+ : geometry;+ return geometry;+}++function labelStyle(node: GraphicsItem | undefined): NodeData['labelStyle'] {+ if (!canLabel(node) || !node.geometry.label) return null;+ const { content: _content, ...style } = node.geometry.label;+ return style;+}++function writeNodeData(+ handle: LoroTreeNode<NodeData>,+ node: Exclude<GraphicsItem, { type: 'surface' }>,+ old: GraphicsItem | undefined,+ next: GraphicsDocument,+ parentChanged: boolean+) {+ const geometry = poseGeometry(node);+ const oldGeometry = poseGeometry(old);+ if (!old || textContent(node) !== textContent(old))+ handle.data.set('textContent', textContent(node));+ if (+ !old ||+ JSON.stringify(labelStyle(node)) !== JSON.stringify(labelStyle(old))+ )+ handle.data.set('labelStyle', labelStyle(node));+ if (+ !old ||+ old.type === 'surface' ||+ parentChanged ||+ !sameMatrix(old.transform, node.transform) ||+ JSON.stringify(geometry) !== JSON.stringify(oldGeometry)+ ) {+ handle.data.set('pose', {+ parentId: node.placement.parentId,+ transform: node.transform,+ world: worldMatrix(next, node.id),+ geometry,+ });+ }+ if (isShape(node)) {+ const appearance = resolveAppearance(node.appearance);+ const previous = isShape(old)+ ? resolveAppearance(old.appearance)+ : undefined;+ for (const key of [+ 'strokeWidth',+ 'strokeStyle',+ 'opacity',+ 'cornerRadius',+ ] as const) {+ if (!previous || previous[key] !== appearance[key])+ handle.data.set(key, appearance[key]);+ }+ if (!isShape(old) || old.appearance.fill !== node.appearance.fill)+ handle.data.set('fill', node.appearance.fill);+ if (!isShape(old) || old.appearance.stroke !== node.appearance.stroke)+ handle.data.set('stroke', node.appearance.stroke);+ }+}++/** Diff a validated proposal; never replace whole nodes or write unchanged fields. */+export function writeScene(+ tree: LoroTree<NodeData>,+ before: GraphicsDocument,+ next: GraphicsDocument+) {+ if (before.rootId !== next.rootId || next.surface)+ throw new Error('Shared graphics backend supports one unbounded surface');+ const handles = new Map(+ tree.getNodes().map((node) => [node.data.get('id'), node])+ );+ const order = paintOrder(next);+ const reposition = new Set<string>();+ const reparent = new Set<string>();+ // Reject unsupported proposals before producing any CRDT operations.+ for (const id of order) {+ if (before.items[id] && before.items[id]!.type !== next.items[id]!.type)+ throw new Error('Shared node kinds are immutable');+ }+ for (const id of order) {+ const node = next.items[id]!,+ old = before.items[id];+ if (node.type === 'surface') continue;+ let handle = handles.get(id);+ if (!handle) {+ handle = tree.createNode();+ handle.data.set('id', id);+ handle.data.set('kind', node.type);+ handles.set(id, handle);+ }+ if (+ !old ||+ old.type === 'surface' ||+ old.placement.parentId !== node.placement.parentId+ ) {+ reparent.add(id);+ reposition.add(id);+ } else if (old.placement.sortKey !== node.placement.sortKey)+ reposition.add(id);+ writeNodeData(handle, node, old, next, reparent.has(id));+ }+ // Lift first so a valid final hierarchy cannot hit an intermediate local cycle.+ for (const id of reparent) handles.get(id)!.move();+ for (const id of order) {+ if (!reparent.has(id)) continue;+ const node = next.items[id]!;+ if (node.type !== 'surface')+ handles.get(id)!.move(handles.get(node.placement.parentId));+ }+ const removed = Object.keys(before.items).filter((id) => !next.items[id]);+ for (const id of roots(before, removed)) {+ const handle = handles.get(id);+ if (handle) tree.delete(handle.id);+ }+ for (const parent of [next.rootId, ...order]) {+ const siblings = children(next, parent);+ for (let i = siblings.length - 1; i >= 0; i--) {+ const id = siblings[i]!;+ if (!reposition.has(id)) continue;+ const handle = handles.get(id)!;+ const after = siblings[i + 1];+ if (after) handle.moveBefore(handles.get(after)!);+ else handle.move(handles.get(parent));+ }+ }+}diff --git a/packages/graphics/src/loro/solid/index.tsx b/packages/graphics/src/loro/solid/index.tsxnew file mode 100644index 0000000000..ff14cd8d2e--- /dev/null+++ b/packages/graphics/src/loro/solid/index.tsx@@ -0,0 +1,269 @@+import {+ type ComponentProps,+ createSignal,+ For,+ onCleanup,+ onMount,+ Show,+ splitProps,+} from 'solid-js';+import { corners, cssMatrix } from '../../core/affine';+import { worldToScreen } from '../../core/camera';+import type { GraphicsEditor } from '../../core/editor';+import type { Point, ShapeItem } from '../../core/model';+import { nodeCorners, roots, worldBounds } from '../../core/scene';+import { isShape, shapePayload } from '../../core/shapes/registry';+import { createGraphicsProjection, GraphicsSurface } from '../../solid';+import { defaultRenderers, ShapeView } from '../../solid/shape-renderers';+import type { GraphicsPresence } from '../presence';+import {+ currentPresencePreview,+ type PeerPresence,+ type PresenceShape,+} from '../presence-state';+import { attachPresencePointer } from './pointer';+import { createPresenceMotion } from './presence-motion';++function GhostShape(props: {+ shape: PresenceShape;+ color: string;+ scale: number;+}) {+ const item = (): ShapeItem => ({+ id: props.shape.id,+ ...shapePayload(+ props.shape.kind,+ props.shape.kind === 'pencil'+ ? props.shape.pencil+ : { width: props.shape.width, height: props.shape.height }+ ),+ placement: { parentId: 'presence-root', sortKey: 'a0' },+ transform: props.shape.world,+ appearance: {+ fill: 'transparent',+ stroke: props.color,+ strokeWidth: props.shape.strokeWidth,+ cornerRadius: props.shape.cornerRadius,+ },+ });+ return (+ <div+ data-presence-preview={props.shape.id}+ style={{+ position: 'absolute',+ left: '0',+ top: '0',+ width: `${props.shape.width}px`,+ height: `${props.shape.height}px`,+ transform: cssMatrix(props.shape.world),+ 'transform-origin': '0 0',+ }}+ >+ <ShapeView+ item={item()}+ renderers={defaultRenderers}+ scale={+ props.scale * Math.hypot(props.shape.world[0], props.shape.world[1])+ }+ preview+ />+ </div>+ );+}++/** A read-only sibling overlay. Remote state never enters GraphicsSurface/editor. */+export function GraphicsPresenceOverlay(props: {+ editor: GraphicsEditor;+ presence: GraphicsPresence;+}) {+ const projection = createGraphicsProjection(props.editor);+ const [peers, setPeers] = createSignal<PeerPresence[]>([]);+ const motion = createPresenceMotion(setPeers);+ const receive = () =>+ motion.update(+ props.presence.getRemote().map((peer) => ({+ ...peer,+ preview: currentPresencePreview(peer, props.presence.getClock()),+ }))+ );+ onCleanup(props.presence.subscribe(receive));+ // Clear obsolete ghosts immediately, even while a spring is in flight.+ onCleanup(props.editor.subscribeDocument(receive));+ onCleanup(motion.dispose);+ receive();+ const screen = (point: Point) => worldToScreen(projection.camera(), point);+ const points = (polygon: readonly Point[]) =>+ polygon+ .map(screen)+ .map((point) => `${point.x},${point.y}`)+ .join(' ');+ return (+ <div+ aria-label="Peer awareness"+ style={{+ position: 'absolute',+ inset: '0',+ overflow: 'hidden',+ 'pointer-events': 'none',+ 'z-index': 2,+ }}+ >+ <For each={peers().map((peer) => peer.id)}>+ {(id) => {+ const peer = () => peers().find((value) => value.id === id)!;+ const preview = () => peer().preview;+ const outlines = () => {+ const action = preview();+ if (action && action.kind !== 'draw' && action.kind !== 'marquee')+ return []; // The ghost itself outlines the pending pose.+ return roots(projection.document, peer().selectedIds).map(+ (selected) =>+ isShape(projection.document.items[selected])+ ? nodeCorners(projection.document, selected)+ : corners(worldBounds(projection.document, selected))+ );+ };+ return (+ <div data-presence-peer={id}>+ <div+ style={{+ position: 'absolute',+ left: '0',+ top: '0',+ 'transform-origin': '0 0',+ transform: `translate(${projection.camera().x}px, ${projection.camera().y}px) scale(${projection.camera().scale})`,+ opacity: 0.7,+ }}+ >+ <For each={preview()?.shapes.map((shape) => shape.id) ?? []}>+ {(shapeId) => (+ <GhostShape+ shape={+ preview()!.shapes.find((shape) => shape.id === shapeId)!+ }+ color={peer().color}+ scale={projection.camera().scale}+ />+ )}+ </For>+ </div>+ <svg+ width="100%"+ height="100%"+ style={{+ position: 'absolute',+ inset: '0',+ overflow: 'visible',+ }}+ >+ <For each={outlines()}>+ {(outline) => (+ <polygon+ data-presence-selection={id}+ points={points(outline)}+ fill="none"+ stroke={peer().color}+ stroke-width="1.5"+ stroke-dasharray="5 3"+ />+ )}+ </For>+ <Show when={preview()?.box}>+ {(box) => (+ <polygon+ data-presence-marquee={id}+ points={points(corners(box()))}+ fill={peer().color}+ fill-opacity="0.08"+ stroke={peer().color}+ stroke-width="1.5"+ stroke-dasharray="5 3"+ />+ )}+ </Show>+ </svg>+ <Show when={peer().cursor}>+ {(cursor) => (+ <div+ data-presence-cursor={id}+ style={{+ position: 'absolute',+ left: '0',+ top: '0',+ transform: `translate(${screen(cursor()).x}px, ${screen(cursor()).y}px)`,+ }}+ >+ <svg+ width="20"+ height="24"+ viewBox="0 0 20 24"+ style={{+ position: 'absolute',+ left: '0',+ top: '0',+ overflow: 'visible',+ }}+ >+ <path+ d="M1.5 1.5 L17 12.5 Q18.5 14 16.5 14.5 L9 16 L3 22 Q1 23.5 1 21 Z"+ fill={peer().color}+ stroke={peer().color}+ stroke-width="1.5"+ stroke-linejoin="round"+ />+ </svg>+ <span+ data-presence-label={id}+ style={{+ position: 'absolute',+ left: '10px',+ top: '25px',+ background: peer().color,+ color: '#202124',+ padding: '3px 9px',+ 'border-radius': '10px',+ 'font-size': '14px',+ 'font-weight': 650,+ 'line-height': '20px',+ 'white-space': 'nowrap',+ }}+ >+ {peer().name}+ </span>+ </div>+ )}+ </Show>+ </div>+ );+ }}+ </For>+ </div>+ );+}++export function CollaborativeGraphicsSurface(+ props: ComponentProps<typeof GraphicsSurface> & { presence: GraphicsPresence }+) {+ const [local, surface] = splitProps(props, ['presence']);+ let host!: HTMLDivElement;+ onMount(() =>+ onCleanup(attachPresencePointer(host, props.editor, local.presence))+ );+ return (+ <div+ ref={host}+ style={{+ position: 'relative',+ isolation: 'isolate',+ width: '100%',+ height: '100%',+ }}+ >+ <GraphicsSurface {...surface} />+ <GraphicsPresenceOverlay+ editor={props.editor}+ presence={local.presence}+ />+ </div>+ );+}diff --git a/packages/graphics/src/loro/solid/pointer.ts b/packages/graphics/src/loro/solid/pointer.tsnew file mode 100644index 0000000000..eb736700ae--- /dev/null+++ b/packages/graphics/src/loro/solid/pointer.ts@@ -0,0 +1,62 @@+import { screenToWorld } from '../../core/camera';+import type { GraphicsEditor } from '../../core/editor';+import type { Point } from '../../core/model';+import type { GraphicsPresence } from '../presence';++/** Browser-only cursor sampling for the collaborative wrapper. No editing handlers. */+export function attachPresencePointer(+ element: HTMLElement,+ editor: GraphicsEditor,+ presence: GraphicsPresence+) {+ let client: Point | null = null;+ const publish = () => {+ const rect = element.getBoundingClientRect();+ if (+ !client ||+ client.x < rect.left ||+ client.y < rect.top ||+ client.x > rect.right ||+ client.y > rect.bottom+ ) {+ presence.setCursor(null);+ return;+ }+ presence.setCursor(+ screenToWorld(editor.getCamera(), {+ x: client.x - rect.left,+ y: client.y - rect.top,+ })+ );+ };+ const pointer = (event: PointerEvent) => {+ client = { x: event.clientX, y: event.clientY };+ publish();+ };+ const leave = () => {+ client = null;+ presence.setCursor(null);+ };+ const visibility = () => {+ if (document.visibilityState === 'hidden') leave();+ };+ element.addEventListener('pointermove', pointer);+ element.addEventListener('pointerdown', pointer);+ element.addEventListener('pointerup', pointer);+ element.addEventListener('pointerleave', leave);+ element.addEventListener('pointercancel', leave);+ window.addEventListener('blur', leave);+ document.addEventListener('visibilitychange', visibility);+ const unsubscribe = editor.subscribeCamera(publish);+ return () => {+ unsubscribe();+ element.removeEventListener('pointermove', pointer);+ element.removeEventListener('pointerdown', pointer);+ element.removeEventListener('pointerup', pointer);+ element.removeEventListener('pointerleave', leave);+ element.removeEventListener('pointercancel', leave);+ window.removeEventListener('blur', leave);+ document.removeEventListener('visibilitychange', visibility);+ leave();+ };+}diff --git a/packages/graphics/src/loro/solid/presence-motion.ts b/packages/graphics/src/loro/solid/presence-motion.tsnew file mode 100644index 0000000000..5a8b998e13--- /dev/null+++ b/packages/graphics/src/loro/solid/presence-motion.ts@@ -0,0 +1,146 @@+import type { PeerPresence, PresenceShape } from '../presence-state';++type Spring = { value: number; target: number; velocity: number };+const FREQUENCY = 26;+const settled = (spring: Spring) =>+ Math.abs(spring.value - spring.target) < 0.0001 &&+ Math.abs(spring.velocity) < 0.001;++/** Receiver-only animation. One frame loop; no writes back to presence or the editor. */+export function createPresenceMotion(render: (peers: PeerPresence[]) => void) {+ const springs = new Map<string, Spring>();+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)');+ let peers: PeerPresence[] = [];+ let frame: number | undefined;+ let previousTime = 0;+ let disposed = false;+ const stop = () => {+ if (frame !== undefined) cancelAnimationFrame(frame);+ frame = undefined;+ };+ const project = () => {+ const used = new Set<string>();+ const sample = (key: string, target: number, angle = false) => {+ used.add(key);+ let spring = springs.get(key);+ if (!spring) {+ spring = { value: target, target, velocity: 0 };+ springs.set(key, spring);+ }+ // Unwrap rotations across ±π; interpolating matrix entries would shrink/skew shapes.+ if (angle)+ target +=+ Math.round((spring.target - target) / (2 * Math.PI)) * 2 * Math.PI;+ spring.target = target;+ if (reducedMotion?.matches) {+ spring.value = target;+ spring.velocity = 0;+ }+ return spring.value;+ };+ const shape = (key: string, target: PresenceShape): PresenceShape => {+ const [a, b, c, d, x, y] = target.world;+ const scaleX = Math.hypot(a, b);+ const angle = sample(`${key}/angle`, Math.atan2(b, a), true);+ const sx = sample(`${key}/sx`, scaleX);+ const sy = sample(`${key}/sy`, (a * d - b * c) / scaleX);+ const shear = sample(`${key}/shear`, (a * c + b * d) / scaleX);+ const cos = Math.cos(angle),+ sin = Math.sin(angle);+ return {+ ...target,+ width: Math.max(0, sample(`${key}/width`, target.width)),+ height: Math.max(0, sample(`${key}/height`, target.height)),+ world: [+ cos * sx,+ sin * sx,+ cos * shear - sin * sy,+ sin * shear + cos * sy,+ sample(`${key}/x`, x),+ sample(`${key}/y`, y),+ ],+ };+ };+ const result = peers.map((peer) => {+ const key = peer.id;+ const preview = peer.preview;+ return {+ ...peer,+ cursor: peer.cursor+ ? {+ x: sample(`${key}/cursor/x`, peer.cursor.x),+ y: sample(`${key}/cursor/y`, peer.cursor.y),+ }+ : null,+ preview: preview+ ? {+ ...preview,+ shapes: preview.shapes.map((target) =>+ shape(+ `${key}/${preview.kind}/${target.kind}/${target.id}`,+ target+ )+ ),+ box: preview.box+ ? {+ x: sample(`${key}/box/x`, preview.box.x),+ y: sample(`${key}/box/y`, preview.box.y),+ width: Math.max(+ 0,+ sample(`${key}/box/width`, preview.box.width)+ ),+ height: Math.max(+ 0,+ sample(`${key}/box/height`, preview.box.height)+ ),+ }+ : null,+ }+ : null,+ };+ });+ for (const key of springs.keys()) if (!used.has(key)) springs.delete(key);+ render(result);+ };+ const moving = () => [...springs.values()].some((spring) => !settled(spring));+ const tick: FrameRequestCallback = (time) => {+ frame = undefined;+ const dt = Math.max(0, (time - previousTime) / 1000);+ previousTime = time;+ const decay = Math.exp(-FREQUENCY * dt);+ for (const spring of springs.values()) {+ // Exact critically damped solution remains stable after a suspended tab resumes.+ const displacement = spring.value - spring.target;+ const impulse = spring.velocity + FREQUENCY * displacement;+ spring.value = spring.target + (displacement + impulse * dt) * decay;+ spring.velocity = (spring.velocity - FREQUENCY * impulse * dt) * decay;+ if (settled(spring)) {+ spring.value = spring.target;+ spring.velocity = 0;+ }+ }+ project();+ if (moving()) frame = requestAnimationFrame(tick);+ };+ const update = (next: PeerPresence[]) => {+ if (disposed) return;+ peers = next;+ project();+ if (!moving()) stop();+ else if (frame === undefined) {+ previousTime = performance.now();+ frame = requestAnimationFrame(tick);+ }+ };+ const preferenceChanged = () => update(peers);+ reducedMotion?.addEventListener('change', preferenceChanged);+ return {+ update,+ dispose() {+ disposed = true;+ stop();+ springs.clear();+ reducedMotion?.removeEventListener('change', preferenceChanged);+ },+ };+}diff --git a/packages/graphics/src/solid/create-shape-view.ts b/packages/graphics/src/solid/create-shape-view.tsnew file mode 100644index 0000000000..bc6d3342f7--- /dev/null+++ b/packages/graphics/src/solid/create-shape-view.ts@@ -0,0 +1,41 @@+import { type Accessor, createMemo } from 'solid-js';+import type { Matrix } from '../core/affine';+import type { ShapeItem } from '../core/model';++/** Render content only depends on shape payload. Transform reads stay live for+ * custom renderers, while geometry retains its immutable cache identity.+ */+export function createShapeView<T extends ShapeItem>(+ source: Accessor<T>,+ transform: Accessor<Matrix> = () => source().transform+): T {+ const content = createMemo(source, undefined, {+ equals: (a, b) =>+ a.id === b.id &&+ a.type === b.type &&+ a.geometry === b.geometry &&+ a.appearance === b.appearance &&+ a.placement === b.placement,+ });+ // All fields come from the same typed source, preserving kind/geometry pairing.+ return {+ get id() {+ return content().id;+ },+ get type() {+ return content().type;+ },+ get placement() {+ return content().placement;+ },+ get transform() {+ return transform();+ },+ get geometry() {+ return content().geometry;+ },+ get appearance() {+ return content().appearance;+ },+ } as T;+}diff --git a/packages/graphics/src/solid/dot-grid-view.tsx b/packages/graphics/src/solid/dot-grid-view.tsxnew file mode 100644index 0000000000..e79e8da31a--- /dev/null+++ b/packages/graphics/src/solid/dot-grid-view.tsx@@ -0,0 +1,54 @@+import { createMemo, createUniqueId, Index } from 'solid-js';+import { dotGridLevels } from '../core/dot-grid';+import type { Camera } from '../core/model';++/** Screen-space SVG patterns keep dots one pixel wide at fractional zoom.+ * The scene transform changes their spacing and origin, never their size.+ */+export function DotGrid(props: { camera: Camera; color: string }) {+ const id = `graphics-grid-${createUniqueId()}`;+ const levels = createMemo(() => dotGridLevels(props.camera.scale));+ return (+ <svg+ aria-hidden="true"+ data-graphics-grid+ shape-rendering="crispEdges"+ style={{+ position: 'absolute',+ inset: 0,+ width: '100%',+ height: '100%',+ overflow: 'hidden',+ 'pointer-events': 'none',+ 'z-index': 0,+ }}+ >+ <defs>+ <Index each={levels()}>+ {(level, index) => (+ <pattern+ id={`${id}-${index}`}+ patternUnits="userSpaceOnUse"+ x={props.camera.x - 0.5}+ y={props.camera.y - 0.5}+ width={level().spacing}+ height={level().spacing}+ >+ <rect+ width="1"+ height="1"+ fill={props.color}+ opacity={level().opacity}+ />+ </pattern>+ )}+ </Index>+ </defs>+ <Index each={levels()}>+ {(_, index) => (+ <rect width="100%" height="100%" fill={`url(#${id}-${index})`} />+ )}+ </Index>+ </svg>+ );+}diff --git a/packages/graphics/src/solid/index.tsx b/packages/graphics/src/solid/index.tsxnew file mode 100644index 0000000000..ee27e5d05d--- /dev/null+++ b/packages/graphics/src/solid/index.tsx@@ -0,0 +1,666 @@+import {+ batch,+ createMemo,+ createRenderEffect,+ createSignal,+ For,+ type JSX,+ onCleanup,+ onMount,+ Show,+ untrack,+} from 'solid-js';+import { createStore, reconcile } from 'solid-js/store';+import {+ attachCameraControls,+ type GraphicsHover,+ type GraphicsInputOptions,+ resizeCursor,+} from '../browser';+import { selectionTarget } from '../browser/selection-target';+import {+ corners,+ cssMatrix,+ enclosing,+ IDENTITY,+ transformPoint,+} from '../core/affine';+import { screenToWorld, worldToScreen } from '../core/camera';+import { connectorWorldView } from '../core/connectors';+import type { GraphicsEditor } from '../core/editor';+import type { GraphicsDocument, Point, ShapeItem } from '../core/model';+import { isRadiusHandle } from '../core/radius';+import { isResizeEdge, resizeHandles } from '../core/resize';+import { selectionFrame } from '../core/selection-frame';+import { isShape, isShapeKind, shapeDefinition } from '../core/shapes/registry';+import { selectedShapeIds } from '../core/style-selection';+import { createShapeView } from './create-shape-view';+import { DotGrid } from './dot-grid-view';+import { RadiusHandles } from './radius-handles';+import { ShapeSelectionOutline } from './selection-outline';+import { SELECTION_COLOR, SELECTION_FILL } from './selection-theme';+import {+ defaultRenderers,+ type ItemRenderers,+ ShapeView,+} from './shape-renderers';++export {+ defaultRenderers,+ type ItemRenderers,+ type ShapeViewProps,+} from './shape-renderers';+export { ConnectorView } from './shapes/connector';+export { EllipseView } from './shapes/ellipse';+export { RectangleView } from './shapes/rectangle';+export { TextView } from './shapes/text';++import {+ drawableIds,+ resolvedShape,+ roots,+ type SceneOverrides,+ shapeProjection,+ worldMatrix,+} from '../core/scene';++export function createGraphicsProjection(editor: GraphicsEditor) {+ const [camera, setCamera] = createSignal(editor.getCamera());+ const [document, setDocument] = createStore(editor.document);+ // Core geometry caches rely on immutable identities. The store is still useful+ // for fine-grained UI reads, but unwraps frozen geometries into mutable proxies.+ const [snapshot, setSnapshot] = createSignal(editor.document);+ const [session, setSession] = createSignal(editor.getSession());+ const [preview, setPreview] = createSignal(editor.getPreview());+ onCleanup(editor.subscribeCamera(setCamera));+ onCleanup(+ editor.subscribeDocument((next) =>+ batch(() => {+ setDocument(reconcile(next));+ setSnapshot(next);+ })+ )+ );+ onCleanup(editor.subscribeSession(setSession));+ onCleanup(editor.subscribePreview(setPreview));+ return { camera, document, snapshot, session, preview };+}+/** Scene paint order is independent of DOM containment; nodes retain keyed mounts. */+export function GraphicsSurface(props: {+ editor: GraphicsEditor;+ renderers?: Partial<ItemRenderers>;+ gridColor?: string;+ class?: string;+ input?: GraphicsInputOptions;+ image?: { src: string; alt: string };+ children?: JSX.Element;+ hideSelection?: boolean;+ /** Allow interactive shape content to receive clicks through the selection box. */+ selectionHitArea?: 'bounds' | 'shapes';+ /** Optional browser feature controls, disposed with the actual viewport. */+ attachControls?: (element: HTMLElement) => () => void;+ /** A feature-owned draft scene. It never replaces the editor document/history. */+ documentPreview?: GraphicsDocument;+}) {+ const projection = createGraphicsProjection(props.editor);+ const [hover, setHover] = createSignal<GraphicsHover>();+ let viewport!: HTMLDivElement;+ onMount(() => {+ onCleanup(+ attachCameraControls(viewport, props.editor, {+ ...props.input,+ onHover: (next) => {+ setHover(next);+ props.input?.onHover?.(next);+ },+ })+ );+ if (props.attachControls) onCleanup(props.attachControls(viewport));+ });+ const scene = createMemo(+ () =>+ props.documentPreview ??+ projection.session().transform?.document ??+ projection.snapshot()+ );+ const emptyOverrides: SceneOverrides = Object.freeze({});+ const overrides = createMemo(+ () => projection.session().transform?.nodes ?? emptyOverrides+ );+ const cameraScale = createMemo(() => projection.camera().scale);+ const selected = createMemo(+ () => roots(scene(), projection.session().selectedIds),+ undefined,+ {+ equals: (a, b) =>+ a.length === b.length && a.every((id, i) => id === b[i]),+ }+ );+ const selectedShapes = createMemo(() =>+ selectedShapeIds(scene(), selected())+ );+ const moving = createMemo(+ () => projection.session().transform?.kind === 'move'+ );+ const movingShapes = createMemo(+ () => new Set(moving() ? selectedShapes() : [])+ );+ const contentOverrides = createMemo(() =>+ moving() ? emptyOverrides : overrides()+ );+ // Every selected root receives the same world-space translation. Keep the+ // flat paint order, including unselected shapes between moving ones.+ const moveOffset = createMemo(() => {+ const id = selected()[0];+ if (!moving() || !id) return { x: 0, y: 0 };+ const base = worldMatrix(scene(), id);+ const next = worldMatrix(scene(), id, overrides());+ return { x: next[4] - base[4], y: next[5] - base[5] };+ });+ const moveElements = new Map<string, Set<HTMLElement | SVGElement>>();+ let translatedElements = new Set<HTMLElement | SVGElement>();+ const registerMoveElement = (+ id: string,+ element: HTMLElement | SVGElement+ ) => {+ const elements =+ moveElements.get(id) ?? new Set<HTMLElement | SVGElement>();+ elements.add(element);+ moveElements.set(id, elements);+ untrack(() => {+ if (movingShapes().has(id) && scene().items[id]?.type !== 'connector') {+ const offset = moveOffset();+ element.style.translate = `${offset.x}px ${offset.y}px`;+ translatedElements.add(element);+ }+ });+ onCleanup(() => {+ elements.delete(element);+ if (!elements.size) moveElements.delete(id);+ translatedElements.delete(element);+ });+ };+ // Update only the moving wrappers and outlines. Inherited CSS variables would+ // invalidate styles throughout the scene, including every embedded subtree.+ createRenderEffect(() => {+ const offset = moveOffset();+ const translate = `${offset.x}px ${offset.y}px`;+ const next = new Set<HTMLElement | SVGElement>();+ for (const id of movingShapes()) {+ if (scene().items[id]?.type === 'connector') continue;+ for (const element of moveElements.get(id) ?? []) {+ element.style.translate = translate;+ next.add(element);+ }+ }+ for (const element of translatedElements) {+ if (!next.has(element)) element.style.removeProperty('translate');+ }+ translatedElements = next;+ });+ const hoveredShapes = createMemo(() => {+ const pointer = hover();+ if (+ !pointer ||+ props.input?.tool?.() !== 'select' ||+ projection.session().transform ||+ projection.session().box ||+ projection.preview()+ )+ return [];+ const camera = projection.camera();+ const id = selectionTarget(+ projection.snapshot(),+ projection.session().selectedIds,+ screenToWorld(camera, pointer.point),+ { ...pointer, tolerance: 3 / camera.scale }+ );+ return id ? selectedShapeIds(projection.snapshot(), [id]) : [];+ });+ const indicatedShapes = createMemo(() => [+ ...new Set([...selectedShapes(), ...hoveredShapes()]),+ ]);+ const singleConnector = () => {+ if (selected().length !== 1) return;+ const item = resolvedShape(scene(), selected()[0]!, overrides());+ return item?.type === 'connector' ? item : undefined;+ };+ const frame = createMemo(() =>+ projection.session().transform+ ? undefined+ : selectionFrame(scene(), selected())+ );+ const radiusRectangle = () => {+ const gesture = projection.session().transform;+ if (+ selected().length !== 1 ||+ props.input?.tool?.() !== 'select' ||+ props.input?.suspended?.() ||+ (gesture && gesture.kind !== 'radius')+ )+ return;+ const item = overrides()[selected()[0]!] ?? scene().items[selected()[0]!];+ return item?.type === 'rectangle' ? item : undefined;+ };+ const screen = (p: Point) => worldToScreen(projection.camera(), p);+ const outline = (id: string) =>+ selectionFrame(scene(), [id], overrides())?.corners.map(screen) ?? [];+ const pointsAttribute = (points: readonly Point[]) =>+ points.map((p) => `${p.x},${p.y}`).join(' ');+ const handleCorners = () => {+ if (projection.session().transform) return [];+ return frame()?.corners.map(screen) ?? [];+ };+ const edgeSegment = (index: number) => {+ const points = handleCorners();+ if (points.length !== 4) return undefined;+ return { start: points[index]!, end: points[(index + 1) % 4]! };+ };+ const rotationHandle = () => {+ const points = handleCorners();+ if (points.length !== 4) return undefined;+ if (selected().length === 1 && isShape(scene().items[selected()[0]!])) {+ const [a, b, c] = [points[0]!, points[1]!, points[2]!];+ const dx = b.x - a.x;+ const dy = b.y - a.y;+ // Keep the normal outside the box even after a resize flips an axis.+ const direction = dy * (c.x - a.x) - dx * (c.y - a.y) > 0 ? -1 : 1;+ const offset = (16 * direction) / Math.hypot(dx, dy);+ return {+ x: (a.x + b.x) / 2 + dy * offset,+ y: (a.y + b.y) / 2 - dx * offset,+ };+ }+ const bounds = enclosing(points);+ return { x: bounds.x + bounds.width / 2, y: bounds.y - 16 };+ };+ const renderers = { ...defaultRenderers, ...props.renderers };+ const previewItem = (): ShapeItem | undefined => {+ if (!projection.preview()) return undefined;+ return props.editor.getDrawingPreview(+ props.input?.appearance?.() ?? {+ fill: 'transparent',+ stroke: '#e53935',+ }+ );+ };+ return (+ <div+ ref={viewport}+ class={props.class}+ tabIndex={0}+ role="region"+ aria-label="Graphics canvas"+ style={{+ position: 'relative',+ isolation: 'isolate',+ overflow: 'hidden',+ width: '100%',+ height: '100%',+ 'touch-action': 'none',+ 'overscroll-behavior': 'contain',+ 'user-select': 'none',+ cursor: isShapeKind(props.input?.tool?.())+ ? 'crosshair'+ : props.input?.tool?.() === 'pan'+ ? 'grab'+ : undefined,+ }}+ >+ <DotGrid+ camera={projection.camera()}+ color={props.gridColor ?? 'currentColor'}+ />+ <div+ style={{+ position: 'absolute',+ top: '0',+ left: '0',+ 'transform-origin': '0 0',+ 'pointer-events': 'none',+ 'z-index': 0,+ transform: `translate(${projection.camera().x}px, ${projection.camera().y}px) scale(${projection.camera().scale})`,+ }}+ >+ <Show when={scene().surface}>+ {(surface) => (+ <Show when={props.image}>+ {(image) => (+ <img+ src={image().src}+ alt={image().alt}+ draggable={false}+ style={{+ position: 'absolute',+ left: '0',+ top: '0',+ width: `${surface().width}px`,+ height: `${surface().height}px`,+ 'max-width': 'none',+ 'pointer-events': 'none',+ }}+ />+ )}+ </Show>+ )}+ </Show>+ <For each={drawableIds(scene())}>+ {(id) => {+ const initial = scene().items[id];+ if (!isShape(initial)) return null;+ const isConnector = () => scene().items[id]?.type === 'connector';+ // Connectors can change their routes when either bound end moves.+ const shapeOverrides = () =>+ isConnector() ? overrides() : contentOverrides();+ const item = createMemo(+ () => resolvedShape(scene(), id, shapeOverrides()) ?? initial+ );+ const world = createMemo(+ () => worldMatrix(scene(), id, shapeOverrides()),+ undefined,+ {+ equals: (a, b) =>+ a.length === b.length &&+ a.every((value, i) => value === b[i]),+ }+ );+ const boundConnector = () => {+ const shape = item();+ return (+ shape.type === 'connector' &&+ !!(shape.geometry.start.binding || shape.geometry.end.binding)+ );+ };+ const renderedItem = createMemo(() => {+ const shape = item();+ return shape.type === 'connector' && boundConnector()+ ? connectorWorldView(shape, world())+ : shape;+ });+ const view = createShapeView(renderedItem, () =>+ isConnector()+ ? renderedItem().transform+ : (resolvedShape(scene(), id, overrides()) ?? initial).transform+ );+ const scale = createMemo(+ () =>+ cameraScale() *+ (boundConnector() ? 1 : Math.hypot(world()[0], world()[1]))+ );+ return (+ <div+ ref={(element) => registerMoveElement(id, element)}+ data-graphics-item={id}+ style={{+ position: 'absolute',+ left: '0',+ top: '0',+ width: `${shapeDefinition(view.type).bounds(view).width}px`,+ height: `${shapeDefinition(view.type).bounds(view).height}px`,+ 'transform-origin': '0 0',+ isolation: 'isolate',+ transform: cssMatrix(boundConnector() ? IDENTITY : world()),+ 'pointer-events': 'auto',+ }}+ >+ <ShapeView renderers={renderers} item={view} scale={scale()} />+ </div>+ );+ }}+ </For>+ <Show when={previewItem()}>+ {(item) => (+ <div+ data-graphics-preview+ style={{+ position: 'absolute',+ left: '0',+ top: '0',+ transform: cssMatrix(item().transform),+ 'transform-origin': '0 0',+ width: `${shapeDefinition(item().type).bounds(item()).width}px`,+ height: `${shapeDefinition(item().type).bounds(item()).height}px`,+ 'pointer-events': 'none',+ }}+ >+ <ShapeView+ renderers={renderers}+ item={item()}+ scale={projection.camera().scale}+ preview+ />+ </div>+ )}+ </Show>+ </div>+ <svg+ aria-label="Selection overlay"+ style={{+ position: 'absolute',+ 'z-index': 1,+ inset: '0',+ width: '100%',+ height: '100%',+ 'pointer-events': 'none',+ overflow: 'visible',+ }}+ >+ <Show when={!props.hideSelection && props.input?.tool?.() === 'select'}>+ <g+ transform={cssMatrix([+ cameraScale(),+ 0,+ 0,+ cameraScale(),+ projection.camera().x,+ projection.camera().y,+ ])}+ >+ <For each={indicatedShapes()}>+ {(id) => {+ const initial = scene().items[id];+ if (!isShape(initial)) return null;+ const isConnector = () =>+ scene().items[id]?.type === 'connector';+ const projection = createMemo(() =>+ shapeProjection(+ scene(),+ id,+ isConnector() ? overrides() : contentOverrides()+ )+ );+ const transform = createMemo(+ () => projection().transform,+ undefined,+ {+ equals: (a, b) => a.every((value, i) => value === b[i]),+ }+ );+ const view = createShapeView(+ () => projection().item ?? initial+ );+ return (+ <ShapeSelectionOutline+ ref={(element) => registerMoveElement(id, element)}+ item={view}+ transform={transform()}+ color={SELECTION_COLOR}+ hovered={!selectedShapes().includes(id)}+ />+ );+ }}+ </For>+ </g>+ <Show when={!projection.session().transform && singleConnector()}>+ {(item) => (+ <For each={['start', 'end'] as const}>+ {(end) => {+ const point = () =>+ screen(+ transformPoint(+ worldMatrix(scene(), item().id, overrides()),+ item().geometry[end].point+ )+ );+ return (+ <circle+ data-graphics-connector-end={end}+ data-graphics-connector-id={item().id}+ aria-label={`Connector ${end}`}+ role="img"+ cx={point().x}+ cy={point().y}+ r="6"+ fill="white"+ stroke={SELECTION_COLOR}+ style={{ 'pointer-events': 'all', cursor: 'grab' }}+ />+ );+ }}+ </For>+ )}+ </Show>+ <For+ each={selected().filter((id) => {+ const item = overrides()[id] ?? scene().items[id];+ if (!isShape(item) || item.type === 'connector') return false;+ // Every selected shape already has a geometry outline. Only a+ // single curved shape needs an additional box while transforming.+ return (+ selected().length === 1 &&+ !!projection.session().transform &&+ (item.type === 'ellipse' ||+ item.type === 'pencil' ||+ (item.type === 'rectangle' && !!item.appearance.cornerRadius))+ );+ })}+ >+ {(id) => (+ <polygon+ points={pointsAttribute(outline(id))}+ fill="none"+ stroke={SELECTION_COLOR}+ stroke-width="1"+ />+ )}+ </For>+ <Show+ when={+ !projection.session().transform && !singleConnector() && frame()+ }+ >+ {(selection) => (+ <polygon+ data-graphics-selection-bounds+ stroke-dasharray={+ selected().length > 1 ||+ scene().items[selected()[0]!]?.type === 'group'+ ? '3 3'+ : undefined+ }+ points={pointsAttribute(selection().corners.map(screen))}+ fill="transparent"+ stroke={SELECTION_COLOR}+ stroke-width="1"+ style={{+ 'pointer-events':+ props.selectionHitArea === 'shapes' ? 'none' : 'all',+ cursor: 'move',+ }}+ />+ )}+ </Show>+ <Show when={!singleConnector()}>+ {/* Screen-space hit strips; corners are painted afterward and win overlaps. */}+ <For each={resizeHandles.filter(isResizeEdge)}>+ {(handle, index) => (+ <Show when={edgeSegment(index())}>+ {(edge) => (+ <line+ data-graphics-handle={handle}+ role="img"+ aria-label={`Resize ${handle}`}+ x1={edge().start.x}+ y1={edge().start.y}+ x2={edge().end.x}+ y2={edge().end.y}+ stroke="transparent"+ stroke-width="10"+ style={{+ 'pointer-events': 'stroke',+ cursor: resizeCursor(handle, frame()),+ }}+ />+ )}+ </Show>+ )}+ </For>+ <For each={resizeHandles.filter((handle) => !isResizeEdge(handle))}>+ {(handle, index) => (+ <Show when={handleCorners()[index()]}>+ {(point) => (+ <rect+ data-graphics-handle={handle}+ role="img"+ aria-label={`Resize ${handle}`}+ x={point().x - 5}+ y={point().y - 5}+ width="10"+ height="10"+ rx="0"+ fill="white"+ stroke={SELECTION_COLOR}+ style={{+ 'pointer-events': 'all',+ cursor: resizeCursor(handle, frame()),+ }}+ />+ )}+ </Show>+ )}+ </For>+ <Show when={rotationHandle()}>+ {(handle) => (+ <circle+ data-graphics-handle="rotate"+ role="img"+ aria-label="Rotate selection"+ cx={handle().x}+ cy={handle().y}+ r="6"+ fill="white"+ stroke={SELECTION_COLOR}+ style={{ 'pointer-events': 'all', cursor: 'grab' }}+ />+ )}+ </Show>+ </Show>+ <Show when={radiusRectangle()}>+ {(item) => (+ <RadiusHandles+ item={item()}+ transform={worldMatrix(scene(), item().id, overrides())}+ camera={projection.camera()}+ active={(() => {+ const handle = projection.session().transform?.handle;+ return isRadiusHandle(handle) ? handle : undefined;+ })()}+ />+ )}+ </Show>+ </Show>+ <Show when={projection.session().box}>+ {(box) => (+ <polygon+ data-graphics-selection-box+ points={pointsAttribute(corners(box()).map(screen))}+ fill={SELECTION_FILL}+ stroke={SELECTION_COLOR}+ />+ )}+ </Show>+ </svg>+ {props.children}+ </div>+ );+}diff --git a/packages/graphics/src/solid/radius-handles.tsx b/packages/graphics/src/solid/radius-handles.tsxnew file mode 100644index 0000000000..57be69d562--- /dev/null+++ b/packages/graphics/src/solid/radius-handles.tsx@@ -0,0 +1,110 @@+import { createMemo, For, Show } from 'solid-js';+import { type Matrix, transformPoint } from '../core/affine';+import { worldToScreen } from '../core/camera';+import type { Camera, Point, RectangleItem } from '../core/model';+import {+ type RadiusHandle,+ radiusHandlePoint,+ radiusHandles,+ rectangleRadius,+} from '../core/radius';+import { SELECTION_COLOR } from './selection-theme';++/** Constant-size controls stay inside the shape even at zero corner radius. */+export function RadiusHandles(props: {+ item: RectangleItem;+ transform: Matrix;+ camera: Camera;+ active?: RadiusHandle;+}) {+ const points = createMemo(() => {+ const { item, transform, camera } = props;+ const xScale = Math.hypot(transform[0], transform[1]) * camera.scale;+ const yScale = Math.hypot(transform[2], transform[3]) * camera.scale;+ const points: Partial<Record<RadiusHandle, Point>> = {};+ if (+ !props.active &&+ Math.min(item.geometry.width * xScale, item.geometry.height * yScale) < 32+ )+ return points;+ for (const handle of radiusHandles) {+ if (props.active && props.active !== handle) continue;+ const point = worldToScreen(+ camera,+ transformPoint(+ transform,+ radiusHandlePoint(item, handle, {+ x: 16 / xScale,+ y: 16 / yScale,+ })+ )+ );+ // Pill/circle radii can put two or four controls at the same point.+ if (+ Object.values(points).some(+ (other) => Math.hypot(other.x - point.x, other.y - point.y) < 16+ )+ )+ continue;+ points[handle] = point;+ }+ return points;+ });+ const radius = () => Number(rectangleRadius(props.item).toFixed(2));+ const labelWidth = () => Math.max(28, String(radius()).length * 7 + 12);+ return (+ <For each={radiusHandles}>+ {(handle) => (+ <Show when={points()[handle]}>+ {(point) => (+ <g+ data-graphics-handle={handle}+ role="img"+ aria-label={`Corner radius ${handle.slice(7)}`}+ style={{+ 'pointer-events': 'all',+ cursor: props.active ? 'grabbing' : 'grab',+ }}+ >+ <title>{`Corner radius: ${radius()}. Drag to round all corners.`}</title>+ <circle cx={point().x} cy={point().y} r="10" fill="transparent" />+ <circle+ cx={point().x}+ cy={point().y}+ r="4"+ fill="white"+ stroke={SELECTION_COLOR}+ stroke-width="1"+ />+ <Show when={props.active === handle}>+ <g+ data-graphics-radius-label+ transform={`translate(${point().x + 12} ${point().y - 30})`}+ style={{ 'pointer-events': 'none' }}+ >+ <rect+ width={labelWidth()}+ height="20"+ rx="5"+ fill={SELECTION_COLOR}+ />+ <text+ x={labelWidth() / 2}+ y="10"+ fill="white"+ text-anchor="middle"+ dominant-baseline="middle"+ font-size="12"+ font-weight="500"+ >+ {radius()}+ </text>+ </g>+ </Show>+ </g>+ )}+ </Show>+ )}+ </For>+ );+}diff --git a/packages/graphics/src/solid/selection-outline.tsx b/packages/graphics/src/solid/selection-outline.tsxnew file mode 100644index 0000000000..e323531571--- /dev/null+++ b/packages/graphics/src/solid/selection-outline.tsx@@ -0,0 +1,111 @@+import { type Component, createMemo } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import type { Matrix } from '../core/affine';+import { cssMatrix } from '../core/affine';+import { resolveAppearance } from '../core/appearance';+import type { ShapeItem, ShapeKind } from '../core/model';+import { connectorPath } from '../core/shapes/connector-routing';+import { pencilInk } from '../core/shapes/pencil';++type OutlineProps<K extends ShapeKind = ShapeKind> = { item: ShapeItem<K> };++/** Geometry-only indicators, independent of content renderers and appearance opacity. */+const outlines: { [K in ShapeKind]: Component<OutlineProps<K>> } = {+ connector: (props) => (+ <path+ d={+ connectorPath(+ props.item.geometry.start,+ props.item.geometry.end,+ props.item.geometry.route+ ).path+ }+ vector-effect="non-scaling-stroke"+ />+ ),+ image: (props) => (+ <rect+ width={props.item.geometry.width}+ height={props.item.geometry.height}+ vector-effect="non-scaling-stroke"+ />+ ),+ video: (props) => (+ <rect+ width={props.item.geometry.width}+ height={props.item.geometry.height}+ vector-effect="non-scaling-stroke"+ />+ ),+ document: (props) => (+ <rect+ width={props.item.geometry.width}+ height={props.item.geometry.height}+ vector-effect="non-scaling-stroke"+ />+ ),+ text: (props) => (+ <rect+ width={props.item.geometry.width}+ height={props.item.geometry.height}+ vector-effect="non-scaling-stroke"+ />+ ),+ rectangle: (props) => (+ <rect+ width={props.item.geometry.width}+ height={props.item.geometry.height}+ rx={Math.min(+ resolveAppearance(props.item.appearance).cornerRadius,+ props.item.geometry.width / 2,+ props.item.geometry.height / 2+ )}+ vector-effect="non-scaling-stroke"+ />+ ),+ ellipse: (props) => (+ <ellipse+ cx={props.item.geometry.width / 2}+ cy={props.item.geometry.height / 2}+ rx={props.item.geometry.width / 2}+ ry={props.item.geometry.height / 2}+ vector-effect="non-scaling-stroke"+ />+ ),+ pencil: (props) => {+ const ink = createMemo(() => pencilInk(props.item));+ return <path d={ink().centerline} vector-effect="non-scaling-stroke" />;+ },+};++/** SVG transforms keep stroke thickness at one screen pixel through any scene transform. */+export function ShapeSelectionOutline<K extends ShapeKind>(+ props: OutlineProps<K> & {+ transform: Matrix;+ color: string;+ hovered?: boolean;+ ref?: (element: SVGGElement) => void;+ }+) {+ // The mapped registry pairs every shape kind with its typed outline.+ const renderer = () =>+ outlines[props.item.type] as Component<OutlineProps<K>>;+ return (+ <g+ ref={props.ref}+ data-graphics-selection-outline={+ props.hovered ? undefined : props.item.id+ }+ data-graphics-hover-outline={props.hovered ? props.item.id : undefined}+ transform={cssMatrix(props.transform)}+ fill="none"+ stroke={props.color}+ stroke-width="1"+ stroke-linecap="round"+ stroke-linejoin="round"+ pointer-events="none"+ >+ <Dynamic component={renderer()} item={props.item} />+ </g>+ );+}diff --git a/packages/graphics/src/solid/selection-theme.ts b/packages/graphics/src/solid/selection-theme.tsnew file mode 100644index 0000000000..e34671a58c--- /dev/null+++ b/packages/graphics/src/solid/selection-theme.ts@@ -0,0 +1,2 @@+export const SELECTION_COLOR = '#5687ff';+export const SELECTION_FILL = 'rgba(86,135,255,0.12)';diff --git a/packages/graphics/src/solid/shape-renderers.tsx b/packages/graphics/src/solid/shape-renderers.tsxnew file mode 100644index 0000000000..f42a369132--- /dev/null+++ b/packages/graphics/src/solid/shape-renderers.tsx@@ -0,0 +1,42 @@+import type { Component } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import type { ShapeItem, ShapeKind } from '../core/model';+import { ConnectorView } from './shapes/connector';+import { EllipseView } from './shapes/ellipse';+import { EmbeddedPlaceholder } from './shapes/embedded';+import { PencilView } from './shapes/pencil';+import { RectangleView } from './shapes/rectangle';+import { TextView } from './shapes/text';++export type ShapeViewProps<K extends ShapeKind = ShapeKind> = {+ /** Live view: read fields in reactive scopes, as with Solid props. */+ item: ShapeItem<K>;+ scale: number;+ preview?: boolean;+};+export type ItemRenderers = { [K in ShapeKind]: Component<ShapeViewProps<K>> };+export const defaultRenderers: ItemRenderers = {+ connector: ConnectorView,+ rectangle: RectangleView,+ ellipse: EllipseView,+ pencil: PencilView,+ text: TextView,+ image: EmbeddedPlaceholder,+ video: EmbeddedPlaceholder,+ document: EmbeddedPlaceholder,+};+export function ShapeView<K extends ShapeKind>(+ props: ShapeViewProps<K> & { renderers: ItemRenderers }+) {+ // The mapped registry guarantees each component receives its own typed item.+ const renderer = () =>+ props.renderers[props.item.type] as Component<ShapeViewProps<K>>;+ return (+ <Dynamic+ component={renderer()}+ item={props.item}+ scale={props.scale}+ preview={props.preview}+ />+ );+}diff --git a/packages/graphics/src/solid/shapes/connector.tsx b/packages/graphics/src/solid/shapes/connector.tsxnew file mode 100644index 0000000000..f8b33c200d--- /dev/null+++ b/packages/graphics/src/solid/shapes/connector.tsx@@ -0,0 +1,133 @@+import { createMemo, createUniqueId, For, Show } from 'solid-js';+import { resolveAppearance, strokeDasharray } from '../../core/appearance';+import {+ connectorHead,+ connectorPath,+} from '../../core/shapes/connector-routing';+import { shapeLabelLayout } from '../../core/shapes/label';+import type { ShapeViewProps } from '../shape-renderers';+import { ShapeLabelView } from './label';+import type { TextContentView } from './text';++export function ConnectorView(+ props: ShapeViewProps<'connector'> & {+ hideLabel?: boolean;+ contentView?: TextContentView;+ }+) {+ const route = createMemo(() =>+ connectorPath(+ props.item.geometry.start,+ props.item.geometry.end,+ props.item.geometry.route+ )+ );+ const maskId = createUniqueId();+ const label = createMemo(() => shapeLabelLayout(props.item));+ const style = () => resolveAppearance(props.item.appearance);+ return (+ <>+ <svg+ width="1"+ height="1"+ style={{+ overflow: 'visible',+ position: 'absolute',+ left: '0',+ top: '0',+ 'pointer-events': 'none',+ }}+ >+ <Show when={label()}>+ {(layout) => (+ <defs>+ <mask+ id={maskId}+ maskUnits="userSpaceOnUse"+ x={route().bounds.x - 100}+ y={route().bounds.y - 100}+ width={route().bounds.width + 200}+ height={route().bounds.height + 200}+ >+ <rect+ x={route().bounds.x - 100}+ y={route().bounds.y - 100}+ width={route().bounds.width + 200}+ height={route().bounds.height + 200}+ fill="white"+ />+ <rect+ x={layout().transform[4] - 4}+ y={layout().transform[5] - 2}+ width={layout().geometry.width + 8}+ height={layout().geometry.height + 4}+ fill="black"+ />+ </mask>+ </defs>+ )}+ </Show>+ <g+ stroke={style().stroke}+ stroke-width={style().strokeWidth}+ opacity={style().opacity}+ stroke-linecap="round"+ stroke-linejoin="round"+ fill="none"+ >+ <path+ mask={label() ? `url(#${maskId})` : undefined}+ stroke-dasharray={strokeDasharray(props.item.appearance)}+ d={route().path}+ data-graphics-connector-path={props.item.id}+ />+ <For each={['start', 'end'] as const}>+ {(end) => {+ const headStyle = () =>+ end === 'start'+ ? props.item.geometry.startHead+ : props.item.geometry.endHead;+ const head = () =>+ connectorHead(+ props.item.geometry[end].point,+ end === 'start' ? route().from : route().to,+ headStyle()+ );+ return (+ <Show when={headStyle() !== 'none'}>+ <Show+ when={head().radius}+ fallback={+ <path+ d={head().path}+ fill={+ headStyle() === 'arrow-filled'+ ? style().stroke+ : 'none'+ }+ />+ }+ >+ <circle+ cx={props.item.geometry[end].point.x}+ cy={props.item.geometry[end].point.y}+ r={head().radius}+ fill={style().stroke}+ stroke="none"+ />+ </Show>+ </Show>+ );+ }}+ </For>+ </g>+ </svg>+ <ShapeLabelView+ item={props.item}+ scale={props.scale}+ hidden={props.hideLabel || props.preview}+ contentView={props.contentView}+ />+ </>+ );+}diff --git a/packages/graphics/src/solid/shapes/ellipse.tsx b/packages/graphics/src/solid/shapes/ellipse.tsxnew file mode 100644index 0000000000..69ee9fb5c1--- /dev/null+++ b/packages/graphics/src/solid/shapes/ellipse.tsx@@ -0,0 +1,35 @@+import type { Component } from 'solid-js';+import { resolveAppearance, strokeDasharray } from '../../core/appearance';+import type { ShapeViewProps } from '../shape-renderers';+import { ShapeLabelView } from './label';+import type { TextContentView } from './text';++export const EllipseView: Component<+ ShapeViewProps<'ellipse'> & {+ hideLabel?: boolean;+ contentView?: TextContentView;+ }+> = (props) => (+ <>+ <svg width="100%" height="100%" style={{ overflow: 'visible' }}>+ <ellipse+ cx="50%"+ cy="50%"+ rx={props.item.geometry.width / 2}+ ry={props.item.geometry.height / 2}+ fill={props.item.appearance.fill}+ stroke={props.item.appearance.stroke}+ stroke-linecap="round"+ stroke-dasharray={strokeDasharray(props.item.appearance)}+ stroke-width={resolveAppearance(props.item.appearance).strokeWidth}+ opacity={resolveAppearance(props.item.appearance).opacity}+ />+ </svg>+ <ShapeLabelView+ item={props.item}+ scale={props.scale}+ hidden={props.hideLabel || props.preview}+ contentView={props.contentView}+ />+ </>+);diff --git a/packages/graphics/src/solid/shapes/embedded.tsx b/packages/graphics/src/solid/shapes/embedded.tsxnew file mode 100644index 0000000000..4ff599b282--- /dev/null+++ b/packages/graphics/src/solid/shapes/embedded.tsx@@ -0,0 +1,20 @@+import type { ShapeViewProps } from '../shape-renderers';+/** Host apps resolve media and document references through their own services. */+export function EmbeddedPlaceholder(+ props: ShapeViewProps<'image' | 'video' | 'document'>+) {+ return (+ <div+ style={{+ width: '100%',+ height: '100%',+ border: '1px solid currentColor',+ display: 'grid',+ 'place-items': 'center',+ opacity: props.item.appearance.opacity ?? 1,+ }}+ >+ {props.item.geometry.name || props.item.type}+ </div>+ );+}diff --git a/packages/graphics/src/solid/shapes/label.tsx b/packages/graphics/src/solid/shapes/label.tsxnew file mode 100644index 0000000000..6d4a9fe25b--- /dev/null+++ b/packages/graphics/src/solid/shapes/label.tsx@@ -0,0 +1,37 @@+import { Show } from 'solid-js';+import { cssMatrix } from '../../core/affine';+import {+ type LabelShape,+ shapeLabelLayout,+ shapeLabelText,+} from '../../core/shapes/label';+import { type TextContentView, TextView } from './text';++export function ShapeLabelView(props: {+ item: LabelShape;+ scale: number;+ hidden?: boolean;+ contentView?: TextContentView;+}) {+ return (+ <Show when={!props.hidden && props.item.geometry.label}>+ <div+ data-graphics-label={props.item.id}+ style={{+ position: 'absolute',+ left: '0',+ top: '0',+ 'transform-origin': '0 0',+ transform: cssMatrix(shapeLabelLayout(props.item)!.transform),+ 'pointer-events': 'none',+ }}+ >+ <TextView+ contentView={props.contentView}+ item={shapeLabelText(props.item)!}+ scale={props.scale}+ />+ </div>+ </Show>+ );+}diff --git a/packages/graphics/src/solid/shapes/pencil.tsx b/packages/graphics/src/solid/shapes/pencil.tsxnew file mode 100644index 0000000000..0c15e85780--- /dev/null+++ b/packages/graphics/src/solid/shapes/pencil.tsx@@ -0,0 +1,22 @@+import { type Component, createMemo } from 'solid-js';+import { resolveAppearance } from '../../core/appearance';+import { pencilInk } from '../../core/shapes/pencil';+import type { ShapeViewProps } from '../shape-renderers';++export const PencilView: Component<ShapeViewProps<'pencil'>> = (props) => {+ const ink = createMemo(() => pencilInk(props.item));+ return (+ <svg width="100%" height="100%" style={{ overflow: 'visible' }}>+ <path+ d={ink().path}+ fill={props.item.appearance.stroke}+ opacity={resolveAppearance(props.item.appearance).opacity}+ visibility={+ resolveAppearance(props.item.appearance).strokeWidth === 0+ ? 'hidden'+ : undefined+ }+ />+ </svg>+ );+};diff --git a/packages/graphics/src/solid/shapes/rectangle.tsx b/packages/graphics/src/solid/shapes/rectangle.tsxnew file mode 100644index 0000000000..1faf1c6569--- /dev/null+++ b/packages/graphics/src/solid/shapes/rectangle.tsx@@ -0,0 +1,42 @@+import type { Component } from 'solid-js';+import { resolveAppearance, strokeDasharray } from '../../core/appearance';+import type { ShapeViewProps } from '../shape-renderers';+import { ShapeLabelView } from './label';+import type { TextContentView } from './text';++export const RectangleView: Component<+ ShapeViewProps<'rectangle'> & {+ hideLabel?: boolean;+ contentView?: TextContentView;+ }+> = (props) => {+ const style = () => resolveAppearance(props.item.appearance);+ return (+ <>+ <svg width="100%" height="100%" style={{ overflow: 'visible' }}>+ <rect+ width={props.item.geometry.width}+ height={props.item.geometry.height}+ rx={Math.min(+ style().cornerRadius,+ props.item.geometry.width / 2,+ props.item.geometry.height / 2+ )}+ fill={style().fill}+ stroke={style().stroke}+ stroke-linejoin="round"+ stroke-linecap="round"+ stroke-dasharray={strokeDasharray(props.item.appearance)}+ stroke-width={style().strokeWidth}+ opacity={style().opacity}+ />+ </svg>+ <ShapeLabelView+ item={props.item}+ scale={props.scale}+ hidden={props.hideLabel || props.preview}+ contentView={props.contentView}+ />+ </>+ );+};diff --git a/packages/graphics/src/solid/shapes/text.tsx b/packages/graphics/src/solid/shapes/text.tsxnew file mode 100644index 0000000000..e853c2a2a1--- /dev/null+++ b/packages/graphics/src/solid/shapes/text.tsx@@ -0,0 +1,30 @@+import '../../browser/rich-text.css';+import type { Component } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import { textLayoutStyle } from '../../browser/rich-text';+import type { RichText } from '../../core/rich-text';+import type { ShapeViewProps } from '../shape-renderers';+export type TextContentView = Component<{ content: RichText }>;+/** Plain strings need no codec. Encoded content requires a host contentView. */+const PlainText: TextContentView = (props) => <>{props.content}</>;+export function TextView(+ props: ShapeViewProps<'text'> & { contentView?: TextContentView }+) {+ return (+ <div+ class="graphics-rich-text"+ data-graphics-text={props.item.id}+ style={{+ ...textLayoutStyle(props.item.geometry),+ color: props.item.appearance.stroke,+ opacity: props.item.appearance.opacity ?? 1,+ 'pointer-events': 'none',+ }}+ >+ <Dynamic+ component={props.contentView ?? PlainText}+ content={props.item.geometry.content}+ />+ </div>+ );+}diff --git a/packages/graphics/tests/appearance.test.ts b/packages/graphics/tests/appearance.test.tsnew file mode 100644index 0000000000..0bd7fa3e97--- /dev/null+++ b/packages/graphics/tests/appearance.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import {+ resolveAppearance,+ strokeDasharray,+ validAppearance,+} from '../src/core/appearance';++describe('stroke patterns', () => {+ const base = { fill: 'transparent', stroke: '#123456', strokeWidth: 3 };+ it('keeps existing documents solid and scales dash spacing with stroke weight', () => {+ expect(resolveAppearance(base).strokeStyle).toBe('solid');+ expect(strokeDasharray(base)).toBeUndefined();+ expect(strokeDasharray({ ...base, strokeStyle: 'dashed' })).toBe('12 9');+ expect(strokeDasharray({ ...base, strokeStyle: 'dotted' })).toBe('0 7.5');+ });+ it('accepts persisted patterns and rejects invalid values', () => {+ for (const strokeStyle of ['solid', 'dashed', 'dotted']) {+ expect(validAppearance({ ...base, strokeStyle })).toBe(true);+ }+ expect(validAppearance({ ...base, strokeStyle: 'invalid' })).toBe(false);+ });+});diff --git a/packages/graphics/tests/boundary.test.ts b/packages/graphics/tests/boundary.test.tsnew file mode 100644index 0000000000..ab89b746ed--- /dev/null+++ b/packages/graphics/tests/boundary.test.ts@@ -0,0 +1,44 @@+// @vitest-environment node+import { readdirSync, readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import ts from 'typescript';+import { expect, it } from 'vitest';++it('keeps the transitive core import graph inside the framework-free core', () => {+ const root = resolve(import.meta.dirname, '../src/core');+ for (const file of readdirSync(root, {+ recursive: true,+ encoding: 'utf8',+ }).filter((name) => name.endsWith('.ts'))) {+ const path = resolve(root, file);+ const source = ts.createSourceFile(+ path,+ readFileSync(path, 'utf8'),+ ts.ScriptTarget.Latest,+ true+ );+ function visit(node: ts.Node) {+ if (+ (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&+ node.moduleSpecifier &&+ ts.isStringLiteral(node.moduleSpecifier)+ ) {+ const specifier = node.moduleSpecifier.text;+ if (specifier === 'perfect-freehand') {+ expect(file).toBe('shapes/pencil.ts');+ return;+ }+ if (specifier === 'fractional-indexing') {+ expect(file).toBe('ordering.ts');+ return;+ }+ expect(specifier.startsWith('.')).toBe(true);+ expect(resolve(dirname(path), specifier).startsWith(`${root}/`)).toBe(+ true+ );+ }+ ts.forEachChild(node, visit);+ }+ visit(source);+ }+});diff --git a/packages/graphics/tests/box-selection.test.ts b/packages/graphics/tests/box-selection.test.tsnew file mode 100644index 0000000000..69cf17b211--- /dev/null+++ b/packages/graphics/tests/box-selection.test.ts@@ -0,0 +1,120 @@+import { expect, it } from 'vitest';+import { attachCameraControls } from '../src/browser';+import { createGraphicsEditor } from '../src/core';+import { translation } from '../src/core/affine';+import { drawableIds, worldBounds } from '../src/core/scene';++const makeEditor = () =>+ createGraphicsEditor(+ ['a', 'b', 'c'].map((id, i) => ({+ id,+ type: 'rectangle' as const,+ placement: { parentId: 'scene-root', sortKey: `a${i}` },+ transform: translation(i * 100, 0),+ geometry: { width: 50, height: 50 },+ appearance: { fill: 'white', stroke: 'black' },+ }))+ );++it('selects touched items in either drag direction, adds with Shift semantics and cancels to the prior selection', () => {+ const editor = makeEditor();+ editor.beginBoxSelection({ x: 110, y: 20 });+ editor.updateBoxSelection({ x: -10, y: -10 });+ expect(editor.getSession().selectedIds).toEqual(['a', 'b']);+ editor.commitBoxSelection();+ expect(editor.getSession().canUndo).toBe(false);+ editor.toggleSelection('a');+ expect(editor.getSession().selectedIds).toEqual(['b']);+ editor.beginBoxSelection({ x: 220, y: 20 }, true);+ editor.updateBoxSelection({ x: 210, y: 10 });+ expect(editor.getSession().selectedIds).toEqual(['b', 'c']);+ editor.cancelTransform();+ expect(editor.getSession().selectedIds).toEqual(['b']);+ editor.beginBoxSelection({ x: -10, y: -10 }, true);+ editor.updateBoxSelection({ x: 20, y: 20 });+ editor.commitBoxSelection();+ expect(editor.getSession().selectedIds).toEqual(['b', 'a']);+ editor.beginBoxSelection({ x: 500, y: 500 });+ editor.commitBoxSelection();+ expect(editor.getSession().selectedIds).toEqual([]);+});++it('moves and deletes groups in single undo steps and cancels group previews', () => {+ const editor = makeEditor();+ editor.select('a');+ editor.toggleSelection('b');+ editor.beginTransform('a', { x: 0, y: 0 });+ editor.updateTransform({ x: 20, y: 30 });+ expect(editor.getSession().transform?.geometries.b?.x).toBe(120);+ expect(worldBounds(editor.document, 'b').x).toBe(100);+ editor.cancelTransform();+ expect(editor.getSession().canUndo).toBe(false);+ editor.beginTransform('b', { x: 100, y: 0 });+ editor.updateTransform({ x: 120, y: 30 });+ editor.commitTransform();+ expect(worldBounds(editor.document, 'a').x).toBe(20);+ expect(worldBounds(editor.document, 'b').x).toBe(120);+ editor.undo();+ expect(worldBounds(editor.document, 'a').x).toBe(0);+ expect(worldBounds(editor.document, 'b').x).toBe(100);+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ editor.deleteSelection();+ expect(drawableIds(editor.document)).toEqual(['c']);+ editor.undo();+ expect(drawableIds(editor.document)).toEqual(['a', 'b', 'c']);+});++it('routes Shift-click, Shift-box and Escape through pointer controls at non-default zoom', () => {+ const editor = makeEditor();+ editor.zoomAt({ x: 0, y: 0 }, 2);+ const viewport = document.createElement('div');+ document.body.append(viewport);+ let captured = false;+ viewport.setPointerCapture = () => {+ captured = true;+ };+ viewport.hasPointerCapture = () => captured;+ viewport.releasePointerCapture = () => {+ captured = false;+ };+ const a = document.createElement('div');+ a.dataset.graphicsItem = 'a';+ viewport.append(a);+ const detach = attachCameraControls(viewport, editor, {+ tool: () => 'select',+ editing: true,+ });+ const pointer = (+ type: string,+ x: number,+ y: number,+ shiftKey = false,+ target = viewport+ ) => {+ const event = new MouseEvent(type, {+ clientX: x,+ clientY: y,+ shiftKey,+ bubbles: true,+ });+ Object.defineProperty(event, 'pointerId', { value: 1 });+ target.dispatchEvent(event);+ };+ pointer('pointerdown', 20, 20, true, a);+ pointer('pointerup', 20, 20, true, a);+ expect(editor.getSession().selectedIds).toEqual(['a']);+ pointer('pointerdown', 190, -10, true);+ pointer('pointermove', 210, 20, true);+ pointer('pointerup', 210, 20, true);+ expect(editor.getSession().selectedIds).toEqual(['a', 'b']);+ pointer('pointerdown', 390, -10);+ pointer('pointermove', 410, 20);+ expect(editor.getSession().selectedIds).toEqual(['c']);+ viewport.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));+ expect(editor.getSession().selectedIds).toEqual(['a', 'b']);+ expect(editor.getSession().box).toBeUndefined();+ expect(captured).toBe(false);+ detach();+ viewport.remove();+});diff --git a/packages/graphics/tests/commands.test.ts b/packages/graphics/tests/commands.test.tsnew file mode 100644index 0000000000..a460bdf5b5--- /dev/null+++ b/packages/graphics/tests/commands.test.ts@@ -0,0 +1,274 @@+import { afterEach, expect, it } from 'vitest';+import {+ alignCommand,+ children,+ copyFragment,+ createGraphicsEditor,+ createScene,+ distributeCommand,+ duplicateCommand,+ freezeDocument,+ isShape,+ multiply,+ nudgeCommand,+ parseFragment,+ pasteCommand,+ rotation,+ selectAllCommand,+ selectedShapeIds,+ translation,+ worldBounds,+ worldMatrix,+} from '../src/core';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const seed = () =>+ createScene([+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(translation(100, 70), rotation(0.4)),+ },+ {+ id: 'inner',+ type: 'group',+ placement: { parentId: 'group', sortKey: 'a0' },+ transform: multiply(translation(10, 30), rotation(-0.2)),+ },+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'inner', sortKey: 'a0' },+ transform: translation(20, 0),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ {+ id: 'b',+ type: 'ellipse',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: translation(300, 200),+ geometry: { width: 60, height: 40 },+ appearance: { fill: 'transparent', stroke: 'black' },+ },+ {+ id: 'c',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a2' },+ transform: translation(470, 150),+ geometry: { width: 80, height: 120 },+ appearance: { fill: 'blue', stroke: 'black' },+ },+ ]);+const ids = () => {+ let n = 0;+ return () => `copy-${++n}`;+};+const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((fn) => fn()));++it('round-trips nested selection with new IDs, ordering and world pose in one undo step', () => {+ const editor = createGraphicsEditor(seed());+ editor.select('group');+ editor.toggleSelection('a');+ const fragment = parseFragment(+ JSON.stringify(+ copyFragment(editor.document, editor.getSession().selectedIds)+ )+ )!;+ expect(children(fragment.scene)).toEqual(['group']);+ editor.execute(pasteCommand, {+ fragment,+ createId: ids(),+ offset: { x: 25, y: -10 },+ });+ const selected = editor.getSession().selectedIds;+ const leaf = selectedShapeIds(editor.document, selected)[0]!;+ expect(selected).toEqual(['copy-1']);+ expect(children(editor.document, 'copy-1')).toEqual(['copy-2']);+ expect(children(editor.document, 'copy-2')).toEqual(['copy-3']);+ expect(worldMatrix(editor.document, leaf)).toEqual(+ multiply(translation(25, -10), worldMatrix(seed(), 'a'))+ );+ expect(children(editor.document)).toEqual(['group', 'b', 'c', 'copy-1']);+ editor.undo();+ expect(editor.document).toEqual(seed());+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ expect(editor.document.items[leaf]).toBeDefined();+});++it('copies a deeply selected child into a different scene without changing its world pose', () => {+ const editor = createGraphicsEditor();+ editor.execute(pasteCommand, {+ fragment: copyFragment(seed(), ['a'])!,+ createId: ids(),+ offset: { x: 0, y: 0 },+ });+ expect(worldMatrix(editor.document, 'copy-1')).toEqual(+ worldMatrix(seed(), 'a')+ );+});++it('duplicates a nested child in its parent, then nudges in world coordinates', () => {+ const editor = createGraphicsEditor(seed());+ editor.select('a');+ editor.execute(duplicateCommand, { createId: ids() });+ const copy = editor.document.items['copy-1'];+ expect(copy).toMatchObject({ placement: { parentId: 'inner' } });+ const before = worldBounds(editor.document, 'copy-1');+ editor.execute(nudgeCommand, { x: 10, y: -1 });+ const after = worldBounds(editor.document, 'copy-1');+ expect(after.x - before.x).toBeCloseTo(10);+ expect(after.y - before.y).toBeCloseTo(-1);+ editor.undo();+ expect(worldBounds(editor.document, 'copy-1')).toEqual(before);+});++it('previews Option-drag copies without committing, cancels cleanly, and commits once', () => {+ const editor = createGraphicsEditor(seed());+ editor.select('group');+ let updates = 0;+ editor.subscribeDocument(() => updates++);+ editor.beginTransform('group', { x: 0, y: 0 }, undefined, ids());+ editor.updateTransform({ x: 80, y: 50 });+ expect(editor.document).toEqual(seed());+ expect(+ editor.getSession().transform?.document?.items['copy-3']+ ).toBeDefined();+ editor.cancelTransform();+ expect(editor.getSession().selectedIds).toEqual(['group']);+ expect(editor.getSession().canUndo).toBe(false);+ expect(updates).toBe(0);+ editor.beginTransform('group', { x: 0, y: 0 }, undefined, ids());+ editor.commitTransform();+ expect(updates).toBe(0);+ editor.beginTransform('group', { x: 0, y: 0 }, undefined, ids());+ editor.updateTransform({ x: 80, y: 50 });+ editor.commitTransform();+ expect(updates).toBe(1);+ expect(editor.getSession().selectedIds).toEqual(['copy-1']);+ editor.undo();+ expect(editor.document).toEqual(seed());+ expect(editor.getSession().canUndo).toBe(false);+});++it('aligns world bounds and distributes equal gaps with endpoints fixed', () => {+ const editor = createGraphicsEditor(seed());+ editor.execute(selectAllCommand, undefined);+ editor.execute(alignCommand, 'top');+ const bounds = children(editor.document).map((id) =>+ worldBounds(editor.document, id)+ );+ bounds.forEach((b) => expect(b.y).toBeCloseTo(bounds[0]!.y));+ editor.undo();+ expect(editor.document).toEqual(seed());+ const first = worldBounds(editor.document, 'group'),+ last = worldBounds(editor.document, 'c');+ editor.execute(distributeCommand, 'horizontal');+ const middle = worldBounds(editor.document, 'b');+ expect(worldBounds(editor.document, 'group')).toEqual(first);+ expect(worldBounds(editor.document, 'c')).toEqual(last);+ expect(middle.x - first.x - first.width).toBeCloseTo(+ last.x - middle.x - middle.width+ );+});++it('styles group descendants once, preserves mixed values, and rejects invalid proposals atomically', () => {+ const editor = createGraphicsEditor(seed());+ editor.select('group');+ editor.toggleSelection('b');+ editor.setSelectionAppearance({+ strokeWidth: 12,+ opacity: 0.5,+ cornerRadius: 15,+ });+ for (const id of ['a', 'b'])+ expect(editor.document.items[id]).toMatchObject({+ appearance: { strokeWidth: 12, opacity: 0.5, cornerRadius: 15 },+ });+ expect(editor.document.items.a).toMatchObject({+ appearance: { fill: 'red' },+ });+ editor.undo();+ expect(editor.document).toEqual(seed());+ expect(() => editor.setSelectionAppearance({ opacity: 2 })).toThrow();+ expect(() =>+ editor.execute(duplicateCommand, { createId: () => 'a' })+ ).toThrow();+ expect(editor.document).toEqual(seed());+ expect(editor.getSession().canUndo).toBe(false);+});++it('rejects malformed, cyclic, unsupported and oversized clipboard data', () => {+ expect(parseFragment('hello')).toBeUndefined();+ expect(parseFragment('x'.repeat(2_000_001))).toBeUndefined();+ const fragment = copyFragment(seed(), ['group'])!;+ for (const change of [+ { type: 'script' },+ { transform: [1, 0, 0, 1, null, 0] },+ { appearance: { fill: 'red', stroke: 'black', opacity: 9 } },+ { placement: { parentId: 'a', sortKey: 'a0' } },+ ]) {+ const scene = {+ ...fragment.scene,+ items: {+ ...fragment.scene.items,+ a: { ...fragment.scene.items.a, ...change },+ },+ };+ expect(+ parseFragment(JSON.stringify({ ...fragment, scene }))+ ).toBeUndefined();+ }+});++it('round-trips A1/A2 edits through Loro and local undo preserves concurrent peer style', () => {+ const lab = createGraphicsPeerLab(seed());+ cleanups.push(lab.dispose);+ lab.setConnected(false);+ const a = lab.peers[0]!.editor,+ b = lab.peers[1]!.editor;+ a.select('group');+ a.execute(duplicateCommand, { createId: ids() });+ lab.syncNow();+ a.execute(nudgeCommand, { x: 10, y: 20 });+ a.reorderSelection('back');+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ expect(() => freezeDocument(a.document)).not.toThrow();+ a.undo();+ a.undo();+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ a.select('a');+ b.select('a');+ a.setSelectionAppearance({ strokeWidth: 9 });+ b.setSelectionAppearance({ opacity: 0.25 });+ lab.syncNow();+ a.undo();+ lab.syncNow();+ const item = a.document.items.a;+ expect(isShape(item) && item.appearance.opacity).toBe(0.25);+ expect(isShape(item) && item.appearance.strokeWidth).toBe(2);+ expect(a.document).toEqual(b.document);+});++it('picks painted thick outlines and rounded fills while respecting empty corners', () => {+ const editor = createGraphicsEditor(seed());+ editor.select('c');+ editor.setSelectionAppearance({+ fill: 'transparent',+ strokeWidth: 20,+ cornerRadius: 20,+ });+ expect(editor.hitTest({ x: 462, y: 210 }, true)).toBe('c');+ expect(editor.hitTest({ x: 510, y: 210 }, true)).toBeUndefined();+ expect(editor.hitTest({ x: 470, y: 150 }, true)).toBe('c'); // rounded border is within its 10px painted band+ editor.setSelectionAppearance({ fill: 'red', strokeWidth: 0 });+ expect(editor.hitTest({ x: 470, y: 150 }, true)).toBeUndefined();+ expect(editor.hitTest({ x: 490, y: 170 }, true)).toBe('c');+ editor.setSelectionAppearance({ opacity: 0 });+ expect(editor.hitTest({ x: 490, y: 170 }, true)).toBeUndefined();+});diff --git a/packages/graphics/tests/connector-labels.test.ts b/packages/graphics/tests/connector-labels.test.tsnew file mode 100644index 0000000000..1b63675311--- /dev/null+++ b/packages/graphics/tests/connector-labels.test.ts@@ -0,0 +1,362 @@+import { expect, it } from 'vitest';+import {+ connectorDefinition,+ copyFragment,+ createGraphicsEditor,+ createScene,+ IDENTITY,+ multiply,+ parseFragment,+ rotation,+ type ShapeItem,+ type ShapeLabel,+ setShapeLabelCommand,+ shapeLabelLayout,+ shapeProjection,+ textTargetAt,+ translation,+ worldBounds,+} from '../src/core';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const label: ShapeLabel = {+ content: 'Connection',+ fontSize: 20,+ fontFamily: 'sans',+ width: 100,+ height: 30,+};+const connector = (): ShapeItem<'connector'> => ({+ id: 'link',+ type: 'connector',+ transform: IDENTITY,+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ appearance: { fill: 'transparent', stroke: 'black' },+ geometry: {+ start: { point: { x: 0, y: 0 } },+ end: { point: { x: 200, y: 0 } },+ route: 'straight',+ startHead: 'none',+ endHead: 'arrow',+ },+});++it('owns, freezes, copies, clears and undoes connector labels', () => {+ const editor = createGraphicsEditor([connector()]);+ try {+ editor.execute(setShapeLabelCommand, { id: 'link', label });+ const item = editor.document.items.link;+ if (item?.type !== 'connector') throw Error();+ expect(Object.isFrozen(item.geometry.label)).toBe(true);+ expect(+ parseFragment(JSON.stringify(copyFragment(editor.document, ['link'])))+ ?.scene.items.link+ ).toMatchObject({ geometry: { label } });+ expect(editor.hitTest({ x: 100, y: 12 })).toBe('link');+ expect(textTargetAt(editor.document, { x: 100, y: 12 })).toBe('link');+ expect(+ connectorDefinition.intersectsBox?.(item, IDENTITY, {+ x: 99,+ y: 10,+ width: 2,+ height: 2,+ })+ ).toBe(true);+ expect(connectorDefinition.bounds(item).height).toBeGreaterThanOrEqual(30);+ editor.execute(setShapeLabelCommand, { id: 'link' });+ expect(editor.document.items.link).toEqual(connector());+ editor.undo();+ expect(editor.document.items.link).toEqual(item);+ } finally {+ editor.dispose();+ }+});++it.each([+ 'straight',+ 'stepped',+ 'smooth',+] as const)('centers labels on a %s route', (route) => {+ const item = connector();+ const layout = shapeLabelLayout({+ ...item,+ geometry: { ...item.geometry, route, label },+ })!;+ expect(layout.transform[4] + layout.geometry.width / 2).toBeCloseTo(100);+ expect(layout.transform[5] + layout.geometry.height / 2).toBeCloseTo(0);+});++it('uses the visible midpoint when a bound target moves', () => {+ const item = connector();+ const box: ShapeItem<'rectangle'> = {+ id: 'box',+ type: 'rectangle',+ transform: translation(300, -50),+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ appearance: { fill: 'transparent', stroke: 'black' },+ geometry: { width: 100, height: 100 },+ };+ const scene = createScene([+ {+ ...item,+ geometry: {+ ...item.geometry,+ label,+ end: {+ point: { x: 200, y: 0 },+ binding: { targetId: 'box', anchor: 'left' },+ },+ },+ },+ box,+ ]);+ const projected = shapeProjection(scene, 'link').item;+ if (projected?.type !== 'connector') throw Error();+ expect(shapeLabelLayout(projected)!.transform[4]).toBeCloseTo(100);+ const moved = shapeProjection(scene, 'link', {+ box: { ...box, transform: translation(500, -50) },+ }).item;+ if (moved?.type !== 'connector') throw Error();+ expect(shapeLabelLayout(moved)!.transform[4]).toBeCloseTo(200);+});++it('rejects invalid connector labels at the geometry boundary', () => {+ for (const invalid of [+ { ...label, width: NaN },+ { ...label, height: -1 },+ { ...label, content: 3 },+ ]) {+ expect(+ connectorDefinition.validateGeometry({+ ...connector().geometry,+ label: invalid,+ })+ ).toBe(false);+ }+});++it('resizes route geometry instead of treating a fixed-size label as scalable', () => {+ const item = connector();+ const labeled = {+ ...item,+ geometry: {+ ...item.geometry,+ end: { point: { x: 20, y: 0 } },+ endHead: 'none' as const,+ label,+ },+ };+ expect(connectorDefinition.bounds(labeled).width).toBe(100);+ const resized = connectorDefinition.resize(labeled, {+ x: 0,+ y: 0,+ width: 200,+ height: 30,+ });+ expect(resized.geometry.end.point.x).toBeCloseTo(120);+ expect(connectorDefinition.bounds(resized).x).toBeCloseTo(-80);+ expect(connectorDefinition.bounds(resized).width).toBeCloseTo(200);+});++it('keeps the opposite visible edge anchored while resizing a labeled connector', () => {+ const item = connector();+ const editor = createGraphicsEditor([+ {+ ...item,+ geometry: {+ ...item.geometry,+ end: { point: { x: 20, y: 0 } },+ endHead: 'none',+ label,+ },+ },+ ]);+ try {+ editor.select('link');+ const before = worldBounds(editor.document, 'link');+ editor.beginTransform(+ 'link',+ { x: before.x + before.width, y: before.y + before.height / 2 },+ 'e'+ );+ editor.updateTransform({+ x: before.x + before.width + 100,+ y: before.y + before.height / 2,+ });+ editor.commitTransform();+ const after = worldBounds(editor.document, 'link');+ expect(after.x).toBeCloseTo(before.x);+ expect(after.width).toBeCloseTo(before.width + 100);+ const resized = editor.document.items.link;+ if (resized?.type !== 'connector') throw Error();+ expect(resized.geometry.start.point.y).toBeCloseTo(+ resized.geometry.end.point.y+ );+ } finally {+ editor.dispose();+ }+});++it('creates the missing route axis when a labeled connector gains height', () => {+ const item = connector();+ const editor = createGraphicsEditor([+ {+ ...item,+ geometry: {+ ...item.geometry,+ end: { point: { x: 20, y: 0 } },+ endHead: 'none',+ label,+ },+ },+ ]);+ try {+ editor.select('link');+ const before = worldBounds(editor.document, 'link');+ editor.beginTransform(+ 'link',+ { x: before.x + before.width / 2, y: before.y + before.height },+ 's'+ );+ editor.updateTransform({+ x: before.x + before.width / 2,+ y: before.y + before.height + 20,+ });+ editor.commitTransform();+ const after = worldBounds(editor.document, 'link');+ expect(after.y).toBeCloseTo(before.y);+ expect(after.height).toBeCloseTo(before.height + 20);+ } finally {+ editor.dispose();+ }+});++it('clamps below-label shrinking at the fixed label size without moving the opposite edge', () => {+ const item = connector();+ const editor = createGraphicsEditor([+ {+ ...item,+ geometry: {+ ...item.geometry,+ end: { point: { x: 20, y: 0 } },+ endHead: 'none',+ label,+ },+ },+ ]);+ try {+ editor.select('link');+ const before = worldBounds(editor.document, 'link');+ editor.beginTransform(+ 'link',+ { x: before.x + before.width, y: before.y + before.height / 2 },+ 'e'+ );+ editor.updateTransform({+ x: before.x + before.width - 20,+ y: before.y + before.height / 2,+ });+ editor.commitTransform();+ expect(worldBounds(editor.document, 'link')).toEqual(before);+ } finally {+ editor.dispose();+ }+});++it('resizes circular endpoint heads by their visible bounds', () => {+ const item = connector();+ const editor = createGraphicsEditor([+ {+ ...item,+ geometry: {+ ...item.geometry,+ startHead: 'circle',+ endHead: 'circle',+ },+ },+ ]);+ try {+ editor.select('link');+ const before = worldBounds(editor.document, 'link');+ editor.beginTransform(+ 'link',+ { x: before.x + before.width, y: before.y + before.height / 2 },+ 'e'+ );+ editor.updateTransform({+ x: before.x + before.width + 100,+ y: before.y + before.height / 2,+ });+ editor.commitTransform();+ const after = worldBounds(editor.document, 'link');+ expect(after.x).toBeCloseTo(before.x);+ expect(after.width).toBeCloseTo(before.width + 100);+ } finally {+ editor.dispose();+ }+});++it('maps a group resize handle into a quarter-turned connector frame', () => {+ const item = connector();+ const editor = createGraphicsEditor(+ createScene([+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: IDENTITY,+ },+ {+ ...item,+ placement: { parentId: 'group', sortKey: 'a0' },+ transform: multiply(translation(100, 100), rotation(Math.PI / 2)),+ geometry: {+ ...item.geometry,+ end: { point: { x: 20, y: 0 } },+ endHead: 'none',+ label,+ },+ },+ ])+ );+ try {+ editor.select('group');+ const before = worldBounds(editor.document, 'group');+ editor.beginTransform(+ 'group',+ { x: before.x + before.width, y: before.y + before.height / 2 },+ 'e'+ );+ editor.updateTransform({+ x: before.x + before.width - 20,+ y: before.y + before.height / 2,+ });+ const after = worldBounds(+ editor.document,+ 'group',+ editor.getSession().transform!.nodes+ );+ expect(after.x).toBeCloseTo(before.x);+ expect(after.width).toBeCloseTo(before.width);+ } finally {+ editor.dispose();+ }+});++it('round trips connector labels through Loro and undo', () => {+ const lab = createGraphicsPeerLab(createScene([connector()]));+ try {+ lab.setConnected(false);+ const a = lab.peers[0]!.editor,+ b = lab.peers[1]!.editor;+ const before = b.document.items.link;+ a.execute(setShapeLabelCommand, { id: 'link', label });+ lab.syncNow();+ expect(b.document.items.link).toMatchObject({ geometry: { label } });+ a.undo();+ lab.syncNow();+ expect(b.document.items.link).toEqual(before);+ } finally {+ lab.dispose();+ }+});diff --git a/packages/graphics/tests/connectors.test.ts b/packages/graphics/tests/connectors.test.tsnew file mode 100644index 0000000000..8ef72c5bc2--- /dev/null+++ b/packages/graphics/tests/connectors.test.ts@@ -0,0 +1,798 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ alignCommand,+ type ConnectorAnchor,+ connectorDefinition,+ connectorDropTarget,+ connectorPorts,+ connectorStyleCommand,+ connectorTargetAt,+ copyFragment,+ createConnectorInteraction,+ createGraphicsEditor,+ createScene,+ deleteSubtrees,+ distributeCommand,+ duplicateNodes,+ freezeDocument,+ type GraphicsDocument,+ groupNodes,+ hitTest,+ IDENTITY,+ layoutBounds,+ multiply,+ paintOrder,+ pasteFragment,+ reorderNodes,+ resolveConnector,+ rotation,+ type ShapeItem,+ scaling,+ selectionFrame,+ setConnectorCommand,+ transformPoint,+ translation,+ worldBounds,+ worldMatrix,+} from '../src/core';+import { connectorWorldView } from '../src/core/connectors';+import {+ connectorHead,+ connectorPath,+} from '../src/core/shapes/connector-routing';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((fn) => fn()));+const rect = (id = 'a', x = 0): ShapeItem<'rectangle'> => ({+ id,+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: id === 'a' ? 'a0' : 'a1' },+ transform: translation(x, 0),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'transparent', stroke: 'black' },+});+const link = (+ start: ConnectorAnchor = 'right',+ end: ConnectorAnchor = 'left'+): ShapeItem<'connector'> => ({+ id: 'link',+ type: 'connector',+ placement: { parentId: 'scene-root', sortKey: 'a2' },+ transform: IDENTITY,+ appearance: { fill: 'transparent', stroke: 'black' },+ geometry: {+ start: {+ point: { x: 100, y: 40 },+ binding: { targetId: 'a', anchor: start },+ },+ end: { point: { x: 300, y: 40 }, binding: { targetId: 'b', anchor: end } },+ route: 'stepped',+ startHead: 'none',+ endHead: 'arrow',+ },+});+const scene = () => createScene([rect(), rect('b', 300), link()]);+const pencil = (): ShapeItem<'pencil'> => ({+ id: 'ink',+ type: 'pencil',+ placement: { parentId: 'scene-root', sortKey: 'a3' },+ transform: IDENTITY,+ geometry: {+ points: [+ [0, 0, 0.5],+ [50, 40, 0.5],+ [100, 80, 0.5],+ ],+ simulatePressure: false,+ },+ appearance: { fill: 'transparent', stroke: 'black', strokeWidth: 4 },+});+const resolved = (doc: GraphicsDocument) =>+ resolveConnector(doc, doc.items.link as ShapeItem<'connector'>).geometry;+const close = (+ actual: { x: number; y: number },+ expected: { x: number; y: number }+) => {+ expect(actual.x).toBeCloseTo(expected.x, 7);+ expect(actual.y).toBeCloseTo(expected.y, 7);+};++describe('connector anchors', () => {+ it('skips pencil ink and its bounds, including ink above an eligible shape', () => {+ const doc = createScene([pencil()]);+ expect(connectorPorts(doc)).toEqual([]);+ for (const point of [+ { x: 50, y: 40 },+ { x: 25, y: 50 },+ ]) {+ expect(connectorTargetAt(doc, point, 14)).toBeUndefined();+ expect(connectorDropTarget(doc, point, 14)).toBeUndefined();+ }+ expect(+ connectorTargetAt(createScene([rect(), pencil()]), { x: 50, y: 40 }, 14)+ ?.targetId+ ).toBe('a');+ });+ it('loads old pencil bindings using stored endpoints without following the ink', () => {+ const connector = link();+ const doc = createScene([+ pencil(),+ {+ ...connector,+ geometry: {+ ...connector.geometry,+ start: {+ point: { x: 50, y: 40 },+ binding: { targetId: 'ink', anchor: 'center' },+ },+ end: { point: { x: 300, y: 40 } },+ },+ },+ ]);+ expect(resolved(doc).start.point).toEqual({ x: 50, y: 40 });+ expect(+ resolveConnector(doc, doc.items.link as ShapeItem<'connector'>, {+ ink: { ...pencil(), transform: translation(200, 100) },+ }).geometry.start.point+ ).toEqual({ x: 50, y: 40 });+ });+ it('offers five ports per shape with screen-independent world positions and frontmost ties', () => {+ const doc = scene(),+ ports = connectorPorts(doc);+ expect(ports).toHaveLength(10);+ expect(ports.filter((p) => p.targetId === 'a').map((p) => p.point)).toEqual(+ [+ { x: 50, y: 40 },+ { x: 50, y: 0 },+ { x: 100, y: 40 },+ { x: 50, y: 80 },+ { x: 0, y: 40 },+ ]+ );+ expect(connectorDropTarget(doc, { x: 102, y: 40 }, 3)?.anchor).toBe(+ 'right'+ );+ expect(connectorDropTarget(doc, { x: 104, y: 40 }, 3)).toBeUndefined();+ expect(+ connectorDropTarget(createScene([rect(), rect('b')]), { x: 50, y: 40 }, 3)+ ?.targetId+ ).toBe('b');+ });+ it('resolves center drops against the rectangle and ellipse outline', () => {+ const b = { ...rect('b', 300), type: 'ellipse' as const };+ const doc = createScene([rect(), b, link('center', 'center')]);+ close(resolved(doc).start.point, { x: 100, y: 40 });+ close(resolved(doc).end.point, { x: 300, y: 40 });+ const moved = {+ ...doc,+ items: { ...doc.items, b: { ...b, transform: translation(300, 200) } },+ };+ const g = resolved(moved),+ p = g.end.point;+ expect(((p.x - 350) / 50) ** 2 + ((p.y - 240) / 40) ** 2).toBeCloseTo(1);+ expect(g.start.point.y).toBeGreaterThan(40);+ });+ it('uses the rounded outline at a corner', () => {+ const a = {+ ...rect(),+ geometry: { width: 100, height: 100 },+ appearance: { fill: 'transparent', stroke: 'black', cornerRadius: 20 },+ };+ const b = {+ ...rect('b', 300),+ transform: translation(300, 300),+ geometry: { width: 100, height: 100 },+ };+ const g = resolved(createScene([a, b, link('center', 'center')]));+ close(g.start.point, { x: 80 + Math.sqrt(200), y: 80 + Math.sqrt(200) });+ });+ it('follows nested rotations and geometry previews without touching stored endpoints', () => {+ const a = {+ ...rect(),+ placement: { parentId: 'group', sortKey: 'a0' },+ transform: rotation(0.3),+ };+ const doc = createScene([+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(translation(50, 75), rotation(0.8)),+ },+ a,+ rect('b', 300),+ link(),+ ]);+ const preview = { ...a, geometry: { width: 220, height: 100 } };+ const g = resolveConnector(doc, doc.items.link as ShapeItem<'connector'>, {+ a: preview,+ }).geometry;+ close(+ g.start.point,+ transformPoint(worldMatrix(doc, 'a'), { x: 220, y: 50 })+ );+ close(g.start.direction!, { x: Math.cos(1.1), y: Math.sin(1.1) });+ expect(+ (doc.items.link as ShapeItem<'connector'>).geometry.start.point+ ).toEqual({ x: 100, y: 40 });+ });+ it('uses inverse transpose normals under nonuniform ancestor transforms', () => {+ const a = {+ ...rect(),+ transform: multiply(scaling(2, 1), rotation(Math.PI / 4)),+ };+ const doc = createScene([a, rect('b', 300), link()]);+ const n = resolved(doc).start.direction!;+ const edge = { x: a.transform[2], y: a.transform[3] };+ expect(n.x * edge.x + n.y * edge.y).toBeCloseTo(0);+ });+ it('ignores missing targets and rejects connector-to-connector bindings', () => {+ const doc = scene(),+ item = doc.items.link as ShapeItem<'connector'>;+ const missing = { ...doc, items: { ...doc.items } };+ delete missing.items.a;+ expect(resolved(freezeDocument(missing)).start.point).toEqual(+ item.geometry.start.point+ );+ expect(() =>+ createScene([+ {+ ...item,+ geometry: {+ ...item.geometry,+ start: {+ ...item.geometry.start,+ binding: { targetId: 'link', anchor: 'center' },+ },+ },+ },+ ])+ ).toThrow('Invalid connector target');+ });+});++describe('legacy routes and picking', () => {+ it('preserves rounded elbow leads and smooth controls', () => {+ const a = { point: { x: 0, y: 0 }, direction: { x: 1, y: 0 } },+ b = { point: { x: 200, y: 100 }, direction: { x: -1, y: 0 } };+ const elbow = connectorPath(a, b, 'stepped');+ expect(elbow.segments[0]!.to).toEqual({ x: 90, y: 0 });+ expect(elbow.segments[1]!.controls).toEqual([+ { x: 95.5, y: 0 },+ { x: 100, y: 4.5 },+ ]);+ expect(elbow.segments.at(-1)!.to).toEqual(b.point);+ const curve = connectorPath(a, b, 'smooth'),+ strength = Math.hypot(200, 100) / 2;+ expect(curve.segments[0]!.controls).toEqual([+ { x: strength, y: 0 },+ { x: 200 - strength, y: 100 },+ ]);+ const straight = connectorPath(a, b, 'straight');+ expect(straight.path).toBe('M 0 0 L 200 100');+ expect(connectorHead(b.point, straight.to, 'circle').radius).toBe(6);+ expect(connectorHead(b.point, straight.to, 'circle-small').radius).toBe(3);+ expect(connectorHead(b.point, straight.to, 'arrow-filled').path).toMatch(+ / Z$/+ );+ });+ it.each([+ 'straight',+ 'stepped',+ 'smooth',+ ] as const)('picks the actual %s path, not its box', (route) => {+ const item = link();+ const g = {+ ...item.geometry,+ route,+ start: { point: { x: 0, y: 0 } },+ end: { point: { x: 200, y: 100 } },+ };+ const doc = createScene([{ ...item, geometry: g }]),+ path = connectorPath(g.start, g.end, route);+ const p = path.points[Math.floor(path.points.length / 2)]!;+ expect(hitTest(doc, p, false, 3)).toBe('link');+ expect(hitTest(doc, { x: 20, y: 85 }, false, 3)).toBeUndefined();+ expect(+ connectorDefinition.intersectsBox({ ...item, geometry: g }, IDENTITY, {+ x: p.x - 1,+ y: p.y - 1,+ width: 2,+ height: 2,+ })+ ).toBe(true);+ });+});++describe('document reference lifecycle', () => {+ it('follows target moves live, detaches deleted targets in place, and restores with undo', () => {+ const editor = createGraphicsEditor(scene());+ cleanups.push(editor.dispose);+ editor.select('a');+ editor.beginTransform('a', { x: 0, y: 0 });+ editor.updateTransform({ x: 20, y: 60 });+ const preview = resolveConnector(+ editor.document,+ editor.document.items.link as ShapeItem<'connector'>,+ editor.getSession().transform!.nodes+ );+ close(preview.geometry.start.point, { x: 120, y: 100 });+ editor.commitTransform();+ expect(resolved(editor.document)).toEqual(preview.geometry);+ const before = editor.document;+ editor.deleteSelection();+ expect(resolved(editor.document).start).toMatchObject({+ point: { x: 120, y: 100 },+ });+ expect(resolved(editor.document).start.binding).toBeUndefined();+ editor.undo();+ expect(editor.document).toEqual(before);+ });+ it('moving a connector body leaves bound ends fixed and moves free ends', () => {+ const item = link(),+ doc = createScene([+ rect(),+ {+ ...item,+ geometry: { ...item.geometry, end: { point: { x: 200, y: 100 } } },+ },+ ]);+ const editor = createGraphicsEditor(doc);+ cleanups.push(editor.dispose);+ editor.select('link');+ editor.beginTransform('link', { x: 150, y: 70 });+ editor.updateTransform({ x: 170, y: 90 });+ editor.commitTransform();+ const g = resolved(editor.document),+ world = worldMatrix(editor.document, 'link');+ close(transformPoint(world, g.start.point), { x: 100, y: 40 });+ close(transformPoint(world, g.end.point), { x: 220, y: 120 });+ });+ it('copies connected objects with remapped references and a connector alone with detached ends', () => {+ const doc = scene();+ let index = 0;+ const pasted = pasteFragment(+ doc,+ copyFragment(doc, ['a', 'b', 'link'])!,+ () => `copy-${index++}`+ );+ const clone = pasted.document.items['copy-2'] as ShapeItem<'connector'>;+ expect(clone.geometry.start.binding?.targetId).toBe('copy-0');+ expect(clone.geometry.end.binding?.targetId).toBe('copy-1');+ close(+ transformPoint(+ worldMatrix(pasted.document, clone.id),+ resolveConnector(pasted.document, clone).geometry.start.point+ ),+ { x: 124, y: 64 }+ );+ const alone = copyFragment(doc, ['link'])!.scene.items+ .link as ShapeItem<'connector'>;+ expect(alone.geometry.start.binding).toBeUndefined();+ expect(alone.geometry.end.binding).toBeUndefined();+ });+ it('duplicates connections across different parents without referencing originals', () => {+ const doc = createScene([+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(10, 20),+ },+ { ...rect(), placement: { parentId: 'group', sortKey: 'a0' } },+ rect('b', 300),+ link(),+ ]);+ let index = 0;+ const result = duplicateNodes(+ doc,+ ['a', 'b', 'link'],+ () => `copy-${index++}`+ );+ const clone = result.document.items['copy-2'] as ShapeItem<'connector'>;+ expect(clone.geometry.start.binding?.targetId).toBe('copy-0');+ expect(clone.geometry.end.binding?.targetId).toBe('copy-1');+ close(+ transformPoint(+ worldMatrix(result.document, clone.id),+ resolveConnector(result.document, clone).geometry.start.point+ ),+ { x: 134, y: 84 }+ );+ expect(+ deleteSubtrees(result.document, ['group']).items[clone.id]+ ).toBeDefined();+ });+ it('syncs connector bindings, target moves, and local undo through Loro without a backend', () => {+ const lab = createGraphicsPeerLab(scene());+ cleanups.push(lab.dispose);+ lab.setConnected(false);+ const a = lab.peers[0]!.editor,+ b = lab.peers[1]!.editor;+ a.select('link');+ a.execute(connectorStyleCommand, { route: 'smooth', endHead: 'circle' });+ lab.syncNow();+ expect(b.document).toEqual(a.document);+ a.select('a');+ a.beginTransform('a', { x: 0, y: 0 });+ a.updateTransform({ x: 25, y: 60 });+ a.commitTransform();+ lab.syncNow();+ close(resolved(b.document).start.point, { x: 125, y: 100 });+ a.undo();+ lab.syncNow();+ close(resolved(b.document).start.point, { x: 100, y: 40 });+ });+});++describe('endpoint interaction', () => {+ it('never binds either end to pencil strokes when creating or reconnecting', () => {+ const editor = createGraphicsEditor([pencil()]);+ cleanups.push(editor.dispose);+ const op = createConnectorInteraction({+ getDocument: () => editor.document,+ commit: (item) => editor.execute(setConnectorCommand, item),+ onChange: () => {},+ });+ op.hover({ x: 50, y: 40 }, 14);+ expect(op.getTarget()).toBeUndefined();+ op.begin(+ 'link',+ { x: 25, y: 20 },+ rect().appearance,+ { route: 'straight', startHead: 'none', endHead: 'arrow' },+ 14+ );+ op.update({ x: 75, y: 60 }, 14);+ expect(op.getState()?.dropTarget).toBeUndefined();+ expect(op.commit()).toBe(true);+ const geometry = resolved(editor.document);+ expect(geometry.start).toEqual({ point: { x: 25, y: 20 } });+ expect(geometry.end).toEqual({ point: { x: 75, y: 60 } });+ for (const endpoint of ['start', 'end'] as const) {+ op.edit('link', endpoint);+ op.update({ x: 50, y: 40 }, 14);+ expect(op.getTarget()).toBeUndefined();+ op.commit();+ expect(resolved(editor.document)[endpoint]).toEqual({+ point: { x: 50, y: 40 },+ });+ }+ });+ it('keeps previews outside history, supports both handles, cancels, and commits once', () => {+ const editor = createGraphicsEditor([rect(), rect('b', 300)]);+ cleanups.push(editor.dispose);+ const onChange = vi.fn(),+ op = createConnectorInteraction({+ getDocument: () => editor.document,+ commit: (item) => editor.execute(setConnectorCommand, item),+ onChange,+ });+ const before = editor.document;+ op.begin(+ 'link',+ { x: 100, y: 40 },+ { fill: 'transparent', stroke: 'black' },+ { route: 'stepped', startHead: 'none', endHead: 'arrow' },+ 14+ );+ op.update({ x: 299, y: 40 }, 14);+ expect(op.getState()?.dropTarget?.anchor).toBe('left');+ expect(editor.document).toBe(before);+ expect(editor.getSession().canUndo).toBe(false);+ expect(op.commit()).toBe(true);+ expect(resolved(editor.document).end.binding?.targetId).toBe('b');+ editor.undo();+ expect(editor.document).toEqual(before);+ editor.redo();+ const committed = editor.document;+ op.edit('link', 'start');+ op.update({ x: 50, y: 80 }, 14);+ op.cancel();+ expect(editor.document).toBe(committed);+ op.edit('link', 'start');+ op.update({ x: 50, y: 80 }, 14);+ op.commit();+ expect(resolved(editor.document).start.binding?.anchor).toBe('bottom');+ editor.undo();+ expect(editor.document).toEqual(committed);+ op.edit('link', 'end');+ op.update({ x: 500, y: 60 }, 14, true);+ op.commit();+ expect(resolved(editor.document).end.binding).toBeUndefined();+ expect(resolved(editor.document).end.point.y).toBeCloseTo(40);+ expect(onChange).toHaveBeenCalled();+ });+ it('does not create a connector for an accidental click', () => {+ const commit = vi.fn(),+ op = createConnectorInteraction({+ getDocument: () => createScene([]),+ commit,+ onChange: () => {},+ });+ op.begin(+ 'link',+ { x: 0, y: 0 },+ { fill: 'transparent', stroke: 'black' },+ { route: 'straight', startHead: 'none', endHead: 'none' },+ 14+ );+ expect(op.commit(3)).toBe(false);+ expect(commit).not.toHaveBeenCalled();+ });+});++it('pastes dangling references as free endpoints even if the destination has matching IDs', () => {+ const source = createScene([link()]);+ const result = pasteFragment(+ scene(),+ { kind: 'macro-graphics-fragment', scene: source },+ () => 'pasted'+ );+ const item = result.document.items.pasted as ShapeItem<'connector'>;+ expect(item.geometry.start.binding).toBeUndefined();+ expect(item.geometry.end.binding).toBeUndefined();+ close(+ transformPoint(+ worldMatrix(result.document, 'pasted'),+ item.geometry.start.point+ ),+ { x: 124, y: 64 }+ );+});++it('keeps target references through grouping and reparenting into a rotated ancestor', () => {+ const doc = scene();+ const editor = createGraphicsEditor({+ ...doc,+ items: {+ ...doc.items,+ parent: {+ id: 'parent',+ type: 'group',+ placement: { parentId: doc.rootId, sortKey: 'a3' },+ transform: multiply(translation(500, 60), rotation(0.8)),+ },+ },+ });+ cleanups.push(editor.dispose);+ const before = resolved(editor.document);+ editor.reparent('a', 'parent');+ close(resolved(editor.document).start.point, before.start.point);+ editor.select('parent');+ editor.beginTransform('parent', { x: 0, y: 0 });+ editor.updateTransform({ x: 50, y: 75 });+ editor.commitTransform();+ close(resolved(editor.document).start.point, { x: 150, y: 115 });+ editor.undo();+ editor.undo();+ close(resolved(editor.document).start.point, before.start.point);+ editor.select('a');+ editor.toggleSelection('b');+ editor.groupSelection('grouped');+ expect(resolved(editor.document)).toEqual(before);+ editor.ungroupSelection();+ expect(resolved(editor.document)).toEqual(before);+});++it('converges after concurrent target deletion and endpoint editing without invalid references', () => {+ const lab = createGraphicsPeerLab(scene());+ cleanups.push(lab.dispose);+ lab.setConnected(false);+ const a = lab.peers[0]!.editor,+ b = lab.peers[1]!.editor;+ a.select('a');+ a.deleteSelection();+ const item = b.document.items.link as ShapeItem<'connector'>;+ b.execute(setConnectorCommand, {+ ...item,+ geometry: {+ ...item.geometry,+ start: {+ ...item.geometry.start,+ binding: { targetId: 'a', anchor: 'bottom' },+ },+ },+ });+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ expect(a.document.items.a).toBeUndefined();+ expect(() => freezeDocument(a.document)).not.toThrow();+ const point = resolved(a.document).start.point;+ expect(Number.isFinite(point.x) && Number.isFinite(point.y)).toBe(true);+});++it('reveals only the hovered shape and activates its core or the nearest edge port', () => {+ const doc = scene();+ expect(connectorTargetAt(doc, { x: 180, y: 150 }, 14)).toBeUndefined();+ const core = connectorTargetAt(doc, { x: 23, y: 25 }, 14)!;+ expect(core.targetId).toBe('a');+ expect(core.ports).toHaveLength(5);+ expect(core.active?.anchor).toBe('center');+ expect(connectorTargetAt(doc, { x: 98, y: 38 }, 14)?.active?.anchor).toBe(+ 'right'+ );+ // Hovering the boundary away from a handle exposes the ports without a halo.+ const rim = connectorTargetAt(doc, { x: 96, y: 20 }, 14)!;+ expect(rim.targetId).toBe('a');+ expect(rim.active).toBeUndefined();+ expect(connectorTargetAt(doc, { x: 323, y: 25 }, 14)?.targetId).toBe('b');+ // The radius is in world units supplied by the camera: 14 px at 2x = 7.+ expect(connectorTargetAt(doc, { x: 108, y: 40 }, 7)).toBeUndefined();+ expect(connectorTargetAt(doc, { x: 108, y: 40 }, 14)?.active?.anchor).toBe(+ 'right'+ );+});++it('honors curved outlines, transformed interiors and frontmost targets for connector hover', () => {+ const ellipse = { ...rect(), type: 'ellipse' as const };+ expect(+ connectorTargetAt(createScene([ellipse]), { x: 1, y: 1 }, 14)+ ).toBeUndefined();+ const rounded = {+ ...rect(),+ appearance: { ...rect().appearance, cornerRadius: 30 },+ };+ expect(+ connectorTargetAt(createScene([rounded]), { x: 1, y: 1 }, 14)+ ).toBeUndefined();+ const rotated = {+ ...ellipse,+ transform: multiply(translation(300, 100), rotation(0.7)),+ };+ const point = transformPoint(rotated.transform, { x: 35, y: 35 });+ expect(+ connectorTargetAt(createScene([rotated]), point, 14)?.active?.anchor+ ).toBe('center');+ const overlapping = createScene([rect(), rect('b', 5)]);+ expect(connectorTargetAt(overlapping, { x: 25, y: 25 }, 14)?.targetId).toBe(+ 'b'+ );+});++it('uses the same core target before pointerdown, at the starting endpoint, and when reconnecting either end', () => {+ const commit = vi.fn();+ const op = createConnectorInteraction({+ getDocument: scene,+ commit,+ onChange: () => {},+ });+ op.hover({ x: 23, y: 25 }, 14);+ const target = op.getTarget();+ op.begin(+ 'new',+ { x: 23, y: 25 },+ rect().appearance,+ { route: 'stepped', startHead: 'none', endHead: 'arrow' },+ 14+ );+ expect(op.getTarget()).toEqual(target);+ expect(op.getState()?.dropTarget).toEqual(target?.active);+ expect(op.getState()?.item.geometry.start.binding).toEqual({+ targetId: 'a',+ anchor: 'center',+ });+ expect(op.commit(3)).toBe(false);+ expect(commit).not.toHaveBeenCalled();+ for (const endpoint of ['start', 'end'] as const) {+ op.edit('link', endpoint);+ op.update({ x: 23, y: 25 }, 14);+ expect(op.getTarget()?.active?.anchor).toBe('center');+ expect(op.getState()?.item.geometry[endpoint].binding).toEqual({+ targetId: 'a',+ anchor: 'center',+ });+ op.cancel();+ }+});++it('paints a bound connector above both endpoints after stacking or grouping changes', () => {+ let doc = scene();+ doc = reorderNodes(doc, ['link'], 'back');+ expect(paintOrder(doc).indexOf('link')).toBeGreaterThan(+ paintOrder(doc).indexOf('a')+ );+ expect(paintOrder(doc).indexOf('link')).toBeGreaterThan(+ paintOrder(doc).indexOf('b')+ );+ doc = groupNodes(doc, ['a', 'link'], 'group');+ doc = reorderNodes(doc, ['b'], 'front');+ expect(paintOrder(doc).indexOf('link')).toBeGreaterThan(+ paintOrder(doc).indexOf('b')+ );+});+it('excludes bound connectors from alignment and distribution, retaining their bindings', () => {+ const editor = createGraphicsEditor(scene());+ editor.select('a');+ editor.toggleSelection('b');+ editor.toggleSelection('link');+ const connector = editor.document.items.link;+ editor.execute(alignCommand, 'left');+ expect(worldMatrix(editor.document, 'a')[4]).toBe(0);+ expect(worldMatrix(editor.document, 'b')[4]).toBe(0);+ expect(editor.document.items.link).toEqual(connector);+ editor.undo();+ const before = editor.document;+ editor.execute(distributeCommand, 'horizontal');+ expect(editor.document).toBe(before); // two eligible objects, not three+ editor.dispose();+});+it('ignores a fully bound connector extending outside a selected group in layout bounds', () => {+ const grouped = groupNodes(scene(), ['a', 'link'], 'group');+ expect(layoutBounds(grouped, 'group')).toEqual({+ x: 0,+ y: 0,+ width: 100,+ height: 80,+ });+});+it('keeps partially attached connectors in layout calculations', () => {+ const doc = scene();+ const connector = link();+ const partial = freezeDocument({+ ...doc,+ items: {+ ...doc.items,+ link: {+ ...connector,+ geometry: { ...connector.geometry, end: { point: { x: 600, y: 40 } } },+ },+ },+ });+ const grouped = groupNodes(partial, ['a', 'link'], 'group');+ expect(layoutBounds(grouped, 'group').width).toBeGreaterThan(100);+});++it('renders connected strokes and heads in world units after connector or group scaling', () => {+ const base = scene();+ const grouped = groupNodes(base, ['a', 'b', 'link'], 'group');+ for (const parentId of ['link', 'group']) {+ const item = grouped.items[parentId]!;+ if (item.type === 'surface') throw new Error('expected transformable item');+ const document = {+ ...grouped,+ items: {+ ...grouped.items,+ [parentId]: { ...item, transform: scaling(4, 2) },+ },+ };+ const resolved = resolveConnector(+ document,+ document.items.link as ShapeItem<'connector'>+ );+ const world = worldMatrix(document, 'link');+ const view = connectorWorldView(resolved, world);+ expect(view.transform).toEqual(IDENTITY);+ expect(worldBounds(document, 'link')).toEqual(+ connectorDefinition.bounds(view)+ );+ expect(selectionFrame(document, ['link'])!.bounds).toEqual(+ connectorDefinition.bounds(view)+ );+ expect(view.appearance).toEqual(resolved.appearance);+ close(+ view.geometry.start.point,+ transformPoint(world, resolved.geometry.start.point)+ );+ close(+ view.geometry.end.point,+ transformPoint(world, resolved.geometry.end.point)+ );+ expect(+ Math.hypot(+ view.geometry.start.direction!.x,+ view.geometry.start.direction!.y+ )+ ).toBeCloseTo(1);+ }+});++it('bounds smooth curves at their extrema rather than their control points', () => {+ const route = connectorPath(+ { point: { x: 0, y: 0 }, direction: { x: 1, y: 0 } },+ { point: { x: 0, y: 200 }, direction: { x: 1, y: 0 } },+ 'smooth'+ );+ expect(route.bounds).toEqual({ x: 0, y: 0, width: 75, height: 200 });+});diff --git a/packages/graphics/tests/core.test.ts b/packages/graphics/tests/core.test.tsnew file mode 100644index 0000000000..a5acbd55ec--- /dev/null+++ b/packages/graphics/tests/core.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest';+import {+ createGraphicsEditor,+ MAX_SCALE,+ MIN_SCALE,+ screenToWorld,+ worldToScreen,+ zoomAt,+} from '../src/core';++describe('camera', () => {+ it('round trips world coordinates through a translated, zoomed viewport', () => {+ const camera = { x: -423, y: 92, scale: 0.25 };+ const point = { x: -1500, y: 808 };+ expect(screenToWorld(camera, worldToScreen(camera, point))).toEqual(point);+ });+ it.each([+ 0.0001, 0.3, 2, 100,+ ])('preserves the world point at the zoom anchor (%s)', (scale) => {+ const camera = { x: 32, y: -18, scale: 1.5 };+ const anchor = { x: 241, y: 173 };+ const next = zoomAt(camera, anchor, scale);+ const before = screenToWorld(camera, anchor);+ const after = screenToWorld(next, anchor);+ expect(after.x).toBeCloseTo(before.x);+ expect(after.y).toBeCloseTo(before.y);+ expect(next.scale).toBeGreaterThanOrEqual(MIN_SCALE);+ expect(next.scale).toBeLessThanOrEqual(MAX_SCALE);+ });+ it('isolates instances, rejects nonfinite input and stops notifications after disposal', () => {+ const first = createGraphicsEditor();+ const second = createGraphicsEditor();+ const listener = vi.fn();+ first.subscribeCamera(listener);+ first.panBy({ x: 30, y: -10 });+ expect(second.getCamera()).toEqual({ x: 0, y: 0, scale: 1 });+ first.panBy({ x: Infinity, y: 0 });+ first.zoomAt({ x: 0, y: 0 }, NaN);+ expect(listener).toHaveBeenCalledTimes(1);+ first.dispose();+ first.resetCamera();+ expect(listener).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/graphics/tests/dot-grid.test.ts b/packages/graphics/tests/dot-grid.test.tsnew file mode 100644index 0000000000..8a14f6af7a--- /dev/null+++ b/packages/graphics/tests/dot-grid.test.ts@@ -0,0 +1,43 @@+import { expect, it } from 'vitest';+import { dotGridLevels } from '../src/core/dot-grid';++it.each([+ 0.01, 0.125, 0.25, 0.5, 1, 2, 4, 7.3848947, 8,+])('keeps coarse dots steady and fine dots faint at scale %s', (scale) => {+ const levels = dotGridLevels(scale);+ expect(levels).toHaveLength(3);+ expect(levels[2]!.opacity).toBe(1);+ for (const level of levels) {+ expect(level.unit).toBeGreaterThanOrEqual(1);+ expect(Math.log(level.unit) / Math.log(4)).toBeCloseTo(+ Math.round(Math.log(level.unit) / Math.log(4))+ );+ expect(level.spacing).toBe(level.unit * scale);+ expect(level.opacity).toBeGreaterThanOrEqual(0);+ expect(level.opacity).toBeLessThanOrEqual(1);+ if (level.spacing <= 4) expect(level.opacity).toBe(0);+ if (level.spacing <= 8) expect(level.opacity).toBeLessThanOrEqual(0.125);+ }+});++it('reveals individual canvas pixels subtly at maximum zoom', () => {+ expect(dotGridLevels(8)[0]).toEqual({ unit: 1, spacing: 8, opacity: 0.125 });+});++it('keeps the opacity at grid intersections continuous when levels change', () => {+ const opacityAt = (scale: number, point: number) =>+ 1 -+ dotGridLevels(scale).reduce(+ (remaining, level) =>+ remaining * (point % level.unit === 0 ? 1 - level.opacity : 1),+ 1+ );+ for (const scale of [4, 1, 0.25, 0.0625, 0.015625]) {+ for (const point of [0, 1, 4, 16, 64, 256, 1024, 4096]) {+ expect(opacityAt(scale * (1 - 1e-7), point)).toBeCloseTo(+ opacityAt(scale * (1 + 1e-7), point),+ 5+ );+ }+ }+});diff --git a/packages/graphics/tests/editing.test.ts b/packages/graphics/tests/editing.test.tsnew file mode 100644index 0000000000..84482024c9--- /dev/null+++ b/packages/graphics/tests/editing.test.ts@@ -0,0 +1,166 @@+import { expect, it, vi } from 'vitest';+import { createGraphicsEditor } from '../src/core';+import { translation } from '../src/core/affine';+import { drawableIds, worldBounds } from '../src/core/scene';++function makeEditor() {+ return createGraphicsEditor([+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(10, 20),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'transparent', stroke: 'black' },+ },+ ]);+}++it('commits one history entry per gesture and keeps camera and selection out of history', () => {+ const editor = makeEditor();+ let changes = 0;+ editor.subscribeDocument(() => changes++);+ editor.beginTransform('a', { x: 30, y: 40 });+ editor.updateTransform({ x: 50, y: 60 });+ editor.updateTransform({ x: 80, y: 90 });+ expect(worldBounds(editor.document, 'a').x).toBe(10);+ expect(changes).toBe(0);+ editor.commitTransform();+ expect(changes).toBe(1);+ expect(worldBounds(editor.document, 'a')).toEqual({+ x: 60,+ y: 70,+ width: 100,+ height: 80,+ });+ editor.panBy({ x: 40, y: 30 });+ editor.select();+ editor.undo();+ expect(worldBounds(editor.document, 'a').x).toBe(10);+ expect(editor.getCamera().x).toBe(40);+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ expect(worldBounds(editor.document, 'a').x).toBe(60);+});++it('supports every resize corner, crossing the anchor, cancellation and no-op gestures', () => {+ for (const corner of ['nw', 'ne', 'sw', 'se'] as const) {+ const editor = makeEditor();+ const origin = {+ x: corner.endsWith('w') ? 10 : 110,+ y: corner.startsWith('n') ? 20 : 100,+ };+ editor.beginTransform('a', origin, corner);+ editor.updateTransform({ x: -30, y: -40 });+ editor.commitTransform();+ expect(worldBounds(editor.document, 'a').width).toBeGreaterThan(0);+ expect(worldBounds(editor.document, 'a').height).toBeGreaterThan(0);+ editor.undo();+ expect(worldBounds(editor.document, 'a')).toEqual({+ x: 10,+ y: 20,+ width: 100,+ height: 80,+ });+ }+ const editor = makeEditor();+ editor.beginTransform('a', { x: 30, y: 40 });+ editor.updateTransform({ x: 90, y: 90 });+ editor.cancelTransform();+ expect(editor.getSession().canUndo).toBe(false);+ editor.beginTransform('a', { x: 30, y: 40 });+ expect(editor.commitTransform()).toBe(false);+ expect(editor.getSession().canUndo).toBe(false);+});++it('undoes creation and deletion and drops redo after a new edit', () => {+ const editor = makeEditor();+ editor.select('a');+ editor.deleteSelection();+ expect(drawableIds(editor.document)).toEqual([]);+ expect(editor.getSession().selectedId).toBeUndefined();+ editor.undo();+ expect(drawableIds(editor.document)).toEqual(['a']);+ editor.beginRectangle({ x: -50, y: -50 });+ editor.updateRectangle({ x: -10, y: -10 });+ editor.commitRectangle('b', { fill: 'white', stroke: 'black' });+ expect(editor.getSession().canRedo).toBe(false);+ editor.undo();+ expect(drawableIds(editor.document)).toEqual(['a']);+ editor.redo();+ expect(drawableIds(editor.document)).toEqual(['a', 'b']);+ editor.select('b');+ editor.undo();+ expect(editor.getSession().selectedId).toBeUndefined();+});++it('bounds image edits and resets history when the image changes', () => {+ const editor = createGraphicsEditor();+ editor.setImageSurface({ id: 'image', width: 200, height: 100 });+ editor.beginRectangle({ x: 10, y: 10 });+ editor.updateRectangle({ x: 60, y: 60 });+ editor.commitRectangle('a', { fill: 'white', stroke: 'black' });+ editor.beginTransform('a', { x: 20, y: 20 });+ editor.updateTransform({ x: 1000, y: 1000 });+ editor.commitTransform();+ expect(worldBounds(editor.document, 'a')).toEqual({+ x: 150,+ y: 50,+ width: 50,+ height: 50,+ });+ editor.setImageSurface({ id: 'next', width: 50, height: 50 });+ expect(editor.getSession()).toMatchObject({+ canUndo: false,+ canRedo: false,+ selectedId: undefined,+ });+});++it('does not resize or create history when a handle is clicked off-center', () => {+ const editor = makeEditor();+ editor.beginTransform('a', { x: 112, y: 103 }, 'se');+ editor.updateTransform({ x: 112, y: 103 });+ expect(editor.commitTransform()).toBe(false);+ expect(editor.getSession().canUndo).toBe(false);+});++it('resets disposable data, clearing previews, selection and both history stacks', () => {+ const editor = makeEditor();+ const seed = editor.document;+ editor.beginTransform('a', { x: 10, y: 20 });+ editor.updateTransform({ x: 40, y: 50 });+ editor.commitTransform();+ editor.select('a');+ editor.deleteSelection();+ editor.undo();+ expect(editor.getSession()).toMatchObject({ canUndo: true, canRedo: true });+ editor.beginTransform('a', { x: 40, y: 50 });+ editor.updateTransform({ x: 80, y: 90 });+ editor.resetDocument(seed);+ expect(editor.document).toEqual(seed);+ expect(editor.getSession()).toMatchObject({+ selectedIds: [],+ transform: undefined,+ box: undefined,+ canUndo: false,+ canRedo: false,+ });+ editor.undo();+ editor.redo();+ expect(editor.document).toEqual(seed);+ editor.beginRectangle({ x: 0, y: 0 });+ editor.updateRectangle({ x: 30, y: 30 });+ editor.resetDocument(seed);+ expect(editor.getPreview()).toBeUndefined();+ expect(+ editor.commitRectangle('discarded', { fill: 'red', stroke: 'black' })+ ).toBe(false);+ const changed = vi.fn();+ editor.subscribeDocument(changed);+ expect(() =>+ editor.resetDocument({ rootId: 'missing', items: {} })+ ).toThrow();+ expect(changed).not.toHaveBeenCalled();+ expect(editor.document).toEqual(seed);+});diff --git a/packages/graphics/tests/ellipse.test.ts b/packages/graphics/tests/ellipse.test.tsnew file mode 100644index 0000000000..9f0a0bfca5--- /dev/null+++ b/packages/graphics/tests/ellipse.test.ts@@ -0,0 +1,318 @@+import { expect, it } from 'vitest';+import {+ around,+ boxHits,+ corners,+ createGraphicsEditor,+ createScene,+ type EllipseItem,+ enclosing,+ IDENTITY,+ layoutBounds,+ type Matrix,+ multiply,+ nodeCorners,+ nudgeCommand,+ type Point,+ rotation,+ scaling,+ selectionFrame,+ transformPoint,+ translation,+ worldBounds,+ worldMatrix,+} from '../src/core';++const ellipse = (+ fill = 'transparent',+ transform: Matrix = IDENTITY+): EllipseItem => ({+ id: 'ellipse',+ type: 'ellipse',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform,+ geometry: { width: 200, height: 100 },+ appearance: { fill, stroke: 'black', strokeWidth: 0.1 },+});++it('keeps rotated circles tight in group bounds and preserves the local resize frame', () => {+ const shape = {+ ...ellipse('red', around({ x: 32, y: 32 }, rotation(Math.PI / 6))),+ geometry: { width: 64, height: 64 },+ placement: { parentId: 'group', sortKey: 'a0' },+ };+ const doc = createScene([+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(200, 100),+ },+ shape,+ {+ ...shape,+ id: 'second',+ placement: { parentId: 'group', sortKey: 'a1' },+ transform: translation(96, 0),+ },+ ]);+ const expected = { x: 200, y: 100, width: 160, height: 64 };+ for (const bounds of [+ worldBounds(doc, 'group'),+ layoutBounds(doc, 'group'),+ selectionFrame(doc, ['group'])!.bounds,+ selectionFrame(doc, ['ellipse', 'second'])!.bounds,+ ]) {+ for (const key of ['x', 'y', 'width', 'height'] as const)+ expect(bounds[key]).toBeCloseTo(expected[key]);+ }+ const single = selectionFrame(doc, ['ellipse'])!;+ expect(single.bounds).toEqual({ x: 0, y: 0, width: 64, height: 64 });+ expect(single.corners).toEqual(nodeCorners(doc, 'ellipse'));+});++it('encloses affine ellipse extrema through nested transforms and preview overrides', () => {+ const shape = {+ ...ellipse('red', multiply(rotation(0.6), scaling(-1, 2))),+ placement: { parentId: 'group', sortKey: 'a0' },+ };+ const doc = createScene([+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: [2, 0.3, 0.8, 0.5, 400, 200],+ },+ shape,+ ]);+ const editor = createGraphicsEditor(doc);+ const frame = selectionFrame(doc, ['group'])!;+ editor.beginTransform('group', frame.corners[2]!, 'se');+ editor.updateTransform({+ x: frame.bounds.x + frame.bounds.width * 1.5,+ y: frame.bounds.y + frame.bounds.height * 1.5,+ });+ const overrides = editor.getSession().transform!.nodes;+ for (const nodes of [{}, overrides]) {+ const projected = nodes.ellipse ?? shape;+ if (projected.type !== 'ellipse') throw new Error('Expected ellipse');+ const { width, height } = projected.geometry;+ const matrix = worldMatrix(doc, 'ellipse', nodes);+ const sampled = enclosing(+ Array.from({ length: 8192 }, (_, i) => {+ const t = (i * Math.PI * 2) / 8192;+ return transformPoint(matrix, {+ x: (width / 2) * (1 + Math.cos(t)),+ y: (height / 2) * (1 + Math.sin(t)),+ });+ })+ );+ const bounds = worldBounds(doc, 'group', nodes);+ for (const key of ['x', 'y', 'width', 'height'] as const)+ expect(bounds[key]).toBeCloseTo(sampled[key], 3);+ expect(selectionFrame(doc, ['group'], nodes)!.corners).toEqual(+ corners(bounds)+ );+ }+ const resized = worldBounds(doc, 'group', overrides);+ expect(resized.x).toBeCloseTo(frame.bounds.x);+ expect(resized.y).toBeCloseTo(frame.bounds.y);+ expect(resized.width).toBeCloseTo(frame.bounds.width * 1.5);+ expect(resized.height).toBeCloseTo(frame.bounds.height * 1.5);+ editor.commitTransform();+ editor.undo();+ expect(editor.document).toEqual(doc);+ editor.dispose();+});++it('snaps ellipse moves and keyboard nudges to the same visible bounds', () => {+ const shape = {+ ...ellipse('red', multiply(translation(3, 5), rotation(0.6))),+ };+ const editor = createGraphicsEditor([shape], { snapUnit: 8 });+ const before = editor.document;+ editor.select(shape.id);+ editor.beginTransform(shape.id, { x: 100, y: 100 });+ editor.updateTransform({ x: 108, y: 108 });+ const preview = worldBounds(+ before,+ shape.id,+ editor.getSession().transform!.nodes+ );+ expect(preview.x / 8).toBeCloseTo(Math.round(preview.x / 8));+ expect(preview.y / 8).toBeCloseTo(Math.round(preview.y / 8));+ editor.cancelTransform();+ editor.execute(nudgeCommand, { x: 8, y: 8 });+ expect(worldBounds(editor.document, shape.id)).toEqual(preview);+ editor.dispose();+});++it('picks the ellipse curve, lets its empty center through, and rejects bounding-box corners', () => {+ const editor = createGraphicsEditor([+ {+ id: 'back',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(0, 0),+ geometry: { width: 200, height: 100 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ ellipse(),+ ]);+ expect(editor.hitTest({ x: 100, y: 50 })).toBe('back');+ expect(editor.hitTest({ x: 199, y: 50 })).toBe('ellipse');+ expect(editor.hitTest({ x: 10, y: 10 })).toBe('back');+ const filled = createGraphicsEditor([ellipse('red')]);+ expect(filled.hitTest({ x: 100, y: 50 })).toBe('ellipse');+ expect(filled.hitTest({ x: 10, y: 10 })).toBeUndefined();+});++it.each([+ 0.25, 1, 4,+])('measures ellipse outline distance after rotation, shear and zoom %s', (zoom) => {+ const parent = multiply(+ translation(80, 60),+ multiply(rotation(0.4), scaling(2, 0.5))+ );+ const node = {+ ...ellipse('transparent', rotation(-0.7)),+ placement: { parentId: 'group', sortKey: 'a0' },+ };+ const editor = createGraphicsEditor([+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: parent,+ },+ node,+ ]);+ editor.zoomAt({ x: 0, y: 0 }, zoom);+ const world = worldMatrix(editor.document, node.id);+ for (const angle of [0, 0.7, 1.6, 3.4, 5.2]) {+ const p = transformPoint(world, {+ x: 100 + 100 * Math.cos(angle),+ y: 50 + 50 * Math.sin(angle),+ });+ const tangent: Point = {+ x: world[0] * -100 * Math.sin(angle) + world[2] * 50 * Math.cos(angle),+ y: world[1] * -100 * Math.sin(angle) + world[3] * 50 * Math.cos(angle),+ };+ const length = Math.hypot(tangent.x, tangent.y);+ const offset = (px: number) => ({+ x: p.x + ((tangent.y / length) * px) / zoom,+ y: p.y - ((tangent.x / length) * px) / zoom,+ });+ expect(editor.hitTest(offset(2.99), true)).toBe(node.id);+ expect(editor.hitTest(offset(3.01), true)).toBeUndefined();+ }+});++it('marquee uses the ellipse, not the unused corners of its bounds', () => {+ const doc = createScene([ellipse()]);+ expect(boxHits(doc, { x: 0, y: 0, width: 10, height: 10 })).toEqual([]);+ expect(boxHits(doc, { x: 90, y: 40, width: 10, height: 10 })).toEqual([+ 'ellipse',+ ]);+ expect(boxHits(doc, { x: -20, y: -20, width: 240, height: 140 })).toEqual([+ 'ellipse',+ ]);+ expect(boxHits(doc, { x: 199, y: 49, width: 10, height: 2 })).toEqual([+ 'ellipse',+ ]);+ expect(boxHits(doc, { x: 201, y: 49, width: 10, height: 2 })).toEqual([]);+});++it('creates and resizes ellipses through the shared gesture and history path', () => {+ const editor = createGraphicsEditor();+ editor.beginShape('ellipse', { x: 210, y: 120 });+ editor.updateShape({ x: 10, y: 20 });+ expect(Object.keys(editor.document.items)).toHaveLength(1);+ editor.commitShape('ellipse', { fill: 'transparent', stroke: 'black' });+ expect(editor.document.items.ellipse?.type).toBe('ellipse');+ editor.beginTransform('ellipse', { x: 10, y: 20 }, 'nw');+ editor.updateTransform({ x: -40, y: -30 });+ expect(editor.document.items.ellipse).toMatchObject({+ geometry: { width: 200, height: 100 },+ });+ editor.commitTransform();+ expect(editor.document.items.ellipse).toMatchObject({+ geometry: { width: 250, height: 150 },+ });+ expect(+ transformPoint(worldMatrix(editor.document, 'ellipse'), { x: 250, y: 150 })+ ).toEqual({ x: 210, y: 120 });+ editor.undo();+ expect(editor.document.items.ellipse).toMatchObject({+ geometry: { width: 200, height: 100 },+ });+ editor.undo();+ expect(editor.document.items.ellipse).toBeUndefined();+ editor.redo();+ editor.beginShape('ellipse', { x: 0, y: 0 });+ editor.updateShape({ x: 30, y: 40 });+ editor.cancelShape();+ expect(+ editor.commitShape('cancelled', { fill: 'red', stroke: 'black' })+ ).toBe(false);+});++it('groups, rotates, scales and reparents mixed shapes without losing ellipse identity', () => {+ const editor = createGraphicsEditor([+ ellipse('red'),+ {+ id: 'rect',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a2' },+ transform: translation(300, 0),+ geometry: { width: 100, height: 100 },+ appearance: { fill: 'blue', stroke: 'black' },+ },+ ]);+ editor.select('ellipse');+ editor.toggleSelection('rect');+ editor.groupSelection('group');+ editor.beginTransform('group', { x: 200, y: -30 }, 'rotate');+ editor.updateTransform({ x: 280, y: 50 });+ editor.commitTransform();+ const rotated = worldMatrix(editor.document, 'ellipse');+ const beforeResize = editor.document;+ const frame = selectionFrame(beforeResize, ['group'])!;+ editor.beginTransform('group', frame.corners[2]!, 'se');+ editor.updateTransform(+ transformPoint(frame.transform, {+ x: frame.bounds.x + frame.bounds.width * 1.5,+ y: frame.bounds.y + frame.bounds.height * 1.25,+ })+ );+ editor.commitTransform();+ const scaled = worldMatrix(editor.document, 'ellipse');+ expect(editor.document.items.ellipse).toMatchObject({+ geometry: { width: 250, height: 150 },+ });+ editor.reparent('ellipse', 'scene-root', 'front');+ worldMatrix(editor.document, 'ellipse').forEach((v, i) =>+ expect(v).toBeCloseTo(scaled[i]!)+ );+ editor.undo();+ expect(editor.document.items.ellipse).toMatchObject({+ type: 'ellipse',+ placement: { parentId: 'group' },+ });+ editor.undo();+ expect(editor.document).toEqual(beforeResize);+ worldMatrix(editor.document, 'ellipse').forEach((v, i) =>+ expect(v).toBeCloseTo(rotated[i]!)+ );+});++it('rejects invalid ellipse geometry and containment', () => {+ expect(() =>+ createScene([{ ...ellipse(), geometry: { width: -1, height: 3 } }])+ ).toThrow();+ expect(() =>+ createScene([+ { ...ellipse(), placement: { parentId: 'ellipse', sortKey: 'a1' } },+ ])+ ).toThrow();+});diff --git a/packages/graphics/tests/embedded.test.ts b/packages/graphics/tests/embedded.test.tsnew file mode 100644index 0000000000..7d2e0ca8bd--- /dev/null+++ b/packages/graphics/tests/embedded.test.ts@@ -0,0 +1,114 @@+import { afterEach, expect, it } from 'vitest';+import {+ copyFragment,+ createGraphicsEditor,+ createScene,+ imageDefinition,+ insertShapesCommand,+ nudgeCommand,+ parseFragment,+ pasteCommand,+ type ShapeItem,+ translation,+} from '../src/core';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const disposers: (() => void)[] = [];+afterEach(() => disposers.splice(0).forEach((dispose) => dispose()));+const media = (type: 'image' | 'video'): ShapeItem<'image' | 'video'> => ({+ id: type,+ type,+ placement: {+ parentId: 'scene-root',+ sortKey: type === 'image' ? 'a0' : 'a1',+ },+ transform: translation(10, 20),+ appearance: { fill: 'transparent', stroke: 'transparent' },+ geometry: {+ width: 320,+ height: 180,+ source: { type: 'document', id: 'existing-file' },+ name: 'Media',+ },+});+it('inserts, transforms, copies and undoes media without losing its durable source', () => {+ const editor = createGraphicsEditor();+ disposers.push(editor.dispose);+ editor.execute(insertShapesCommand, [+ { item: media('image'), point: { x: 100, y: 100 } },+ { item: media('video'), point: { x: 450, y: 100 } },+ ]);+ editor.execute(nudgeCommand, { x: 20, y: 10 });+ const fragment = parseFragment(+ JSON.stringify(copyFragment(editor.document, ['image', 'video']))+ )!;+ let index = 0;+ editor.execute(pasteCommand, { fragment, createId: () => `copy-${index++}` });+ expect(editor.document.items['copy-0']).toMatchObject({+ geometry: { source: { type: 'document', id: 'existing-file' } },+ });+ editor.undo();+ editor.undo();+ editor.undo();+ expect(Object.keys(editor.document.items)).toEqual(['scene-root']);+ editor.redo();+ editor.select('image');+ editor.beginTransform('image', { x: 420, y: 280 }, 'se');+ editor.updateTransform({ x: 740, y: 460 });+ editor.commitTransform();+ expect(editor.document.items.image).toMatchObject({+ geometry: { width: 640, height: 360, source: { id: 'existing-file' } },+ });+});+it('validates references and rejects transient URLs and executable sources', () => {+ for (const url of [+ 'javascript:alert(1)',+ 'data:image/png;base64,xx',+ 'blob:local',+ '//other-host/file',+ ])+ expect(+ imageDefinition.validateGeometry({+ ...media('image').geometry,+ source: { type: 'url', url },+ })+ ).toBe(false);+ expect(+ imageDefinition.validateGeometry({+ ...media('image').geometry,+ source: { type: 'url', url: '/test.png' },+ })+ ).toBe(true);+});+it('replicates media and document cards through the existing Loro mapping', () => {+ const doc: ShapeItem<'document'> = {+ id: 'doc',+ type: 'document',+ placement: { parentId: 'scene-root', sortKey: 'a2' },+ transform: translation(100, 200),+ appearance: { fill: 'transparent', stroke: 'transparent' },+ geometry: {+ width: 320,+ height: 240,+ documentId: 'doc-id',+ fileType: 'md',+ name: 'Document',+ },+ };+ const lab = createGraphicsPeerLab(+ createScene([media('image'), media('video'), doc])+ );+ disposers.push(lab.dispose);+ const [a, b] = lab.peers.map((p) => p.editor);+ lab.setConnected(false);+ a!.select('doc');+ a!.execute(nudgeCommand, { x: 25, y: 50 });+ b!.select('image');+ b!.setSelectionAppearance({ opacity: 0.5 });+ lab.syncNow();+ expect(a!.document).toEqual(b!.document);+ expect(a!.document.items.doc).toMatchObject({+ geometry: doc.geometry,+ transform: translation(125, 250),+ });+});diff --git a/packages/graphics/tests/helpers/peer-lab.ts b/packages/graphics/tests/helpers/peer-lab.tsnew file mode 100644index 0000000000..8b4d5a2187--- /dev/null+++ b/packages/graphics/tests/helpers/peer-lab.ts@@ -0,0 +1,151 @@+import { createGraphicsEditorFromBackend } from '../../src/core/editor';+import type { GraphicsDocument } from '../../src/core/model';+import {+ createLoroGraphicsBackend,+ createLoroSeed,+} from '../../src/loro/backend';+import {+ createGraphicsPresence,+ type PresencePacket,+} from '../../src/loro/presence';++/** Two-replica in-memory transport for collaboration tests. */+export function createGraphicsPeerLab(seed: GraphicsDocument) {+ const snapshot = createLoroSeed(seed);+ const backends = [+ createLoroGraphicsBackend(snapshot, '1', seed.rootId),+ createLoroGraphicsBackend(snapshot, '2', seed.rootId),+ ] as const;+ const editors = backends.map((backend) =>+ createGraphicsEditorFromBackend(backend)+ );+ const awareness = editors.map((editor, index) =>+ createGraphicsPresence(+ editor,+ {+ id: String(index + 1),+ name: index === 0 ? 'Alice' : 'Bob',+ color: index === 0 ? '#c084fc' : '#22d3ee',+ },+ backends[index]!.getClock+ )+ );+ let connected = true;+ let latency = 0;+ let delivered = 0;+ let disposed = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let presenceTimer: ReturnType<typeof setTimeout> | undefined;+ const latestPresence = new Map<number, PresencePacket>();+ const queue: { from: number; bytes: Uint8Array }[] = [];+ const listeners = new Set<() => void>();+ const notify = () => {+ for (const listener of listeners) listener();+ };+ const clearTimer = () => {+ if (timer !== undefined) clearTimeout(timer);+ timer = undefined;+ };+ const clearPresenceTimer = () => {+ if (presenceTimer !== undefined) clearTimeout(presenceTimer);+ presenceTimer = undefined;+ };+ const flushPresence = () => {+ clearPresenceTimer();+ if (disposed || !connected) return;+ const packets = [...latestPresence];+ latestPresence.clear();+ for (const [from, packet] of packets) awareness[1 - from]!.receive(packet);+ };+ const schedulePresence = () => {+ if (+ !disposed &&+ connected &&+ latestPresence.size &&+ presenceTimer === undefined+ )+ presenceTimer = setTimeout(flushPresence, latency);+ };+ function syncNow() {+ if (disposed) return;+ clearTimer();+ while (queue.length) {+ const message = queue[0]!;+ backends[1 - message.from]!.receive(message.bytes);+ queue.shift();+ delivered++;+ }+ if (connected) flushPresence();+ notify();+ }+ const schedule = () => {+ if (!disposed && connected && queue.length && timer === undefined)+ timer = setTimeout(syncNow, latency);+ };+ const detach = backends.map((backend, from) =>+ backend.subscribeUpdates((bytes) => {+ queue.push({ from, bytes });+ notify();+ schedule();+ })+ );+ const detachPresence = awareness.map((presence, from) =>+ presence.subscribeUpdates((packet) => {+ if (!connected || disposed) return;+ latestPresence.set(from, packet);+ schedulePresence();+ })+ );+ awareness.forEach((presence) => presence.publish());+ return {+ peers: backends.map((backend, index) => ({+ name: index === 0 ? 'Alice' : 'Bob',+ editor: editors[index]!,+ backend,+ presence: awareness[index]!,+ })),+ status: () => ({ connected, latency, pending: queue.length, delivered }),+ subscribe(listener: () => void) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ setConnected(value: boolean) {+ if (disposed) return;+ connected = value;+ clearTimer();+ clearPresenceTimer();+ latestPresence.clear();+ awareness.forEach((presence) => presence.setOnline(value));+ schedule();+ notify();+ },+ setLatency(value: number) {+ if (disposed) return;+ latency = Math.max(0, Math.min(2000, value));+ clearTimer();+ clearPresenceTimer();+ schedule();+ schedulePresence();+ notify();+ },+ syncNow,+ dispose() {+ if (disposed) return;+ disposed = true;+ clearTimer();+ clearPresenceTimer();+ detach.forEach((unsubscribe) => unsubscribe());+ detachPresence.forEach((unsubscribe) => unsubscribe());+ awareness.forEach((presence) => presence.dispose());+ editors.forEach((editor) => editor.dispose());+ backends.forEach((backend) => backend.dispose());+ listeners.clear();+ queue.length = 0;+ latestPresence.clear();+ },+ };+}++export type GraphicsPeerLab = ReturnType<typeof createGraphicsPeerLab>;diff --git a/packages/graphics/tests/history.test.ts b/packages/graphics/tests/history.test.tsnew file mode 100644index 0000000000..0811c6662e--- /dev/null+++ b/packages/graphics/tests/history.test.ts@@ -0,0 +1,174 @@+import { expect, it } from 'vitest';+import { translation } from '../src/core/affine';+import { nudgeCommand } from '../src/core/commands';+import { createGraphicsEditor } from '../src/core/editor';+import {+ applyDocumentDelta,+ type DocumentDelta,+ documentDelta,+} from '../src/core/history';+import type {+ GraphicsItem,+ PencilItem,+ RectangleItem,+} from '../src/core/model';+import { sortKeysBetween } from '../src/core/ordering';+import { createScene, freezeDocument } from '../src/core/scene';++function rectangle(id = 'a', sortKey = 'a0'): RectangleItem {+ return {+ id,+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey },+ transform: translation(0, 0),+ geometry: { width: 20, height: 20 },+ appearance: { fill: 'red', stroke: 'black' },+ };+}++it('shares untouched items and pencil samples through local edits, undo and redo', () => {+ const pencil: PencilItem = {+ ...rectangle('ink', 'a1'),+ type: 'pencil',+ geometry: {+ simulatePressure: false,+ points: Array.from({ length: 1000 }, (_, i) => [i, i % 10, 0.5]),+ },+ };+ const editor = createGraphicsEditor([rectangle(), pencil]);+ const original = editor.document.items.ink as PencilItem;+ const untouched = editor.document.items.a;+ editor.select('ink');+ editor.execute(nudgeCommand, { x: 10, y: 5 });+ const moved = editor.document.items.ink as PencilItem;+ expect(moved).not.toBe(original);+ expect(moved.geometry).toBe(original.geometry);+ expect(moved.geometry.points).toBe(original.geometry.points);+ expect(editor.document.items.a).toBe(untouched);+ editor.undo();+ expect(editor.document.items.ink).toBe(original);+ expect(editor.document.items.a).toBe(untouched);+ editor.redo();+ expect(editor.document.items.ink).toBe(moved);+ expect(editor.document.items.a).toBe(untouched);+ editor.dispose();+});++it('retains 500 changed-item pairs for 100 edits of five out of 1000 items', () => {+ const keys = sortKeysBetween(null, null, 1000);+ const editor = createGraphicsEditor(+ keys.map((key, i) => rectangle(`r${i}`, key))+ );+ for (let i = 0; i < 5; i++) editor.toggleSelection(`r${i}`);+ const entries: DocumentDelta[] = [];+ for (let i = 0; i < 100; i++) {+ const before = editor.document;+ editor.execute(nudgeCommand, { x: 1, y: 0 });+ const delta = documentDelta(before, editor.document)!;+ expect(delta.items).toHaveLength(5);+ entries.push(delta);+ }+ const retained = new Set(Object.values(editor.document.items));+ for (const entry of entries) {+ for (const change of entry.items) {+ if (change.before) retained.add(change.before);+ if (change.after) retained.add(change.after);+ }+ }+ // 1000 live shapes + 500 previous versions + the single surface root.+ expect(retained.size).toBe(1501);+ const geometries = new Set(+ [...retained].flatMap((item) => ('geometry' in item ? [item.geometry] : []))+ );+ expect(geometries.size).toBe(1000);+ for (let i = 0; i < 100; i++) editor.undo();+ expect((editor.document.items.r0 as RectangleItem).transform[4]).toBe(0);+ expect(editor.getSession().canUndo).toBe(false);+ for (let i = 0; i < 100; i++) editor.redo();+ expect((editor.document.items.r0 as RectangleItem).transform[4]).toBe(100);+ expect(editor.getSession().canRedo).toBe(false);+ editor.dispose();+});++it('keeps the 100-step limit and preserves redo across an unchanged proposal', () => {+ const editor = createGraphicsEditor([rectangle()]);+ editor.select('a');+ for (let i = 0; i < 105; i++) editor.execute(nudgeCommand, { x: 1, y: 0 });+ for (let i = 0; i < 100; i++) editor.undo();+ expect((editor.document.items.a as RectangleItem).transform[4]).toBe(5);+ expect(editor.getSession().canUndo).toBe(false);+ editor.execute(+ {+ id: 'same-items',+ apply: ({ document }) => ({ document: { ...document } }),+ },+ undefined+ );+ expect(editor.getSession().canRedo).toBe(true);+ editor.redo();+ expect((editor.document.items.a as RectangleItem).transform[4]).toBe(6);+ editor.execute(nudgeCommand, { x: 10, y: 0 });+ expect(editor.getSession().canRedo).toBe(false);+ editor.dispose();+});++it('reverses creation, deletion, root and surface changes in one transaction', () => {+ const before = createScene([rectangle('__proto__')]);+ const after = freezeDocument({+ rootId: 'other-root',+ items: {+ 'other-root': { id: 'other-root', type: 'surface' },+ b: {+ ...rectangle('b'),+ placement: { parentId: 'other-root', sortKey: 'a0' },+ },+ },+ surface: { id: 'image', width: 100, height: 200 },+ });+ const delta = documentDelta(before, after)!;+ const undone = applyDocumentDelta(after, delta, 'before');+ expect(undone).toEqual(before);+ expect(+ Object.getOwnPropertyDescriptor(undone.items, '__proto__')?.value+ ).toBe(Object.getOwnPropertyDescriptor(before.items, '__proto__')?.value);+ expect(Object.isFrozen(undone.items)).toBe(true);+ expect(Object.hasOwn(undone, 'surface')).toBe(false);+ const redone = applyDocumentDelta(undone, delta, 'after');+ expect(redone).toEqual(after);+ expect(redone.items.b).toBe(after.items.b);+});++it('does not trust shallow-frozen external data or freeze caller-owned geometry', () => {+ const points: [number, number, number][] = [+ [0, 0, 0.5],+ [1, 1, 0.5],+ ];+ const input: PencilItem = Object.freeze({+ ...rectangle(),+ type: 'pencil',+ geometry: Object.freeze({ points, simulatePressure: false }),+ });+ const document = createScene([input]);+ const stored = document.items.a as PencilItem;+ points[0]![0] = 999;+ expect(stored.geometry.points[0]![0]).toBe(0);+ expect(Object.isFrozen(points)).toBe(false);+ expect(freezeDocument(document)).toBe(document);+});++it('revalidates document-wide invariants when reusing already frozen items', () => {+ const document = createScene([+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(0, 0),+ },+ { ...rectangle(), placement: { parentId: 'group', sortKey: 'a0' } },+ ]);+ const items: Record<string, GraphicsItem> = { ...document.items };+ delete items.group;+ expect(() => freezeDocument({ ...document, items })).toThrow(+ 'Invalid parent'+ );+});diff --git a/packages/graphics/tests/hit-testing.test.ts b/packages/graphics/tests/hit-testing.test.tsnew file mode 100644index 0000000000..1cdc3873f4--- /dev/null+++ b/packages/graphics/tests/hit-testing.test.ts@@ -0,0 +1,73 @@+import { expect, it } from 'vitest';+import {+ createGraphicsEditor,+ createScene,+ multiply,+ rotation,+ scaling,+ transformPoint,+ translation,+ worldMatrix,+} from '../src/core';++it('clicks through unfilled interiors and picks outlines with round corner tolerance', () => {+ const editor = createGraphicsEditor(+ ['back', 'front'].map((id, index) => ({+ id,+ type: 'rectangle' as const,+ placement: { parentId: 'scene-root', sortKey: `a${index}` },+ transform: translation(0, 0),+ geometry: { width: 100, height: 100 },+ appearance: {+ fill: id === 'front' ? 'transparent' : 'red',+ stroke: 'black',+ },+ }))+ );+ expect(editor.hitTest({ x: 50, y: 50 })).toBe('back');+ expect(editor.hitTest({ x: 2, y: 50 })).toBe('front');+ expect(editor.hitTest({ x: -3, y: 50 })).toBe('front');+ expect(editor.hitTest({ x: -3.1, y: 50 })).toBeUndefined();+ expect(editor.hitTest({ x: -2, y: -2 })).toBe('front');+ expect(editor.hitTest({ x: -2.2, y: -2.2 })).toBeUndefined();+});+it.each([+ 0.25, 1, 4,+])('keeps a 3px tolerance at zoom %s through nested transforms', (zoom) => {+ const scene = createScene([+ {+ id: 'g',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(+ translation(100, 80),+ multiply(rotation(0.4), scaling(2, 0.7))+ ),+ },+ {+ id: 'r',+ type: 'rectangle',+ placement: { parentId: 'g', sortKey: 'a0' },+ transform: rotation(-0.6),+ geometry: { width: 100, height: 100 },+ appearance: { fill: 'transparent', stroke: 'black', strokeWidth: 0.1 },+ },+ ]);+ const editor = createGraphicsEditor(scene);+ editor.zoomAt({ x: 0, y: 0 }, zoom);+ const matrix = worldMatrix(scene, 'r');+ const midpoint = transformPoint(matrix, { x: 50, y: 0 });+ const length = Math.hypot(matrix[0], matrix[1]);+ const nearEdge = (pixels: number) => ({+ x: midpoint.x - ((matrix[1] / length) * pixels) / zoom,+ y: midpoint.y + ((matrix[0] / length) * pixels) / zoom,+ });+ for (const direction of [-1, 1]) {+ expect(editor.hitTest(nearEdge(direction * 2.99))).toBe('g');+ expect(editor.hitTest(nearEdge(direction * 2.99), true)).toBe('r');+ expect(editor.hitTest(nearEdge(direction * 3.01))).toBeUndefined();+ }+ expect(+ editor.hitTest(transformPoint(matrix, { x: 50, y: 50 }))+ ).toBeUndefined();+});diff --git a/packages/graphics/tests/labels.test.ts b/packages/graphics/tests/labels.test.tsnew file mode 100644index 0000000000..044726c124--- /dev/null+++ b/packages/graphics/tests/labels.test.ts@@ -0,0 +1,190 @@+import { afterEach, expect, it, vi } from 'vitest';+import {+ canLabel,+ copyFragment,+ createGraphicsEditor,+ createScene,+ freezeDocument,+ multiply,+ parseFragment,+ pasteCommand,+ rectangleDefinition,+ rotation,+ type ShapeItem,+ type ShapeLabel,+ setShapeLabelCommand,+ shapeLabelLayout,+ shapeLabelText,+ textTargetAt,+ transformPoint,+ translation,+ worldMatrix,+} from '../src/core';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((fn) => fn()));+const label = (text = 'Shape label'): ShapeLabel => ({+ content: text,+ fontSize: 20,+ fontFamily: 'sans',+ height: 27,+});+const shape = (+ type: 'rectangle' | 'ellipse' = 'rectangle'+): ShapeItem<'rectangle' | 'ellipse'> => ({+ id: 'shape',+ type,+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(30, 40),+ geometry: { width: 200, height: 100 },+ appearance: { fill: 'transparent', stroke: 'black' },+});+it('commits a frozen shape-owned label, copies it, and clears just the label with undo', () => {+ const editor = createGraphicsEditor([shape()]);+ cleanups.push(editor.dispose);+ editor.execute(setShapeLabelCommand, { id: 'shape' });+ expect(editor.getSession().canUndo).toBe(false);+ editor.execute(setShapeLabelCommand, { id: 'shape', label: label() });+ const item = editor.document.items.shape;+ if (!canLabel(item)) throw Error();+ expect(Object.isFrozen(item.geometry.label!)).toBe(true);+ const fragment = parseFragment(+ JSON.stringify(copyFragment(editor.document, ['shape']))+ )!;+ editor.execute(pasteCommand, { fragment, createId: () => 'copy' });+ expect(editor.document.items.copy).toMatchObject({+ geometry: { label: label() },+ });+ editor.execute(setShapeLabelCommand, { id: 'shape' });+ expect(editor.document.items.shape).toEqual(shape());+ expect(editor.getSession().selectedId).toBe('shape');+ editor.undo();+ expect(editor.document.items.shape).toEqual(item);+});+it('reflows labels on side resize while retaining typography and shape dimensions', () => {+ const item = {+ ...shape(),+ geometry: { ...shape().geometry, label: label() },+ };+ const measure = vi.fn((g) => ({ width: g.width, height: 81 }));+ const editor = createGraphicsEditor([item], { measureText: measure });+ cleanups.push(editor.dispose);+ editor.select('shape');+ editor.beginTransform('shape', { x: 230, y: 90 }, 'e');+ editor.updateTransform({ x: 130, y: 90 });+ editor.commitTransform();+ expect(editor.document.items.shape).toMatchObject({+ geometry: {+ width: 100,+ height: 100,+ label: { fontSize: 20, height: 81, content: label().content },+ },+ });+ expect(measure).toHaveBeenCalledWith(+ expect.objectContaining({ width: 76, autoWidth: false })+ );+ editor.undo();+ expect(editor.document.items.shape).toEqual(item);+});++it('preserves empty and host-defined label payloads until explicitly cleared', () => {+ const editor = createGraphicsEditor([shape()]);+ cleanups.push(editor.dispose);+ for (const content of ['', ' ', '<host-text>Label</host-text>']) {+ editor.execute(setShapeLabelCommand, {+ id: 'shape',+ label: label(content),+ });+ expect(editor.document.items.shape).toMatchObject({+ geometry: { label: { content } },+ });+ }+ editor.execute(setShapeLabelCommand, { id: 'shape' });+ expect(editor.document.items.shape).toEqual(shape());+});+it.each([+ 'rectangle',+ 'ellipse',+] as const)('centers and uniformly fits %s labels through nested transforms', (type) => {+ const item = {+ ...shape(type),+ placement: { parentId: 'group', sortKey: 'a0' },+ transform: rotation(0.4),+ geometry: { width: 80, height: 40, label: label() },+ };+ const scene = createScene([+ {+ id: 'group',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(translation(300, 150), rotation(-0.8)),+ },+ item,+ ]);+ const layout = shapeLabelLayout(item)!,+ projected = shapeLabelText(item)!;+ expect(layout.transform[0]).toBe(layout.transform[3]);+ expect(layout.transform[0]).toBeLessThan(1);+ const center = {+ x: layout.geometry.width / 2,+ y: layout.geometry.height / 2,+ };+ const projectedWorld = multiply(+ worldMatrix(scene, 'group'),+ projected.transform+ );+ const actual = transformPoint(projectedWorld, center),+ expected = transformPoint(worldMatrix(scene, 'shape'), { x: 40, y: 20 });+ expect(actual.x).toBeCloseTo(expected.x);+ expect(actual.y).toBeCloseTo(expected.y);+});+it('keeps ordinary click-through while text gestures enter unfilled shapes and painted labels select their owner', () => {+ const editor = createGraphicsEditor([shape()]);+ cleanups.push(editor.dispose);+ const center = { x: 130, y: 90 };+ expect(editor.hitTest(center)).toBeUndefined();+ expect(textTargetAt(editor.document, center)).toBe('shape');+ editor.execute(setShapeLabelCommand, { id: 'shape', label: label() });+ expect(editor.hitTest(center)).toBe('shape');+ expect(editor.hitTest({ x: 40, y: 50 })).toBeUndefined();+ const ellipse = createScene([shape('ellipse')]);+ expect(textTargetAt(ellipse, { x: 31, y: 41 })).toBeUndefined();+ expect(textTargetAt(ellipse, center)).toBe('shape');+});+it('rejects invalid and unsafe label data at the document boundary', () => {+ const item = shape();+ for (const invalid of [+ { ...label(), height: NaN },+ { ...label(), fontSize: -1 },+ { ...label(), content: 'x'.repeat(2_000_001) },+ ]) {+ expect(+ rectangleDefinition.validateGeometry({ ...item.geometry, label: invalid })+ ).toBe(false);+ expect(() =>+ freezeDocument(+ createScene([+ { ...item, geometry: { ...item.geometry, label: invalid } },+ ])+ )+ ).toThrow();+ }+});+it('round trips labels through the existing Loro geometry adapter and local undo', () => {+ const lab = createGraphicsPeerLab(createScene([shape()]));+ cleanups.push(lab.dispose);+ lab.setConnected(false);+ const a = lab.peers[0]!.editor,+ b = lab.peers[1]!.editor;+ const before = a.document.items.shape;+ a.execute(setShapeLabelCommand, { id: 'shape', label: label() });+ lab.syncNow();+ expect(b.document).toEqual(a.document);+ expect(b.document.items.shape).toMatchObject({+ geometry: { label: label() },+ });+ a.undo();+ lab.syncNow();+ expect(b.document.items.shape).toEqual(before);+});diff --git a/packages/graphics/tests/layering.test.ts b/packages/graphics/tests/layering.test.tsnew file mode 100644index 0000000000..490d29b04d--- /dev/null+++ b/packages/graphics/tests/layering.test.ts@@ -0,0 +1,159 @@+import { expect, it } from 'vitest';+import {+ children,+ createGraphicsEditor,+ createScene,+ drawableIds,+ freezeDocument,+ type GraphicsDocument,+ groupNodes,+ hitTest,+ isSortKey,+ type LayerOperation,+ reorderNodes,+ reparent,+ sortKeysBetween,+ ungroupNode,+ worldMatrix,+} from '../src/core';+import { translation } from '../src/core/affine';++const scene = () =>+ createScene(+ ['a', 'b', 'c', 'd', 'e'].map((id, index) => ({+ id,+ type: 'rectangle' as const,+ placement: { parentId: 'scene-root', sortKey: `a${index}` },+ transform: translation(0, 0),+ geometry: { width: 100, height: 100 },+ appearance: { fill: 'red', stroke: 'black' },+ }))+ );+const key = (doc: GraphicsDocument, id: string) => {+ const node = doc.items[id];+ if (!node || node.type === 'surface') throw new Error('Missing spatial node');+ return node.placement.sortKey;+};++it('supports repeated insertion without numeric precision loss or changing neighbors', () => {+ const [first, last] = sortKeysBetween(null, null, 2);+ let upper = last!;+ for (let i = 0; i < 600; i++) {+ const next = sortKeysBetween(first!, upper, 1)[0]!;+ expect(first! < next && next < upper).toBe(true);+ expect(isSortKey(next)).toBe(true);+ upper = next;+ }+ expect(sortKeysBetween(null, first!, 1)[0]! < first!).toBe(true);+ expect(sortKeysBetween(last!, null, 1)[0]! > last!).toBe(true);+ expect(() => sortKeysBetween(last!, first!, 1)).toThrow();+});++it.each([+ ['front', ['a', 'c', 'e', 'b', 'd']],+ ['back', ['b', 'd', 'a', 'c', 'e']],+ ['forward', ['a', 'c', 'b', 'e', 'd']],+ ['backward', ['b', 'a', 'd', 'c', 'e']],+] satisfies [+ LayerOperation,+ string[],+][])('moves a disjoint selection %s without renumbering other nodes', (operation, expected) => {+ const before = scene();+ const after = reorderNodes(before, ['d', 'b'], operation);+ expect(children(after)).toEqual(expected);+ for (const id of ['a', 'c', 'e'])+ expect(key(after, id)).toBe(key(before, id));+ for (const id of children(before))+ expect(worldMatrix(after, id)).toEqual(worldMatrix(before, id));+ expect(hitTest(after, { x: 50, y: 50 })).toBe(expected.at(-1));+});++it('moves contiguous selections one sibling and leaves boundary no-ops out of undo', () => {+ const before = scene();+ expect(children(reorderNodes(before, ['b', 'c', 'e'], 'forward'))).toEqual([+ 'a',+ 'd',+ 'b',+ 'c',+ 'e',+ ]);+ const editor = createGraphicsEditor(before);+ const unchanged = editor.document;+ editor.select('e');+ editor.reorderSelection('front');+ expect(editor.document).toBe(unchanged);+ expect(editor.getSession().canUndo).toBe(false);+ editor.select('b');+ editor.toggleSelection('c');+ const original = editor.document;+ editor.reorderSelection('front');+ const reordered = editor.document;+ expect(children(reordered)).toEqual(['a', 'd', 'e', 'b', 'c']);+ editor.undo();+ expect(editor.document).toEqual(original);+ expect(editor.getSession().selectedIds).toEqual(['b', 'c']);+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ expect(editor.document).toEqual(reordered);+});++it('keeps groups contiguous and preserves unrelated keys across group, reparent and ungroup', () => {+ const before = scene();+ const grouped = groupNodes(before, ['d', 'b'], 'g');+ expect(children(grouped)).toEqual(['a', 'g', 'c', 'e']);+ expect(children(grouped, 'g')).toEqual(['b', 'd']);+ expect(key(grouped, 'g')).toBe(key(before, 'b'));+ const moved = reorderNodes(grouped, ['g', 'b'], 'front');+ expect(drawableIds(moved)).toEqual(['a', 'c', 'e', 'b', 'd']);+ expect(key(moved, 'b')).toBe(key(before, 'b'));+ const nested = reparent(moved, 'a', 'g', { before: 'd' });+ expect(children(nested, 'g')).toEqual(['b', 'a', 'd']);+ expect(worldMatrix(nested, 'a')).toEqual(worldMatrix(before, 'a'));+ const ungrouped = ungroupNode(nested, 'g');+ expect(children(ungrouped)).toEqual(['c', 'e', 'b', 'a', 'd']);+ for (const id of ['c', 'e']) expect(key(ungrouped, id)).toBe(key(before, id));+ expect(() =>+ reparent(before, 'a', before.rootId, { before: 'missing' })+ ).toThrow();+});++it('reorders independently across parents without flattening the scene', () => {+ const grouped = groupNodes(scene(), ['a', 'b', 'c'], 'g');+ const next = reorderNodes(grouped, ['a', 'd'], 'front');+ expect(children(next, 'g')).toEqual(['b', 'c', 'a']);+ expect(children(next)).toEqual(['g', 'e', 'd']);+ expect(key(next, 'g')).toBe(key(grouped, 'g'));+});++it('creates new shapes above existing content after reorder and deletion', () => {+ const editor = createGraphicsEditor(scene());+ editor.select('a');+ editor.reorderSelection('front');+ editor.select('c');+ editor.deleteSelection();+ const previousKeys = children(editor.document).map(+ (id) => [id, key(editor.document, id)] as const+ );+ editor.beginRectangle({ x: 0, y: 0 });+ editor.updateRectangle({ x: 100, y: 100 });+ editor.commitRectangle('new', { fill: 'blue', stroke: 'black' });+ expect(children(editor.document).at(-1)).toBe('new');+ for (const [id, value] of previousKeys)+ expect(key(editor.document, id)).toBe(value);+});++it('rejects malformed and duplicate sibling sort keys at document boundaries', () => {+ const doc = scene();+ const node = doc.items.b;+ if (!node || node.type === 'surface') throw new Error('fixture');+ for (const sortKey of ['', 'a', 'a!', 'a00', key(doc, 'a')]) {+ const invalid = {+ ...doc,+ items: {+ ...doc.items,+ b: { ...node, placement: { ...node.placement, sortKey } },+ },+ };+ expect(() => freezeDocument(invalid)).toThrow();+ }+});diff --git a/packages/graphics/tests/loro-text.test.ts b/packages/graphics/tests/loro-text.test.tsnew file mode 100644index 0000000000..4f073e6169--- /dev/null+++ b/packages/graphics/tests/loro-text.test.ts@@ -0,0 +1,136 @@+import { afterEach, expect, it } from 'vitest';+import {+ createScene,+ nudgeCommand,+ type ShapeItem,+ setShapeLabelCommand,+ setTextCommand,+ translation,+ validRichText,+} from '../src/core';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const disposers: (() => void)[] = [];+afterEach(() => disposers.splice(0).forEach((fn) => fn()));+const item: ShapeItem<'text'> = {+ id: 'text',+ type: 'text',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(0, 0),+ appearance: { fill: 'transparent', stroke: 'black' },+ geometry: {+ width: 200,+ height: 32,+ autoWidth: false,+ fontSize: 24,+ fontFamily: 'sans',+ content: 'Original',+ },+};+function setup() {+ const lab = createGraphicsPeerLab(createScene([item]));+ disposers.push(lab.dispose);+ lab.setConnected(false);+ return { lab, a: lab.peers[0]!.editor, b: lab.peers[1]!.editor };+}+it('merges a whole-string edit with a concurrent move and independently undoes each', () => {+ const { lab, a, b } = setup();+ const content = 'Edited';+ a.execute(setTextCommand, {+ ...item,+ geometry: { ...item.geometry, content },+ });+ b.select('text');+ b.execute(nudgeCommand, { x: 50, y: 40 });+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ expect(a.document.items.text).toMatchObject({+ geometry: { content },+ transform: translation(50, 40),+ });+ a.undo();+ lab.syncNow();+ expect(b.document.items.text).toMatchObject({+ geometry: { content: item.geometry.content },+ transform: translation(50, 40),+ });+});+it('concurrent edits choose one complete content string, never combine characters', () => {+ const { lab, a, b } = setup();+ const left = 'Alice complete edit',+ right = 'Bob complete edit';+ a.execute(setTextCommand, {+ ...item,+ geometry: { ...item.geometry, content: left },+ });+ b.execute(setTextCommand, {+ ...item,+ geometry: { ...item.geometry, content: right },+ });+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ const text = a.document.items.text;+ if (text?.type !== 'text') throw Error();+ expect([left, right]).toContain(text.geometry.content);+ expect(validRichText(text.geometry.content)).toBe(true);+});+it('label strings merge independently of moving their owner', () => {+ const label = {+ content: 'Label',+ fontSize: 20,+ fontFamily: 'sans' as const,+ height: 27,+ };+ const shape: ShapeItem<'rectangle'> = {+ ...item,+ type: 'rectangle',+ geometry: { width: 200, height: 100, label },+ };+ const lab = createGraphicsPeerLab(createScene([shape]));+ disposers.push(lab.dispose);+ lab.setConnected(false);+ const a = lab.peers[0]!.editor,+ b = lab.peers[1]!.editor;+ a.execute(setShapeLabelCommand, {+ id: 'text',+ label: { ...label, content: 'Changed' },+ });+ b.select('text');+ b.execute(nudgeCommand, { x: 40, y: 0 });+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ expect(b.document.items.text).toMatchObject({+ geometry: { label: { content: 'Changed' } },+ transform: translation(40, 0),+ });+});++it('adding a new label and moving the previously unlabeled shape both survive', () => {+ const shape: ShapeItem<'rectangle'> = {+ ...item,+ type: 'rectangle',+ geometry: { width: 200, height: 100 },+ };+ const lab = createGraphicsPeerLab(createScene([shape]));+ disposers.push(lab.dispose);+ lab.setConnected(false);+ const a = lab.peers[0]!.editor,+ b = lab.peers[1]!.editor;+ a.execute(setShapeLabelCommand, {+ id: 'text',+ label: {+ content: 'New label',+ fontSize: 24,+ fontFamily: 'sans',+ height: 32,+ },+ });+ b.select('text');+ b.execute(nudgeCommand, { x: 60, y: 0 });+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ expect(b.document.items.text).toMatchObject({+ transform: translation(60, 0),+ geometry: { label: { content: 'New label' } },+ });+});diff --git a/packages/graphics/tests/loro.test.ts b/packages/graphics/tests/loro.test.tsnew file mode 100644index 0000000000..99b2f8d322--- /dev/null+++ b/packages/graphics/tests/loro.test.ts@@ -0,0 +1,297 @@+import { afterEach, expect, it, vi } from 'vitest';+import {+ children,+ createGraphicsEditorFromBackend,+ createScene,+ freezeDocument,+ type GraphicsEditor,+ IDENTITY,+ translation,+ worldMatrix,+} from '../src/core';+import { createLoroGraphicsBackend, createLoroSeed } from '../src/loro';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const seed = () =>+ createScene([+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(10, 20),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ {+ id: 'b',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: translation(130, 30),+ geometry: { width: 90, height: 70 },+ appearance: { fill: 'blue', stroke: 'black' },+ },+ {+ id: 'g',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a2' },+ transform: translation(100, 100),+ },+ ]);+const disposers: (() => void)[] = [];+afterEach(() => {+ disposers.splice(0).forEach((dispose) => dispose());+ vi.useRealTimers();+});+function setup(document = seed()) {+ const lab = createGraphicsPeerLab(document);+ disposers.push(lab.dispose);+ lab.setConnected(false);+ return { lab, a: lab.peers[0]!.editor, b: lab.peers[1]!.editor };+}+function move(editor: GraphicsEditor, id: string, dx: number) {+ editor.select(id);+ editor.beginTransform(id, { x: 0, y: 0 });+ editor.updateTransform({ x: dx, y: 0 });+ editor.commitTransform();+}+function converge(a: GraphicsEditor, b: GraphicsEditor) {+ expect(a.document).toEqual(b.document);+ expect(() => freezeDocument(a.document)).not.toThrow();+}+it('merges move and restyle, and local undo preserves remote style', () => {+ const { lab, a, b } = setup();+ move(a, 'a', 50);+ b.select('a');+ b.setSelectionAppearance({ fill: 'green' });+ expect(lab.status().pending).toBe(2);+ lab.syncNow();+ converge(a, b);+ expect(worldMatrix(a.document, 'a')[4]).toBe(60);+ expect(a.document.items.a).toMatchObject({ appearance: { fill: 'green' } });+ a.undo();+ lab.syncNow();+ converge(a, b);+ expect(worldMatrix(a.document, 'a')[4]).toBe(10);+ expect(a.document.items.a).toMatchObject({ appearance: { fill: 'green' } });+ a.redo();+ lab.syncNow();+ converge(a, b);+ expect(worldMatrix(a.document, 'a')[4]).toBe(60);+});+it('retains native same-property undo semantics explicitly', () => {+ const { lab, a, b } = setup();+ a.select('a');+ a.setSelectionAppearance({ fill: 'green' });+ lab.syncNow();+ b.select('a');+ b.setSelectionAppearance({ fill: 'yellow' });+ lab.syncNow();+ a.undo();+ lab.syncNow();+ converge(a, b);+ expect(a.document.items.a).toMatchObject({ appearance: { fill: 'red' } });+ a.redo();+ lab.syncNow();+ converge(a, b);+ expect(a.document.items.a).toMatchObject({ appearance: { fill: 'yellow' } });+});+it('concurrent inserts and layer moves converge without duplicate core keys', () => {+ const { lab, a, b } = setup();+ for (const [editor, id] of [+ [a, 'new-a'],+ [b, 'new-b'],+ ] as const) {+ editor.beginRectangle({ x: 0, y: 0 });+ editor.updateRectangle({ x: 60, y: 60 });+ editor.commitRectangle(id, { fill: 'red', stroke: 'black' });+ editor.select('a');+ editor.reorderSelection('front');+ }+ lab.syncNow();+ converge(a, b);+ expect(children(a.document)).toHaveLength(5);+ a.reorderSelection('back');+ lab.syncNow();+ converge(a, b);+ expect(children(a.document)[0]).toBe('a');+});+it('group, ungroup and undo keep hierarchy and world poses', () => {+ const { lab, a, b } = setup();+ a.select('a');+ a.toggleSelection('b');+ a.groupSelection('pair');+ lab.syncNow();+ converge(a, b);+ expect(children(b.document, 'pair')).toEqual(['a', 'b']);+ expect(worldMatrix(b.document, 'a')).toEqual(translation(10, 20));+ a.ungroupSelection();+ lab.syncNow();+ converge(a, b);+ expect(a.document.items.pair).toBeUndefined();+ a.undo();+ lab.syncNow();+ converge(a, b);+ expect(children(b.document, 'pair')).toEqual(['a', 'b']);+});+it('opposite reparenting converges to an acyclic scene', () => {+ const doc = seed();+ const { lab, a, b } = setup(+ createScene([+ ...Object.values(doc.items).filter((n) => n.type !== 'surface'),+ {+ id: 'h',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a3' },+ transform: IDENTITY,+ },+ ])+ );+ a.reparent('g', 'h');+ b.reparent('h', 'g');+ lab.syncNow();+ converge(a, b);+ expect(a.document.items.g).toBeDefined();+ expect(a.document.items.h).toBeDefined();+});+it('concurrent reparent/move uses the winning pose in its recorded frame', () => {+ const { lab, a, b } = setup();+ a.reparent('a', 'g');+ move(b, 'a', 50);+ lab.syncNow();+ converge(a, b);+ expect(a.document.items.a).toMatchObject({ placement: { parentId: 'g' } });+ expect([10, 60]).toContain(worldMatrix(a.document, 'a')[4]);+});+it('deleting a group while another peer extracts a child converges', () => {+ const { lab, a, b } = setup();+ a.reparent('a', 'g');+ lab.syncNow();+ a.select('g');+ a.deleteSelection();+ b.reparent('a', 'scene-root');+ lab.syncNow();+ converge(a, b);+ expect(a.document.items.g).toBeUndefined();+ // Loro keeps a concurrently extracted child alive.+ expect(a.document.items.a).toMatchObject({+ placement: { parentId: 'scene-root' },+ });+});+it('remote changes cancel previews and never enter the other peer history', () => {+ const { lab, a, b } = setup();+ b.select('a');+ b.beginTransform('a', { x: 0, y: 0 });+ b.updateTransform({ x: 100, y: 0 });+ move(a, 'a', 50);+ lab.syncNow();+ expect(b.getSession().transform).toBeUndefined();+ expect(b.getSession().canUndo).toBe(false);+ expect(b.commitTransform()).toBe(false);+ converge(a, b);+});+it('transport queues offline edits, honors latency and disposes timers', () => {+ vi.useFakeTimers();+ const { lab, a, b } = setup();+ move(a, 'a', 20);+ vi.advanceTimersByTime(2000);+ expect(worldMatrix(b.document, 'a')[4]).toBe(10);+ lab.setLatency(400);+ lab.setConnected(true);+ vi.advanceTimersByTime(399);+ expect(lab.status().pending).toBe(1);+ vi.advanceTimersByTime(1);+ converge(a, b);+ expect(lab.status().pending).toBe(0);+ move(a, 'a', 20);+ lab.dispose();+ vi.runAllTimers();+});+it('duplicate and reversed deliveries converge and do not echo', () => {+ const bytes = createLoroSeed(seed());+ const first = createLoroGraphicsBackend(bytes, '3', 'scene-root'),+ second = createLoroGraphicsBackend(bytes, '4', 'scene-root');+ const a = createGraphicsEditorFromBackend(first),+ b = createGraphicsEditorFromBackend(second);+ disposers.push(() => {+ a.dispose();+ b.dispose();+ first.dispose();+ second.dispose();+ });+ const messages: Uint8Array[] = [];+ first.subscribeUpdates((bytes) => messages.push(bytes));+ const echo = vi.fn();+ second.subscribeUpdates(echo);+ move(a, 'a', 10);+ move(a, 'b', 20);+ second.receive(messages[1]!);+ second.receive(messages[0]!);+ second.receive(messages[1]!);+ converge(a, b);+ expect(echo).not.toHaveBeenCalled();+});++it('uses captured world pose when a later concurrent move wins under a new parent', () => {+ const { lab, a, b } = setup();+ a.reparent('a', 'g');+ // Advance this replica's Lamport clock while still disconnected.+ for (let i = 0; i < 8; i++) {+ b.select('b');+ b.setSelectionAppearance({ fill: `color-${i}` });+ }+ move(b, 'a', 50);+ lab.syncNow();+ converge(a, b);+ expect(worldMatrix(a.document, 'a')).toEqual(translation(60, 20));+ expect(lab.peers[0]!.backend.getFrameConflicts()).toContain('a');+ move(a, 'g', 40);+ lab.syncNow();+ converge(a, b);+ expect(worldMatrix(a.document, 'a')).toEqual(translation(60, 20));+ move(a, 'a', 10);+ lab.syncNow();+ expect(lab.peers[0]!.backend.getFrameConflicts()).not.toContain('a');+ move(a, 'g', 20);+ lab.syncNow();+ converge(a, b);+ expect(worldMatrix(a.document, 'a')).toEqual(translation(90, 20));+});++it('delete wins over concurrent editing; native undo restores pre-delete data', () => {+ const { lab, a, b } = setup();+ a.select('a');+ a.deleteSelection();+ b.select('a');+ b.setSelectionAppearance({ fill: 'green' });+ lab.syncNow();+ converge(a, b);+ expect(a.document.items.a).toBeUndefined();+ a.undo();+ lab.syncNow();+ converge(a, b);+ expect(a.document.items.a).toMatchObject({ appearance: { fill: 'red' } });+});++it('rejects unsupported proposals before touching Loro or local history', () => {+ const { lab, a, b } = setup();+ const backend = lab.peers[0]!.backend;+ const before = backend.getDocument();+ const node = before.items.a!;+ if (node.type !== 'rectangle') throw new Error('Missing fixture');+ const changed = {+ ...before,+ items: {+ ...before.items,+ b: { ...before.items.b!, transform: translation(999, 999) },+ a: { ...node, type: 'ellipse' as const },+ },+ };+ expect(() => backend.commit(changed)).toThrow('immutable');+ expect(backend.getDocument()).toBe(before);+ expect(a.getSession().canUndo).toBe(false);+ move(a, 'b', 30);+ lab.syncNow();+ converge(a, b);+ expect(worldMatrix(b.document, 'a')).toEqual(translation(10, 20));+ expect(worldMatrix(b.document, 'b')).toEqual(translation(160, 30));+});diff --git a/packages/graphics/tests/pencil.test.ts b/packages/graphics/tests/pencil.test.tsnew file mode 100644index 0000000000..8cc7a9508a--- /dev/null+++ b/packages/graphics/tests/pencil.test.ts@@ -0,0 +1,270 @@+import { expect, it } from 'vitest';+import {+ boxHits,+ copyFragment,+ createGraphicsEditor,+ createScene,+ drawableIds,+ freezeDocument,+ IDENTITY,+ multiply,+ type PencilItem,+ parseFragment,+ pasteFragment,+ rotation,+ scaling,+ selectionFrame,+ transformPoint,+ translation,+ worldMatrix,+} from '../src/core';+import { pencilDefinition, pencilInk } from '../src/core/shapes/pencil';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const appearance = { fill: 'red', stroke: 'black', strokeWidth: 12 };+const pencil = (simulatePressure = true): PencilItem => ({+ id: 'ink',+ type: 'pencil',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: IDENTITY,+ geometry: {+ simulatePressure,+ points: Array.from({ length: 60 }, (_, i) => [+ i * 4,+ 60 * Math.sin(i / 10),+ 0.5,+ ]),+ },+ appearance,+});++it('keeps one stroke transient until release and commits one undo step, including dots', () => {+ const editor = createGraphicsEditor();+ const before = editor.document;+ editor.beginShape('pencil', { x: 100, y: 150 });+ editor.updateDrawing([+ { x: 105, y: 160 },+ { x: 120, y: 170 },+ { x: 180, y: 160 },+ ]);+ expect(editor.document).toBe(before);+ const preview = editor.getDrawingPreview(appearance)!;+ expect(editor.commitShape('ink', appearance, 3)).toBe(true);+ const stroke = editor.document.items.ink;+ expect(stroke).toMatchObject({+ type: 'pencil',+ geometry: preview.geometry,+ transform: preview.transform,+ });+ editor.undo();+ expect(editor.document).toEqual(before);+ editor.redo();+ expect(editor.document.items.ink).toEqual(stroke);+ editor.beginShape('pencil', { x: 10, y: 20, pressure: 0.8 });+ expect(editor.commitShape('dot', appearance, 3)).toBe(true);+ expect(editor.hitTest({ x: 10, y: 20 })).toBe('dot');+ editor.beginShape('pencil', { x: 20, y: 20 });+ editor.cancelShape();+ expect(editor.commitShape('cancelled', appearance)).toBe(false);+});++it('uses point spacing for mouse width and actual pressure for pen width', () => {+ const line = (+ spacing: number,+ pressure = 0.5,+ simulatePressure = true+ ): PencilItem => ({+ ...pencil(),+ geometry: {+ simulatePressure,+ points: Array.from({ length: 100 }, (_, i) => [i * spacing, 0, pressure]),+ },+ });+ expect(pencilInk(line(0.8)).bounds.height).toBeGreaterThan(+ pencilInk(line(12)).bounds.height * 1.2+ );+ expect(pencilInk(line(3, 0.9, false)).bounds.height).toBeGreaterThan(+ pencilInk(line(3, 0.1, false)).bounds.height * 1.2+ );+});++it.each([+ 0.25, 1, 4,+])('picks the actual ink with 3 screen px tolerance at zoom %s', (zoom) => {+ const dot: PencilItem = {+ ...pencil(false),+ geometry: { points: [[0, 0, 0.5]], simulatePressure: false },+ transform: multiply(+ translation(120, 80),+ multiply(rotation(0.7), scaling(2, 0.6))+ ),+ };+ const editor = createGraphicsEditor([dot]);+ editor.zoomAt({ x: 0, y: 0 }, zoom);+ const polygon = pencilInk(dot).outline.map((point) =>+ transformPoint(dot.transform, point)+ );+ const max = polygon.reduce((p, q) => (p.x > q.x ? p : q));+ expect(editor.hitTest({ x: max.x + 2.99 / zoom, y: max.y })).toBe('ink');+ expect(editor.hitTest({ x: max.x + 3.01 / zoom, y: max.y })).toBeUndefined();+});++it('uses smoothed ink bounds and leaves empty loops and bounding-box gaps clickable', () => {+ const loop: PencilItem = {+ ...pencil(),+ geometry: {+ simulatePressure: true,+ points: Array.from({ length: 90 }, (_, i) => [+ 100 + 80 * Math.cos((i * Math.PI) / 44),+ 100 + 80 * Math.sin((i * Math.PI) / 44),+ 0.5,+ ]),+ },+ };+ const back = {+ id: 'back',+ type: 'rectangle' as const,+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: IDENTITY,+ geometry: { width: 220, height: 220 },+ appearance: { fill: 'blue', stroke: 'black' },+ };+ const editor = createGraphicsEditor([back, loop]);+ expect(editor.hitTest({ x: 100, y: 100 })).toBe('back');+ const scene = createScene([loop]);+ expect(boxHits(scene, { x: 90, y: 90, width: 20, height: 20 })).toEqual([]);+ expect(boxHits(scene, { x: 0, y: 0, width: 220, height: 220 })).toEqual([+ 'ink',+ ]);+ const frame = selectionFrame(scene, ['ink'])!;+ expect(frame.bounds).toEqual(pencilInk(loop).bounds);+ for (const point of pencilInk(loop).outline) {+ expect(point.x).toBeGreaterThanOrEqual(frame.bounds.x);+ expect(point.y).toBeGreaterThanOrEqual(frame.bounds.y);+ expect(point.x).toBeLessThanOrEqual(+ frame.bounds.x + frame.bounds.width + 1e-9+ );+ expect(point.y).toBeLessThanOrEqual(+ frame.bounds.y + frame.bounds.height + 1e-9+ );+ }+ const corner = { x: frame.bounds.x + 1, y: frame.bounds.y + 1 };+ expect(editor.hitTest(corner)).toBe('back');+});++it('resizes samples and regenerates pressure without magnifying the nominal brush', () => {+ const item = pencil();+ const bounds = pencilDefinition.bounds(item);+ const resized = pencilDefinition.resize(item, {+ ...bounds,+ width: bounds.width * 2,+ height: bounds.height,+ });+ expect(resized.geometry.points[40]![0]).toBe(+ item.geometry.points[40]![0] * 2+ );+ expect(resized.geometry.points[40]![1]).toBe(item.geometry.points[40]![1]);+ expect(resized.appearance.strokeWidth).toBe(12);+ expect(resized.geometry.simulatePressure).toBe(true);+ expect(pencilInk(resized).path).not.toBe(pencilInk(item).path);+});++it('supports flip-through-zero and uniform resize inside nested rotated groups', () => {+ const editor = createGraphicsEditor([pencil()]);+ const initial = editor.document;+ editor.select('ink');+ const frame = selectionFrame(editor.document, ['ink'])!;+ editor.beginTransform('ink', frame.corners[1]!, 'e');+ editor.updateTransform({+ x: frame.bounds.x - frame.bounds.width,+ y: frame.corners[1]!.y,+ });+ expect(editor.commitTransform()).toBe(true);+ expect(worldMatrix(editor.document, 'ink')[0]).toBeLessThan(0);+ editor.undo();+ expect(editor.document).toEqual(initial);+ editor.groupSelection('group');+ editor.groupSelection('outer');+ editor.beginTransform('outer', { x: 0, y: -100 }, 'rotate');+ editor.updateTransform({ x: 200, y: 0 });+ editor.commitTransform();+ const before = editor.document;+ const group = selectionFrame(before, ['outer'])!;+ editor.beginTransform('outer', group.corners[2]!, 'se');+ editor.updateTransform(+ {+ x: group.bounds.x + group.bounds.width * 2,+ y: group.bounds.y + group.bounds.height * 2,+ },+ { proportional: true }+ );+ editor.commitTransform();+ const ink = editor.document.items.ink;+ if (ink?.type !== 'pencil') throw new Error('Missing pencil');+ expect(ink.geometry.points[20]![0]).toBeCloseTo(+ pencil().geometry.points[20]![0] * 2+ );+ expect(+ Math.hypot(...worldMatrix(editor.document, 'ink').slice(0, 2))+ ).toBeCloseTo(1);+ expect(ink.appearance.strokeWidth).toBe(12);+ editor.undo();+ expect(editor.document).toEqual(before);+});++it('round-trips pencil data through clipboard with deeply immutable samples', () => {+ const input = pencil();+ const scene = createScene([input]);+ const fragment = parseFragment(JSON.stringify(copyFragment(scene, ['ink'])))!;+ const next = pasteFragment(createScene(), fragment, () => 'copy').document;+ const copy = next.items.copy;+ if (copy?.type !== 'pencil') throw new Error('Missing copied pencil');+ expect(copy.geometry).toEqual(input.geometry);+ expect(Object.isFrozen(copy.geometry.points)).toBe(true);+ expect(Object.isFrozen(copy.geometry.points[0])).toBe(true);+ expect(() => freezeDocument(next)).not.toThrow();+ for (const points of [[], [[NaN, 0, 0.5]], [[0, 0, 2]], [[0, 0]]]) {+ expect(() =>+ createScene([+ {+ ...input,+ geometry: { simulatePressure: true, points },+ } as unknown as PencilItem,+ ])+ ).toThrow();+ }+});++it('syncs finalized pencil strokes and preserves remote styles through local undo', () => {+ const lab = createGraphicsPeerLab(createScene());+ try {+ lab.setConnected(false);+ const a = lab.peers[0]!.editor,+ b = lab.peers[1]!.editor;+ a.beginShape('pencil', { x: 20, y: 30 });+ a.updateDrawing([+ { x: 30, y: 50 },+ { x: 70, y: 80 },+ ]);+ expect(lab.status().pending).toBe(0);+ a.commitShape('ink', appearance);+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ b.select('ink');+ b.setSelectionAppearance({ stroke: 'blue' });+ a.beginTransform('ink', { x: 20, y: 30 });+ a.updateTransform({ x: 40, y: 60 });+ a.commitTransform();+ lab.syncNow();+ a.undo();+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ expect(a.document.items.ink).toMatchObject({+ appearance: { stroke: 'blue' },+ transform: translation(20, 30),+ });+ expect(drawableIds(a.document)).toEqual(['ink']);+ } finally {+ lab.dispose();+ }+});diff --git a/packages/graphics/tests/presence-motion.test.ts b/packages/graphics/tests/presence-motion.test.tsnew file mode 100644index 0000000000..4c72620d9c--- /dev/null+++ b/packages/graphics/tests/presence-motion.test.ts@@ -0,0 +1,109 @@+import { afterEach, expect, it, vi } from 'vitest';+import type { PeerPresence } from '../src/loro';+import { createPresenceMotion } from '../src/loro/solid/presence-motion';++const peer = (x: number): PeerPresence => ({+ id: 'alice',+ name: 'Alice',+ color: '#ffabcd',+ cursor: { x, y: 0 },+ selectedIds: [],+ clock: {},+ preview: null,+});+const dispose: (() => void)[] = [];+afterEach(() => {+ dispose.splice(0).forEach((fn) => fn());+ vi.useRealTimers();+ vi.unstubAllGlobals();+});+function setup() {+ vi.useFakeTimers();+ let rendered: PeerPresence[] = [];+ const motion = createPresenceMotion((peers) => {+ rendered = peers;+ });+ dispose.push(motion.dispose);+ return { motion, rendered: () => rendered };+}++it('springs between remote targets, retargets without jumping and stops when settled', () => {+ const { motion, rendered } = setup();+ motion.update([peer(0)]);+ motion.update([peer(100)]);+ expect(rendered()[0]!.cursor!.x).toBe(0);+ vi.advanceTimersByTime(80);+ const intermediate = rendered()[0]!.cursor!.x;+ expect(intermediate).toBeGreaterThan(0);+ expect(intermediate).toBeLessThan(100);+ motion.update([peer(200)]);+ expect(rendered()[0]!.cursor!.x).toBe(intermediate);+ vi.advanceTimersByTime(1000);+ expect(rendered()[0]!.cursor!.x).toBe(200);+ expect(vi.getTimerCount()).toBe(0);+ motion.update([peer(400)]);+ motion.update([]);+ expect(rendered()).toEqual([]);+ expect(vi.getTimerCount()).toBe(0);+});++it('interpolates rotation across the short arc without shrinking or skewing the ghost', () => {+ const { motion, rendered } = setup();+ const rotated = (degrees: number): PeerPresence => {+ const angle = (degrees * Math.PI) / 180;+ return {+ ...peer(0),+ preview: {+ kind: 'rotate',+ box: null,+ shapes: [+ {+ id: 'shape',+ kind: 'rectangle',+ width: 100,+ height: 80,+ world: [+ Math.cos(angle),+ Math.sin(angle),+ -Math.sin(angle),+ Math.cos(angle),+ 10,+ 20,+ ],+ },+ ],+ },+ };+ };+ motion.update([rotated(170)]);+ motion.update([rotated(-170)]);+ vi.advanceTimersByTime(80);+ const [a, b, c, d] = rendered()[0]!.preview!.shapes[0]!.world;+ expect(a).toBeLessThan(-0.98);+ expect(Math.hypot(a, b)).toBeCloseTo(1, 10);+ expect(a * d - b * c).toBeCloseTo(1, 10);+ // Clear while still moving; no trailing frames may resurrect the preview.+ motion.update([peer(0)]);+ expect(rendered()[0]!.preview).toBeNull();+ expect(vi.getTimerCount()).toBe(0);+});++it('honors reduced motion and cancels the frame loop on disposal', () => {+ const media = {+ matches: true,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ };+ vi.stubGlobal('matchMedia', () => media);+ const { motion, rendered } = setup();+ motion.update([peer(0)]);+ motion.update([peer(100)]);+ expect(rendered()[0]!.cursor!.x).toBe(100);+ expect(vi.getTimerCount()).toBe(0);+ media.matches = false;+ motion.update([peer(200)]);+ expect(vi.getTimerCount()).toBe(1);+ motion.dispose();+ expect(vi.getTimerCount()).toBe(0);+ expect(media.removeEventListener).toHaveBeenCalled();+});diff --git a/packages/graphics/tests/presence.test.ts b/packages/graphics/tests/presence.test.tsnew file mode 100644index 0000000000..1ba5fff38d--- /dev/null+++ b/packages/graphics/tests/presence.test.ts@@ -0,0 +1,218 @@+import { afterEach, expect, it, vi } from 'vitest';+import { createScene, translation } from '../src/core';+import { currentPresencePreview } from '../src/loro';+import type { PresencePacket } from '../src/loro/presence';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const dispose: (() => void)[] = [];+afterEach(() => {+ dispose.splice(0).forEach((fn) => fn());+ vi.useRealTimers();+});+function setup() {+ vi.useFakeTimers();+ const lab = createGraphicsPeerLab(+ createScene([+ {+ id: 'g',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(100, 100),+ },+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'g', sortKey: 'a0' },+ transform: translation(10, 20),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ {+ id: 'b',+ type: 'ellipse',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: translation(230, 40),+ geometry: { width: 70, height: 70 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ ])+ );+ dispose.push(lab.dispose);+ return { lab, a: lab.peers[0]!, b: lab.peers[1]! };+}+it('shares cursor and selection without any document update, local selection or history change', () => {+ const { lab, a, b } = setup();+ const beforeA = a.editor.document,+ beforeB = b.editor.document;+ const clock = a.backend.getClock();+ a.editor.select('g');+ a.presence.setCursor({ x: 150, y: 160 });+ vi.advanceTimersByTime(50);+ expect(b.presence.getRemote()[0]).toMatchObject({+ name: 'Alice',+ cursor: { x: 150, y: 160 },+ selectedIds: ['g'],+ preview: null,+ });+ expect(b.editor.getSession().selectedIds).toEqual([]);+ expect(a.editor.document).toBe(beforeA);+ expect(b.editor.document).toBe(beforeB);+ expect(a.backend.getClock()).toEqual(clock);+ expect(a.editor.getSession().canUndo).toBe(false);+ expect(lab.status()).toMatchObject({ pending: 0, delivered: 0 });+});+it('captures nested pending moves in world space and clears on cancel', () => {+ const { lab, a, b } = setup();+ a.editor.select('g');+ a.editor.beginTransform('g', { x: 0, y: 0 });+ a.editor.updateTransform({ x: 50, y: 30 });+ vi.advanceTimersByTime(50);+ const state = b.presence.getRemote()[0]!;+ expect(currentPresencePreview(state, b.backend.getClock())).toMatchObject({+ kind: 'move',+ shapes: [{ id: 'a', world: [1, 0, 0, 1, 160, 150] }],+ });+ expect(b.editor.document.items.g).toMatchObject({+ transform: [1, 0, 0, 1, 100, 100],+ });+ a.editor.cancelTransform();+ vi.advanceTimersByTime(50);+ expect(b.presence.getRemote()[0]!.preview).toBeNull();+ expect(lab.status().delivered).toBe(0);+});+it.each([+ 'rectangle',+ 'ellipse',+] as const)('shares a pending %s without creating a remote item', (kind) => {+ const { a, b } = setup();+ a.editor.beginShape(kind, { x: 20, y: 30 });+ a.editor.updateShape({ x: 100, y: 90 });+ vi.advanceTimersByTime(50);+ expect(b.presence.getRemote()[0]?.preview).toMatchObject({+ kind: 'draw',+ shapes: [{ kind, width: 80, height: 60, world: [1, 0, 0, 1, 20, 30] }],+ });+ expect(Object.keys(b.editor.document.items)).toHaveLength(4);+ a.editor.cancelShape();+ vi.advanceTimersByTime(50);+ expect(b.presence.getRemote()[0]?.preview).toBeNull();+});+it('shares box selection and resize/rotation action kinds', () => {+ const { a, b } = setup();+ a.editor.beginBoxSelection({ x: 0, y: 0 });+ a.editor.updateBoxSelection({ x: 300, y: 300 });+ vi.advanceTimersByTime(50);+ expect(b.presence.getRemote()[0]?.preview).toMatchObject({+ kind: 'marquee',+ box: { x: 0, y: 0, width: 300, height: 300 },+ });+ a.editor.cancelTransform();+ a.editor.select('b');+ a.editor.beginTransform('b', { x: 300, y: 110 }, 'se');+ a.editor.updateTransform({ x: 320, y: 130 });+ vi.advanceTimersByTime(50);+ expect(b.presence.getRemote()[0]?.preview?.kind).toBe('resize');+ a.editor.cancelTransform();+ a.editor.beginTransform('b', { x: 265, y: 0 }, 'rotate');+ a.editor.updateTransform({ x: 400, y: 75 });+ vi.advanceTimersByTime(50);+ expect(b.presence.getRemote()[0]?.preview?.kind).toBe('rotate');+});+it('coalesces pending presence and drops it while offline instead of replaying a gesture', () => {+ const { lab, a, b } = setup();+ lab.setLatency(500);+ a.editor.select('a');+ a.editor.beginTransform('a', { x: 0, y: 0 });+ for (let i = 0; i < 100; i++) {+ a.editor.updateTransform({ x: i, y: 0 });+ a.presence.setCursor({ x: i, y: 0 });+ }+ a.editor.cancelTransform();+ vi.advanceTimersByTime(500);+ expect(b.presence.getRemote()[0]).toMatchObject({+ cursor: { x: 99, y: 0 },+ preview: null,+ });+ lab.setConnected(false);+ expect(b.presence.getRemote()).toEqual([]);+ a.editor.beginTransform('a', { x: 0, y: 0 });+ a.editor.updateTransform({ x: 300, y: 0 });+ vi.advanceTimersByTime(1000);+ expect(b.presence.getRemote()).toEqual([]);+ a.editor.cancelTransform();+ lab.syncNow();+ expect(b.presence.getRemote()).toEqual([]);+ lab.setConnected(true);+ vi.advanceTimersByTime(500);+ expect(b.presence.getRemote()[0]?.preview).toBeNull();+});+it('rejects a delayed preview after the committed document advances', () => {+ const { lab, a, b } = setup();+ a.editor.select('a');+ a.editor.beginTransform('a', { x: 0, y: 0 });+ a.editor.updateTransform({ x: 50, y: 0 });+ vi.advanceTimersByTime(50);+ const pending = b.presence.getRemote()[0]!;+ expect(currentPresencePreview(pending, b.backend.getClock())).not.toBeNull();+ a.editor.commitTransform();+ lab.syncNow();+ expect(currentPresencePreview(pending, b.backend.getClock())).toBeNull();+ expect(b.presence.getRemote()[0]?.preview).toBeNull();+ expect(a.editor.getSession().canUndo).toBe(true);+ expect(b.editor.getSession().canUndo).toBe(false);+});+it('ignores duplicated/out-of-order presence packets', () => {+ const { a, b } = setup();+ const packets: PresencePacket[] = [];+ a.presence.subscribeUpdates((packet) => packets.push(packet));+ a.presence.setCursor({ x: 10, y: 10 });+ a.presence.publish();+ a.presence.setCursor(null);+ b.presence.receive(packets[1]!);+ b.presence.receive(packets[0]!);+ b.presence.receive(packets[1]!);+ expect(b.presence.getRemote()[0]?.cursor).toBeNull();+});+it('debounces capture and encoding with a maximum wait during continuous movement', () => {+ const { a } = setup();+ const send = vi.fn();+ a.presence.subscribeUpdates(send);+ a.presence.setCursor({ x: 1, y: 0 });+ vi.advanceTimersByTime(30);+ a.presence.setCursor({ x: 2, y: 0 });+ vi.advanceTimersByTime(39);+ expect(send).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(send).toHaveBeenCalledTimes(1);+ send.mockClear();+ for (let i = 0; i < 10; i++) {+ a.presence.setCursor({ x: i, y: 0 });+ vi.advanceTimersByTime(10);+ }+ expect(send).toHaveBeenCalledTimes(1);+ a.presence.setCursor({ x: 99, y: 0 });+ a.presence.setCursor(null);+ expect(send).toHaveBeenCalledTimes(2);+ vi.advanceTimersByTime(100);+ expect(send).toHaveBeenCalledTimes(2);+});+it('cleans up all heartbeat, transport and expiry timers', () => {+ const { lab, a, b } = setup();+ a.presence.setCursor({ x: 1, y: 2 });+ vi.advanceTimersByTime(50);+ expect(b.presence.getRemote()).toHaveLength(1);+ lab.dispose();+ expect(vi.getTimerCount()).toBe(0);+ a.presence.setCursor({ x: 3, y: 4 });+ expect(b.presence.getRemote()).toEqual([]);+});++it('expires an absent peer while heartbeats retain an idle connected selection', () => {+ const { a, b } = setup();+ a.editor.select('a');+ vi.advanceTimersByTime(61_000);+ expect(b.presence.getRemote()[0]?.selectedIds).toEqual(['a']);+ a.presence.dispose();+ vi.advanceTimersByTime(46_000);+ expect(b.presence.getRemote()).toEqual([]);+});diff --git a/packages/graphics/tests/rectangle.test.ts b/packages/graphics/tests/rectangle.test.tsnew file mode 100644index 0000000000..94381b92a1--- /dev/null+++ b/packages/graphics/tests/rectangle.test.ts@@ -0,0 +1,78 @@+import { expect, it, vi } from 'vitest';+import {+ createGraphicsEditor,+ fitImageCamera,+ screenToWorld,+} from '../src/core';+import { drawableIds, worldBounds } from '../src/core/scene';++const appearance = { fill: 'transparent', stroke: '#e53935' };++it('keeps reversed drags in image coordinates and commits exactly one change', () => {+ const editor = createGraphicsEditor();+ editor.setImageSurface({ id: 'image', width: 800, height: 600 });+ editor.fitImage({ width: 448, height: 348 });+ const changed = vi.fn();+ editor.subscribeDocument(changed);+ const camera = editor.getCamera();+ editor.beginRectangle(screenToWorld(camera, { x: 224, y: 174 }));+ editor.updateRectangle(screenToWorld(camera, { x: 74, y: 74 }));+ expect(editor.getPreview()).toEqual({+ x: 100,+ y: 100,+ width: 300,+ height: 200,+ });+ expect(drawableIds(editor.document)).toHaveLength(0);+ expect(changed).not.toHaveBeenCalled();+ expect(editor.commitRectangle('rect', appearance)).toBe(true);+ expect(worldBounds(editor.document, 'rect')).toEqual({+ x: 100,+ y: 100,+ width: 300,+ height: 200,+ });+ expect(changed).toHaveBeenCalledTimes(1);+ editor.panBy({ x: 100, y: -200 });+ editor.zoomAt({ x: 100, y: 100 }, 2);+ expect(worldBounds(editor.document, 'rect').x).toBe(100);+});++it('rejects starts outside the image, clips ends and drops cancelled or tiny rectangles', () => {+ const editor = createGraphicsEditor();+ editor.setImageSurface({ id: 'image', width: 100, height: 80 });+ expect(editor.beginRectangle({ x: -1, y: 0 })).toBe(false);+ editor.beginRectangle({ x: 50, y: 50 });+ editor.updateRectangle({ x: 200, y: 200 });+ expect(editor.getPreview()).toEqual({ x: 50, y: 50, width: 50, height: 30 });+ editor.cancelRectangle();+ expect(editor.commitRectangle('cancelled', appearance)).toBe(false);+ editor.beginRectangle({ x: 50, y: 50 });+ editor.updateRectangle({ x: 51, y: 51 });+ expect(editor.commitRectangle('tiny', appearance, 3)).toBe(false);+ expect(drawableIds(editor.document)).toHaveLength(0);+});++it('clears previews and annotations when replacing the image', () => {+ const editor = createGraphicsEditor();+ editor.setImageSurface({ id: 'first', width: 100, height: 80 });+ editor.beginRectangle({ x: 10, y: 10 });+ editor.updateRectangle({ x: 60, y: 60 });+ editor.commitRectangle('one', appearance);+ editor.beginRectangle({ x: 20, y: 20 });+ editor.setImageSurface({ id: 'second', width: 200, height: 100 });+ expect(drawableIds(editor.document)).toHaveLength(0);+ expect(editor.getPreview()).toBeUndefined();+ expect(editor.document.surface?.id).toBe('second');+});++it('fits large images and preserves their aspect ratio in narrow viewports', () => {+ const camera = fitImageCamera(+ { width: 4000, height: 3000 },+ { width: 300, height: 200 }+ );+ expect(camera.scale * 4000).toBeLessThan(300);+ expect(camera.scale * 3000).toBeLessThan(200);+ expect(camera.x).toBeGreaterThan(0);+ expect(camera.y).toBeGreaterThan(0);+});diff --git a/packages/graphics/tests/resize-inversion.test.ts b/packages/graphics/tests/resize-inversion.test.tsnew file mode 100644index 0000000000..1674a07c6d--- /dev/null+++ b/packages/graphics/tests/resize-inversion.test.ts@@ -0,0 +1,158 @@+import { expect, it } from 'vitest';+import {+ around,+ createGraphicsEditor,+ createScene,+ freezeDocument,+ inverse,+ multiply,+ nodeCorners,+ type Point,+ rotation,+ scaling,+ selectionFrame,+ transformPoint,+ translation,+} from '../src/core';++const fixture = (layout: string) =>+ createScene([+ ...(layout === 'group' || layout === 'nested'+ ? [+ {+ id: 'g',+ type: 'group' as const,+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: rotation(layout === 'nested' ? 0.4 : 0),+ },+ ]+ : []),+ ...['a', 'b'].map((id, i) => ({+ id,+ type: 'rectangle' as const,+ placement: {+ parentId:+ layout === 'group' || layout === 'nested' ? 'g' : 'scene-root',+ sortKey: `a${i}`,+ },+ transform: translation(20 + i * 200, 30 + i * 120),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'red', stroke: 'black' },+ })),+ ]);+const closePoint = (a: Point, b: Point) => {+ expect(a.x).toBeCloseTo(b.x, 7);+ expect(a.y).toBeCloseTo(b.y, 7);+};++it.each([+ 'single',+ 'multi',+ 'group',+ 'nested',+])('resizes %s through zero, reflects its contents and undoes in one step', (layout) => {+ for (const handle of ['n', 'e', 's', 'w'] as const) {+ const editor = createGraphicsEditor(fixture(layout));+ const ids =+ layout === 'single' ? ['a'] : layout === 'multi' ? ['a', 'b'] : ['g'];+ editor.select(ids[0]);+ if (ids.length === 2) editor.toggleSelection('b');+ const before = editor.document;+ const frame = selectionFrame(before, ids)!;+ const b = frame.bounds;+ const horizontal = handle === 'e' || handle === 'w';+ const negative = handle === 'n' || handle === 'w';+ const start = {+ x: horizontal ? b.x + (negative ? 0 : b.width) : b.x + b.width / 2,+ y: horizontal ? b.y + b.height / 2 : b.y + (negative ? 0 : b.height),+ };+ const anchor = {+ x: horizontal ? b.x + (negative ? b.width : 0) : start.x,+ y: horizontal ? start.y : b.y + (negative ? b.height : 0),+ };+ const end = {+ x: start.x + (horizontal ? (negative ? 1 : -1) * b.width * 1.5 : 0),+ y: start.y + (horizontal ? 0 : (negative ? 1 : -1) * b.height * 1.5),+ };+ editor.beginTransform(+ ids[0]!,+ transformPoint(frame.transform, start),+ handle+ );+ // The exact crossing remains finite and can be validated as scene data.+ editor.updateTransform(transformPoint(frame.transform, anchor));+ expect(() =>+ freezeDocument({+ ...before,+ items: { ...before.items, ...editor.getSession().transform!.nodes },+ })+ ).not.toThrow();+ editor.updateTransform(transformPoint(frame.transform, end));+ const nodes = editor.getSession().transform!.nodes;+ const inactive = frame.canDeform ? 1 : 0.5;+ const delta = multiply(+ frame.transform,+ multiply(+ around(+ anchor,+ scaling(horizontal ? -0.5 : inactive, horizontal ? inactive : -0.5)+ ),+ inverse(frame.transform)+ )+ );+ for (const id of layout === 'single' ? ['a'] : ['a', 'b']) {+ const original = nodeCorners(before, id);+ nodeCorners(before, id, nodes).forEach((point, i) =>+ closePoint(point, transformPoint(delta, original[i]!))+ );+ }+ expect(editor.document).toBe(before);+ editor.updateTransform(transformPoint(frame.transform, start));+ nodeCorners(before, 'a', editor.getSession().transform!.nodes).forEach(+ (point, i) => closePoint(point, nodeCorners(before, 'a')[i]!)+ );+ editor.updateTransform(transformPoint(frame.transform, end));+ editor.commitTransform();+ const after = editor.document;+ editor.undo();+ expect(editor.document).toEqual(before);+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ expect(editor.document).toEqual(after);+ editor.dispose();+ }+});++it.each([+ 'single',+ 'multi',+ 'group',+])('keeps centered proportional corner flips stable for %s when modifiers change', (layout) => {+ const editor = createGraphicsEditor(fixture(layout));+ const ids =+ layout === 'single' ? ['a'] : layout === 'multi' ? ['a', 'b'] : ['g'];+ editor.select(ids[0]);+ if (ids.length === 2) editor.toggleSelection('b');+ const before = editor.document;+ const frame = selectionFrame(before, ids)!;+ const b = frame.bounds;+ const start = frame.corners[2]!;+ editor.beginTransform(ids[0]!, start, 'se');+ const end = { x: start.x - b.width, y: start.y - b.height * 0.8 };+ editor.updateTransform(end, { proportional: true, fromCenter: true });+ const delta = around(frame.center, scaling(-1, -1));+ nodeCorners(before, 'a', editor.getSession().transform!.nodes).forEach(+ (point, i) =>+ closePoint(point, transformPoint(delta, nodeCorners(before, 'a')[i]!))+ );+ editor.updateTransform(end, { fromCenter: true });+ editor.updateTransform(end, { proportional: true, fromCenter: true });+ nodeCorners(before, 'a', editor.getSession().transform!.nodes).forEach(+ (point, i) =>+ closePoint(point, transformPoint(delta, nodeCorners(before, 'a')[i]!))+ );+ editor.cancelTransform();+ expect(editor.document).toBe(before);+ expect(editor.getSession().canUndo).toBe(false);+ editor.dispose();+});diff --git a/packages/graphics/tests/resize-modifiers.test.ts b/packages/graphics/tests/resize-modifiers.test.tsnew file mode 100644index 0000000000..ef732a29d1--- /dev/null+++ b/packages/graphics/tests/resize-modifiers.test.ts@@ -0,0 +1,235 @@+import { expect, it, vi } from 'vitest';+import { attachCameraControls } from '../src/browser';+import {+ createGraphicsEditor,+ multiply,+ type Point,+ rotation,+ type ShapeKind,+ scaling,+ transformPoint,+ translation,+ worldBounds,+ worldMatrix,+} from '../src/core';++const closePoint = (a: Point, b: Point) => {+ expect(a.x).toBeCloseTo(b.x, 8);+ expect(a.y).toBeCloseTo(b.y, 8);+};+const nestedEditor = (kind: ShapeKind) =>+ createGraphicsEditor([+ {+ id: 'parent',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(+ translation(100, 80),+ multiply(rotation(0.4), scaling(1.8, 0.7))+ ),+ },+ {+ id: 'shape',+ ...(kind === 'rectangle'+ ? { type: 'rectangle' as const }+ : { type: 'ellipse' as const }),+ placement: { parentId: 'parent', sortKey: 'a0' },+ transform: multiply(translation(40, 50), rotation(-0.6)),+ geometry: { width: 200, height: 100 },+ appearance: { fill: 'transparent', stroke: 'black' },+ },+ ]);++it.each([+ 'rectangle',+ 'ellipse',+] as const)('keeps the opposite corner fixed and preserves aspect ratio for a nested %s', (kind) => {+ for (const corner of ['nw', 'ne', 'sw', 'se'] as const) {+ const editor = nestedEditor(kind);+ const before = editor.document;+ const world = worldMatrix(before, 'shape');+ const west = corner.endsWith('w'),+ north = corner.startsWith('n');+ const origin = { x: (west ? 0 : 200) + 3, y: (north ? 0 : 100) - 2 };+ const fixed = transformPoint(world, {+ x: west ? 200 : 0,+ y: north ? 100 : 0,+ });+ editor.beginTransform('shape', transformPoint(world, origin), corner);+ editor.updateTransform(+ transformPoint(world, {+ x: origin.x + (west ? -80 : 80),+ y: origin.y + (north ? -10 : 10),+ }),+ { proportional: true }+ );+ expect(editor.document).toBe(before);+ const overrides = editor.getSession().transform?.nodes;+ expect(overrides?.shape).toMatchObject({+ geometry: { width: 280, height: 140 },+ });+ closePoint(+ transformPoint(worldMatrix(before, 'shape', overrides), {+ x: west ? 280 : 0,+ y: north ? 140 : 0,+ }),+ fixed+ );+ editor.commitTransform();+ editor.undo();+ expect(editor.document).toEqual(before);+ }+});++it.each([+ false,+ true,+])('holds the original center with proportional=%s through nested transforms', (proportional) => {+ const editor = nestedEditor('ellipse');+ const world = worldMatrix(editor.document, 'shape');+ const center = transformPoint(world, { x: 100, y: 50 });+ editor.beginTransform(+ 'shape',+ transformPoint(world, { x: 200, y: 100 }),+ 'se'+ );+ editor.updateTransform(transformPoint(world, { x: 230, y: 90 }), {+ fromCenter: true,+ proportional,+ });+ const nodes = editor.getSession().transform?.nodes;+ const expectedHeight = proportional ? 130 : 80;+ const previewShape = nodes?.shape;+ if (previewShape?.type !== 'ellipse')+ throw new Error('Missing ellipse preview');+ expect(previewShape.geometry.width).toBeCloseTo(260, 8);+ expect(previewShape.geometry.height).toBeCloseTo(expectedHeight, 8);+ closePoint(+ transformPoint(worldMatrix(editor.document, 'shape', nodes), {+ x: 130,+ y: expectedHeight / 2,+ }),+ center+ );+ editor.cancelTransform();+ expect(editor.getSession().canUndo).toBe(false);+});++it('scales a mixed selection around its collective center in one undo step', () => {+ const editor = createGraphicsEditor([+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(0, 0),+ geometry: { width: 100, height: 100 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ {+ id: 'b',+ type: 'ellipse',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: translation(200, 0),+ geometry: { width: 100, height: 100 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ ]);+ const before = editor.document;+ editor.select('a');+ editor.toggleSelection('b');+ editor.beginTransform('a', { x: 300, y: 100 }, 'se');+ editor.updateTransform(+ { x: 330, y: 105 },+ { fromCenter: true, proportional: true }+ );+ editor.commitTransform();+ const bounds = worldBounds(editor.document, editor.document.rootId);+ closePoint(+ { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 },+ { x: 150, y: 50 }+ );+ expect(bounds.width).toBeCloseTo(360);+ expect(bounds.height).toBeCloseTo(120);+ editor.undo();+ expect(editor.document).toEqual(before);+});++it('updates modifiers at a stationary pointer and uses the final pointer-up modifiers', () => {+ const editor = createGraphicsEditor([+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(20, 20),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ ]);+ const viewport = document.createElement('div');+ document.body.append(viewport);+ const handle = document.createElement('div');+ handle.dataset.graphicsHandle = 'se';+ viewport.append(handle);+ viewport.setPointerCapture = vi.fn();+ viewport.hasPointerCapture = () => false;+ const detach = attachCameraControls(viewport, editor, {+ tool: () => 'select',+ editing: true,+ });+ editor.select('a');+ const changed = vi.fn();+ editor.subscribeDocument(changed);+ const pointer = (+ target: HTMLElement,+ type: string,+ x: number,+ y: number,+ modifiers = {}+ ) => {+ const event = new MouseEvent(type, {+ bubbles: true,+ cancelable: true,+ button: 0,+ clientX: x,+ clientY: y,+ ...modifiers,+ });+ Object.defineProperty(event, 'pointerId', { value: 1 });+ target.dispatchEvent(event);+ };+ const key = (type: string, key: string, shiftKey: boolean, altKey: boolean) =>+ viewport.dispatchEvent(+ new KeyboardEvent(type, {+ key,+ shiftKey,+ altKey,+ bubbles: true,+ cancelable: true,+ })+ );+ const geometry = () => editor.getSession().transform?.nodes.a;+ pointer(handle, 'pointerdown', 120, 100, { shiftKey: true, altKey: true });+ expect(editor.getSession().selectedIds).toEqual(['a']);+ pointer(viewport, 'pointermove', 150, 110);+ expect(geometry()).toMatchObject({ geometry: { width: 130, height: 90 } });+ key('keydown', 'Shift', true, false);+ expect(geometry()).toMatchObject({ geometry: { width: 130, height: 104 } });+ key('keydown', 'Alt', true, true);+ expect(geometry()).toMatchObject({ geometry: { width: 160, height: 128 } });+ key('keyup', 'Shift', false, true);+ expect(geometry()).toMatchObject({ geometry: { width: 160, height: 100 } });+ key('keyup', 'Alt', false, false);+ expect(geometry()).toMatchObject({ geometry: { width: 130, height: 90 } });+ expect(changed).not.toHaveBeenCalled();+ pointer(viewport, 'pointerup', 150, 110, { shiftKey: true, altKey: true });+ expect(changed).toHaveBeenCalledTimes(1);+ expect(editor.document.items.a).toMatchObject({+ geometry: { width: 160, height: 128 },+ });+ closePoint(+ transformPoint(worldMatrix(editor.document, 'a'), { x: 80, y: 64 }),+ { x: 70, y: 60 }+ );+ detach();+ viewport.remove();+});diff --git a/packages/graphics/tests/rotation.test.ts b/packages/graphics/tests/rotation.test.tsnew file mode 100644index 0000000000..e40de584ad--- /dev/null+++ b/packages/graphics/tests/rotation.test.ts@@ -0,0 +1,171 @@+import { expect, it, vi } from 'vitest';+import { attachCameraControls } from '../src/browser';+import {+ createGraphicsEditor,+ multiply,+ type Point,+ rotation,+ scaling,+ translation,+ worldBounds,+ worldMatrix,+} from '../src/core';++const radians = (degrees: number) => (degrees * Math.PI) / 180;+const pointerAt = (pivot: Point, degrees: number) => ({+ x: pivot.x + 100 * Math.sin(radians(degrees)),+ y: pivot.y - 100 * Math.cos(radians(degrees)),+});+const angle = (matrix: readonly number[]) =>+ (Math.atan2(matrix[1]!, matrix[0]!) * 180) / Math.PI;++it.each([+ 1, -1,+])('snaps nested shapes and groups to absolute world angles in direction %s', (direction) => {+ for (const id of ['shape', 'parent']) {+ const editor = createGraphicsEditor([+ {+ id: 'parent',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(+ translation(100, 80),+ multiply(rotation(radians(23 * direction)), scaling(1.6, 0.8))+ ),+ },+ {+ id: 'shape',+ type: 'rectangle',+ placement: { parentId: 'parent', sortKey: 'a0' },+ transform: multiply(+ translation(40, 50),+ rotation(radians(-12 * direction))+ ),+ geometry: { width: 200, height: 100 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ ]);+ const before = editor.document;+ const bounds = worldBounds(before, id);+ const pivot = {+ x: bounds.x + bounds.width / 2,+ y: bounds.y + bounds.height / 2,+ };+ editor.beginTransform(id, pointerAt(pivot, 0), 'rotate');+ editor.updateTransform(pointerAt(pivot, 11 * direction), {+ snapRotation: true,+ });+ expect(editor.document).toBe(before);+ const nodes = editor.getSession().transform?.nodes;+ expect(angle(worldMatrix(before, id, nodes))).toBeCloseTo(30 * direction);+ const preview = worldBounds(before, id, nodes);+ expect(preview.x + preview.width / 2).toBeCloseTo(pivot.x);+ expect(preview.y + preview.height / 2).toBeCloseTo(pivot.y);+ editor.commitTransform();+ editor.undo();+ expect(editor.document).toEqual(before);+ expect(editor.getSession().canUndo).toBe(false);+ }+});++it('snaps a multiselection as a whole while retaining relative angles', () => {+ const editor = createGraphicsEditor(+ [17, -23].map((degrees, index) => ({+ id: String(index),+ type: 'rectangle' as const,+ placement: { parentId: 'scene-root', sortKey: `a${index}` },+ transform: multiply(+ translation(index * 200, 0),+ rotation(radians(degrees))+ ),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'red', stroke: 'black' },+ }))+ );+ editor.select('0');+ editor.toggleSelection('1');+ const bounds = worldBounds(editor.document, editor.document.rootId);+ const pivot = {+ x: bounds.x + bounds.width / 2,+ y: bounds.y + bounds.height / 2,+ };+ editor.beginTransform('0', pointerAt(pivot, 0), 'rotate');+ editor.updateTransform(pointerAt(pivot, 41), { snapRotation: true });+ const nodes = editor.getSession().transform?.nodes;+ expect(angle(worldMatrix(editor.document, '0', nodes))).toBeCloseTo(47);+ expect(angle(worldMatrix(editor.document, '1', nodes))).toBeCloseTo(7);+ editor.updateTransform(pointerAt(pivot, 41));+ expect(+ angle(+ worldMatrix(editor.document, '0', editor.getSession().transform?.nodes)+ )+ ).toBeCloseTo(58);+ editor.cancelTransform();+ expect(editor.getSession().canUndo).toBe(false);+});++it('updates rotation snapping on stationary Shift changes and commits pointer-up modifiers once', () => {+ const editor = createGraphicsEditor([+ {+ id: 'shape',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(20, 20),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ ]);+ const viewport = document.createElement('div');+ document.body.append(viewport);+ const handle = document.createElement('div');+ handle.dataset.graphicsHandle = 'rotate';+ viewport.append(handle);+ viewport.setPointerCapture = vi.fn();+ viewport.hasPointerCapture = () => false;+ const detach = attachCameraControls(viewport, editor, {+ tool: () => 'select',+ });+ editor.select('shape');+ const changed = vi.fn();+ editor.subscribeDocument(changed);+ const pointer = (+ target: HTMLElement,+ type: string,+ degrees: number,+ shiftKey = false+ ) => {+ const point = pointerAt({ x: 70, y: 60 }, degrees);+ const event = new MouseEvent(type, {+ bubbles: true,+ button: 0,+ clientX: point.x,+ clientY: point.y,+ shiftKey,+ });+ Object.defineProperty(event, 'pointerId', { value: 1 });+ target.dispatchEvent(event);+ };+ const previewAngle = () =>+ angle(+ worldMatrix(+ editor.document,+ 'shape',+ editor.getSession().transform?.nodes+ )+ );+ pointer(handle, 'pointerdown', 0);+ pointer(viewport, 'pointermove', 41, true);+ expect(previewAngle()).toBeCloseTo(30);+ viewport.dispatchEvent(new KeyboardEvent('keyup', { key: 'Shift' }));+ expect(previewAngle()).toBeCloseTo(41);+ viewport.dispatchEvent(+ new KeyboardEvent('keydown', { key: 'Shift', shiftKey: true })+ );+ expect(previewAngle()).toBeCloseTo(30);+ expect(changed).not.toHaveBeenCalled();+ pointer(viewport, 'pointerup', 79, true);+ expect(angle(worldMatrix(editor.document, 'shape'))).toBeCloseTo(90);+ expect(changed).toHaveBeenCalledTimes(1);+ detach();+ viewport.remove();+});diff --git a/packages/graphics/tests/scene.test.ts b/packages/graphics/tests/scene.test.tsnew file mode 100644index 0000000000..22703e8678--- /dev/null+++ b/packages/graphics/tests/scene.test.ts@@ -0,0 +1,370 @@+import { describe, expect, it } from 'vitest';+import {+ around,+ boxHits,+ children,+ createGraphicsEditor,+ createScene,+ deleteSubtrees,+ freezeDocument,+ type GraphicsDocument,+ type GraphicsItem,+ groupNodes,+ hitTest,+ IDENTITY,+ inverse,+ type Matrix,+ multiply,+ nodeCorners,+ reparent,+ roots,+ rotation,+ scaling,+ selectionFrame,+ transformPoint,+ translation,+ ungroupNode,+ worldBounds,+ worldMatrix,+} from '../src/core';++const closeMatrix = (a: Matrix, b: Matrix) =>+ a.forEach((v, i) => expect(v).toBeCloseTo(b[i] ?? 0, 8));+const fixture = (): GraphicsDocument =>+ createScene([+ {+ id: 'outer',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(+ translation(100, 80),+ multiply(rotation(0.4), scaling(1.6, 0.7))+ ),+ },+ {+ id: 'inner',+ type: 'group',+ placement: { parentId: 'outer', sortKey: 'a0' },+ transform: multiply(translation(50, 30), rotation(-0.7)),+ },+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'inner', sortKey: 'a0' },+ transform: translation(10, 20),+ geometry: { width: 80, height: 50 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ {+ id: 'b',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: translation(400, 100),+ geometry: { width: 70, height: 40 },+ appearance: { fill: 'blue', stroke: 'black' },+ },+ ]);+describe('scene foundation', () => {+ it('composes and inverts nested affine transforms including reflection and shear', () => {+ const matrix = multiply(+ translation(70, -80),+ multiply(rotation(0.7), multiply(scaling(-2, 0.3), rotation(-0.4)))+ );+ const point = { x: 31, y: -29 };+ const back = transformPoint(inverse(matrix), transformPoint(matrix, point));+ expect(back.x).toBeCloseTo(point.x);+ expect(back.y).toBeCloseTo(point.y);+ closeMatrix(multiply(matrix, inverse(matrix)), IDENTITY);+ expect(() => inverse(scaling(0, 1))).toThrow();+ expect(() => inverse(translation(Infinity, 0))).toThrow();+ });+ it('preserves world pose when reparenting and rejects cycles without partial edits', () => {+ const doc = fixture(),+ before = worldMatrix(doc, 'a');+ const moved = reparent(doc, 'a', 'scene-root', 'front');+ closeMatrix(worldMatrix(moved, 'a'), before);+ expect(children(moved, 'inner')).toEqual([]);+ expect(() => reparent(doc, 'outer', 'inner', 'front')).toThrow();+ expect(children(doc, 'inner')).toEqual(['a']);+ expect(() => reparent(doc, 'a', 'b', 'front')).toThrow();+ });+ it('groups and ungroups preserving geometry, order and identity', () => {+ const doc = createScene([+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(10, 10),+ geometry: { width: 20, height: 20 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ {+ id: 'b',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: translation(50, 10),+ geometry: { width: 20, height: 20 },+ appearance: { fill: 'blue', stroke: 'black' },+ },+ ]);+ const grouped = groupNodes(doc, ['b', 'a'], 'g');+ expect(children(grouped)).toEqual(['g']);+ expect(children(grouped, 'g')).toEqual(['a', 'b']);+ closeMatrix(worldMatrix(grouped, 'a'), worldMatrix(doc, 'a'));+ const ungrouped = ungroupNode(grouped, 'g');+ expect(children(ungrouped)).toEqual(['a', 'b']);+ closeMatrix(worldMatrix(ungrouped, 'b'), worldMatrix(doc, 'b'));+ });+ it('normalizes selected roots and removes subtrees atomically with undo', () => {+ const editor = createGraphicsEditor(fixture());+ editor.select('outer');+ editor.toggleSelection('a');+ expect(roots(editor.document, editor.getSession().selectedIds)).toEqual([+ 'outer',+ ]);+ const before = worldMatrix(editor.document, 'a');+ editor.beginTransform('outer', { x: 0, y: 0 });+ editor.updateTransform({ x: 30, y: 10 });+ editor.commitTransform();+ closeMatrix(+ worldMatrix(editor.document, 'a'),+ multiply(translation(30, 10), before)+ );+ editor.undo();+ closeMatrix(worldMatrix(editor.document, 'a'), before);+ editor.deleteSelection();+ expect(editor.document.items.a).toBeUndefined();+ editor.undo();+ closeMatrix(worldMatrix(editor.document, 'a'), before);+ expect(deleteSubtrees(fixture(), ['inner']).items.outer).toBeDefined();+ });+ it('moves nodes under different parents in world space and rotates a nested subtree in one undo step', () => {+ const editor = createGraphicsEditor(fixture());+ editor.select('a');+ editor.toggleSelection('b');+ const a = worldMatrix(editor.document, 'a'),+ b = worldMatrix(editor.document, 'b');+ editor.beginTransform('a', { x: 0, y: 0 });+ editor.updateTransform({ x: 20, y: -10 });+ editor.commitTransform();+ closeMatrix(+ worldMatrix(editor.document, 'a'),+ multiply(translation(20, -10), a)+ );+ closeMatrix(+ worldMatrix(editor.document, 'b'),+ multiply(translation(20, -10), b)+ );+ editor.undo();+ editor.select('inner');+ const bounds = worldBounds(editor.document, 'inner');+ const pivot = {+ x: bounds.x + bounds.width / 2,+ y: bounds.y + bounds.height / 2,+ };+ editor.beginTransform('inner', { x: pivot.x + 100, y: pivot.y }, 'rotate');+ editor.updateTransform({ x: pivot.x, y: pivot.y + 100 });+ expect(editor.document.items.inner).toEqual(fixture().items.inner);+ editor.commitTransform();+ closeMatrix(+ worldMatrix(editor.document, 'a'),+ multiply(around(pivot, rotation(Math.PI / 2)), a)+ );+ editor.undo();+ closeMatrix(worldMatrix(editor.document, 'a'), a);+ expect(editor.getSession().canUndo).toBe(false);+ });+ it('keeps the opposite corner fixed while resizing under rotated and scaled ancestors', () => {+ const editor = createGraphicsEditor(fixture());+ const node = editor.document.items.a;+ if (node?.type !== 'rectangle') throw new Error('fixture');+ const world = worldMatrix(editor.document, 'a');+ const start = transformPoint(world, {+ x: node.geometry.width,+ y: node.geometry.height,+ });+ const end = transformPoint(world, { x: 120, y: 90 });+ editor.select('a');+ editor.beginTransform('a', start, 'se');+ editor.updateTransform(end);+ editor.commitTransform();+ closeMatrix(worldMatrix(editor.document, 'a'), world);+ const resized = editor.document.items.a;+ if (resized?.type !== 'rectangle') throw new Error('fixture');+ expect(resized.geometry.width).toBeCloseTo(120);+ expect(resized.geometry.height).toBeCloseTo(90);+ editor.undo();+ closeMatrix(worldMatrix(editor.document, 'a'), world);+ });+ it('hit tests actual transformed polygons instead of enclosing bounds', () => {+ const node: GraphicsItem = {+ id: 'r',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: rotation(Math.PI / 4),+ geometry: { width: 100, height: 100 },+ appearance: { fill: 'red', stroke: 'black' },+ };+ const doc = createScene([node]);+ expect(hitTest(doc, { x: -60, y: 5 })).toBeUndefined();+ expect(boxHits(doc, { x: -65, y: 0, width: 5, height: 5 })).toEqual([]);+ expect(hitTest(doc, { x: 0, y: 50 })).toBe('r');+ expect(boxHits(doc, { x: -2, y: 48, width: 4, height: 4 })).toEqual(['r']);+ const nested = fixture(),+ center = transformPoint(worldMatrix(nested, 'a'), { x: 40, y: 25 });+ expect(hitTest(nested, center)).toBe('outer');+ expect(hitTest(nested, center, true)).toBe('a');+ expect(nodeCorners(nested, 'a')).toHaveLength(4);+ });+ it('rejects invalid roots, placements and transforms before history changes', () => {+ const doc = fixture(),+ node = doc.items.b;+ if (node?.type !== 'rectangle') throw new Error('fixture');+ expect(() =>+ freezeDocument({+ ...doc,+ items: { ...doc.items, b: { ...node, transform: scaling(0) } },+ })+ ).toThrow();+ expect(() =>+ freezeDocument({+ ...doc,+ items: {+ ...doc.items,+ b: { ...node, placement: { parentId: 'missing', sortKey: 'a0' } },+ },+ })+ ).toThrow();+ const editor = createGraphicsEditor(doc);+ expect(() => editor.reparent('outer', 'inner', 'front')).toThrow();+ expect(editor.getSession().canUndo).toBe(false);+ });+});++it('scales a mixed-parent selection around the opposite corner and commits one undo step', () => {+ const editor = createGraphicsEditor(fixture());+ editor.select('a');+ editor.toggleSelection('b');+ const originalA = worldMatrix(editor.document, 'a'),+ originalB = worldMatrix(editor.document, 'b');+ const a = worldBounds(editor.document, 'a'),+ b = worldBounds(editor.document, 'b');+ const left = Math.min(a.x, b.x),+ top = Math.min(a.y, b.y);+ const right = Math.max(a.x + a.width, b.x + b.width),+ bottom = Math.max(a.y + a.height, b.y + b.height);+ const start = { x: right, y: bottom },+ end = { x: right + (right - left), y: bottom + (bottom - top) * 0.5 };+ editor.beginTransform('a', start, 'se');+ editor.updateTransform(end);+ expect(editor.getSession().transform?.kind).toBe('scale');+ closeMatrix(worldMatrix(editor.document, 'a'), originalA);+ editor.commitTransform();+ const delta = around({ x: left, y: top }, scaling(2));+ closeMatrix(worldMatrix(editor.document, 'a'), multiply(delta, originalA));+ closeMatrix(worldMatrix(editor.document, 'b'), multiply(delta, originalB));+ editor.undo();+ closeMatrix(worldMatrix(editor.document, 'a'), originalA);+ closeMatrix(worldMatrix(editor.document, 'b'), originalB);+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ closeMatrix(worldMatrix(editor.document, 'a'), multiply(delta, originalA));+});++it('scales a selected subtree once, preserves the opposite anchor and supports cancellation', () => {+ for (const corner of ['nw', 'ne', 'sw', 'se'] as const) {+ const editor = createGraphicsEditor(fixture());+ editor.select('outer');+ editor.toggleSelection('a');+ const before = worldMatrix(editor.document, 'a'),+ frame = selectionFrame(editor.document, ['outer'])!,+ bounds = frame.bounds;+ const west = corner.endsWith('w'),+ north = corner.startsWith('n');+ const start = {+ x: west ? bounds.x : bounds.x + bounds.width,+ y: north ? bounds.y : bounds.y + bounds.height,+ };+ const anchor = {+ x: west ? bounds.x + bounds.width : bounds.x,+ y: north ? bounds.y + bounds.height : bounds.y,+ };+ editor.beginTransform(+ 'outer',+ transformPoint(frame.transform, start),+ corner+ );+ editor.updateTransform(+ transformPoint(frame.transform, {+ x: start.x + (west ? -1 : 1) * bounds.width,+ y: start.y + (north ? -1 : 1) * bounds.height,+ })+ );+ editor.commitTransform();+ closeMatrix(+ worldMatrix(editor.document, 'a'),+ multiply(+ around(transformPoint(frame.transform, anchor), scaling(2)),+ before+ )+ );+ editor.undo();+ editor.beginTransform(+ 'outer',+ transformPoint(frame.transform, start),+ corner+ );+ editor.updateTransform(transformPoint(frame.transform, anchor));+ expect(editor.getSession().transform).toBeDefined();+ editor.cancelTransform();+ closeMatrix(worldMatrix(editor.document, 'a'), before);+ expect(editor.getSession().canUndo).toBe(false);+ }+});++it('preserves right angles, orientation and aspect ratios when scaling rotated multiselection with an uneven drag', () => {+ const doc = createScene([+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(translation(30, 40), rotation(0.6)),+ geometry: { width: 100, height: 60 },+ appearance: { fill: 'red', stroke: 'black' },+ },+ {+ id: 'b',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: multiply(translation(180, 150), rotation(-0.4)),+ geometry: { width: 70, height: 40 },+ appearance: { fill: 'blue', stroke: 'black' },+ },+ ]);+ const editor = createGraphicsEditor(doc);+ editor.select('a');+ editor.toggleSelection('b');+ const bounds = worldBounds(doc, doc.rootId);+ const start = { x: bounds.x + bounds.width, y: bounds.y + bounds.height };+ editor.beginTransform('a', start, 'se');+ editor.updateTransform({+ x: start.x + bounds.width * 0.5,+ y: start.y - bounds.height * 0.8,+ });+ editor.commitTransform();+ for (const id of ['a', 'b']) {+ const before = worldMatrix(doc, id),+ after = worldMatrix(editor.document, id);+ expect(after[0] * after[2] + after[1] * after[3]).toBeCloseTo(0);+ expect(Math.atan2(after[1], after[0])).toBeCloseTo(+ Math.atan2(before[1], before[0])+ );+ expect(+ Math.hypot(after[0], after[1]) / Math.hypot(after[2], after[3])+ ).toBeCloseTo(1);+ closeMatrix(+ after,+ multiply(around({ x: bounds.x, y: bounds.y }, scaling(1.5)), before)+ );+ }+});diff --git a/packages/graphics/tests/selection.test.ts b/packages/graphics/tests/selection.test.tsnew file mode 100644index 0000000000..7ad257eda9--- /dev/null+++ b/packages/graphics/tests/selection.test.ts@@ -0,0 +1,43 @@+import { expect, it, vi } from 'vitest';+import { translation } from '../src/core/affine';+import type { GraphicsDocument } from '../src/core/model';+import { createScene, worldBounds } from '../src/core/scene';+import { createSelection } from '../src/core/selection';++it('runs against an injected document host without an editor or history backend', () => {+ let document: GraphicsDocument = createScene([+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(10, 20),+ geometry: { width: 100, height: 80 },+ appearance: { fill: 'white', stroke: 'black' },+ },+ ]);+ const commit = vi.fn((next: GraphicsDocument) => {+ document = next;+ });+ const changed = vi.fn();+ const selection = createSelection({+ getDocument: () => document,+ commitDocument: commit,+ cancelDrawing: vi.fn(),+ onChange: changed,+ });+ selection.beginTransform('a', { x: 20, y: 30 });+ selection.updateTransform({ x: 40, y: 60 });+ expect(selection.getState().transform?.geometry.x).toBe(30);+ expect(worldBounds(document, 'a').x).toBe(10);+ expect(commit).not.toHaveBeenCalled();+ selection.commitTransform();+ expect(commit).toHaveBeenCalledTimes(1);+ expect(worldBounds(document, 'a').x).toBe(30);+ selection.reconcile(createScene());+ expect(selection.getState().selectedId).toBeUndefined();+ selection.dispose();+ changed.mockClear();+ selection.select('a');+ selection.cancelTransform();+ expect(changed).not.toHaveBeenCalled();+});diff --git a/packages/graphics/tests/shift-gestures.test.ts b/packages/graphics/tests/shift-gestures.test.tsnew file mode 100644index 0000000000..59f346afe6--- /dev/null+++ b/packages/graphics/tests/shift-gestures.test.ts@@ -0,0 +1,244 @@+import { afterEach, expect, it, vi } from 'vitest';+import { attachCameraControls } from '../src/browser';+import {+ createGraphicsEditor,+ multiply,+ rotation,+ scaling,+ translation,+ worldBounds,+} from '../src/core';++const appearance = { fill: 'red', stroke: 'black' };+const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((cleanup) => cleanup()));++function input(tool: 'rectangle' | 'ellipse' | 'select') {+ const editor = createGraphicsEditor([+ {+ id: 'a',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(0, 0),+ geometry: { width: 100, height: 80 },+ appearance,+ },+ ]);+ const viewport = document.createElement('div');+ viewport.tabIndex = 0;+ document.body.append(viewport);+ viewport.setPointerCapture = vi.fn();+ viewport.hasPointerCapture = () => false;+ const detach = attachCameraControls(viewport, editor, {+ tool: () => tool,+ duplicateOnAltDrag: true,+ createId: () => 'new',+ appearance: () => appearance,+ });+ cleanups.push(() => {+ detach();+ editor.dispose();+ viewport.remove();+ });+ function pointer(+ type: string,+ x: number,+ y: number,+ modifiers: MouseEventInit = {}+ ) {+ const event = new MouseEvent(type, {+ bubbles: true,+ clientX: x,+ clientY: y,+ ...modifiers,+ });+ Object.defineProperty(event, 'pointerId', { value: 1 });+ viewport.dispatchEvent(event);+ }+ function shift(pressed: boolean) {+ viewport.dispatchEvent(+ new KeyboardEvent(pressed ? 'keydown' : 'keyup', {+ key: 'Shift',+ shiftKey: pressed,+ bubbles: true,+ })+ );+ }+ return { editor, viewport, pointer, shift };+}++it.each([+ 'rectangle',+ 'ellipse',+] as const)('creates a proportional %s in every drag direction without losing the unconstrained endpoint', (kind) => {+ for (const [dx, dy] of [+ [80, 30],+ [-80, 30],+ [80, -30],+ [-80, -30],+ ]) {+ const editor = createGraphicsEditor();+ editor.beginShape(kind, { x: 100, y: 100 });+ editor.updateShape({ x: 100 + dx!, y: 100 + dy! }, { proportional: true });+ expect(editor.getPreview()).toEqual({+ x: dx! < 0 ? 20 : 100,+ y: dy! < 0 ? 20 : 100,+ width: 80,+ height: 80,+ });+ editor.updateDrawing([], { proportional: false });+ expect(editor.getPreview()).toMatchObject({ width: 80, height: 30 });+ editor.updateDrawing([], { proportional: true });+ const before = editor.document;+ editor.commitShape('new', appearance);+ expect(editor.document.items.new).toMatchObject({+ type: kind,+ geometry: { width: 80, height: 80 },+ });+ editor.undo();+ expect(editor.document).toEqual(before);+ editor.dispose();+ }+});++it('keeps constrained image annotations square and inside the surface', () => {+ const editor = createGraphicsEditor();+ editor.setImageSurface({ id: 'image', width: 200, height: 120 });+ editor.beginShape('rectangle', { x: 100, y: 100 });+ editor.updateShape({ x: 190, y: 110 }, { proportional: true });+ expect(editor.getPreview()).toEqual({+ x: 100,+ y: 100,+ width: 20,+ height: 20,+ });+ editor.cancelShape();+ editor.beginShape('ellipse', { x: 10, y: 100 });+ editor.updateShape({ x: -100, y: 0 }, { proportional: true });+ expect(editor.getPreview()).toEqual({ x: 0, y: 90, width: 10, height: 10 });+ editor.dispose();+});++it.each([+ 'rectangle',+ 'ellipse',+] as const)('updates %s drawing on stationary Shift changes and final release', (tool) => {+ const { editor, pointer, shift } = input(tool);+ const before = editor.document;+ pointer('pointerdown', 150, 150, { shiftKey: true });+ pointer('pointermove', 230, 180, { shiftKey: true });+ expect(editor.getPreview()).toMatchObject({ width: 80, height: 80 });+ shift(false);+ expect(editor.getPreview()).toMatchObject({ width: 80, height: 30 });+ shift(true);+ expect(editor.getPreview()).toMatchObject({ width: 80, height: 80 });+ expect(editor.document).toBe(before);+ pointer('pointerup', 230, 180);+ expect(editor.document.items.new).toMatchObject({+ geometry: { width: 80, height: 30 },+ });+ editor.undo();+ expect(editor.document).toEqual(before);+});++it.each([+ 'child',+ 'group',+ 'multi',+] as const)('constrains a %s move along world axes through nested transforms', (selection) => {+ const editor = createGraphicsEditor([+ {+ id: 'g',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(rotation(0.6), scaling(2, 0.7)),+ },+ ...['a', 'b'].map((id, i) => ({+ id,+ type: 'rectangle' as const,+ placement: { parentId: 'g', sortKey: `a${i}` },+ transform: translation(100 * i, 30),+ geometry: { width: 50, height: 30 },+ appearance,+ })),+ ]);+ const target = selection === 'group' ? 'g' : 'a';+ editor.select(target);+ if (selection === 'multi') editor.toggleSelection('b');+ const before = editor.document;+ const initial = worldBounds(before, target);+ editor.beginTransform(target, { x: 10, y: 10 });+ editor.updateTransform({ x: 90, y: 40 }, { constrainAxis: true });+ const horizontal = worldBounds(+ before,+ target,+ editor.getSession().transform?.nodes+ );+ expect(horizontal.x - initial.x).toBeCloseTo(80);+ expect(horizontal.y).toBeCloseTo(initial.y);+ editor.updateTransform({ x: 90, y: 40 });+ expect(+ worldBounds(before, target, editor.getSession().transform?.nodes).y -+ initial.y+ ).toBeCloseTo(30);+ editor.updateTransform({ x: -10, y: -90 }, { constrainAxis: true });+ editor.commitTransform();+ expect(worldBounds(editor.document, target).x).toBeCloseTo(initial.x);+ expect(worldBounds(editor.document, target).y - initial.y).toBeCloseTo(-100);+ editor.undo();+ expect(editor.document).toEqual(before);+ editor.dispose();+});++it('preserves Shift-click toggling while Shift-drag moves, with live modifier changes and one undo', () => {+ const { editor, pointer, shift } = input('select');+ pointer('pointerdown', 20, 20, { shiftKey: true });+ expect(editor.getSession().selectedIds).toEqual([]);+ pointer('pointerup', 21, 21, { shiftKey: true });+ expect(editor.getSession().selectedIds).toEqual(['a']);+ const before = editor.document;+ pointer('pointerdown', 20, 20, { shiftKey: true });+ pointer('pointermove', 70, 35, { shiftKey: true });+ expect(editor.getSession().selectedIds).toEqual(['a']);+ expect(editor.getSession().transform?.geometries.a).toMatchObject({+ x: 50,+ y: 0,+ });+ shift(false);+ expect(editor.getSession().transform?.geometries.a).toMatchObject({+ x: 50,+ y: 15,+ });+ shift(true);+ expect(editor.getSession().transform?.geometries.a).toMatchObject({+ x: 50,+ y: 0,+ });+ pointer('pointerup', 70, 35, { shiftKey: true });+ expect(worldBounds(editor.document, 'a')).toMatchObject({ x: 50, y: 0 });+ editor.undo();+ expect(editor.document).toEqual(before);+ pointer('pointerdown', 20, 20, { shiftKey: true });+ pointer('pointerup', 20, 20, { shiftKey: true });+ expect(editor.getSession().selectedIds).toEqual([]);+});++it('constrains Option-Shift duplicates and cancels a pending Shift gesture without changing selection', () => {+ const { editor, viewport, pointer } = input('select');+ editor.select('a');+ const before = editor.document;+ pointer('pointerdown', 20, 20, { shiftKey: true, altKey: true });+ pointer('pointerup', 80, 35, { shiftKey: true, altKey: true });+ expect(editor.document.items.a).toEqual(before.items.a);+ expect(worldBounds(editor.document, 'new')).toMatchObject({ x: 60, y: 0 });+ editor.undo();+ expect(editor.document).toEqual(before);+ editor.select('a');+ pointer('pointerdown', 20, 20, { shiftKey: true });+ viewport.dispatchEvent(+ new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })+ );+ pointer('pointerup', 20, 20, { shiftKey: true });+ expect(editor.getSession().selectedIds).toEqual(['a']);+ expect(editor.getSession().canUndo).toBe(false);+});diff --git a/packages/graphics/tests/snapping.test.ts b/packages/graphics/tests/snapping.test.tsnew file mode 100644index 0000000000..d1b038219c--- /dev/null+++ b/packages/graphics/tests/snapping.test.ts@@ -0,0 +1,327 @@+import { afterEach, expect, it } from 'vitest';+import {+ copyFragment,+ createConnectorInteraction,+ createGraphicsEditor,+ createScene,+ duplicateCommand,+ type GraphicsDocument,+ type GraphicsEditor,+ type GraphicsItem,+ multiply,+ nudgeCommand,+ pasteCommand,+ rotation,+ type ShapeItem,+ scaling,+ snapPoint,+ snapValue,+ transformPoint,+ translation,+ worldBounds,+ worldMatrix,+} from '../src/core';+import { resizeHandles } from '../src/core/resize';+import { createGraphicsPeerLab } from './helpers/peer-lab';++const appearance = { fill: 'red', stroke: 'black' };+function rectangle(id = 'a', x = 0, y = 0): ShapeItem<'rectangle'> {+ return {+ id,+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: id === 'a' ? 'a0' : 'a1' },+ transform: translation(x, y),+ geometry: { width: 32, height: 16 },+ appearance,+ };+}+const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((dispose) => dispose()));+function setup(+ unit?: number,+ seed: readonly GraphicsItem[] | GraphicsDocument = [rectangle()]+) {+ const editor = createGraphicsEditor(seed, { snapUnit: unit });+ cleanups.push(editor.dispose);+ return editor;+}+function preview(editor: GraphicsEditor, id = 'a') {+ return worldBounds(editor.document, id, editor.getSession().transform?.nodes);+}++it.each([+ 0.25, 1, 2, 2.5, 4, 8, 13,+])('snaps drawing preview and commit to arbitrary unit %s', (unit) => {+ const editor = setup(unit, []);+ editor.beginRectangle({ x: unit * 0.3, y: -unit * 1.3 });+ editor.updateRectangle({ x: unit * 4.2, y: unit * 2.8 });+ const expected = { x: 0, y: -unit, width: unit * 4, height: unit * 4 };+ expect(editor.getPreview()).toEqual(expected);+ expect(editor.commitRectangle('a', appearance)).toBe(true);+ expect(worldBounds(editor.document, 'a')).toEqual(expected);+});++it('leaves precision unrestricted by default and rejects invalid units without changing configuration', () => {+ const editor = setup();+ expect(editor.getSnapUnit()).toBeUndefined();+ const point = { x: 0.123, y: -4.567 };+ expect(snapPoint(point)).toEqual(point);+ expect(Object.is(snapValue(-0.1, 1), -0)).toBe(false);+ expect(snapValue(0.36, 0.1)).toBeCloseTo(0.4);+ for (const unit of [0, -1, NaN, Infinity]) {+ expect(() => createGraphicsEditor([], { snapUnit: unit })).toThrow(+ 'positive finite'+ );+ expect(() => editor.setSnapUnit(unit)).toThrow('positive finite');+ expect(editor.getSnapUnit()).toBeUndefined();+ }+ editor.beginTransform('a', { x: 5, y: 6 });+ editor.updateTransform({ x: 5.3, y: 6.5 });+ expect(preview(editor).x).toBeCloseTo(0.3);+ expect(preview(editor).y).toBeCloseTo(0.5);+});++it('snaps the common selection anchor while preserving grab offset, spacing, and one undo step', () => {+ const editor = setup(8, [rectangle('a', 3, 5), rectangle('b', 50, 27)]);+ editor.select('a');+ editor.toggleSelection('b');+ const before = editor.document;+ editor.beginTransform('a', { x: 11, y: 12 });+ editor.updateTransform({ x: 11, y: 12 });+ expect(editor.commitTransform()).toBe(false);+ editor.beginTransform('a', { x: 11, y: 12 });+ editor.updateTransform({ x: 17, y: 19 });+ expect(editor.document).toBe(before);+ expect(preview(editor)).toMatchObject({ x: 8, y: 16 });+ expect(preview(editor, 'b')).toMatchObject({ x: 55, y: 38 });+ editor.commitTransform();+ expect(worldBounds(editor.document, 'a')).toMatchObject({ x: 8, y: 16 });+ editor.undo();+ expect(editor.document).toEqual(before);+ expect(editor.getSession().canUndo).toBe(false);+ editor.redo();+ expect(worldBounds(editor.document, 'b')).toMatchObject({ x: 55, y: 38 });+});++it('snaps nested moves in world coordinates and preserves the constrained axis', () => {+ const editor = setup(4, [+ {+ id: 'g',+ type: 'group',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: multiply(+ translation(51, 63),+ multiply(rotation(0.6), scaling(2, 3))+ ),+ },+ { ...rectangle(), placement: { parentId: 'g', sortKey: 'a0' } },+ ]);+ const before = worldBounds(editor.document, 'a');+ editor.beginTransform('a', { x: 20, y: 40 });+ editor.updateTransform({ x: 27, y: 41 }, { constrainAxis: true });+ expect(preview(editor).x / 4).toBeCloseTo(Math.round((before.x + 7) / 4));+ expect(preview(editor).y).toBeCloseTo(before.y);+ editor.cancelTransform();+ expect(editor.getSession().canUndo).toBe(false);+});++it.each(+ resizeHandles+)('snaps dimensions with handle %s and keeps the opposite edge fixed', (handle) => {+ const editor = setup(8);+ const horizontal = handle.includes('e') || handle.includes('w');+ const vertical = handle.includes('n') || handle.includes('s');+ const west = handle.includes('w'),+ north = handle.includes('n');+ const start = { x: (west ? 0 : 32) + 2, y: (north ? 0 : 16) - 1 };+ editor.beginTransform('a', start, handle);+ editor.updateTransform({+ x: start.x + (west ? -11 : 11),+ y: start.y + (north ? -7 : 7),+ });+ const expected = {+ x: west ? -8 : 0,+ y: north ? -8 : 0,+ width: horizontal ? 40 : 32,+ height: vertical ? 24 : 16,+ };+ expect(preview(editor)).toEqual(expected);+ editor.commitTransform();+ expect(worldBounds(editor.document, 'a')).toEqual(expected);+});++it('accounts for rotation and ancestor scale when snapping physical dimensions', () => {+ const matrix = multiply(+ translation(13, 27),+ multiply(rotation(0.6), scaling(2, 3))+ );+ const editor = setup(8, [{ ...rectangle(), transform: matrix }]);+ editor.beginTransform('a', transformPoint(matrix, { x: 32, y: 16 }), 'se');+ editor.updateTransform(transformPoint(matrix, { x: 37.4, y: 19.3 }));+ editor.commitTransform();+ const item = editor.document.items.a;+ if (item?.type !== 'rectangle') throw new Error('Missing rectangle');+ const world = worldMatrix(editor.document, 'a');+ expect(item.geometry.width * Math.hypot(world[0], world[1])).toBeCloseTo(72);+ expect(item.geometry.height * Math.hypot(world[2], world[3])).toBeCloseTo(56);+ expect(world[4]).toBeCloseTo(matrix[4]);+ expect(world[5]).toBeCloseTo(matrix[5]);+});++it('preserves proportional and center constraints, including group scaling', () => {+ for (const grouped of [false, true]) {+ const editor = setup(8);+ if (grouped) {+ editor.select('a');+ editor.groupSelection('g');+ }+ const id = grouped ? 'g' : 'a';+ editor.beginTransform(id, { x: 32, y: 16 }, 'se');+ editor.updateTransform(+ { x: 38, y: 18 },+ { proportional: true, fromCenter: true }+ );+ expect(preview(editor, id)).toEqual({+ x: -8,+ y: -4,+ width: 48,+ height: 24,+ });+ }+});++it('gives bounded image edges priority over snapping for drawing, resizing, and moving', () => {+ const editor = setup(8, []);+ editor.setImageSurface({ id: 'image', width: 101, height: 79 });+ editor.beginRectangle({ x: 8, y: 8 });+ editor.updateRectangle({ x: 500, y: 500 });+ expect(editor.getPreview()).toEqual({ x: 8, y: 8, width: 93, height: 71 });+ editor.commitRectangle('a', appearance);+ editor.beginTransform('a', { x: 101, y: 79 }, 'se');+ editor.updateTransform({ x: 500, y: 500 });+ expect(preview(editor)).toEqual({ x: 8, y: 8, width: 93, height: 71 });+ editor.cancelTransform();+ editor.beginTransform('a', { x: 50, y: 50 });+ editor.updateTransform({ x: 500, y: 500 });+ expect(preview(editor)).toEqual({ x: 8, y: 8, width: 93, height: 71 });+});++it('keeps freehand samples and rotation independent of pixel snapping', () => {+ const snapped = setup(8),+ free = setup();+ for (const editor of [snapped, free]) {+ editor.beginShape('pencil', { x: 1.3, y: 3.7, pressure: 0.4 });+ editor.updateShape({ x: 4.6, y: 7.8, pressure: 0.6 });+ editor.updateShape({ x: 11.2, y: 4.1, pressure: 0.7 });+ editor.commitShape('ink', appearance);+ editor.beginTransform('a', { x: 16, y: -10 }, 'rotate');+ editor.updateTransform({ x: 30.3, y: -2.6 });+ }+ expect(snapped.document.items.ink).toEqual(free.document.items.ink);+ expect(snapped.getSession().transform?.nodes).toEqual(+ free.getSession().transform?.nodes+ );+});++it('changes local policy without writing history and snaps keyboard moves on only the active axis', () => {+ const editor = setup(4, [rectangle('a', 3, 5)]);+ const before = editor.document;+ editor.beginTransform('a', { x: 10, y: 10 });+ editor.updateTransform({ x: 20, y: 20 });+ editor.setSnapUnit(8);+ expect(editor.getSession().snapUnit).toBe(8);+ expect(editor.getSession().transform).toBeUndefined();+ expect(editor.document).toBe(before);+ expect(editor.getSession().canUndo).toBe(false);+ editor.execute(nudgeCommand, { x: 8, y: 0 });+ expect(worldBounds(editor.document, 'a')).toMatchObject({ x: 8, y: 5 });+ editor.setSnapUnit(undefined);+ editor.execute(nudgeCommand, { x: 0.2, y: 0.3 });+ expect(worldBounds(editor.document, 'a').x).toBeCloseTo(8.2);+ expect(worldBounds(editor.document, 'a').y).toBeCloseTo(5.3);+});++it('snaps free connector ends, retaining exact bound ports and Shift angles', () => {+ const doc = createScene([rectangle('a', 3, 5)]);+ const op = createConnectorInteraction({+ getDocument: () => doc,+ getSnapUnit: () => 8,+ commit: () => {},+ onChange: () => {},+ });+ op.begin(+ 'connector',+ { x: 81, y: 83 },+ appearance,+ { route: 'straight', startHead: 'none', endHead: 'arrow' },+ 1+ );+ op.update({ x: 105, y: 107 }, 1);+ expect(op.getState()?.item.geometry).toMatchObject({+ start: { point: { x: 80, y: 80 } },+ end: { point: { x: 104, y: 104 } },+ });+ op.update({ x: 101, y: 98 }, 1, true);+ const end = op.getState()!.item.geometry.end.point;+ expect(end.x).toBeCloseTo(96);+ expect(end.y).toBeCloseTo(96);+ op.update({ x: 35, y: 13 }, 1);+ expect(op.getState()?.item.geometry.end).toMatchObject({+ point: { x: 35, y: 13 },+ binding: { targetId: 'a' },+ });+});++it('stores snapped poses through Loro while each peer keeps its own unit', () => {+ const lab = createGraphicsPeerLab(createScene([rectangle()]));+ cleanups.push(lab.dispose);+ lab.setConnected(false);+ const a = lab.peers[0]!.editor,+ b = lab.peers[1]!.editor;+ a.setSnapUnit(2.5);+ b.setSnapUnit(8);+ a.beginTransform('a', { x: 0, y: 0 });+ a.updateTransform({ x: 6.2, y: 8.1 });+ a.commitTransform();+ lab.syncNow();+ expect(a.document).toEqual(b.document);+ expect(worldBounds(b.document, 'a')).toMatchObject({ x: 5, y: 7.5 });+ expect(b.getSnapUnit()).toBe(8);+ a.undo();+ lab.syncNow();+ expect(worldBounds(b.document, 'a')).toMatchObject({ x: 0, y: 0 });+});++it('snaps duplicate and paste anchors without changing the spacing inside a fragment', () => {+ const editor = setup(13, [rectangle('a', 3, 5), rectangle('b', 50, 27)]);+ editor.select('a');+ editor.toggleSelection('b');+ const fragment = copyFragment(editor.document, ['a', 'b'])!;+ let count = 0;+ const createId = () => `copy-${count++}`;+ editor.execute(duplicateCommand, { createId });+ expect(worldBounds(editor.document, 'copy-0')).toMatchObject({+ x: 26,+ y: 26,+ });+ expect(worldBounds(editor.document, 'copy-1')).toMatchObject({+ x: 73,+ y: 48,+ });+ editor.execute(pasteCommand, {+ fragment,+ createId,+ offset: { x: 30, y: 40 },+ });+ expect(worldBounds(editor.document, 'copy-2')).toMatchObject({+ x: 39,+ y: 39,+ });+ expect(worldBounds(editor.document, 'copy-3')).toMatchObject({+ x: 86,+ y: 61,+ });+ // An explicitly requested in-place copy retains the exact source pose.+ editor.execute(pasteCommand, { fragment, createId, offset: { x: 0, y: 0 } });+ expect(worldBounds(editor.document, 'copy-4')).toMatchObject({ x: 3, y: 5 });+});diff --git a/packages/graphics/tests/text.test.ts b/packages/graphics/tests/text.test.tsnew file mode 100644index 0000000000..4d6d6e0cb4--- /dev/null+++ b/packages/graphics/tests/text.test.ts@@ -0,0 +1,219 @@+import { afterEach, expect, it, vi } from 'vitest';+import {+ copyFragment,+ createGraphicsEditor,+ multiply,+ nodeCorners,+ parseFragment,+ pasteCommand,+ rotation,+ type ShapeItem,+ setTextCommand,+ textDefinition,+ translation,+ validRichText,+ worldBounds,+} from '../src/core';++const cleanups: (() => void)[] = [];+afterEach(() => cleanups.splice(0).forEach((fn) => fn()));+const text = (content = 'Hello world'): ShapeItem<'text'> => ({+ id: 'text',+ type: 'text',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(20, 30),+ appearance: { fill: 'transparent', stroke: 'black' },+ geometry: {+ width: 200,+ height: 32.4,+ autoWidth: true,+ fontSize: 24,+ fontFamily: 'sans',+ content,+ },+});+it('stores frozen rich text and copies nested formatting without mutable input', () => {+ const source = JSON.stringify({+ format: 'host-defined',+ blocks: [{ text: 'Title', bold: true }],+ });+ const editor = createGraphicsEditor([text(source)]);+ cleanups.push(editor.dispose);+ const node = editor.document.items.text;+ if (node?.type !== 'text') throw Error();+ expect(Object.isFrozen(node.geometry)).toBe(true);+ expect(typeof node.geometry.content).toBe('string');+ expect(node.geometry.content).toBe(source);+ editor.select('text');+ const fragment = copyFragment(editor.document, ['text'])!;+ editor.execute(pasteCommand, {+ fragment: parseFragment(JSON.stringify(fragment))!,+ createId: () => 'copy',+ });+ const copy = editor.document.items.copy;+ if (copy?.type !== 'text') throw Error();+ expect(copy.geometry.content).toEqual(source);+ expect(copy.transform[4]).toBe(44);+ editor.undo();+ expect(editor.document.items.copy).toBeUndefined();+});+it('stores empty and whitespace content verbatim until the host explicitly deletes it', () => {+ const editor = createGraphicsEditor();+ cleanups.push(editor.dispose);+ editor.execute(setTextCommand, text(''));+ expect(editor.document.items.text).toEqual(text(''));+ expect(editor.getSession().canUndo).toBe(true);+ editor.execute(setTextCommand, text('Edited'));+ editor.execute(setTextCommand, text(' '));+ expect(editor.document.items.text).toEqual(text(' '));+ editor.undo();+ expect(editor.document.items.text).toEqual(text('Edited'));+ editor.select('text');+ editor.deleteSelection();+ expect(editor.document.items.text).toBeUndefined();+ editor.undo();+ expect(editor.document.items.text).toEqual(text('Edited'));+});+it('uses injected measurement for rotated side reflow and keeps the opposite edge fixed', () => {+ const measure = vi.fn((geometry: ShapeItem<'text'>['geometry']) => ({+ width: geometry.width,+ height: 64.8,+ }));+ const item = {+ ...text(),+ transform: multiply(translation(20, 30), rotation(Math.PI / 2)),+ };+ const editor = createGraphicsEditor([item], { measureText: measure });+ cleanups.push(editor.dispose);+ editor.select('text');+ editor.beginTransform('text', { x: 20, y: 230 }, 'e');+ editor.updateTransform({ x: 20, y: 130 });+ const preview = editor.getSession().transform?.nodes.text;+ if (preview?.type !== 'text') throw Error();+ expect(preview.geometry.fontSize).toBe(24);+ expect(preview.geometry.autoWidth).toBe(false);+ expect(preview.geometry.width).toBeCloseTo(100);+ expect(preview.geometry.height).toBeCloseTo(64.8);+ expect(preview.transform).toEqual(item.transform);+ expect(measure).toHaveBeenCalled();+ editor.commitTransform();+ expect(worldBounds(editor.document, 'text').height).toBeCloseTo(100);+ editor.undo();+ expect(editor.document.items.text).toEqual(item);+});+it('scales font size with a corner and flips through zero', () => {+ const editor = createGraphicsEditor([text()]);+ cleanups.push(editor.dispose);+ editor.select('text');+ editor.beginTransform('text', { x: 220, y: 62.4 }, 'se');+ editor.updateTransform({ x: 420, y: 94.8 });+ const preview = editor.getSession().transform?.nodes.text;+ if (preview?.type !== 'text') throw Error();+ expect(preview.geometry.fontSize).toBeCloseTo(48);+ expect(preview.geometry.width).toBeCloseTo(400);+ editor.updateTransform({ x: -180, y: -2.4 });+ editor.commitTransform();+ const item = editor.document.items.text;+ if (item?.type !== 'text') throw Error();+ expect(item.geometry.fontSize).toBeGreaterThan(0);+ expect(item.transform[0]).toBeLessThan(0);+});++it.each([+ 'nw',+ 'ne',+ 'se',+ 'sw',+] as const)('shrinks text from %s with horizontal pointer movement and keeps the opposite corner fixed', (handle) => {+ const item = text();+ const editor = createGraphicsEditor([item]);+ cleanups.push(editor.dispose);+ const index = ['nw', 'ne', 'se', 'sw'].indexOf(handle);+ const before = nodeCorners(editor.document, item.id);+ const start = before[index]!;+ editor.select(item.id);+ editor.beginTransform(item.id, start, handle);+ editor.updateTransform({+ x: start.x + (handle.endsWith('w') ? 100 : -100),+ y: start.y,+ });+ editor.commitTransform();+ const next = editor.document.items[item.id];+ if (next?.type !== 'text') throw Error();+ expect(next.geometry.fontSize).toBeGreaterThan(12);+ expect(next.geometry.fontSize).toBeLessThan(13);+ const anchor = (index + 2) % 4;+ const after = nodeCorners(editor.document, item.id)[anchor]!;+ expect(after.x).toBeCloseTo(before[anchor]!.x);+ expect(after.y).toBeCloseTo(before[anchor]!.y);+ editor.undo();+ expect(editor.document.items[item.id]).toEqual(item);+});++it('does not amplify vertical jitter or reflow text during corner scaling, including scaling from center', () => {+ const measure = vi.fn(() => ({ width: 999, height: 999 }));+ const item = text();+ const editor = createGraphicsEditor([item], { measureText: measure });+ cleanups.push(editor.dispose);+ editor.select(item.id);+ editor.beginTransform(item.id, { x: 220, y: 62.4 }, 'se');+ editor.updateTransform({ x: 220, y: 72.4 }, { fromCenter: true });+ editor.commitTransform();+ const next = editor.document.items[item.id];+ if (next?.type !== 'text') throw Error();+ expect(next.geometry.fontSize).toBeGreaterThan(24);+ expect(next.geometry.fontSize).toBeLessThan(25);+ expect(measure).not.toHaveBeenCalled();+ const bounds = worldBounds(editor.document, item.id);+ expect(bounds.x + bounds.width / 2).toBeCloseTo(120);+ expect(bounds.y + bounds.height / 2).toBeCloseTo(46.2);+ expect(next.geometry.width / next.geometry.height).toBeCloseTo(200 / 32.4);+});+it('bounds opaque content without interpreting its format and rejects invalid typography', () => {+ const content = '<img src=x onerror=alert(1)>';+ expect(validRichText(content)).toBe(true);+ expect(validRichText('{not-json')).toBe(true);+ expect(validRichText('')).toBe(true);+ const link = {+ blocks: [+ {+ type: 'paragraph',+ align: 'left',+ children: [{ type: 'link', href: 'javascript:alert(1)', children: [] }],+ },+ ],+ };+ expect(validRichText(link)).toBe(false);+ expect(validRichText('a'.repeat(2_000_001))).toBe(false);+ expect(+ textDefinition.validateGeometry({ ...text().geometry, fontSize: NaN })+ ).toBe(false);+ expect(+ textDefinition.validateGeometry({+ ...text().geometry,+ fontFamily: 'arbitrary-font',+ })+ ).toBe(false);+});++it('scales a mixed text selection uniformly instead of distorting glyphs or mismatching its box', () => {+ const rectangle: ShapeItem<'rectangle'> = {+ id: 'rect',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: translation(20, 100),+ appearance: { fill: 'transparent', stroke: 'black' },+ geometry: { width: 100, height: 50 },+ };+ const editor = createGraphicsEditor([text(), rectangle]);+ cleanups.push(editor.dispose);+ editor.select('text');+ editor.toggleSelection('rect');+ editor.beginTransform('text', { x: 220, y: 90 }, 'e');+ editor.updateTransform({ x: 420, y: 90 });+ const preview = editor.getSession().transform?.nodes.text;+ if (preview?.type !== 'text') throw Error();+ expect(Math.hypot(preview.transform[0], preview.transform[1])).toBeCloseTo(2);+ expect(Math.hypot(preview.transform[2], preview.transform[3])).toBeCloseTo(2);+ expect(preview.geometry.content).toEqual(text().geometry.content);+});diff --git a/packages/graphics/tsconfig.core.json b/packages/graphics/tsconfig.core.jsonnew file mode 100644index 0000000000..9f7b4c60e8--- /dev/null+++ b/packages/graphics/tsconfig.core.json@@ -0,0 +1,5 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": { "lib": ["ES2022"], "types": [] },+ "include": ["src/core"]+}diff --git a/packages/graphics/tsconfig.json b/packages/graphics/tsconfig.jsonnew file mode 100644index 0000000000..76f021cbf6--- /dev/null+++ b/packages/graphics/tsconfig.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "noEmit": true,+ "skipLibCheck": true,+ "jsx": "preserve",+ "jsxImportSource": "solid-js",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "types": ["node"]+ },+ "include": ["src", "tests", "vitest.config.ts"]+}diff --git a/packages/graphics/vitest.config.ts b/packages/graphics/vitest.config.tsnew file mode 100644index 0000000000..e65843b677--- /dev/null+++ b/packages/graphics/vitest.config.ts@@ -0,0 +1,16 @@+import solid from 'vite-plugin-solid';+import { defineConfig } from 'vitest/config';++export default defineConfig({+ plugins: [solid()],+ resolve: {+ dedupe: ['solid-js'],+ conditions: ['browser', 'development'],+ alias: { 'loro-crdt': 'loro-crdt/nodejs' },+ },+ test: {+ name: 'graphics',+ environment: 'jsdom',+ include: ['tests/**/*.test.{ts,tsx}'],+ },+});