@g9tm/lynxcontrols-canvas 2.5.10 → 2.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"board-controller.js","sources":["../src/board-controller.ts"],"sourcesContent":["import { observable } from './observable';\n\nimport type {\n CvBoxEvent,\n CvDownEvent,\n CvEraseEvent,\n CvItem,\n CvLineEvent,\n CvMessage,\n CvMoveEvent,\n CvPeer,\n CvPointEvent,\n CvSelection,\n CvShapeEvent,\n CvStrokeEvent,\n CvTapEvent,\n CvTool,\n CvTransformEvent,\n CvView,\n CvViewEvent,\n} from './protocol';\nimport {\n createFreeDraw,\n createImage,\n createLinear,\n createShape,\n createText,\n deleteElements,\n duplicate,\n editText,\n erasedBy,\n expandSelection,\n group,\n hitTest,\n inBox,\n lockElements,\n moveElements,\n movePoint,\n movingSet,\n type OrderMove,\n reorder,\n resizeElements,\n rotateElements,\n styleElements,\n ungroup,\n} from './scene/edit';\nimport { bump, DEFAULT_STYLE, FONT_FAMILY, isLinear } from './scene/elements';\nimport { absoluteCoords, commonBounds, elementBounds } from './scene/geometry';\nimport type { Scene, SceneChange } from './scene/scene';\nimport { toItem } from './scene/shapes';\nimport type { ExElement, ItemStyle, Point } from './scene/types';\n\n/**\n * Everything a board does between the scene and `<g9-canvas>`, without React (the view renders `state`): it turns the\n * element's gesture events into scene edits (Excalidraw's rules: what a tap selects, which tool stays active, how\n * texts are made and edited), keeps the element's items, selection, collaborators and pictures in step with the scene\n * — sending only what changed — and owns the current style, the tool and live text editing.\n */\n\nexport interface TextEdit {\n /** The text element (null until the first character makes one). */\n id: string | null;\n /** Where a new text goes (scene). */\n x: number;\n y: number;\n /** A label inside this shape. */\n containerId: string | null;\n value: string;\n}\n\n/** What a board UI shows: the tool, the selection, its style, the text being edited, the status. */\nexport interface BoardState {\n tool: CvTool;\n /** Keep the tool after drawing (Excalidraw's lock). */\n toolLocked: boolean;\n style: ItemStyle;\n selected: string[];\n canUndo: boolean;\n canRedo: boolean;\n status: BoardStatus;\n /** Collaborators (user ids) on the board now. */\n peers: string[];\n text: TextEdit | null;\n zoom: number;\n editable: boolean;\n empty: boolean;\n}\n\nexport interface PeerIdentity {\n name: string;\n color: string;\n}\n\nexport interface ControllerOptions {\n scene: Scene;\n /** Sends a message to the element (null before it exists: the next attach sends the full state). */\n send: (message: CvMessage) => void;\n identify: (userId: string) => PeerIdentity;\n /** My pointer for the others. */\n pointer?: (x: number, y: number, down: boolean, selected: readonly string[], gone: boolean) => void;\n}\n\nconst BACKGROUND = '#ffffff';\n\n/** A board's connection as the app's sync reports it. */\nexport type BoardStatus = 'connecting' | 'synced' | 'saving' | 'offline' | 'failed' | 'closed';\n\n/** A collaborator's pointer and selection (by connection). */\nexport interface BoardPeerState {\n peerKey: string;\n userId: string;\n x: number;\n y: number;\n down: boolean;\n laser: boolean;\n selectedIds: string[];\n gone: boolean;\n}\n\n/** Drives a board: the scene, the element's events, styles, history, collaborators and the order. */\nexport class BoardController {\n readonly state: BoardState;\n /** Told after every change of {@link state}. */\n private readonly listeners = new Set<() => void>();\n /** Listens to the state's changes; returns the unsubscribe. */\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n private readonly items = new Map<string, { v: number; item: CvItem }>();\n private order: string[] = [];\n private files: Record<string, string> = {};\n private peers: BoardPeerState[] = [];\n private view: CvViewEvent = { scrollX: 0, scrollY: 0, zoom: 1, width: 0, height: 0 };\n private attached = false;\n private fitted = false;\n private textBefore: Map<string, ExElement | null> | null = null;\n private readonly off: () => void;\n private pendingDone: number[] = [];\n /** Gestures whose pointer-down already did the shift toggle (their tap must not undo it; 2.5.8). */\n private readonly shiftHandled = new Set<number>();\n\n constructor(private readonly options: ControllerOptions) {\n this.state = observable<BoardState>(this.listeners, {\n tool: 'selection',\n toolLocked: false,\n style: { ...DEFAULT_STYLE },\n selected: [],\n canUndo: false,\n canRedo: false,\n status: 'connecting',\n peers: [],\n text: null,\n zoom: 1,\n editable: false,\n empty: true,\n });\n this.off = options.scene.on((change) => this.sceneChanged(change));\n }\n\n get scene(): Scene {\n return this.options.scene;\n }\n\n destroy(): void {\n this.off();\n }\n\n // ================================================================================================ element link\n\n /** The element exists (again): it gets the whole state. */\n attach(): void {\n this.attached = true;\n this.items.clear();\n this.order = [];\n const message: CvMessage = {\n reset: true,\n ...this.diff(this.scene.all(), true),\n files: this.files,\n selection: this.selectionMessage(),\n peers: this.peerMessage(),\n };\n if (this.fitted) message.view = { scrollX: this.view.scrollX, scrollY: this.view.scrollY, zoom: this.view.zoom };\n this.options.send(message);\n }\n\n detach(): void {\n this.attached = false;\n }\n\n /** The scene was (re)loaded: everything is sent again and the camera fits the content once. */\n loaded(): void {\n this.state.empty = this.scene.visible().length === 0;\n if (this.attached) this.attach();\n this.updateHistory();\n // Open on the content (the element may have measured itself before the scene arrived).\n this.fitted = this.view.width > 0 && this.view.height > 0;\n if (this.fitted) this.fit(false);\n }\n\n private send(message: CvMessage): void {\n if (!this.attached) return;\n if (this.pendingDone.length) {\n message.done = [...(message.done ?? []), ...this.pendingDone];\n this.pendingDone = [];\n }\n this.options.send(message);\n }\n\n /** Item changes since the last message (all = the full scene). */\n private diff(elements: readonly ExElement[], all = false): Pick<CvMessage, 'items' | 'remove' | 'order'> {\n const upsert: CvItem[] = [];\n const remove: string[] = [];\n let orderChanged = all;\n for (const element of elements) {\n const known = this.items.get(element.id);\n if (element.isDeleted) {\n if (known) {\n this.items.delete(element.id);\n remove.push(element.id);\n orderChanged = true;\n }\n continue;\n }\n if (known && known.v === element.version && !all) continue;\n const item = toItem(element, { background: BACKGROUND });\n if (!known) orderChanged = true;\n this.items.set(element.id, { v: element.version, item });\n upsert.push(item);\n }\n const result: Pick<CvMessage, 'items' | 'remove' | 'order'> = {};\n if (upsert.length) result.items = upsert;\n if (remove.length) result.remove = remove;\n if (orderChanged || all) {\n const order = this.scene.visible().map((element) => element.id);\n if (all || order.join() !== this.order.join()) {\n this.order = order;\n result.order = order;\n }\n }\n return result;\n }\n\n private sceneChanged(change: SceneChange): void {\n const message: CvMessage = this.diff(change.changed);\n if (change.orderChanged && !message.order) {\n const order = this.scene.visible().map((element) => element.id);\n if (order.join() !== this.order.join()) {\n this.order = order;\n message.order = order;\n }\n }\n // Selected elements deleted elsewhere leave the selection; moved ones redraw their boxes.\n const selected = this.state.selected.filter((id) => this.scene.get(id) && !this.scene.get(id)!.isDeleted);\n if (selected.length !== this.state.selected.length) this.state.selected = selected;\n if (selected.some((id) => change.changed.some((element) => element.id === id)))\n message.selection = this.selectionMessage();\n if (!change.local) message.peers = this.peerMessage();\n this.state.empty = this.scene.visible().length === 0;\n this.updateHistory();\n this.send(message);\n if (\n change.local &&\n this.state.text?.id &&\n change.changed.some((element) => element.id === this.state.text?.id && element.isDeleted)\n )\n this.state.text = null;\n }\n\n private updateHistory(): void {\n if (this.state.canUndo !== this.scene.canUndo) this.state.canUndo = this.scene.canUndo;\n if (this.state.canRedo !== this.scene.canRedo) this.state.canRedo = this.scene.canRedo;\n }\n\n // ================================================================================================ selection\n\n select(ids: readonly string[]): void {\n this.state.selected = [...ids];\n // The style panel shows the selection's style (Excalidraw: the first element's).\n const first = ids.length ? this.scene.get(ids[0]) : undefined;\n if (first) this.adoptStyle(first);\n this.send({ selection: this.selectionMessage() });\n this.options.pointer?.(this.lastPointer[0], this.lastPointer[1], false, this.state.selected, false);\n }\n\n private adoptStyle(element: ExElement): void {\n const style = { ...this.state.style };\n if (element.type !== 'image') style.strokeColor = element.strokeColor;\n if (\n element.type !== 'text' &&\n element.type !== 'arrow' &&\n element.type !== 'line' &&\n element.type !== 'freedraw' &&\n element.type !== 'image'\n ) {\n style.backgroundColor = element.backgroundColor;\n style.fillStyle = element.fillStyle;\n }\n style.strokeWidth = element.strokeWidth;\n style.strokeStyle = element.strokeStyle;\n style.roughness = element.roughness;\n style.opacity = element.opacity;\n if (element.type === 'rectangle' || element.type === 'diamond' || isLinear(element))\n style.roundness = element.roundness ? 'round' : 'sharp';\n if (element.type === 'text') {\n style.fontSize = element.fontSize ?? style.fontSize;\n style.fontFamily = element.fontFamily ?? style.fontFamily;\n style.textAlign = element.textAlign ?? style.textAlign;\n }\n if (element.type === 'arrow') {\n style.startArrowhead = element.startArrowhead ?? null;\n style.endArrowhead = element.endArrowhead ?? null;\n }\n this.state.style = style;\n }\n\n selectedElements(): ExElement[] {\n return this.state.selected\n .map((id) => this.scene.get(id))\n .filter((element): element is ExElement => Boolean(element && !element.isDeleted));\n }\n\n private selectionMessage(): CvSelection | null {\n const elements = this.selectedElements().filter(\n (element) =>\n !(element.type === 'text' && element.containerId && this.state.selected.includes(element.containerId)),\n );\n if (!elements.length) return null;\n const boxes = elements.map((element) => {\n const [x1, y1, x2, y2] = absoluteCoords(element);\n return { b: [x1, y1, x2, y2] as [number, number, number, number], a: element.angle || 0 };\n });\n const locked = elements.some((element) => element.locked) || !this.state.editable;\n const ids = movingSet(\n this.scene,\n elements.map((element) => element.id),\n );\n if (elements.length === 1) {\n const element = elements[0];\n if (isLinear(element) && (element.points?.length ?? 0) >= 2) {\n const [, , , , cx, cy] = absoluteCoords(element);\n const angle = element.angle || 0;\n const points = (element.points ?? []).map(([px, py]) => {\n const x = px + element.x;\n const y = py + element.y;\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n return [(x - cx) * cos - (y - cy) * sin + cx, (x - cx) * sin + (y - cy) * cos + cy] as [number, number];\n });\n return {\n ids,\n boxes: [],\n frame: boxes[0],\n handles: locked ? 'none' : points.length === 2 ? 'none' : 'corners',\n ...(locked ? {} : { points }),\n };\n }\n return {\n ids,\n boxes,\n frame: boxes[0],\n handles: locked\n ? 'none'\n : element.type === 'text' || element.type === 'freedraw' || element.type === 'image'\n ? 'corners'\n : 'all',\n };\n }\n const bounds = commonBounds(elements)!;\n return { ids, boxes, frame: { b: bounds, a: 0 }, handles: locked ? 'none' : 'corners' };\n }\n\n // ================================================================================================ collaborators\n\n setPeers(peers: BoardPeerState[]): void {\n this.peers = peers;\n this.state.peers = [...new Set(peers.filter((peer) => !peer.gone).map((peer) => peer.userId))];\n this.send({ peers: this.peerMessage() });\n }\n\n refreshPeers(): void {\n this.send({ peers: this.peerMessage() });\n }\n\n private peerMessage(): CvPeer[] {\n return this.peers.map((peer) => {\n const who = this.options.identify(peer.userId);\n const boxes = peer.selectedIds\n .map((id) => this.scene.get(id))\n .filter((element): element is ExElement => Boolean(element && !element.isDeleted))\n .map((element) => {\n const [x1, y1, x2, y2] = absoluteCoords(element);\n return { b: [x1, y1, x2, y2] as [number, number, number, number], a: element.angle || 0 };\n });\n return {\n id: peer.peerKey,\n name: who.name,\n color: who.color,\n x: peer.gone ? null : peer.x,\n y: peer.gone ? null : peer.y,\n down: peer.down,\n boxes,\n };\n });\n }\n\n addFiles(urls: Record<string, string>): void {\n this.files = { ...this.files, ...urls };\n this.send({ files: urls });\n }\n\n // ================================================================================================ camera\n\n onView(view: CvViewEvent): void {\n const resized = view.width !== this.view.width || view.height !== this.view.height;\n this.view = view;\n if (Math.abs(this.state.zoom - view.zoom) > 1e-4) this.state.zoom = view.zoom;\n // Fit once the element knows its size — again while it is still settling (a webview grows after its first\n // layout), until the person moved the camera themselves.\n if (view.width > 0 && view.height > 0 && (!this.fitted || (resized && !this.cameraTouched))) {\n this.fitted = true;\n this.fit(false);\n } else if (!resized && this.fitted && !this.isRequested(view)) this.cameraTouched = true;\n }\n\n private requested: CvView | null = null;\n\n private isRequested(view: CvView): boolean {\n const r = this.requested;\n return (\n !!r &&\n Math.abs(r.zoom - view.zoom) < 1e-6 &&\n Math.abs(r.scrollX - view.scrollX) < 1e-3 &&\n Math.abs(r.scrollY - view.scrollY) < 1e-3\n );\n }\n\n /** The person moved the camera (pan/zoom): no automatic fitting any more. */\n private cameraTouched = false;\n\n get camera(): CvViewEvent {\n return this.view;\n }\n\n setView(view: CvView): void {\n this.requested = view;\n this.view = { ...this.view, ...view };\n this.state.zoom = view.zoom;\n this.send({ view });\n }\n\n /** Centres the content (Excalidraw's scrollToContent), at most at 100 % (`zoomToFit` may enlarge). */\n fit(enlarge = true): void {\n const bounds = commonBounds(this.scene.visible());\n const { width, height } = this.view;\n if (!width || !height) return;\n if (!bounds) {\n this.setView({ zoom: 1, scrollX: width / 2, scrollY: height / 2 });\n return;\n }\n // The floating toolbars cover about 60 px at the top and bottom: the content goes between them.\n const padding = 40;\n const bars = 64;\n const fitZoom = Math.min(\n (width - padding * 2) / Math.max(1, bounds[2] - bounds[0]),\n (height - bars * 2) / Math.max(1, bounds[3] - bounds[1]),\n );\n const zoom = Math.max(0.1, Math.min(enlarge ? 3 : 1, fitZoom));\n const cx = (bounds[0] + bounds[2]) / 2;\n const cy = (bounds[1] + bounds[3]) / 2;\n this.setView({ zoom, scrollX: width / 2 / zoom - cx, scrollY: height / 2 / zoom - cy });\n }\n\n zoomBy(factor: number): void {\n this.cameraTouched = true;\n const { width, height, zoom, scrollX, scrollY } = this.view;\n const next = Math.max(0.1, Math.min(30, factor === 0 ? 1 : zoom * factor));\n const cx = width / 2 / zoom - scrollX;\n const cy = height / 2 / zoom - scrollY;\n this.setView({ zoom: next, scrollX: width / 2 / next - cx, scrollY: height / 2 / next - cy });\n }\n\n /** The scene point at the middle of the element. */\n centre(): Point {\n const { width, height, zoom, scrollX, scrollY } = this.view;\n return [width / 2 / zoom - scrollX, height / 2 / zoom - scrollY];\n }\n\n // ================================================================================================ tool and style\n\n setTool(tool: CvTool): void {\n if (this.state.text) this.finishText();\n this.state.tool = tool;\n if (tool !== 'selection' && this.state.selected.length && tool !== 'hand') this.select([]);\n }\n\n /** A style change: the selection takes it, and new elements will. */\n setStyle(patch: Partial<ItemStyle>): void {\n this.state.style = { ...this.state.style, ...patch };\n if (!this.state.selected.length || !this.state.editable) return;\n const ids = this.state.selected;\n const { roundness, ...rest } = patch;\n const merged = new Map<string, ExElement>();\n if (Object.keys(rest).length)\n for (const element of styleElements(this.scene, ids, rest as Partial<ExElement>)) merged.set(element.id, element);\n if (roundness !== undefined) {\n for (const id of ids) {\n const element = merged.get(id) ?? this.scene.get(id);\n if (\n !element ||\n element.isDeleted ||\n element.locked ||\n !['rectangle', 'diamond', 'line', 'arrow', 'image'].includes(element.type)\n )\n continue;\n const value =\n roundness === 'round'\n ? element.type === 'rectangle' || element.type === 'image'\n ? { type: 3 }\n : { type: 2 }\n : null;\n merged.set(id, merged.has(id) ? { ...element, roundness: value } : bump(element, { roundness: value }));\n }\n }\n this.commit([...merged.values()]);\n }\n\n // ================================================================================================ commands\n\n private commit(edits: ExElement[], history = true): void {\n if (!edits.length || !this.state.editable) return;\n this.scene.commit(edits, history);\n }\n\n undo(): void {\n if (!this.state.editable) return;\n if (this.state.text) this.finishText();\n this.scene.undo();\n this.refreshSelection();\n }\n\n redo(): void {\n if (!this.state.editable) return;\n this.scene.redo();\n this.refreshSelection();\n }\n\n private refreshSelection(): void {\n const selected = this.state.selected.filter((id) => this.scene.get(id) && !this.scene.get(id)!.isDeleted);\n this.state.selected = selected;\n this.send({ selection: this.selectionMessage() });\n }\n\n deleteSelection(): void {\n if (!this.state.selected.length) return;\n this.commit(deleteElements(this.scene, this.state.selected));\n this.select([]);\n }\n\n duplicateSelection(): void {\n if (!this.state.selected.length) return;\n const copy = duplicate(this.scene, this.state.selected);\n this.commit(copy.elements);\n this.select(copy.selected);\n }\n\n selectAll(): void {\n this.setTool('selection');\n this.select(\n this.scene\n .visible()\n .filter((element) => !(element.type === 'text' && element.containerId) && !element.locked)\n .map((element) => element.id),\n );\n }\n\n reorder(move: OrderMove): void {\n if (!this.state.selected.length) return;\n this.commit(reorder(this.scene, movingSet(this.scene, this.state.selected), move));\n }\n\n group(): void {\n this.commit(group(this.scene, this.state.selected));\n this.refreshSelection();\n }\n\n ungroup(): void {\n this.commit(ungroup(this.scene, this.state.selected));\n this.refreshSelection();\n }\n\n setLocked(locked: boolean): void {\n this.commit(lockElements(this.scene, this.state.selected, locked));\n this.refreshSelection();\n }\n\n clear(): void {\n this.commit(\n deleteElements(\n this.scene,\n this.scene.visible().map((element) => element.id),\n ),\n );\n this.select([]);\n }\n\n insertImage(fileId: string, width: number, height: number): void {\n const max = 360 / Math.max(this.view.zoom, 0.1);\n const scale = Math.min(1, max / Math.max(width, height, 1));\n const w = Math.max(20, width * scale);\n const h = Math.max(20, height * scale);\n const [cx, cy] = this.centre();\n const element = {\n ...createImage(this.scene, fileId, cx - w / 2, cy - h / 2, w, h, this.state.style),\n status: 'saved' as const,\n };\n this.commit([element]);\n this.state.tool = 'selection';\n this.select([element.id]);\n }\n\n // ================================================================================================ text\n\n /** Starts editing a text element, a shape's label, or a new text at a point. */\n beginText(target: ExElement | null, at: Point): void {\n if (!this.state.editable) return;\n if (this.state.text) this.finishText();\n let id: string | null = null;\n let containerId: string | null = null;\n if (target?.type === 'text') id = target.id;\n else if (target && (target.type === 'rectangle' || target.type === 'ellipse' || target.type === 'diamond')) {\n containerId = target.id;\n id = target.boundElements?.find((bound) => bound.type === 'text')?.id ?? null;\n }\n const element = id ? this.scene.get(id) : undefined;\n this.textBefore = new Map();\n if (element) {\n this.textBefore.set(element.id, element);\n this.scene.editing.add(element.id);\n this.adoptStyle(element);\n }\n if (containerId) this.textBefore.set(containerId, this.scene.get(containerId) ?? null);\n this.state.text = { id: element ? element.id : null, x: at[0], y: at[1], containerId, value: element?.text ?? '' };\n this.select(element ? [element.id] : containerId ? [containerId] : []);\n }\n\n /** The text field changed: the element follows live (the others see it being typed). */\n typeText(value: string): void {\n const edit = this.state.text;\n if (!edit || !this.state.editable) return;\n this.state.text = { ...edit, value };\n if (edit.id && this.scene.get(edit.id) && !this.scene.get(edit.id)!.isDeleted) {\n if (!value.trim()) return;\n this.commit(editText(this.scene, edit.id, value), false);\n return;\n }\n if (!value.trim()) return;\n const container = edit.containerId ? this.scene.get(edit.containerId) : undefined;\n const lineHeight = this.state.style.fontSize * 1.25;\n const created = createText(\n this.scene,\n edit.x,\n edit.y - lineHeight / 2,\n value,\n this.state.style,\n container && !container.isDeleted ? container : undefined,\n );\n for (const element of created)\n if (!this.textBefore?.has(element.id))\n this.textBefore?.set(element.id, element.type === 'text' ? null : (this.scene.get(element.id) ?? null));\n this.commit(created, false);\n this.scene.editing.add(created[0].id);\n this.state.text = { ...edit, value, id: created[0].id };\n this.select([created[0].id]);\n }\n\n finishText(): void {\n const edit = this.state.text;\n if (!edit) return;\n this.state.text = null;\n if (edit.id) this.scene.editing.delete(edit.id);\n const element = edit.id ? this.scene.get(edit.id) : undefined;\n if (element && !element.isDeleted) {\n if (!edit.value.trim()) this.commit(deleteElements(this.scene, [element.id]), false);\n else if (element.text !== edit.value) this.commit(editText(this.scene, element.id, edit.value), false);\n }\n if (this.textBefore) this.scene.record(this.textBefore);\n this.textBefore = null;\n this.updateHistory();\n if (!this.state.toolLocked && this.state.tool === 'text') this.state.tool = 'selection';\n this.refreshSelection();\n }\n\n // ================================================================================================ element events\n\n private lastPointer: [number, number] = [0, 0];\n\n private threshold(): number {\n return 10 / Math.max(this.view.zoom, 0.1);\n }\n\n private afterDrawing(): void {\n if (!this.state.toolLocked) this.state.tool = 'selection';\n }\n\n onDown(event: CvDownEvent): void {\n if (this.state.text) this.finishText();\n const hit = hitTest(this.scene, [event.x, event.y], this.threshold(), new Set(this.state.selected));\n let grab = false;\n if (hit) {\n const ids = expandSelection(this.scene, [hit.id]);\n if (event.shift) {\n const already = this.state.selected.includes(hit.id);\n this.select(\n already\n ? this.state.selected.filter((id) => !ids.includes(id))\n : [...new Set([...this.state.selected, ...ids])],\n );\n this.shiftHandled.add(event.g);\n } else if (!this.state.selected.includes(hit.id)) this.select(ids);\n grab = this.state.editable && !hit.locked && this.state.selected.includes(hit.id);\n } else if (!event.shift && this.state.selected.length) this.select([]);\n this.options.send({\n gesture: { id: event.g, grab },\n ...(this.attached ? { selection: this.selectionMessage() } : {}),\n });\n }\n\n onTap(event: CvTapEvent): void {\n const point: Point = [event.x, event.y];\n const hit = hitTest(this.scene, point, this.threshold());\n if (event.tool === 'text') {\n this.beginText(\n hit && (hit.type === 'text' || hit.type === 'rectangle' || hit.type === 'ellipse' || hit.type === 'diamond')\n ? hit\n : null,\n point,\n );\n this.done(event.g);\n return;\n }\n if (event.tool === 'eraser') {\n if (hit) this.commit(deleteElements(this.scene, [hit.id]));\n this.done(event.g);\n return;\n }\n if (event.tool !== 'selection') {\n this.done(event.g);\n return;\n }\n if (event.count === 2 && this.state.editable) {\n // Double tap: edit a text or a shape's label, or a new text where nothing is.\n const target = hit\n ? hit.type === 'text'\n ? hit\n : hit.boundElements?.some((bound) => bound.type === 'text') ||\n hit.type === 'rectangle' ||\n hit.type === 'ellipse' ||\n hit.type === 'diamond'\n ? hit\n : null\n : null;\n if (target || !hit) this.beginText(target, point);\n this.done(event.g);\n return;\n }\n if (this.state.text) this.finishText();\n const handled = this.shiftHandled.delete(event.g);\n if (hit && event.shift && handled) {\n // the pointer-down of this click toggled it already\n } else if (hit) {\n const ids = expandSelection(this.scene, [hit.id]);\n if (event.shift) {\n const already = this.state.selected.includes(hit.id);\n this.select(\n already\n ? this.state.selected.filter((id) => !ids.includes(id))\n : [...new Set([...this.state.selected, ...ids])],\n );\n } else this.select(ids);\n } else if (!event.shift) this.select([]);\n this.done(event.g);\n }\n\n private done(g: number): void {\n this.pendingDone.push(g);\n this.send({});\n }\n\n onMove(event: CvMoveEvent): void {\n if (event.alt) {\n const copy = duplicate(this.scene, this.state.selected, 0);\n this.commit(copy.elements);\n this.commit(moveElements(this.scene, copy.selected, event.dx, event.dy));\n this.select(copy.selected);\n } else {\n this.commit(moveElements(this.scene, this.state.selected, event.dx, event.dy));\n this.pendingDone.push(event.g);\n this.send({ selection: this.selectionMessage() });\n return;\n }\n this.done(event.g);\n }\n\n onTransform(event: CvTransformEvent): void {\n const elements = this.selectedElements();\n if (event.handle === 'rotation') {\n const pivot: Point = [(event.from[0] + event.from[2]) / 2, (event.from[1] + event.from[3]) / 2];\n this.commit(rotateElements(this.scene, this.state.selected, event.angle, pivot));\n } else {\n const angle = elements.length === 1 ? elements[0].angle || 0 : 0;\n this.commit(resizeElements(this.scene, this.state.selected, event.from, event.to, angle));\n }\n this.pendingDone.push(event.g);\n this.send({ selection: this.selectionMessage() });\n }\n\n onBox(event: CvBoxEvent): void {\n const ids = inBox(this.scene, event.b);\n this.select(event.shift ? [...new Set([...this.state.selected, ...ids])] : ids);\n this.done(event.g);\n }\n\n onShape(event: CvShapeEvent): void {\n const element = createShape(this.scene, event.tool, event.b, this.state.style);\n this.commit([element]);\n this.afterDrawing();\n this.pendingDone.push(event.g);\n this.select([element.id]);\n }\n\n onLine(event: CvLineEvent): void {\n const created = createLinear(this.scene, event.tool, event.points as Point[], this.state.style, this.view.zoom);\n this.commit(created);\n this.afterDrawing();\n this.pendingDone.push(event.g);\n this.select([created[0].id]);\n }\n\n onStroke(event: CvStrokeEvent): void {\n const element = createFreeDraw(this.scene, event.points, event.pressures, this.state.style);\n this.commit([element]);\n this.done(event.g);\n }\n\n onErase(event: CvEraseEvent): void {\n const ids = erasedBy(this.scene, event.points, this.threshold());\n if (ids.length) this.commit(deleteElements(this.scene, ids));\n this.done(event.g);\n }\n\n onPoint(event: CvPointEvent): void {\n const id = this.state.selected[0];\n if (id) this.commit(movePoint(this.scene, id, event.index, event.x, event.y, this.view.zoom));\n this.pendingDone.push(event.g);\n this.send({ selection: this.selectionMessage() });\n }\n\n onCursor(x: number, y: number, down: boolean, gone: boolean): void {\n this.lastPointer = [x, y];\n this.options.pointer?.(x, y, down, this.state.selected, gone);\n }\n\n setEditable(editable: boolean): void {\n this.state.editable = editable;\n if (!editable && this.state.text) this.finishText();\n this.send({ selection: this.selectionMessage() });\n }\n\n setStatus(status: BoardStatus): void {\n this.state.status = status;\n }\n\n /** The selection's bounds (scene), for placing the floating actions. */\n selectionBounds(): [number, number, number, number] | null {\n const elements = this.selectedElements();\n return elements.length ? commonBounds(elements) : null;\n }\n\n /** Every element's box (export, tests). */\n boundsOf(id: string): [number, number, number, number] | null {\n const element = this.scene.get(id);\n return element ? elementBounds(element) : null;\n }\n\n /** Font families offered (Excalidraw 0.18's picker: hand-drawn, normal, code). */\n static readonly FONTS = [FONT_FAMILY.Excalifont, FONT_FAMILY.Nunito, FONT_FAMILY['Comic Shanns']];\n}\n"],"names":["BACKGROUND","BoardController","listener","message","_message_done","elements","all","upsert","remove","orderChanged","element","known","item","toItem","result","order","change","_this_state_text","selected","id","ids","_this_options","first","undefined","style","isLinear","_element_fontSize","_element_fontFamily","_element_textAlign","_element_startArrowhead","_element_endArrowhead","Boolean","boxes","x1","y1","x2","y2","absoluteCoords","locked","movingSet","_element_points","_element_points1","cx","cy","angle","points","px","py","x","y","cos","Math","sin","bounds","commonBounds","peers","Set","peer","who","urls","view","resized","r","enlarge","width","height","padding","bars","fitZoom","zoom","factor","scrollX","scrollY","next","tool","patch","roundness","rest","merged","Map","Object","styleElements","_merged_get","value","bump","edits","history","deleteElements","copy","duplicate","move","reorder","group","ungroup","lockElements","fileId","max","scale","w","h","createImage","target","at","_this_scene_get","containerId","_target_boundElements_find","bound","_this_textBefore","_this_textBefore1","edit","editText","container","lineHeight","created","createText","event","hit","hitTest","grab","expandSelection","already","point","_hit_boundElements","handled","g","moveElements","pivot","rotateElements","resizeElements","inBox","createShape","createLinear","createFreeDraw","erasedBy","movePoint","down","gone","editable","status","elementBounds","options","observable","DEFAULT_STYLE","FONT_FAMILY"],"mappings":";;;;;;;;;;;;;;;AAsGA,MAAMA,aAAa;AAkBZ,MAAMC;IAKX,UAAUC,QAAoB,EAAc;QAC1C,IAAI,CAAC,SAAS,CAAC,GAAG,CAACA;QACnB,OAAO,IAAM,IAAI,CAAC,SAAS,CAAC,MAAM,CAACA;IACrC;IAgCA,IAAI,QAAe;QACjB,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK;IAC3B;IAEA,UAAgB;QACd,IAAI,CAAC,GAAG;IACV;IAKA,SAAe;QACb,IAAI,CAAC,QAAQ,GAAG;QAChB,IAAI,CAAC,KAAK,CAAC,KAAK;QAChB,IAAI,CA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candidate.version > current.version || candidate.version === current.version && candidate.versionNonce < current.versionNonce;
4
+ }
5
+ function changedSince(elements, synced) {
6
+ return elements.filter((element)=>isNewer(element, synced.get(element.id)));
7
+ }
8
+ function chunkElements(elements, maxChars = 600000) {
9
+ const chunks = [];
10
+ let current = [];
11
+ let size = 2;
12
+ for (const element of elements){
13
+ const json = JSON.stringify(element);
14
+ if (current.length && size + json.length + 1 > maxChars) {
15
+ chunks.push(`[${current.join(',')}]`);
16
+ current = [];
17
+ size = 2;
18
+ }
19
+ current.push(json);
20
+ size += json.length + 1;
21
+ }
22
+ if (current.length) chunks.push(`[${current.join(',')}]`);
23
+ return chunks;
24
+ }
25
+ function randomNonce() {
26
+ return Math.floor(Math.random() * 2 ** 31);
27
+ }
28
+ function restoreAsEdits(saved, current, nonce = randomNonce) {
29
+ const now = new Map(current.map((element)=>[
30
+ element.id,
31
+ element
32
+ ]));
33
+ const kept = new Set(saved.map((element)=>element.id));
34
+ const restored = saved.map((element)=>{
35
+ var _ref;
36
+ var _now_get;
37
+ return {
38
+ ...element,
39
+ isDeleted: false,
40
+ version: Math.max(element.version, null != (_ref = null == (_now_get = now.get(element.id)) ? void 0 : _now_get.version) ? _ref : 0) + 1,
41
+ versionNonce: nonce()
42
+ };
43
+ });
44
+ const removed = current.filter((element)=>!kept.has(element.id) && !element.isDeleted).map((element)=>({
45
+ ...element,
46
+ isDeleted: true,
47
+ version: element.version + 1,
48
+ versionNonce: nonce()
49
+ }));
50
+ return [
51
+ ...restored,
52
+ ...removed
53
+ ];
54
+ }
55
+ function boardText(elements) {
56
+ return elements.filter((element)=>!element.isDeleted && 'string' == typeof element.text && element.text.trim()).map((element)=>element.text.trim()).join('\n');
57
+ }
58
+ function byIndex(elements) {
59
+ return [
60
+ ...elements
61
+ ].sort((a, b)=>{
62
+ var _a_index, _b_index, _a_index1, _b_index1;
63
+ return (null != (_a_index = a.index) ? _a_index : '￿') < (null != (_b_index = b.index) ? _b_index : '￿') ? -1 : (null != (_a_index1 = a.index) ? _a_index1 : '￿') > (null != (_b_index1 = b.index) ? _b_index1 : '￿') ? 1 : 0;
64
+ });
65
+ }
66
+ export { boardText, byIndex, changedSince, chunkElements, isNewer, randomNonce, restoreAsEdits };
67
+
68
+ //# sourceMappingURL=board-model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"board-model.js","sources":["../src/board-model.ts"],"sourcesContent":["/**\n * Whiteboard element bookkeeping (Plan-V3 §5.3), free of Excalidraw imports so it is testable (board-model.test.ts):\n * which elements changed since they were last synced, the reconciliation rule the server applies, batching of pushes\n * under the hub's message size, and restoring a version as ordinary edits.\n */\nexport interface BoardElement {\n id: string;\n type: string;\n version: number;\n versionNonce: number;\n isDeleted?: boolean;\n index?: string | null;\n text?: string;\n fileId?: string | null;\n [key: string]: unknown;\n}\n\n/** Excalidraw's (and the server's) rule: a higher version wins; on a tie the lower versionNonce wins. */\nexport function isNewer(\n candidate: Pick<BoardElement, 'version' | 'versionNonce'>,\n current: Pick<BoardElement, 'version' | 'versionNonce'> | undefined,\n): boolean {\n if (!current) return true;\n return (\n candidate.version > current.version ||\n (candidate.version === current.version && candidate.versionNonce < current.versionNonce)\n );\n}\n\n/** Elements whose version moved past what the server confirmed (or that it never saw). */\nexport function changedSince<T extends BoardElement>(\n elements: readonly T[],\n synced: ReadonlyMap<string, { version: number; versionNonce: number }>,\n): T[] {\n return elements.filter((element) => isNewer(element, synced.get(element.id)));\n}\n\n/**\n * JSON arrays of elements, each under <paramref name=\"maxChars\"/> characters (a hub message is at most 1 MiB, and the\n * array travels as a string inside JSON). An element larger than the limit goes alone (the server refuses it if it is\n * over its own per-element limit).\n */\nexport function chunkElements(elements: readonly BoardElement[], maxChars = 600_000): string[] {\n const chunks: string[] = [];\n let current: string[] = [];\n let size = 2;\n for (const element of elements) {\n const json = JSON.stringify(element);\n if (current.length && size + json.length + 1 > maxChars) {\n chunks.push(`[${current.join(',')}]`);\n current = [];\n size = 2;\n }\n current.push(json);\n size += json.length + 1;\n }\n if (current.length) chunks.push(`[${current.join(',')}]`);\n return chunks;\n}\n\n/** A 32-bit random nonce, like Excalidraw's `randomInteger`. */\nexport function randomNonce(): number {\n return Math.floor(Math.random() * 2 ** 31);\n}\n\n/**\n * Restoring a saved version as edits everybody receives: the version's elements come back with versions above anything\n * seen now, and elements added since are deleted (tombstones), so the reconciliation on every client and the server\n * converges on the old scene.\n */\nexport function restoreAsEdits(\n saved: readonly BoardElement[],\n current: readonly BoardElement[],\n nonce: () => number = randomNonce,\n): BoardElement[] {\n const now = new Map(current.map((element) => [element.id, element]));\n const kept = new Set(saved.map((element) => element.id));\n const restored = saved.map((element) => ({\n ...element,\n isDeleted: false,\n version: Math.max(element.version, now.get(element.id)?.version ?? 0) + 1,\n versionNonce: nonce(),\n }));\n const removed = current\n .filter((element) => !kept.has(element.id) && !element.isDeleted)\n .map((element) => ({ ...element, isDeleted: true, version: element.version + 1, versionNonce: nonce() }));\n return [...restored, ...removed];\n}\n\n/** The words on a board (text elements), for search. */\nexport function boardText(elements: readonly BoardElement[]): string {\n return elements\n .filter((element) => !element.isDeleted && typeof element.text === 'string' && element.text.trim())\n .map((element) => (element.text as string).trim())\n .join('\\n');\n}\n\n/** Fractional-index order (Excalidraw's z-order); elements without an index keep their place at the end. */\nexport function byIndex<T extends BoardElement>(elements: readonly T[]): T[] {\n return [...elements].sort((a, b) =>\n (a.index ?? '￿') < (b.index ?? '￿') ? -1 : (a.index ?? '￿') > (b.index ?? '￿') ? 1 : 0,\n );\n}\n"],"names":["isNewer","candidate","current","changedSince","elements","synced","element","chunkElements","maxChars","chunks","size","json","JSON","randomNonce","Math","restoreAsEdits","saved","nonce","now","Map","kept","Set","restored","_now_get","removed","boardText","byIndex","a","b","_a_index","_b_index","_a_index1","_b_index1"],"mappings":"AAkBO,SAASA,QACdC,SAAyD,EACzDC,OAAmE;IAEnE,IAAI,CAACA,SAAS,OAAO;IACrB,OACED,UAAU,OAAO,GAAGC,QAAQ,OAAO,IAClCD,UAAU,OAA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