@dou-ui/editor 0.1.0-alpha.15 → 0.1.0-alpha.16

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.
@@ -1 +1 @@
1
- {"version":3,"file":"board-block.js","names":["_sfc_main"],"sources":["../../src/flow/board-block.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n DouFlowControls,\n DouFlowEditor,\n defineFlowExtension,\n type FlowDocument,\n type FlowExtension,\n type FlowHistoryHandler,\n type FlowNode,\n type FlowTransaction,\n} from '@dou-ui/flow'\nimport { EyeIcon, PencilIcon } from '@dou-ui/icons'\nimport { DouButton, DouDialog } from 'dou-ui'\nimport { NodeSelection } from 'prosemirror-state'\nimport {\n computed,\n nextTick,\n onBeforeUnmount,\n onMounted,\n shallowRef,\n useTemplateRef,\n watch,\n} from 'vue'\nimport { findBlockById } from '../core/blocks'\nimport { historyCommands } from '../core/editor'\nimport { labelOf } from '../core/extension'\nimport type { BlockProps } from '../core/model'\nimport { joinStepKey, ownStepKey } from '../core/transaction'\nimport { useEditor } from '../editor'\nimport {\n BOARD_HEIGHT,\n BOARD_OPEN_EVENT,\n boardOf,\n clampHeight,\n onlyBoardChanged,\n type BoardBlockSettings,\n} from './board'\n\n/** The board with the groups this reader folded or unfolded. */\nfunction withFolded(board: FlowDocument, folded: Map<string, boolean>): FlowDocument {\n if (!folded.size) return board\n const nodes = board.nodes.map((node) => {\n if (!folded.has(node.id)) return node\n const { collapsed: _, ...data } = node.data ?? {}\n return { ...node, data: folded.get(node.id) ? { ...data, collapsed: true } : data }\n })\n return { ...board, nodes }\n}\n\nconst props = defineProps<{\n block: { id: string; type: string; props: BlockProps }\n updateProps: (props: BlockProps) => void\n selected: boolean\n editable: boolean\n settings: BoardBlockSettings\n}>()\n\nconst { view, messages } = useEditor()\nconst text = computed(() => messages.value.board)\nconst label = computed(() => labelOf(props.settings.label, messages.value))\nconst stored = computed(() => boardOf(props.block.props.board))\n/*\n * Whether a group is folded is each reader's own view, as with toggles: it\n * stays out of the document (what it holds there is kept), and is shown\n * from here.\n */\nconst folded = shallowRef(new Map<string, boolean>())\nconst board = computed(() => withFolded(stored.value, folded.value))\nconst empty = computed(() => !board.value.nodes.length)\n\n/* the fullscreen editor */\nconst open = shallowRef(false)\nwatch(open, (value) => {\n if (!value) shown.value = board.value\n})\n\nconst root = useTemplateRef<HTMLElement>('root')\nconst canvas = useTemplateRef<HTMLElement>('canvas')\nconst preview = useTemplateRef<InstanceType<typeof DouFlowEditor>>('preview')\n\n/* the height, followed live while the bar is dragged */\nconst dragged = shallowRef<number | null>(null)\nconst height = computed(\n () => dragged.value ?? clampHeight(Number(props.block.props.height) || props.settings.height),\n)\n\n/* the preview is drawn once the block comes near the screen */\nconst seen = shallowRef(typeof IntersectionObserver === 'undefined')\nlet observer: IntersectionObserver | null = null\nlet resized: ResizeObserver | null = null\nlet frame = 0\n/** Fits the preview to its box again, once the nodes have been laid out. */\nfunction refit() {\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => preview.value?.fit())\n}\nonMounted(() => {\n const element = root.value!\n element.addEventListener(BOARD_OPEN_EVENT, openEditor)\n if (!seen.value) {\n observer = new IntersectionObserver(\n (entries) => {\n if (!entries.some((entry) => entry.isIntersecting)) return\n seen.value = true\n observer?.disconnect()\n observer = null\n },\n { rootMargin: '200px' },\n )\n observer.observe(element)\n }\n if (typeof ResizeObserver !== 'undefined') {\n let width = element.clientWidth\n resized = new ResizeObserver(() => {\n if (element.clientWidth === width) return\n width = element.clientWidth\n refit()\n })\n resized.observe(element)\n }\n})\nonBeforeUnmount(() => {\n settle()\n root.value?.removeEventListener(BOARD_OPEN_EVENT, openEditor)\n observer?.disconnect()\n resized?.disconnect()\n cancelAnimationFrame(frame)\n})\n/* what the preview shows: held while the fullscreen editor covers it, so it isn't redrawn each frame */\nconst shown = shallowRef(board.value)\nwatch(board, (value) => {\n if (!open.value) shown.value = value\n})\nwatch(shown, () => void nextTick(refit))\nwatch(height, () => void nextTick(refit))\n\nfunction openEditor() {\n if (!props.editable && empty.value) return\n steps.undo = 0\n steps.redo = 0\n pending = null\n open.value = true\n}\n\nconst contentPos = () => {\n const state = view.value?.state\n return state ? (findBlockById(state.doc, props.block.id)?.contentPos ?? null) : null\n}\n\n/** The keys go to the canvas from the start: a tool's letter, `Esc` letting go of a selection. */\nfunction onOpened() {\n canvas.value?.querySelector<HTMLElement>('.dou-flow-editor')?.focus({ preventScroll: true })\n}\n\n/** Back in the document: the block selected, the editor focused. */\nfunction onClosed() {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n if (props.editable)\n editor.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, pos)))\n editor.focus()\n}\n\n/*\n * Changes on the board go into the document as they are made, so `v-model`,\n * collaboration and the other blocks see them, and into the editor's undo\n * history: undo in the fullscreen editor is the document's, one step per\n * change on the board. The frames of a drag (or nudges with the arrow keys,\n * or typing in one node) join the step of the first one; only the fields\n * they change are written, so what others change meanwhile stays theirs. A\n * cancelled drag takes its step back.\n */\nconst GROUP_WINDOW = 1000\n/** A drag going on: its group, and when its last frame came. */\nlet pending: { group: string; time: number } | null = null\n/** The steps taken on the board since it was opened, and those undone. */\nconst steps = { undo: 0, redo: 0 }\n\n/** The board as the document keeps it: groups folded as they are there; and what this reader folded. */\nfunction toDocument(next: FlowDocument): FlowDocument {\n const before = new Map(stored.value.nodes.map((node) => [node.id, node]))\n let changed: Map<string, boolean> | null = null\n const nodes = next.nodes.map((node) => {\n const mine = !!node.data?.collapsed\n const theirs = before.get(node.id)?.data?.collapsed\n if (mine === !!theirs) {\n if (folded.value.has(node.id)) (changed ??= new Map(folded.value)).delete(node.id)\n return node\n }\n if (folded.value.get(node.id) !== mine) (changed ??= new Map(folded.value)).set(node.id, mine)\n const { collapsed: _, ...data } = node.data ?? {}\n if (theirs !== undefined) return { ...node, data: { ...data, collapsed: theirs } }\n // a node with no data before has none after\n if (Object.keys(data).length || before.get(node.id)?.data) return { ...node, data }\n const { data: __, ...rest } = node\n return rest as FlowNode\n })\n if (changed) folded.value = changed\n warnDataImages(next, before)\n return { ...next, nodes }\n}\n\nlet warned = false\n/** Pictures kept in the document as data URLs make it large: say so once, while developing. */\nfunction warnDataImages(next: FlowDocument, before: Map<string, FlowNode>) {\n if (warned || process.env.NODE_ENV === 'production') return\n const added = next.nodes.find(\n (node) =>\n typeof node.data?.src === 'string' &&\n node.data.src.startsWith('data:') &&\n before.get(node.id)?.data?.src !== node.data.src,\n )\n if (!added) return\n warned = true\n console.warn(\n `[@dou-ui/editor] a picture on the \"${props.block.type}\" block is kept in the document as a data URL; pass \\`upload\\` to whiteboardBlock() to keep only its address`,\n )\n}\n\nconst currentBoard = () => {\n const pos = contentPos()\n return pos === null ? null : (view.value?.state.doc.nodeAt(pos)?.attrs.board ?? null)\n}\n\n/** Writes the board as one undo step of its own. */\nfunction record(next: unknown) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n editor.dispatch(editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta(ownStepKey, true))\n steps.undo++\n steps.redo = 0\n}\n\n/** Writes the board into the undo step before, the drag's. */\nfunction join(next: unknown) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n const tr = editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta(joinStepKey, true)\n // for the built-in history: part of the step before, however long after\n editor.dispatch(tr.setMeta('appendedTransaction', editor.state.tr))\n}\n\n/** Ends the drag going on: the next change is a step of its own. */\nfunction settle() {\n pending = null\n}\n\nfunction forward(tr: FlowTransaction) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null || !props.editable) return\n const group = tr.meta.group\n const next = toDocument(tr.doc)\n // only folded or unfolded: nothing for the document\n if (JSON.stringify(next) === JSON.stringify(currentBoard())) return\n const now = Date.now()\n if (pending && (pending.group !== group || now - pending.time >= GROUP_WINDOW)) {\n // a cancelled drag putting the board back: part of its step\n if (tr.meta.history === false) return join(next)\n settle()\n }\n if (tr.meta.history === false) {\n editor.dispatch(\n editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta('addToHistory', false),\n )\n return\n }\n if (!group) return record(next)\n if (pending) {\n pending.time = now\n return join(next)\n }\n pending = { group, time: now }\n record(next)\n}\n\n/** Undo or redo in the document; refused when it would change something besides this board. */\nfunction travel(kind: 'undo' | 'redo') {\n settle()\n const editor = view.value\n if (!editor || !steps[kind]) return false\n const before = editor.state.doc\n const commands = historyCommands(editor.state)\n if (!commands[kind](editor.state, editor.dispatch, editor)) return false\n if (!onlyBoardChanged(before, editor.state.doc, props.block.id)) {\n // the board's own steps are used up: put back what was taken\n historyCommands(editor.state)[kind === 'undo' ? 'redo' : 'undo'](\n editor.state,\n editor.dispatch,\n editor,\n )\n steps[kind] = 0\n return false\n }\n steps[kind]--\n steps[kind === 'undo' ? 'redo' : 'undo']++\n return true\n}\n\n/** A cancelled drag: the board is back where it started, and its step is taken back. */\nfunction drop(group: string) {\n if (pending?.group !== group) return\n pending = null\n const editor = view.value\n if (!editor || !steps.undo) return\n if (historyCommands(editor.state).undo(editor.state, editor.dispatch, editor)) steps.undo--\n}\n\nconst history: FlowHistoryHandler = {\n undo: () => travel('undo'),\n redo: () => travel('redo'),\n canUndo: () => steps.undo > 0,\n canRedo: () => steps.redo > 0 && !pending,\n drop,\n close: settle,\n}\nconst bridge: FlowExtension = defineFlowExtension({\n name: 'editor-board-history',\n history: () => history,\n})\nconst extensions = [...props.settings.extensions, bridge]\n\n/* changing the height: drag the bar under the block, or the arrow keys on it */\nfunction onResizeStart(event: PointerEvent) {\n if (event.button !== 0) return\n event.preventDefault()\n const bar = event.currentTarget as HTMLElement\n bar.setPointerCapture(event.pointerId)\n const startY = event.clientY\n const start = height.value\n const move = (e: PointerEvent) => (dragged.value = clampHeight(start + e.clientY - startY))\n const finish = (commit: boolean) => {\n bar.removeEventListener('pointermove', move)\n bar.removeEventListener('pointerup', up)\n bar.removeEventListener('pointercancel', cancel)\n window.removeEventListener('keydown', escape, true)\n const value = dragged.value\n dragged.value = null\n if (commit && value !== null && value !== start) props.updateProps({ height: value })\n }\n const up = () => finish(true)\n const cancel = () => finish(false)\n const escape = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return\n e.preventDefault()\n e.stopPropagation()\n finish(false)\n }\n bar.addEventListener('pointermove', move)\n bar.addEventListener('pointerup', up)\n bar.addEventListener('pointercancel', cancel)\n window.addEventListener('keydown', escape, true)\n}\n\nfunction onResizeKey(event: KeyboardEvent) {\n const by = { ArrowUp: -BOARD_HEIGHT.step, ArrowDown: BOARD_HEIGHT.step }[event.key]\n if (by) {\n event.preventDefault()\n props.updateProps({ height: clampHeight(height.value + by) })\n } else if (event.key === 'Escape') {\n event.preventDefault()\n onClosed()\n }\n}\n\nfunction resetHeight() {\n props.updateProps({ height: props.settings.height })\n}\n</script>\n\n<template>\n <div\n ref=\"root\"\n class=\"dou-editor-board\"\n :class=\"{ 'is-selected': selected, 'is-empty': empty }\"\n :style=\"{ height: `${height}px` }\"\n @dblclick=\"openEditor\"\n >\n <div v-if=\"!empty\" class=\"dou-editor-board__preview\" role=\"img\" :aria-label=\"label\">\n <DouFlowEditor\n class=\"dou-editor-board__canvas\"\n inert\n v-if=\"seen\"\n ref=\"preview\"\n :model-value=\"shown\"\n v-bind=\"settings.editorProps\"\n :extensions=\"settings.extensions\"\n readonly\n fit-view\n :fit-min-zoom=\"0.05\"\n :simple-zoom=\"0\"\n :min-zoom=\"0.05\"\n :max-zoom=\"1\"\n :bordered=\"false\"\n :searchable=\"false\"\n :commentable=\"false\"\n :pan-on-scroll=\"false\"\n />\n </div>\n <div v-else class=\"dou-editor-board__empty\">\n <span class=\"dou-editor-board__empty-text\">{{ text.empty }}</span>\n <DouButton v-if=\"editable\" size=\"sm\" variant=\"outline\" @click=\"openEditor\">\n <template #leading><PencilIcon /></template>\n {{ text.start }}\n </DouButton>\n </div>\n\n <div v-if=\"!empty\" class=\"dou-editor-board__actions\">\n <DouButton size=\"sm\" variant=\"outline\" class=\"dou-editor-board__open\" @click=\"openEditor\">\n <template #leading><PencilIcon v-if=\"editable\" /><EyeIcon v-else /></template>\n {{ editable ? text.edit : text.view }}\n </DouButton>\n </div>\n\n <div\n v-if=\"editable\"\n class=\"dou-editor-board__resize\"\n role=\"separator\"\n aria-orientation=\"horizontal\"\n tabindex=\"0\"\n :aria-label=\"text.resize\"\n :aria-valuemin=\"BOARD_HEIGHT.min\"\n :aria-valuemax=\"BOARD_HEIGHT.max\"\n :aria-valuenow=\"height\"\n data-editor-control\n @pointerdown=\"onResizeStart\"\n @keydown=\"onResizeKey\"\n @dblclick.stop=\"resetHeight\"\n />\n\n <DouDialog\n v-model:open=\"open\"\n :title=\"label\"\n fullscreen\n destroy-on-close\n @opened=\"onOpened\"\n @close=\"settle\"\n @closed=\"onClosed\"\n >\n <div ref=\"canvas\" class=\"dou-editor-board__editor\" data-editor-control>\n <DouFlowEditor\n :model-value=\"board\"\n v-bind=\"settings.editorProps\"\n :extensions=\"extensions\"\n :readonly=\"!editable\"\n fit-view\n :fit-min-zoom=\"0.1\"\n :simple-zoom=\"0.1\"\n :commentable=\"false\"\n :aria-label=\"label\"\n @transaction=\"forward\"\n >\n <DouFlowControls />\n </DouFlowEditor>\n </div>\n </DouDialog>\n </div>\n</template>\n"],"mappings":""}
1
+ {"version":3,"file":"board-block.js","names":["_sfc_main"],"sources":["../../src/flow/board-block.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n defaultNode,\n defineNodeType,\n DouFlowControls,\n DouFlowEditor,\n defineFlowExtension,\n type NodeTypeSpec,\n type FlowDocument,\n type FlowExtension,\n type FlowHistoryHandler,\n type FlowNode,\n type FlowTransaction,\n} from '@dou-ui/flow'\nimport { EyeIcon, PencilIcon, PlusIcon, SquareIcon } from '@dou-ui/icons'\nimport { DouButton, DouCommand, DouDialog, DouPopover, type CommandItem } from 'dou-ui'\nimport { NodeSelection } from 'prosemirror-state'\nimport {\n computed,\n nextTick,\n onBeforeUnmount,\n onMounted,\n shallowRef,\n useTemplateRef,\n watch,\n} from 'vue'\nimport { findBlockById } from '../core/blocks'\nimport { historyCommands } from '../core/editor'\nimport { labelOf } from '../core/extension'\nimport type { BlockProps } from '../core/model'\nimport { joinStepKey, ownStepKey } from '../core/transaction'\nimport { useEditor } from '../editor'\nimport {\n BOARD_HEIGHT,\n BOARD_OPEN_EVENT,\n boardOf,\n clampHeight,\n onlyBoardChanged,\n type BoardBlockSettings,\n} from './board'\n\n/** The board with the groups this reader folded or unfolded. */\nfunction withFolded(board: FlowDocument, folded: Map<string, boolean>): FlowDocument {\n if (!folded.size) return board\n const nodes = board.nodes.map((node) => {\n if (!folded.has(node.id)) return node\n const { collapsed: _, ...data } = node.data ?? {}\n return { ...node, data: folded.get(node.id) ? { ...data, collapsed: true } : data }\n })\n return { ...board, nodes }\n}\n\nconst props = defineProps<{\n block: { id: string; type: string; props: BlockProps }\n updateProps: (props: BlockProps) => void\n selected: boolean\n editable: boolean\n settings: BoardBlockSettings\n}>()\n\nconst { view, messages } = useEditor()\nconst text = computed(() => messages.value.board)\nconst label = computed(() => labelOf(props.settings.label, messages.value))\nconst stored = computed(() => boardOf(props.block.props.board))\n/*\n * Whether a group is folded is each reader's own view, as with toggles: it\n * stays out of the document (what it holds there is kept), and is shown\n * from here.\n */\nconst folded = shallowRef(new Map<string, boolean>())\nconst board = computed(() => withFolded(stored.value, folded.value))\nconst empty = computed(() => !board.value.nodes.length)\n\n/* the fullscreen editor */\nconst open = shallowRef(false)\nwatch(open, (value) => {\n if (!value) shown.value = board.value\n})\n\nconst root = useTemplateRef<HTMLElement>('root')\nconst canvas = useTemplateRef<HTMLElement>('canvas')\nconst preview = useTemplateRef<InstanceType<typeof DouFlowEditor>>('preview')\n\n/* the height, followed live while the bar is dragged */\nconst dragged = shallowRef<number | null>(null)\nconst height = computed(\n () => dragged.value ?? clampHeight(Number(props.block.props.height) || props.settings.height),\n)\n\n/* the preview is drawn once the block comes near the screen */\nconst seen = shallowRef(typeof IntersectionObserver === 'undefined')\nlet observer: IntersectionObserver | null = null\nlet resized: ResizeObserver | null = null\nlet frame = 0\n/** Fits the preview to its box again, once the nodes have been laid out. */\nfunction refit() {\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => preview.value?.fit())\n}\nonMounted(() => {\n const element = root.value!\n element.addEventListener(BOARD_OPEN_EVENT, openEditor)\n if (!seen.value) {\n observer = new IntersectionObserver(\n (entries) => {\n if (!entries.some((entry) => entry.isIntersecting)) return\n seen.value = true\n observer?.disconnect()\n observer = null\n },\n { rootMargin: '200px' },\n )\n observer.observe(element)\n }\n if (typeof ResizeObserver !== 'undefined') {\n let width = element.clientWidth\n resized = new ResizeObserver(() => {\n if (element.clientWidth === width) return\n width = element.clientWidth\n refit()\n })\n resized.observe(element)\n }\n})\nonBeforeUnmount(() => {\n settle()\n root.value?.removeEventListener(BOARD_OPEN_EVENT, openEditor)\n observer?.disconnect()\n resized?.disconnect()\n cancelAnimationFrame(frame)\n})\n/* what the preview shows: held while the fullscreen editor covers it, so it isn't redrawn each frame */\nconst shown = shallowRef(board.value)\nwatch(board, (value) => {\n if (!open.value) shown.value = value\n})\nwatch(shown, () => void nextTick(refit))\nwatch(height, () => void nextTick(refit))\n\nfunction openEditor() {\n if (!props.editable && empty.value) return\n steps.undo = 0\n steps.redo = 0\n pending = null\n open.value = true\n}\n\nconst contentPos = () => {\n const state = view.value?.state\n return state ? (findBlockById(state.doc, props.block.id)?.contentPos ?? null) : null\n}\n\n/** The keys go to the canvas from the start: a tool's letter, `Esc` letting go of a selection. */\nfunction onOpened() {\n canvas.value?.querySelector<HTMLElement>('.dou-flow-editor')?.focus({ preventScroll: true })\n}\n\n/** Back in the document: the block selected, the editor focused. */\nfunction onClosed() {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n if (props.editable)\n editor.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, pos)))\n editor.focus()\n}\n\n/*\n * Changes on the board go into the document as they are made, so `v-model`,\n * collaboration and the other blocks see them, and into the editor's undo\n * history: undo in the fullscreen editor is the document's, one step per\n * change on the board. The frames of a drag (or nudges with the arrow keys,\n * or typing in one node) join the step of the first one; only the fields\n * they change are written, so what others change meanwhile stays theirs. A\n * cancelled drag takes its step back.\n */\nconst GROUP_WINDOW = 1000\n/** A drag going on: its group, and when its last frame came. */\nlet pending: { group: string; time: number } | null = null\n/** The steps taken on the board since it was opened, and those undone. */\nconst steps = { undo: 0, redo: 0 }\n\n/** The board as the document keeps it: groups folded as they are there; and what this reader folded. */\nfunction toDocument(next: FlowDocument): FlowDocument {\n const before = new Map(stored.value.nodes.map((node) => [node.id, node]))\n let changed: Map<string, boolean> | null = null\n const nodes = next.nodes.map((node) => {\n const mine = !!node.data?.collapsed\n const theirs = before.get(node.id)?.data?.collapsed\n if (mine === !!theirs) {\n if (folded.value.has(node.id)) (changed ??= new Map(folded.value)).delete(node.id)\n return node\n }\n if (folded.value.get(node.id) !== mine) (changed ??= new Map(folded.value)).set(node.id, mine)\n const { collapsed: _, ...data } = node.data ?? {}\n if (theirs !== undefined) return { ...node, data: { ...data, collapsed: theirs } }\n // a node with no data before has none after\n if (Object.keys(data).length || before.get(node.id)?.data) return { ...node, data }\n const { data: __, ...rest } = node\n return rest as FlowNode\n })\n if (changed) folded.value = changed\n warnDataImages(next, before)\n return { ...next, nodes }\n}\n\nlet warned = false\n/** Pictures kept in the document as data URLs make it large: say so once, while developing. */\nfunction warnDataImages(next: FlowDocument, before: Map<string, FlowNode>) {\n if (warned || process.env.NODE_ENV === 'production') return\n const added = next.nodes.find(\n (node) =>\n typeof node.data?.src === 'string' &&\n node.data.src.startsWith('data:') &&\n before.get(node.id)?.data?.src !== node.data.src,\n )\n if (!added) return\n warned = true\n console.warn(\n `[@dou-ui/editor] a picture on the \"${props.block.type}\" block is kept in the document as a data URL; pass \\`upload\\` to whiteboardBlock() to keep only its address`,\n )\n}\n\nconst currentBoard = () => {\n const pos = contentPos()\n return pos === null ? null : (view.value?.state.doc.nodeAt(pos)?.attrs.board ?? null)\n}\n\n/** Writes the board as one undo step of its own. */\nfunction record(next: unknown) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n editor.dispatch(editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta(ownStepKey, true))\n steps.undo++\n steps.redo = 0\n}\n\n/** Writes the board into the undo step before, the drag's. */\nfunction join(next: unknown) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n const tr = editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta(joinStepKey, true)\n // for the built-in history: part of the step before, however long after\n editor.dispatch(tr.setMeta('appendedTransaction', editor.state.tr))\n}\n\n/** Ends the drag going on: the next change is a step of its own. */\nfunction settle() {\n pending = null\n}\n\nfunction forward(tr: FlowTransaction) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null || !props.editable) return\n const group = tr.meta.group\n const next = toDocument(tr.doc)\n // only folded or unfolded: nothing for the document\n if (JSON.stringify(next) === JSON.stringify(currentBoard())) return\n const now = Date.now()\n if (pending && (pending.group !== group || now - pending.time >= GROUP_WINDOW)) {\n // a cancelled drag putting the board back: part of its step\n if (tr.meta.history === false) return join(next)\n settle()\n }\n if (tr.meta.history === false) {\n editor.dispatch(\n editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta('addToHistory', false),\n )\n return\n }\n if (!group) return record(next)\n if (pending) {\n pending.time = now\n return join(next)\n }\n pending = { group, time: now }\n record(next)\n}\n\n/** Undo or redo in the document; refused when it would change something besides this board. */\nfunction travel(kind: 'undo' | 'redo') {\n settle()\n const editor = view.value\n if (!editor || !steps[kind]) return false\n const before = editor.state.doc\n const commands = historyCommands(editor.state)\n if (!commands[kind](editor.state, editor.dispatch, editor)) return false\n if (!onlyBoardChanged(before, editor.state.doc, props.block.id)) {\n // the board's own steps are used up: put back what was taken\n historyCommands(editor.state)[kind === 'undo' ? 'redo' : 'undo'](\n editor.state,\n editor.dispatch,\n editor,\n )\n steps[kind] = 0\n return false\n }\n steps[kind]--\n steps[kind === 'undo' ? 'redo' : 'undo']++\n return true\n}\n\n/** A cancelled drag: the board is back where it started, and its step is taken back. */\nfunction drop(group: string) {\n if (pending?.group !== group) return\n pending = null\n const editor = view.value\n if (!editor || !steps.undo) return\n if (historyCommands(editor.state).undo(editor.state, editor.dispatch, editor)) steps.undo--\n}\n\nconst history: FlowHistoryHandler = {\n undo: () => travel('undo'),\n redo: () => travel('redo'),\n canUndo: () => steps.undo > 0,\n canRedo: () => steps.redo > 0 && !pending,\n drop,\n close: settle,\n}\nconst bridge: FlowExtension = defineFlowExtension({\n name: 'editor-board-history',\n history: () => history,\n})\nconst extensions = [...props.settings.extensions, bridge]\n\n/*\n * Adding nodes: the types the extensions offer (`palette`), from a button\n * at the top left. When none is offered (`flowKit()` alone), a node of its\n * own with an input and an output, so what is added can be connected right\n * away.\n */\nconst offered = [\n ...props.settings.extensions.flat(),\n { nodeTypes: props.settings.editorProps.nodeTypes ?? [] },\n].some((extension) => extension.nodeTypes?.some((spec) => spec.palette))\nconst nodeTypes = computed(() => {\n const given = (props.settings.editorProps.nodeTypes ?? []) as NodeTypeSpec[]\n if (offered || !props.settings.fallbackNode) return given\n const name = text.value.node\n const step = defineNodeType({\n ...defaultNode,\n defaults: () => ({ label: name, inputs: [{ id: 'in' }], outputs: [{ id: 'out' }] }),\n palette: { label: name, icon: SquareIcon },\n }) as unknown as NodeTypeSpec\n return [step, ...given]\n})\nconst full = useTemplateRef<InstanceType<typeof DouFlowEditor>>('full')\nconst palette = computed(() => (props.editable ? (full.value?.paletteTypes ?? []) : []))\n/* several types: the same searchable list as when an edge is dropped on the canvas */\nconst adding = shallowRef(false)\nconst query = shallowRef('')\nconst addTrigger = useTemplateRef<InstanceType<typeof DouButton>>('addTrigger')\nconst command = useTemplateRef<InstanceType<typeof DouCommand>>('command')\nconst items = computed<CommandItem[]>(() =>\n palette.value.map((spec) => ({\n value: spec.type,\n label: spec.palette!.label,\n group: spec.palette!.group,\n description: spec.palette!.description,\n keywords: spec.palette!.keywords,\n icon: spec.palette!.icon,\n })),\n)\nwatch(adding, (value) => {\n if (!value) return\n query.value = ''\n // a phone's keyboard would cover the list: search only with a mouse\n if (!matchMedia('(pointer: coarse)').matches) void nextTick(() => command.value?.focus())\n})\n\nfunction addNode(type: string) {\n adding.value = false\n full.value?.insertNode(type)\n}\nfunction dragNode(type: string, event: PointerEvent) {\n if (event.button !== 0) return\n full.value?.startInsertDrag(type, event)\n // the list goes once the node is dropped, or the drag ends otherwise\n window.addEventListener(\n 'pointerup',\n () => {\n if (!adding.value) return\n adding.value = false\n // a drag let go of (or cancelled) off the canvas: back to the button\n void nextTick(() => {\n // the list may not be hidden yet: focus still in its search field\n const active = document.activeElement\n const list = command.value?.$el as HTMLElement | undefined\n if (!active || active === document.body || list?.contains(active))\n (addTrigger.value?.$el as HTMLElement | undefined)?.focus({ preventScroll: true })\n })\n },\n { once: true },\n )\n}\n\n/** A label cut into the letters the search matched and the rest. */\nfunction parts(name: string, indices: number[]) {\n const hit = new Set(indices)\n const out: { text: string; match: boolean }[] = []\n for (let i = 0; i < name.length; i++) {\n const match = hit.has(i)\n const last = out[out.length - 1]\n if (last && last.match === match) last.text += name[i]\n else out.push({ text: name[i]!, match })\n }\n return out\n}\n\n/* changing the height: drag the bar under the block, or the arrow keys on it */\nfunction onResizeStart(event: PointerEvent) {\n if (event.button !== 0) return\n event.preventDefault()\n const bar = event.currentTarget as HTMLElement\n bar.setPointerCapture(event.pointerId)\n const startY = event.clientY\n const start = height.value\n const move = (e: PointerEvent) => (dragged.value = clampHeight(start + e.clientY - startY))\n const finish = (commit: boolean) => {\n bar.removeEventListener('pointermove', move)\n bar.removeEventListener('pointerup', up)\n bar.removeEventListener('pointercancel', cancel)\n window.removeEventListener('keydown', escape, true)\n const value = dragged.value\n dragged.value = null\n if (commit && value !== null && value !== start) props.updateProps({ height: value })\n }\n const up = () => finish(true)\n const cancel = () => finish(false)\n const escape = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return\n e.preventDefault()\n e.stopPropagation()\n finish(false)\n }\n bar.addEventListener('pointermove', move)\n bar.addEventListener('pointerup', up)\n bar.addEventListener('pointercancel', cancel)\n window.addEventListener('keydown', escape, true)\n}\n\nfunction onResizeKey(event: KeyboardEvent) {\n const by = { ArrowUp: -BOARD_HEIGHT.step, ArrowDown: BOARD_HEIGHT.step }[event.key]\n if (by) {\n event.preventDefault()\n props.updateProps({ height: clampHeight(height.value + by) })\n } else if (event.key === 'Escape') {\n event.preventDefault()\n onClosed()\n }\n}\n\nfunction resetHeight() {\n props.updateProps({ height: props.settings.height })\n}\n</script>\n\n<template>\n <div\n ref=\"root\"\n class=\"dou-editor-board\"\n :class=\"{ 'is-selected': selected, 'is-empty': empty }\"\n :style=\"{ height: `${height}px` }\"\n @dblclick=\"openEditor\"\n >\n <div v-if=\"!empty\" class=\"dou-editor-board__preview\" role=\"img\" :aria-label=\"label\">\n <DouFlowEditor\n class=\"dou-editor-board__canvas\"\n inert\n v-if=\"seen\"\n ref=\"preview\"\n :model-value=\"shown\"\n v-bind=\"settings.editorProps\"\n :extensions=\"settings.extensions\"\n :node-types=\"nodeTypes\"\n readonly\n fit-view\n :fit-min-zoom=\"0.05\"\n :simple-zoom=\"0\"\n :min-zoom=\"0.05\"\n :max-zoom=\"1\"\n :bordered=\"false\"\n :searchable=\"false\"\n :commentable=\"false\"\n :pan-on-scroll=\"false\"\n />\n </div>\n <div v-else class=\"dou-editor-board__empty\">\n <span class=\"dou-editor-board__empty-text\">{{ text.empty }}</span>\n <DouButton v-if=\"editable\" size=\"sm\" variant=\"outline\" @click=\"openEditor\">\n <template #leading><PencilIcon /></template>\n {{ text.start }}\n </DouButton>\n </div>\n\n <div v-if=\"!empty\" class=\"dou-editor-board__actions\">\n <DouButton size=\"sm\" variant=\"outline\" class=\"dou-editor-board__open\" @click=\"openEditor\">\n <template #leading><PencilIcon v-if=\"editable\" /><EyeIcon v-else /></template>\n {{ editable ? text.edit : text.view }}\n </DouButton>\n </div>\n\n <div\n v-if=\"editable\"\n class=\"dou-editor-board__resize\"\n role=\"separator\"\n aria-orientation=\"horizontal\"\n tabindex=\"0\"\n :aria-label=\"text.resize\"\n :aria-valuemin=\"BOARD_HEIGHT.min\"\n :aria-valuemax=\"BOARD_HEIGHT.max\"\n :aria-valuenow=\"height\"\n data-editor-control\n @pointerdown=\"onResizeStart\"\n @keydown=\"onResizeKey\"\n @dblclick.stop=\"resetHeight\"\n />\n\n <DouDialog\n v-model:open=\"open\"\n :title=\"label\"\n fullscreen\n destroy-on-close\n @opened=\"onOpened\"\n @close=\"settle\"\n @closed=\"onClosed\"\n >\n <div ref=\"canvas\" class=\"dou-editor-board__editor\" data-editor-control>\n <DouFlowEditor\n ref=\"full\"\n :model-value=\"board\"\n v-bind=\"settings.editorProps\"\n :extensions=\"extensions\"\n :node-types=\"nodeTypes\"\n :readonly=\"!editable\"\n fit-view\n :fit-min-zoom=\"0.1\"\n :simple-zoom=\"0.1\"\n :commentable=\"false\"\n :aria-label=\"label\"\n @transaction=\"forward\"\n >\n <DouFlowControls />\n <div v-if=\"palette.length\" class=\"dou-editor-board__add\">\n <DouButton\n v-if=\"palette.length === 1\"\n size=\"sm\"\n variant=\"outline\"\n @pointerdown=\"dragNode(palette[0]!.type, $event)\"\n @click=\"addNode(palette[0]!.type)\"\n >\n <template #leading><PlusIcon /></template>\n {{ text.addNode }}\n </DouButton>\n <DouPopover v-else v-model:open=\"adding\" placement=\"bottom-start\">\n <DouButton ref=\"addTrigger\" size=\"sm\" variant=\"outline\">\n <template #leading><PlusIcon /></template>\n {{ text.addNode }}\n </DouButton>\n <template #content>\n <DouCommand\n ref=\"command\"\n v-model:query=\"query\"\n class=\"dou-editor-board__types\"\n :items=\"items\"\n :placeholder=\"text.searchNodes\"\n :aria-label=\"text.addNode\"\n :empty-text=\"text.noNodes\"\n :max-height=\"280\"\n @select=\"addNode(String($event.value))\"\n >\n <template #item=\"{ item, indices }\">\n <span\n class=\"dou-editor-board__type\"\n @pointerdown=\"dragNode(String(item.value), $event)\"\n >\n <span class=\"dou-editor-board__type-icon\">\n <component :is=\"item.icon\" v-if=\"item.icon\" />\n </span>\n <span class=\"dou-command__label\">\n <template v-for=\"(part, at) in parts(item.label, indices)\" :key=\"at\">\n <mark v-if=\"part.match\" class=\"dou-command__match\">{{ part.text }}</mark>\n <template v-else>{{ part.text }}</template>\n </template>\n </span>\n <span v-if=\"item.description\" class=\"dou-command__description\">\n {{ item.description }}\n </span>\n </span>\n </template>\n </DouCommand>\n </template>\n </DouPopover>\n </div>\n <p v-if=\"palette.length && !board.nodes.length\" class=\"dou-editor-board__hint\">\n {{ text.emptyFlow }}\n </p>\n </DouFlowEditor>\n </div>\n </DouDialog>\n </div>\n</template>\n"],"mappings":""}
@@ -4,11 +4,11 @@ import { useEditor } from "../editor.js";
4
4
  import { historyCommands } from "../core/editor.js";
5
5
  import { joinStepKey, ownStepKey } from "../core/transaction.js";
6
6
  import { BOARD_HEIGHT, BOARD_OPEN_EVENT, boardOf, clampHeight, onlyBoardChanged } from "./board.js";
7
- import { DouButton, DouDialog } from "dou-ui";
8
- import { computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, mergeProps, nextTick, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, shallowRef, toDisplayString, unref, useTemplateRef, watch, withCtx, withModifiers } from "vue";
7
+ import { DouButton, DouCommand, DouDialog, DouPopover } from "dou-ui";
8
+ import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, mergeProps, nextTick, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, renderList, resolveDynamicComponent, shallowRef, toDisplayString, unref, useTemplateRef, watch, withCtx, withModifiers } from "vue";
9
9
  import { NodeSelection } from "prosemirror-state";
10
- import { EyeIcon, PencilIcon } from "@dou-ui/icons";
11
- import { DouFlowControls, DouFlowEditor, defineFlowExtension } from "@dou-ui/flow";
10
+ import { EyeIcon, PencilIcon, PlusIcon, SquareIcon } from "@dou-ui/icons";
11
+ import { DouFlowControls, DouFlowEditor, defaultNode, defineFlowExtension, defineNodeType } from "@dou-ui/flow";
12
12
  // src/flow/board-block.vue?vue&type=script&setup=true&lang.ts
13
13
  var _hoisted_1 = ["aria-label"];
14
14
  var _hoisted_2 = {
@@ -26,6 +26,25 @@ var _hoisted_5 = [
26
26
  "aria-valuemax",
27
27
  "aria-valuenow"
28
28
  ];
29
+ var _hoisted_6 = {
30
+ key: 0,
31
+ class: "dou-editor-board__add"
32
+ };
33
+ var _hoisted_7 = ["onPointerdown"];
34
+ var _hoisted_8 = { class: "dou-editor-board__type-icon" };
35
+ var _hoisted_9 = { class: "dou-command__label" };
36
+ var _hoisted_10 = {
37
+ key: 0,
38
+ class: "dou-command__match"
39
+ };
40
+ var _hoisted_11 = {
41
+ key: 0,
42
+ class: "dou-command__description"
43
+ };
44
+ var _hoisted_12 = {
45
+ key: 1,
46
+ class: "dou-editor-board__hint"
47
+ };
29
48
  /** The board with the groups this reader folded or unfolded. */
30
49
  var GROUP_WINDOW = 1e3;
31
50
  /** A drag going on: its group, and when its last frame came. */
@@ -278,6 +297,75 @@ var board_block_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defi
278
297
  history: () => history
279
298
  });
280
299
  const extensions = [...props.settings.extensions, bridge];
300
+ const offered = [...props.settings.extensions.flat(), { nodeTypes: props.settings.editorProps.nodeTypes ?? [] }].some((extension) => extension.nodeTypes?.some((spec) => spec.palette));
301
+ const nodeTypes = computed(() => {
302
+ const given = props.settings.editorProps.nodeTypes ?? [];
303
+ if (offered || !props.settings.fallbackNode) return given;
304
+ const name = text.value.node;
305
+ return [defineNodeType({
306
+ ...defaultNode,
307
+ defaults: () => ({
308
+ label: name,
309
+ inputs: [{ id: "in" }],
310
+ outputs: [{ id: "out" }]
311
+ }),
312
+ palette: {
313
+ label: name,
314
+ icon: SquareIcon
315
+ }
316
+ }), ...given];
317
+ });
318
+ const full = useTemplateRef("full");
319
+ const palette = computed(() => props.editable ? full.value?.paletteTypes ?? [] : []);
320
+ const adding = shallowRef(false);
321
+ const query = shallowRef("");
322
+ const addTrigger = useTemplateRef("addTrigger");
323
+ const command = useTemplateRef("command");
324
+ const items = computed(() => palette.value.map((spec) => ({
325
+ value: spec.type,
326
+ label: spec.palette.label,
327
+ group: spec.palette.group,
328
+ description: spec.palette.description,
329
+ keywords: spec.palette.keywords,
330
+ icon: spec.palette.icon
331
+ })));
332
+ watch(adding, (value) => {
333
+ if (!value) return;
334
+ query.value = "";
335
+ if (!matchMedia("(pointer: coarse)").matches) nextTick(() => command.value?.focus());
336
+ });
337
+ function addNode(type) {
338
+ adding.value = false;
339
+ full.value?.insertNode(type);
340
+ }
341
+ function dragNode(type, event) {
342
+ if (event.button !== 0) return;
343
+ full.value?.startInsertDrag(type, event);
344
+ window.addEventListener("pointerup", () => {
345
+ if (!adding.value) return;
346
+ adding.value = false;
347
+ nextTick(() => {
348
+ const active = document.activeElement;
349
+ const list = command.value?.$el;
350
+ if (!active || active === document.body || list?.contains(active)) (addTrigger.value?.$el)?.focus({ preventScroll: true });
351
+ });
352
+ }, { once: true });
353
+ }
354
+ /** A label cut into the letters the search matched and the rest. */
355
+ function parts(name, indices) {
356
+ const hit = new Set(indices);
357
+ const out = [];
358
+ for (let i = 0; i < name.length; i++) {
359
+ const match = hit.has(i);
360
+ const last = out[out.length - 1];
361
+ if (last && last.match === match) last.text += name[i];
362
+ else out.push({
363
+ text: name[i],
364
+ match
365
+ });
366
+ }
367
+ return out;
368
+ }
281
369
  function onResizeStart(event) {
282
370
  if (event.button !== 0) return;
283
371
  event.preventDefault();
@@ -349,6 +437,7 @@ var board_block_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defi
349
437
  "model-value": shown.value
350
438
  }, __props.settings.editorProps, {
351
439
  extensions: __props.settings.extensions,
440
+ "node-types": nodeTypes.value,
352
441
  readonly: "",
353
442
  "fit-view": "",
354
443
  "fit-min-zoom": .05,
@@ -359,7 +448,11 @@ var board_block_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defi
359
448
  searchable: false,
360
449
  commentable: false,
361
450
  "pan-on-scroll": false
362
- }), null, 16, ["model-value", "extensions"])) : createCommentVNode("", true)], 8, _hoisted_1)) : (openBlock(), createElementBlock("div", _hoisted_2, [createElementVNode("span", _hoisted_3, toDisplayString(text.value.empty), 1), __props.editable ? (openBlock(), createBlock(unref(DouButton), {
451
+ }), null, 16, [
452
+ "model-value",
453
+ "extensions",
454
+ "node-types"
455
+ ])) : createCommentVNode("", true)], 8, _hoisted_1)) : (openBlock(), createElementBlock("div", _hoisted_2, [createElementVNode("span", _hoisted_3, toDisplayString(text.value.empty), 1), __props.editable ? (openBlock(), createBlock(unref(DouButton), {
363
456
  key: 0,
364
457
  size: "sm",
365
458
  variant: "outline",
@@ -396,7 +489,7 @@ var board_block_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defi
396
489
  }, null, 40, _hoisted_5)) : createCommentVNode("", true),
397
490
  createVNode(unref(DouDialog), {
398
491
  open: open.value,
399
- "onUpdate:open": _cache[0] || (_cache[0] = ($event) => open.value = $event),
492
+ "onUpdate:open": _cache[5] || (_cache[5] = ($event) => open.value = $event),
400
493
  title: label.value,
401
494
  fullscreen: "",
402
495
  "destroy-on-close": "",
@@ -409,8 +502,13 @@ var board_block_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defi
409
502
  ref: canvas,
410
503
  class: "dou-editor-board__editor",
411
504
  "data-editor-control": ""
412
- }, [createVNode(unref(DouFlowEditor), mergeProps({ "model-value": board.value }, __props.settings.editorProps, {
505
+ }, [createVNode(unref(DouFlowEditor), mergeProps({
506
+ ref_key: "full",
507
+ ref: full,
508
+ "model-value": board.value
509
+ }, __props.settings.editorProps, {
413
510
  extensions,
511
+ "node-types": nodeTypes.value,
414
512
  readonly: !__props.editable,
415
513
  "fit-view": "",
416
514
  "fit-min-zoom": .1,
@@ -419,10 +517,73 @@ var board_block_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defi
419
517
  "aria-label": label.value,
420
518
  onTransaction: forward
421
519
  }), {
422
- default: withCtx(() => [createVNode(unref(DouFlowControls))]),
520
+ default: withCtx(() => [
521
+ createVNode(unref(DouFlowControls)),
522
+ palette.value.length ? (openBlock(), createElementBlock("div", _hoisted_6, [palette.value.length === 1 ? (openBlock(), createBlock(unref(DouButton), {
523
+ key: 0,
524
+ size: "sm",
525
+ variant: "outline",
526
+ onPointerdown: _cache[0] || (_cache[0] = ($event) => dragNode(palette.value[0].type, $event)),
527
+ onClick: _cache[1] || (_cache[1] = ($event) => addNode(palette.value[0].type))
528
+ }, {
529
+ leading: withCtx(() => [createVNode(unref(PlusIcon))]),
530
+ default: withCtx(() => [createTextVNode(" " + toDisplayString(text.value.addNode), 1)]),
531
+ _: 1
532
+ })) : (openBlock(), createBlock(unref(DouPopover), {
533
+ key: 1,
534
+ open: adding.value,
535
+ "onUpdate:open": _cache[4] || (_cache[4] = ($event) => adding.value = $event),
536
+ placement: "bottom-start"
537
+ }, {
538
+ content: withCtx(() => [createVNode(unref(DouCommand), {
539
+ ref_key: "command",
540
+ ref: command,
541
+ query: query.value,
542
+ "onUpdate:query": _cache[2] || (_cache[2] = ($event) => query.value = $event),
543
+ class: "dou-editor-board__types",
544
+ items: items.value,
545
+ placeholder: text.value.searchNodes,
546
+ "aria-label": text.value.addNode,
547
+ "empty-text": text.value.noNodes,
548
+ "max-height": 280,
549
+ onSelect: _cache[3] || (_cache[3] = ($event) => addNode(String($event.value)))
550
+ }, {
551
+ item: withCtx(({ item, indices }) => [createElementVNode("span", {
552
+ class: "dou-editor-board__type",
553
+ onPointerdown: ($event) => dragNode(String(item.value), $event)
554
+ }, [
555
+ createElementVNode("span", _hoisted_8, [item.icon ? (openBlock(), createBlock(resolveDynamicComponent(item.icon), { key: 0 })) : createCommentVNode("", true)]),
556
+ createElementVNode("span", _hoisted_9, [(openBlock(true), createElementBlock(Fragment, null, renderList(parts(item.label, indices), (part, at) => {
557
+ return openBlock(), createElementBlock(Fragment, { key: at }, [part.match ? (openBlock(), createElementBlock("mark", _hoisted_10, toDisplayString(part.text), 1)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode(toDisplayString(part.text), 1)], 64))], 64);
558
+ }), 128))]),
559
+ item.description ? (openBlock(), createElementBlock("span", _hoisted_11, toDisplayString(item.description), 1)) : createCommentVNode("", true)
560
+ ], 40, _hoisted_7)]),
561
+ _: 1
562
+ }, 8, [
563
+ "query",
564
+ "items",
565
+ "placeholder",
566
+ "aria-label",
567
+ "empty-text"
568
+ ])]),
569
+ default: withCtx(() => [createVNode(unref(DouButton), {
570
+ ref_key: "addTrigger",
571
+ ref: addTrigger,
572
+ size: "sm",
573
+ variant: "outline"
574
+ }, {
575
+ leading: withCtx(() => [createVNode(unref(PlusIcon))]),
576
+ default: withCtx(() => [createTextVNode(" " + toDisplayString(text.value.addNode), 1)]),
577
+ _: 1
578
+ }, 512)]),
579
+ _: 1
580
+ }, 8, ["open"]))])) : createCommentVNode("", true),
581
+ palette.value.length && !board.value.nodes.length ? (openBlock(), createElementBlock("p", _hoisted_12, toDisplayString(text.value.emptyFlow), 1)) : createCommentVNode("", true)
582
+ ]),
423
583
  _: 1
424
584
  }, 16, [
425
585
  "model-value",
586
+ "node-types",
426
587
  "readonly",
427
588
  "aria-label"
428
589
  ])], 512)]),
@@ -1 +1 @@
1
- {"version":3,"file":"board-block.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createElementBlock","_normalizeClass","_normalizeStyle","_createBlock","_unref","_mergeProps","_createCommentVNode","_createElementVNode","_toDisplayString","_withCtx","_createVNode","_createTextVNode","_withModifiers"],"sources":["../../src/flow/board-block.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n DouFlowControls,\n DouFlowEditor,\n defineFlowExtension,\n type FlowDocument,\n type FlowExtension,\n type FlowHistoryHandler,\n type FlowNode,\n type FlowTransaction,\n} from '@dou-ui/flow'\nimport { EyeIcon, PencilIcon } from '@dou-ui/icons'\nimport { DouButton, DouDialog } from 'dou-ui'\nimport { NodeSelection } from 'prosemirror-state'\nimport {\n computed,\n nextTick,\n onBeforeUnmount,\n onMounted,\n shallowRef,\n useTemplateRef,\n watch,\n} from 'vue'\nimport { findBlockById } from '../core/blocks'\nimport { historyCommands } from '../core/editor'\nimport { labelOf } from '../core/extension'\nimport type { BlockProps } from '../core/model'\nimport { joinStepKey, ownStepKey } from '../core/transaction'\nimport { useEditor } from '../editor'\nimport {\n BOARD_HEIGHT,\n BOARD_OPEN_EVENT,\n boardOf,\n clampHeight,\n onlyBoardChanged,\n type BoardBlockSettings,\n} from './board'\n\n/** The board with the groups this reader folded or unfolded. */\nfunction withFolded(board: FlowDocument, folded: Map<string, boolean>): FlowDocument {\n if (!folded.size) return board\n const nodes = board.nodes.map((node) => {\n if (!folded.has(node.id)) return node\n const { collapsed: _, ...data } = node.data ?? {}\n return { ...node, data: folded.get(node.id) ? { ...data, collapsed: true } : data }\n })\n return { ...board, nodes }\n}\n\nconst props = defineProps<{\n block: { id: string; type: string; props: BlockProps }\n updateProps: (props: BlockProps) => void\n selected: boolean\n editable: boolean\n settings: BoardBlockSettings\n}>()\n\nconst { view, messages } = useEditor()\nconst text = computed(() => messages.value.board)\nconst label = computed(() => labelOf(props.settings.label, messages.value))\nconst stored = computed(() => boardOf(props.block.props.board))\n/*\n * Whether a group is folded is each reader's own view, as with toggles: it\n * stays out of the document (what it holds there is kept), and is shown\n * from here.\n */\nconst folded = shallowRef(new Map<string, boolean>())\nconst board = computed(() => withFolded(stored.value, folded.value))\nconst empty = computed(() => !board.value.nodes.length)\n\n/* the fullscreen editor */\nconst open = shallowRef(false)\nwatch(open, (value) => {\n if (!value) shown.value = board.value\n})\n\nconst root = useTemplateRef<HTMLElement>('root')\nconst canvas = useTemplateRef<HTMLElement>('canvas')\nconst preview = useTemplateRef<InstanceType<typeof DouFlowEditor>>('preview')\n\n/* the height, followed live while the bar is dragged */\nconst dragged = shallowRef<number | null>(null)\nconst height = computed(\n () => dragged.value ?? clampHeight(Number(props.block.props.height) || props.settings.height),\n)\n\n/* the preview is drawn once the block comes near the screen */\nconst seen = shallowRef(typeof IntersectionObserver === 'undefined')\nlet observer: IntersectionObserver | null = null\nlet resized: ResizeObserver | null = null\nlet frame = 0\n/** Fits the preview to its box again, once the nodes have been laid out. */\nfunction refit() {\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => preview.value?.fit())\n}\nonMounted(() => {\n const element = root.value!\n element.addEventListener(BOARD_OPEN_EVENT, openEditor)\n if (!seen.value) {\n observer = new IntersectionObserver(\n (entries) => {\n if (!entries.some((entry) => entry.isIntersecting)) return\n seen.value = true\n observer?.disconnect()\n observer = null\n },\n { rootMargin: '200px' },\n )\n observer.observe(element)\n }\n if (typeof ResizeObserver !== 'undefined') {\n let width = element.clientWidth\n resized = new ResizeObserver(() => {\n if (element.clientWidth === width) return\n width = element.clientWidth\n refit()\n })\n resized.observe(element)\n }\n})\nonBeforeUnmount(() => {\n settle()\n root.value?.removeEventListener(BOARD_OPEN_EVENT, openEditor)\n observer?.disconnect()\n resized?.disconnect()\n cancelAnimationFrame(frame)\n})\n/* what the preview shows: held while the fullscreen editor covers it, so it isn't redrawn each frame */\nconst shown = shallowRef(board.value)\nwatch(board, (value) => {\n if (!open.value) shown.value = value\n})\nwatch(shown, () => void nextTick(refit))\nwatch(height, () => void nextTick(refit))\n\nfunction openEditor() {\n if (!props.editable && empty.value) return\n steps.undo = 0\n steps.redo = 0\n pending = null\n open.value = true\n}\n\nconst contentPos = () => {\n const state = view.value?.state\n return state ? (findBlockById(state.doc, props.block.id)?.contentPos ?? null) : null\n}\n\n/** The keys go to the canvas from the start: a tool's letter, `Esc` letting go of a selection. */\nfunction onOpened() {\n canvas.value?.querySelector<HTMLElement>('.dou-flow-editor')?.focus({ preventScroll: true })\n}\n\n/** Back in the document: the block selected, the editor focused. */\nfunction onClosed() {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n if (props.editable)\n editor.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, pos)))\n editor.focus()\n}\n\n/*\n * Changes on the board go into the document as they are made, so `v-model`,\n * collaboration and the other blocks see them, and into the editor's undo\n * history: undo in the fullscreen editor is the document's, one step per\n * change on the board. The frames of a drag (or nudges with the arrow keys,\n * or typing in one node) join the step of the first one; only the fields\n * they change are written, so what others change meanwhile stays theirs. A\n * cancelled drag takes its step back.\n */\nconst GROUP_WINDOW = 1000\n/** A drag going on: its group, and when its last frame came. */\nlet pending: { group: string; time: number } | null = null\n/** The steps taken on the board since it was opened, and those undone. */\nconst steps = { undo: 0, redo: 0 }\n\n/** The board as the document keeps it: groups folded as they are there; and what this reader folded. */\nfunction toDocument(next: FlowDocument): FlowDocument {\n const before = new Map(stored.value.nodes.map((node) => [node.id, node]))\n let changed: Map<string, boolean> | null = null\n const nodes = next.nodes.map((node) => {\n const mine = !!node.data?.collapsed\n const theirs = before.get(node.id)?.data?.collapsed\n if (mine === !!theirs) {\n if (folded.value.has(node.id)) (changed ??= new Map(folded.value)).delete(node.id)\n return node\n }\n if (folded.value.get(node.id) !== mine) (changed ??= new Map(folded.value)).set(node.id, mine)\n const { collapsed: _, ...data } = node.data ?? {}\n if (theirs !== undefined) return { ...node, data: { ...data, collapsed: theirs } }\n // a node with no data before has none after\n if (Object.keys(data).length || before.get(node.id)?.data) return { ...node, data }\n const { data: __, ...rest } = node\n return rest as FlowNode\n })\n if (changed) folded.value = changed\n warnDataImages(next, before)\n return { ...next, nodes }\n}\n\nlet warned = false\n/** Pictures kept in the document as data URLs make it large: say so once, while developing. */\nfunction warnDataImages(next: FlowDocument, before: Map<string, FlowNode>) {\n if (warned || process.env.NODE_ENV === 'production') return\n const added = next.nodes.find(\n (node) =>\n typeof node.data?.src === 'string' &&\n node.data.src.startsWith('data:') &&\n before.get(node.id)?.data?.src !== node.data.src,\n )\n if (!added) return\n warned = true\n console.warn(\n `[@dou-ui/editor] a picture on the \"${props.block.type}\" block is kept in the document as a data URL; pass \\`upload\\` to whiteboardBlock() to keep only its address`,\n )\n}\n\nconst currentBoard = () => {\n const pos = contentPos()\n return pos === null ? null : (view.value?.state.doc.nodeAt(pos)?.attrs.board ?? null)\n}\n\n/** Writes the board as one undo step of its own. */\nfunction record(next: unknown) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n editor.dispatch(editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta(ownStepKey, true))\n steps.undo++\n steps.redo = 0\n}\n\n/** Writes the board into the undo step before, the drag's. */\nfunction join(next: unknown) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n const tr = editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta(joinStepKey, true)\n // for the built-in history: part of the step before, however long after\n editor.dispatch(tr.setMeta('appendedTransaction', editor.state.tr))\n}\n\n/** Ends the drag going on: the next change is a step of its own. */\nfunction settle() {\n pending = null\n}\n\nfunction forward(tr: FlowTransaction) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null || !props.editable) return\n const group = tr.meta.group\n const next = toDocument(tr.doc)\n // only folded or unfolded: nothing for the document\n if (JSON.stringify(next) === JSON.stringify(currentBoard())) return\n const now = Date.now()\n if (pending && (pending.group !== group || now - pending.time >= GROUP_WINDOW)) {\n // a cancelled drag putting the board back: part of its step\n if (tr.meta.history === false) return join(next)\n settle()\n }\n if (tr.meta.history === false) {\n editor.dispatch(\n editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta('addToHistory', false),\n )\n return\n }\n if (!group) return record(next)\n if (pending) {\n pending.time = now\n return join(next)\n }\n pending = { group, time: now }\n record(next)\n}\n\n/** Undo or redo in the document; refused when it would change something besides this board. */\nfunction travel(kind: 'undo' | 'redo') {\n settle()\n const editor = view.value\n if (!editor || !steps[kind]) return false\n const before = editor.state.doc\n const commands = historyCommands(editor.state)\n if (!commands[kind](editor.state, editor.dispatch, editor)) return false\n if (!onlyBoardChanged(before, editor.state.doc, props.block.id)) {\n // the board's own steps are used up: put back what was taken\n historyCommands(editor.state)[kind === 'undo' ? 'redo' : 'undo'](\n editor.state,\n editor.dispatch,\n editor,\n )\n steps[kind] = 0\n return false\n }\n steps[kind]--\n steps[kind === 'undo' ? 'redo' : 'undo']++\n return true\n}\n\n/** A cancelled drag: the board is back where it started, and its step is taken back. */\nfunction drop(group: string) {\n if (pending?.group !== group) return\n pending = null\n const editor = view.value\n if (!editor || !steps.undo) return\n if (historyCommands(editor.state).undo(editor.state, editor.dispatch, editor)) steps.undo--\n}\n\nconst history: FlowHistoryHandler = {\n undo: () => travel('undo'),\n redo: () => travel('redo'),\n canUndo: () => steps.undo > 0,\n canRedo: () => steps.redo > 0 && !pending,\n drop,\n close: settle,\n}\nconst bridge: FlowExtension = defineFlowExtension({\n name: 'editor-board-history',\n history: () => history,\n})\nconst extensions = [...props.settings.extensions, bridge]\n\n/* changing the height: drag the bar under the block, or the arrow keys on it */\nfunction onResizeStart(event: PointerEvent) {\n if (event.button !== 0) return\n event.preventDefault()\n const bar = event.currentTarget as HTMLElement\n bar.setPointerCapture(event.pointerId)\n const startY = event.clientY\n const start = height.value\n const move = (e: PointerEvent) => (dragged.value = clampHeight(start + e.clientY - startY))\n const finish = (commit: boolean) => {\n bar.removeEventListener('pointermove', move)\n bar.removeEventListener('pointerup', up)\n bar.removeEventListener('pointercancel', cancel)\n window.removeEventListener('keydown', escape, true)\n const value = dragged.value\n dragged.value = null\n if (commit && value !== null && value !== start) props.updateProps({ height: value })\n }\n const up = () => finish(true)\n const cancel = () => finish(false)\n const escape = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return\n e.preventDefault()\n e.stopPropagation()\n finish(false)\n }\n bar.addEventListener('pointermove', move)\n bar.addEventListener('pointerup', up)\n bar.addEventListener('pointercancel', cancel)\n window.addEventListener('keydown', escape, true)\n}\n\nfunction onResizeKey(event: KeyboardEvent) {\n const by = { ArrowUp: -BOARD_HEIGHT.step, ArrowDown: BOARD_HEIGHT.step }[event.key]\n if (by) {\n event.preventDefault()\n props.updateProps({ height: clampHeight(height.value + by) })\n } else if (event.key === 'Escape') {\n event.preventDefault()\n onClosed()\n }\n}\n\nfunction resetHeight() {\n props.updateProps({ height: props.settings.height })\n}\n</script>\n\n<template>\n <div\n ref=\"root\"\n class=\"dou-editor-board\"\n :class=\"{ 'is-selected': selected, 'is-empty': empty }\"\n :style=\"{ height: `${height}px` }\"\n @dblclick=\"openEditor\"\n >\n <div v-if=\"!empty\" class=\"dou-editor-board__preview\" role=\"img\" :aria-label=\"label\">\n <DouFlowEditor\n class=\"dou-editor-board__canvas\"\n inert\n v-if=\"seen\"\n ref=\"preview\"\n :model-value=\"shown\"\n v-bind=\"settings.editorProps\"\n :extensions=\"settings.extensions\"\n readonly\n fit-view\n :fit-min-zoom=\"0.05\"\n :simple-zoom=\"0\"\n :min-zoom=\"0.05\"\n :max-zoom=\"1\"\n :bordered=\"false\"\n :searchable=\"false\"\n :commentable=\"false\"\n :pan-on-scroll=\"false\"\n />\n </div>\n <div v-else class=\"dou-editor-board__empty\">\n <span class=\"dou-editor-board__empty-text\">{{ text.empty }}</span>\n <DouButton v-if=\"editable\" size=\"sm\" variant=\"outline\" @click=\"openEditor\">\n <template #leading><PencilIcon /></template>\n {{ text.start }}\n </DouButton>\n </div>\n\n <div v-if=\"!empty\" class=\"dou-editor-board__actions\">\n <DouButton size=\"sm\" variant=\"outline\" class=\"dou-editor-board__open\" @click=\"openEditor\">\n <template #leading><PencilIcon v-if=\"editable\" /><EyeIcon v-else /></template>\n {{ editable ? text.edit : text.view }}\n </DouButton>\n </div>\n\n <div\n v-if=\"editable\"\n class=\"dou-editor-board__resize\"\n role=\"separator\"\n aria-orientation=\"horizontal\"\n tabindex=\"0\"\n :aria-label=\"text.resize\"\n :aria-valuemin=\"BOARD_HEIGHT.min\"\n :aria-valuemax=\"BOARD_HEIGHT.max\"\n :aria-valuenow=\"height\"\n data-editor-control\n @pointerdown=\"onResizeStart\"\n @keydown=\"onResizeKey\"\n @dblclick.stop=\"resetHeight\"\n />\n\n <DouDialog\n v-model:open=\"open\"\n :title=\"label\"\n fullscreen\n destroy-on-close\n @opened=\"onOpened\"\n @close=\"settle\"\n @closed=\"onClosed\"\n >\n <div ref=\"canvas\" class=\"dou-editor-board__editor\" data-editor-control>\n <DouFlowEditor\n :model-value=\"board\"\n v-bind=\"settings.editorProps\"\n :extensions=\"extensions\"\n :readonly=\"!editable\"\n fit-view\n :fit-min-zoom=\"0.1\"\n :simple-zoom=\"0.1\"\n :commentable=\"false\"\n :aria-label=\"label\"\n @transaction=\"forward\"\n >\n <DouFlowControls />\n </DouFlowEditor>\n </div>\n </DouDialog>\n </div>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6KA,IAAM,eAAe;;;;;;;;;;;;EAtIrB,SAAS,WAAW,OAAqB,QAA4C;GACnF,IAAI,CAAC,OAAO,MAAM,OAAO;GACzB,MAAM,QAAQ,MAAM,MAAM,KAAK,SAAS;IACtC,IAAI,CAAC,OAAO,IAAI,KAAK,EAAE,GAAG,OAAO;IACjC,MAAM,EAAE,WAAW,GAAG,GAAG,SAAS,KAAK,QAAQ,CAAC;IAChD,OAAO;KAAE,GAAG;KAAM,MAAM,OAAO,IAAI,KAAK,EAAE,IAAI;MAAE,GAAG;MAAM,WAAW;KAAK,IAAI;IAAK;GACpF,CAAC;GACD,OAAO;IAAE,GAAG;IAAO;GAAM;EAC3B;EAEA,MAAM,QAAQ;EAQd,MAAM,EAAE,MAAM,aAAa,UAAU;EACrC,MAAM,OAAO,eAAe,SAAS,MAAM,KAAK;EAChD,MAAM,QAAQ,eAAe,QAAQ,MAAM,SAAS,OAAO,SAAS,KAAK,CAAC;EAC1E,MAAM,SAAS,eAAe,QAAQ,MAAM,MAAM,MAAM,KAAK,CAAC;EAM9D,MAAM,SAAS,2BAAW,IAAI,IAAqB,CAAC;EACpD,MAAM,QAAQ,eAAe,WAAW,OAAO,OAAO,OAAO,KAAK,CAAC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AAA,C;;;IAK/B,QAAA,YADRT,UAAA,GAAAC,mBAcE,OAAA;;KAZA,OAAM;KACN,MAAK;KACL,oBAAiB;KACjB,UAAS;KACR,cAAY,KAAA,MAAK;KACjB,iBAAeI,MAAA,YAAA,CAAY,CAAC;KAC5B,iBAAeA,MAAA,YAAA,CAAY,CAAC;KAC5B,iBAAe,OAAA;KAChB,uBAAA;KACC,eAAa;KACb,WAAS;KACT,YAAQQ,cAAO,aAAW,CAAA,MAAA,CAAA;;IAG7BF,YAyBYN,MAAA,SAAA,GAAA;KAxBF,MAAM,KAAA;KAAA,iBAAA,OAAA,OAAA,OAAA,MAAA,WAAA,KAAI,QAAA;KACjB,OAAO,MAAA;KACR,YAAA;KACA,oBAAA;KACS;KACR,SAAO;KACC;;KAET,SAAAK,cAeM,CAfNF,mBAeM,OAAA;MAfG,SAAA;MAAJ,KAAI;MAAS,OAAM;MAA2B,uBAAA;K,IACjDG,YAagBN,MAAA,aAAA,GAbhBC,WAagB,EAZb,eAAa,MAAA,MAAK,GACX,QAAA,SAAS,aAAW;MACf;MACZ,UAAQ,CAAG,QAAA;MACZ,YAAA;MACC,gBAAc;MACd,eAAa;MACb,aAAa;MACb,cAAY,MAAA;MACZ,eAAa;;MAEd,SAAAI,cAAmB,CAAnBC,YAAmBN,MAAA,eAAA,CAAA,C"}
1
+ {"version":3,"file":"board-block.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createElementBlock","_normalizeClass","_normalizeStyle","_createBlock","_unref","_mergeProps","_createCommentVNode","_createElementVNode","_toDisplayString","_withCtx","_createVNode","_createTextVNode","_withModifiers","_resolveDynamicComponent","_Fragment","_renderList"],"sources":["../../src/flow/board-block.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n defaultNode,\n defineNodeType,\n DouFlowControls,\n DouFlowEditor,\n defineFlowExtension,\n type NodeTypeSpec,\n type FlowDocument,\n type FlowExtension,\n type FlowHistoryHandler,\n type FlowNode,\n type FlowTransaction,\n} from '@dou-ui/flow'\nimport { EyeIcon, PencilIcon, PlusIcon, SquareIcon } from '@dou-ui/icons'\nimport { DouButton, DouCommand, DouDialog, DouPopover, type CommandItem } from 'dou-ui'\nimport { NodeSelection } from 'prosemirror-state'\nimport {\n computed,\n nextTick,\n onBeforeUnmount,\n onMounted,\n shallowRef,\n useTemplateRef,\n watch,\n} from 'vue'\nimport { findBlockById } from '../core/blocks'\nimport { historyCommands } from '../core/editor'\nimport { labelOf } from '../core/extension'\nimport type { BlockProps } from '../core/model'\nimport { joinStepKey, ownStepKey } from '../core/transaction'\nimport { useEditor } from '../editor'\nimport {\n BOARD_HEIGHT,\n BOARD_OPEN_EVENT,\n boardOf,\n clampHeight,\n onlyBoardChanged,\n type BoardBlockSettings,\n} from './board'\n\n/** The board with the groups this reader folded or unfolded. */\nfunction withFolded(board: FlowDocument, folded: Map<string, boolean>): FlowDocument {\n if (!folded.size) return board\n const nodes = board.nodes.map((node) => {\n if (!folded.has(node.id)) return node\n const { collapsed: _, ...data } = node.data ?? {}\n return { ...node, data: folded.get(node.id) ? { ...data, collapsed: true } : data }\n })\n return { ...board, nodes }\n}\n\nconst props = defineProps<{\n block: { id: string; type: string; props: BlockProps }\n updateProps: (props: BlockProps) => void\n selected: boolean\n editable: boolean\n settings: BoardBlockSettings\n}>()\n\nconst { view, messages } = useEditor()\nconst text = computed(() => messages.value.board)\nconst label = computed(() => labelOf(props.settings.label, messages.value))\nconst stored = computed(() => boardOf(props.block.props.board))\n/*\n * Whether a group is folded is each reader's own view, as with toggles: it\n * stays out of the document (what it holds there is kept), and is shown\n * from here.\n */\nconst folded = shallowRef(new Map<string, boolean>())\nconst board = computed(() => withFolded(stored.value, folded.value))\nconst empty = computed(() => !board.value.nodes.length)\n\n/* the fullscreen editor */\nconst open = shallowRef(false)\nwatch(open, (value) => {\n if (!value) shown.value = board.value\n})\n\nconst root = useTemplateRef<HTMLElement>('root')\nconst canvas = useTemplateRef<HTMLElement>('canvas')\nconst preview = useTemplateRef<InstanceType<typeof DouFlowEditor>>('preview')\n\n/* the height, followed live while the bar is dragged */\nconst dragged = shallowRef<number | null>(null)\nconst height = computed(\n () => dragged.value ?? clampHeight(Number(props.block.props.height) || props.settings.height),\n)\n\n/* the preview is drawn once the block comes near the screen */\nconst seen = shallowRef(typeof IntersectionObserver === 'undefined')\nlet observer: IntersectionObserver | null = null\nlet resized: ResizeObserver | null = null\nlet frame = 0\n/** Fits the preview to its box again, once the nodes have been laid out. */\nfunction refit() {\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => preview.value?.fit())\n}\nonMounted(() => {\n const element = root.value!\n element.addEventListener(BOARD_OPEN_EVENT, openEditor)\n if (!seen.value) {\n observer = new IntersectionObserver(\n (entries) => {\n if (!entries.some((entry) => entry.isIntersecting)) return\n seen.value = true\n observer?.disconnect()\n observer = null\n },\n { rootMargin: '200px' },\n )\n observer.observe(element)\n }\n if (typeof ResizeObserver !== 'undefined') {\n let width = element.clientWidth\n resized = new ResizeObserver(() => {\n if (element.clientWidth === width) return\n width = element.clientWidth\n refit()\n })\n resized.observe(element)\n }\n})\nonBeforeUnmount(() => {\n settle()\n root.value?.removeEventListener(BOARD_OPEN_EVENT, openEditor)\n observer?.disconnect()\n resized?.disconnect()\n cancelAnimationFrame(frame)\n})\n/* what the preview shows: held while the fullscreen editor covers it, so it isn't redrawn each frame */\nconst shown = shallowRef(board.value)\nwatch(board, (value) => {\n if (!open.value) shown.value = value\n})\nwatch(shown, () => void nextTick(refit))\nwatch(height, () => void nextTick(refit))\n\nfunction openEditor() {\n if (!props.editable && empty.value) return\n steps.undo = 0\n steps.redo = 0\n pending = null\n open.value = true\n}\n\nconst contentPos = () => {\n const state = view.value?.state\n return state ? (findBlockById(state.doc, props.block.id)?.contentPos ?? null) : null\n}\n\n/** The keys go to the canvas from the start: a tool's letter, `Esc` letting go of a selection. */\nfunction onOpened() {\n canvas.value?.querySelector<HTMLElement>('.dou-flow-editor')?.focus({ preventScroll: true })\n}\n\n/** Back in the document: the block selected, the editor focused. */\nfunction onClosed() {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n if (props.editable)\n editor.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, pos)))\n editor.focus()\n}\n\n/*\n * Changes on the board go into the document as they are made, so `v-model`,\n * collaboration and the other blocks see them, and into the editor's undo\n * history: undo in the fullscreen editor is the document's, one step per\n * change on the board. The frames of a drag (or nudges with the arrow keys,\n * or typing in one node) join the step of the first one; only the fields\n * they change are written, so what others change meanwhile stays theirs. A\n * cancelled drag takes its step back.\n */\nconst GROUP_WINDOW = 1000\n/** A drag going on: its group, and when its last frame came. */\nlet pending: { group: string; time: number } | null = null\n/** The steps taken on the board since it was opened, and those undone. */\nconst steps = { undo: 0, redo: 0 }\n\n/** The board as the document keeps it: groups folded as they are there; and what this reader folded. */\nfunction toDocument(next: FlowDocument): FlowDocument {\n const before = new Map(stored.value.nodes.map((node) => [node.id, node]))\n let changed: Map<string, boolean> | null = null\n const nodes = next.nodes.map((node) => {\n const mine = !!node.data?.collapsed\n const theirs = before.get(node.id)?.data?.collapsed\n if (mine === !!theirs) {\n if (folded.value.has(node.id)) (changed ??= new Map(folded.value)).delete(node.id)\n return node\n }\n if (folded.value.get(node.id) !== mine) (changed ??= new Map(folded.value)).set(node.id, mine)\n const { collapsed: _, ...data } = node.data ?? {}\n if (theirs !== undefined) return { ...node, data: { ...data, collapsed: theirs } }\n // a node with no data before has none after\n if (Object.keys(data).length || before.get(node.id)?.data) return { ...node, data }\n const { data: __, ...rest } = node\n return rest as FlowNode\n })\n if (changed) folded.value = changed\n warnDataImages(next, before)\n return { ...next, nodes }\n}\n\nlet warned = false\n/** Pictures kept in the document as data URLs make it large: say so once, while developing. */\nfunction warnDataImages(next: FlowDocument, before: Map<string, FlowNode>) {\n if (warned || process.env.NODE_ENV === 'production') return\n const added = next.nodes.find(\n (node) =>\n typeof node.data?.src === 'string' &&\n node.data.src.startsWith('data:') &&\n before.get(node.id)?.data?.src !== node.data.src,\n )\n if (!added) return\n warned = true\n console.warn(\n `[@dou-ui/editor] a picture on the \"${props.block.type}\" block is kept in the document as a data URL; pass \\`upload\\` to whiteboardBlock() to keep only its address`,\n )\n}\n\nconst currentBoard = () => {\n const pos = contentPos()\n return pos === null ? null : (view.value?.state.doc.nodeAt(pos)?.attrs.board ?? null)\n}\n\n/** Writes the board as one undo step of its own. */\nfunction record(next: unknown) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n editor.dispatch(editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta(ownStepKey, true))\n steps.undo++\n steps.redo = 0\n}\n\n/** Writes the board into the undo step before, the drag's. */\nfunction join(next: unknown) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null) return\n const tr = editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta(joinStepKey, true)\n // for the built-in history: part of the step before, however long after\n editor.dispatch(tr.setMeta('appendedTransaction', editor.state.tr))\n}\n\n/** Ends the drag going on: the next change is a step of its own. */\nfunction settle() {\n pending = null\n}\n\nfunction forward(tr: FlowTransaction) {\n const editor = view.value\n const pos = contentPos()\n if (!editor || pos === null || !props.editable) return\n const group = tr.meta.group\n const next = toDocument(tr.doc)\n // only folded or unfolded: nothing for the document\n if (JSON.stringify(next) === JSON.stringify(currentBoard())) return\n const now = Date.now()\n if (pending && (pending.group !== group || now - pending.time >= GROUP_WINDOW)) {\n // a cancelled drag putting the board back: part of its step\n if (tr.meta.history === false) return join(next)\n settle()\n }\n if (tr.meta.history === false) {\n editor.dispatch(\n editor.state.tr.setNodeAttribute(pos, 'board', next).setMeta('addToHistory', false),\n )\n return\n }\n if (!group) return record(next)\n if (pending) {\n pending.time = now\n return join(next)\n }\n pending = { group, time: now }\n record(next)\n}\n\n/** Undo or redo in the document; refused when it would change something besides this board. */\nfunction travel(kind: 'undo' | 'redo') {\n settle()\n const editor = view.value\n if (!editor || !steps[kind]) return false\n const before = editor.state.doc\n const commands = historyCommands(editor.state)\n if (!commands[kind](editor.state, editor.dispatch, editor)) return false\n if (!onlyBoardChanged(before, editor.state.doc, props.block.id)) {\n // the board's own steps are used up: put back what was taken\n historyCommands(editor.state)[kind === 'undo' ? 'redo' : 'undo'](\n editor.state,\n editor.dispatch,\n editor,\n )\n steps[kind] = 0\n return false\n }\n steps[kind]--\n steps[kind === 'undo' ? 'redo' : 'undo']++\n return true\n}\n\n/** A cancelled drag: the board is back where it started, and its step is taken back. */\nfunction drop(group: string) {\n if (pending?.group !== group) return\n pending = null\n const editor = view.value\n if (!editor || !steps.undo) return\n if (historyCommands(editor.state).undo(editor.state, editor.dispatch, editor)) steps.undo--\n}\n\nconst history: FlowHistoryHandler = {\n undo: () => travel('undo'),\n redo: () => travel('redo'),\n canUndo: () => steps.undo > 0,\n canRedo: () => steps.redo > 0 && !pending,\n drop,\n close: settle,\n}\nconst bridge: FlowExtension = defineFlowExtension({\n name: 'editor-board-history',\n history: () => history,\n})\nconst extensions = [...props.settings.extensions, bridge]\n\n/*\n * Adding nodes: the types the extensions offer (`palette`), from a button\n * at the top left. When none is offered (`flowKit()` alone), a node of its\n * own with an input and an output, so what is added can be connected right\n * away.\n */\nconst offered = [\n ...props.settings.extensions.flat(),\n { nodeTypes: props.settings.editorProps.nodeTypes ?? [] },\n].some((extension) => extension.nodeTypes?.some((spec) => spec.palette))\nconst nodeTypes = computed(() => {\n const given = (props.settings.editorProps.nodeTypes ?? []) as NodeTypeSpec[]\n if (offered || !props.settings.fallbackNode) return given\n const name = text.value.node\n const step = defineNodeType({\n ...defaultNode,\n defaults: () => ({ label: name, inputs: [{ id: 'in' }], outputs: [{ id: 'out' }] }),\n palette: { label: name, icon: SquareIcon },\n }) as unknown as NodeTypeSpec\n return [step, ...given]\n})\nconst full = useTemplateRef<InstanceType<typeof DouFlowEditor>>('full')\nconst palette = computed(() => (props.editable ? (full.value?.paletteTypes ?? []) : []))\n/* several types: the same searchable list as when an edge is dropped on the canvas */\nconst adding = shallowRef(false)\nconst query = shallowRef('')\nconst addTrigger = useTemplateRef<InstanceType<typeof DouButton>>('addTrigger')\nconst command = useTemplateRef<InstanceType<typeof DouCommand>>('command')\nconst items = computed<CommandItem[]>(() =>\n palette.value.map((spec) => ({\n value: spec.type,\n label: spec.palette!.label,\n group: spec.palette!.group,\n description: spec.palette!.description,\n keywords: spec.palette!.keywords,\n icon: spec.palette!.icon,\n })),\n)\nwatch(adding, (value) => {\n if (!value) return\n query.value = ''\n // a phone's keyboard would cover the list: search only with a mouse\n if (!matchMedia('(pointer: coarse)').matches) void nextTick(() => command.value?.focus())\n})\n\nfunction addNode(type: string) {\n adding.value = false\n full.value?.insertNode(type)\n}\nfunction dragNode(type: string, event: PointerEvent) {\n if (event.button !== 0) return\n full.value?.startInsertDrag(type, event)\n // the list goes once the node is dropped, or the drag ends otherwise\n window.addEventListener(\n 'pointerup',\n () => {\n if (!adding.value) return\n adding.value = false\n // a drag let go of (or cancelled) off the canvas: back to the button\n void nextTick(() => {\n // the list may not be hidden yet: focus still in its search field\n const active = document.activeElement\n const list = command.value?.$el as HTMLElement | undefined\n if (!active || active === document.body || list?.contains(active))\n (addTrigger.value?.$el as HTMLElement | undefined)?.focus({ preventScroll: true })\n })\n },\n { once: true },\n )\n}\n\n/** A label cut into the letters the search matched and the rest. */\nfunction parts(name: string, indices: number[]) {\n const hit = new Set(indices)\n const out: { text: string; match: boolean }[] = []\n for (let i = 0; i < name.length; i++) {\n const match = hit.has(i)\n const last = out[out.length - 1]\n if (last && last.match === match) last.text += name[i]\n else out.push({ text: name[i]!, match })\n }\n return out\n}\n\n/* changing the height: drag the bar under the block, or the arrow keys on it */\nfunction onResizeStart(event: PointerEvent) {\n if (event.button !== 0) return\n event.preventDefault()\n const bar = event.currentTarget as HTMLElement\n bar.setPointerCapture(event.pointerId)\n const startY = event.clientY\n const start = height.value\n const move = (e: PointerEvent) => (dragged.value = clampHeight(start + e.clientY - startY))\n const finish = (commit: boolean) => {\n bar.removeEventListener('pointermove', move)\n bar.removeEventListener('pointerup', up)\n bar.removeEventListener('pointercancel', cancel)\n window.removeEventListener('keydown', escape, true)\n const value = dragged.value\n dragged.value = null\n if (commit && value !== null && value !== start) props.updateProps({ height: value })\n }\n const up = () => finish(true)\n const cancel = () => finish(false)\n const escape = (e: KeyboardEvent) => {\n if (e.key !== 'Escape') return\n e.preventDefault()\n e.stopPropagation()\n finish(false)\n }\n bar.addEventListener('pointermove', move)\n bar.addEventListener('pointerup', up)\n bar.addEventListener('pointercancel', cancel)\n window.addEventListener('keydown', escape, true)\n}\n\nfunction onResizeKey(event: KeyboardEvent) {\n const by = { ArrowUp: -BOARD_HEIGHT.step, ArrowDown: BOARD_HEIGHT.step }[event.key]\n if (by) {\n event.preventDefault()\n props.updateProps({ height: clampHeight(height.value + by) })\n } else if (event.key === 'Escape') {\n event.preventDefault()\n onClosed()\n }\n}\n\nfunction resetHeight() {\n props.updateProps({ height: props.settings.height })\n}\n</script>\n\n<template>\n <div\n ref=\"root\"\n class=\"dou-editor-board\"\n :class=\"{ 'is-selected': selected, 'is-empty': empty }\"\n :style=\"{ height: `${height}px` }\"\n @dblclick=\"openEditor\"\n >\n <div v-if=\"!empty\" class=\"dou-editor-board__preview\" role=\"img\" :aria-label=\"label\">\n <DouFlowEditor\n class=\"dou-editor-board__canvas\"\n inert\n v-if=\"seen\"\n ref=\"preview\"\n :model-value=\"shown\"\n v-bind=\"settings.editorProps\"\n :extensions=\"settings.extensions\"\n :node-types=\"nodeTypes\"\n readonly\n fit-view\n :fit-min-zoom=\"0.05\"\n :simple-zoom=\"0\"\n :min-zoom=\"0.05\"\n :max-zoom=\"1\"\n :bordered=\"false\"\n :searchable=\"false\"\n :commentable=\"false\"\n :pan-on-scroll=\"false\"\n />\n </div>\n <div v-else class=\"dou-editor-board__empty\">\n <span class=\"dou-editor-board__empty-text\">{{ text.empty }}</span>\n <DouButton v-if=\"editable\" size=\"sm\" variant=\"outline\" @click=\"openEditor\">\n <template #leading><PencilIcon /></template>\n {{ text.start }}\n </DouButton>\n </div>\n\n <div v-if=\"!empty\" class=\"dou-editor-board__actions\">\n <DouButton size=\"sm\" variant=\"outline\" class=\"dou-editor-board__open\" @click=\"openEditor\">\n <template #leading><PencilIcon v-if=\"editable\" /><EyeIcon v-else /></template>\n {{ editable ? text.edit : text.view }}\n </DouButton>\n </div>\n\n <div\n v-if=\"editable\"\n class=\"dou-editor-board__resize\"\n role=\"separator\"\n aria-orientation=\"horizontal\"\n tabindex=\"0\"\n :aria-label=\"text.resize\"\n :aria-valuemin=\"BOARD_HEIGHT.min\"\n :aria-valuemax=\"BOARD_HEIGHT.max\"\n :aria-valuenow=\"height\"\n data-editor-control\n @pointerdown=\"onResizeStart\"\n @keydown=\"onResizeKey\"\n @dblclick.stop=\"resetHeight\"\n />\n\n <DouDialog\n v-model:open=\"open\"\n :title=\"label\"\n fullscreen\n destroy-on-close\n @opened=\"onOpened\"\n @close=\"settle\"\n @closed=\"onClosed\"\n >\n <div ref=\"canvas\" class=\"dou-editor-board__editor\" data-editor-control>\n <DouFlowEditor\n ref=\"full\"\n :model-value=\"board\"\n v-bind=\"settings.editorProps\"\n :extensions=\"extensions\"\n :node-types=\"nodeTypes\"\n :readonly=\"!editable\"\n fit-view\n :fit-min-zoom=\"0.1\"\n :simple-zoom=\"0.1\"\n :commentable=\"false\"\n :aria-label=\"label\"\n @transaction=\"forward\"\n >\n <DouFlowControls />\n <div v-if=\"palette.length\" class=\"dou-editor-board__add\">\n <DouButton\n v-if=\"palette.length === 1\"\n size=\"sm\"\n variant=\"outline\"\n @pointerdown=\"dragNode(palette[0]!.type, $event)\"\n @click=\"addNode(palette[0]!.type)\"\n >\n <template #leading><PlusIcon /></template>\n {{ text.addNode }}\n </DouButton>\n <DouPopover v-else v-model:open=\"adding\" placement=\"bottom-start\">\n <DouButton ref=\"addTrigger\" size=\"sm\" variant=\"outline\">\n <template #leading><PlusIcon /></template>\n {{ text.addNode }}\n </DouButton>\n <template #content>\n <DouCommand\n ref=\"command\"\n v-model:query=\"query\"\n class=\"dou-editor-board__types\"\n :items=\"items\"\n :placeholder=\"text.searchNodes\"\n :aria-label=\"text.addNode\"\n :empty-text=\"text.noNodes\"\n :max-height=\"280\"\n @select=\"addNode(String($event.value))\"\n >\n <template #item=\"{ item, indices }\">\n <span\n class=\"dou-editor-board__type\"\n @pointerdown=\"dragNode(String(item.value), $event)\"\n >\n <span class=\"dou-editor-board__type-icon\">\n <component :is=\"item.icon\" v-if=\"item.icon\" />\n </span>\n <span class=\"dou-command__label\">\n <template v-for=\"(part, at) in parts(item.label, indices)\" :key=\"at\">\n <mark v-if=\"part.match\" class=\"dou-command__match\">{{ part.text }}</mark>\n <template v-else>{{ part.text }}</template>\n </template>\n </span>\n <span v-if=\"item.description\" class=\"dou-command__description\">\n {{ item.description }}\n </span>\n </span>\n </template>\n </DouCommand>\n </template>\n </DouPopover>\n </div>\n <p v-if=\"palette.length && !board.nodes.length\" class=\"dou-editor-board__hint\">\n {{ text.emptyFlow }}\n </p>\n </DouFlowEditor>\n </div>\n </DouDialog>\n </div>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgLA,IAAM,eAAe;;;;;;;;;;;;EAtIrB,SAAS,WAAW,OAAqB,QAA4C;GACnF,IAAI,CAAC,OAAO,MAAM,OAAO;GACzB,MAAM,QAAQ,MAAM,MAAM,KAAK,SAAS;IACtC,IAAI,CAAC,OAAO,IAAI,KAAK,EAAE,GAAG,OAAO;IACjC,MAAM,EAAE,WAAW,GAAG,GAAG,SAAS,KAAK,QAAQ,CAAC;IAChD,OAAO;KAAE,GAAG;KAAM,MAAM,OAAO,IAAI,KAAK,EAAE,IAAI;MAAE,GAAG;MAAM,WAAW;KAAK,IAAI;IAAK;GACpF,CAAC;GACD,OAAO;IAAE,GAAG;IAAO;GAAM;EAC3B;EAEA,MAAM,QAAQ;EAQd,MAAM,EAAE,MAAM,aAAa,UAAU;EACrC,MAAM,OAAO,eAAe,SAAS,MAAM,KAAK;EAChD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,SAAA;SAAJ,KAAI;SAAa,MAAK;SAAK,SAAQ;;SACjC,SAAOK,cAAa,CAAZC,YAAYN,MAAA,QAAA,CAAA,C;SAAW,SAAAK,cAC1C,CAD0CE,gBAAA,MAC1CH,gBAAG,KAAA,MAAK,OAAO,GAAA,CAAA,C;;;;;OAqCZ,QAAA,MAAQ,UAAM,CAAK,MAAA,MAAM,MAAM,UAAxCT,UAAA,GAAAC,mBAEI,KAFJ,aAEIQ,gBADC,KAAA,MAAK,SAAS,GAAA,CAAA,K"}
@@ -1 +1 @@
1
- {"version":3,"file":"board.js","names":[],"sources":["../../src/flow/board.ts"],"sourcesContent":["import type { FlowDocument, FlowExtension } from '@dou-ui/flow'\nimport type { Node as PMNode } from 'prosemirror-model'\nimport type { Label } from '../core/extension'\nimport type { FlowBlockEditorProps } from './index'\n\n/** Sent to a block's element to open its fullscreen editor (`Enter` on the selected block). */\nexport const BOARD_OPEN_EVENT = 'dou-editor-board-open'\n\n/** Heights a block may have in the document, in px. */\nexport const BOARD_HEIGHT = { min: 160, max: 1200, step: 40 }\n\nexport interface BoardBlockSettings {\n label: Label\n extensions: (FlowExtension | FlowExtension[])[]\n editorProps: FlowBlockEditorProps\n height: number\n}\n\n/** The items of a list that are objects. */\nconst objects = <T>(list: unknown) =>\n Array.isArray(list)\n ? (list.filter((item) => item && typeof item === 'object' && !Array.isArray(item)) as T[])\n : []\n\n/**\n * A block's `board` prop as a flow document; one that is missing or not\n * shaped like one is read as an empty flow (nodes and edges that aren't\n * objects are left out).\n */\nexport function boardOf(value: unknown): FlowDocument {\n const source =\n value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Partial<FlowDocument>)\n : {}\n return {\n ...source,\n version: 1,\n nodes: objects(source.nodes),\n edges: objects(source.edges),\n } as FlowDocument\n}\n\nexport const clampHeight = (height: number) =>\n Math.round(Math.min(BOARD_HEIGHT.max, Math.max(BOARD_HEIGHT.min, height)))\n\n/** A block's `height` prop in px: the default when it isn't a positive number. */\nexport const heightOf = (value: unknown, fallback: number) =>\n typeof value === 'number' && value > 0 ? clampHeight(value) : fallback\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\n/** What `checkDocument` reports of a block's props: a board or height it would read differently. */\nexport function checkBoardProps(props: Record<string, unknown>) {\n const problems: { prop: string; message: string }[] = []\n const { board, height } = props\n if (board != null) {\n if (!isObject(board))\n problems.push({\n prop: 'board',\n message: 'The board is not a flow document; it would be shown empty',\n })\n else\n for (const list of ['nodes', 'edges'] as const) {\n const items = board[list]\n if (items === undefined) continue\n if (!Array.isArray(items))\n problems.push({\n prop: `board.${list}`,\n message: `\"${list}\" is not a list; it would be read as empty`,\n })\n else if (items.some((item) => !isObject(item)))\n problems.push({\n prop: `board.${list}`,\n message: `Some ${list} are not objects; they would be left out`,\n })\n }\n }\n if (height != null && !(typeof height === 'number' && height > 0))\n problems.push({\n prop: 'height',\n message: `The height ${JSON.stringify(height)} is not a positive number; the default would be used`,\n })\n else if (typeof height === 'number' && (height < BOARD_HEIGHT.min || height > BOARD_HEIGHT.max))\n problems.push({\n prop: 'height',\n message: `The height ${height} is outside ${BOARD_HEIGHT.min}–${BOARD_HEIGHT.max}; it would be clamped`,\n })\n return problems\n}\n\ninterface Found {\n pos: number\n node: PMNode\n}\n\nconst endOf = (at: Found) => at.pos + at.node.nodeSize\n/** A content node's attributes besides the board. */\nconst restOf = (node: PMNode) => JSON.stringify({ ...node.attrs, board: null })\n\n/**\n * Whether `a` and `b` differ only in the `board` prop of the block `id`:\n * an undo taken from the fullscreen editor must not change anything the\n * person can't see there.\n */\nexport function onlyBoardChanged(a: PMNode, b: PMNode, id: string): boolean {\n const find = (doc: PMNode) => {\n let found: Found | null = null\n doc.descendants((node, pos) => {\n if (found) return false\n if (node.type.name === 'block' && node.attrs.id === id) {\n found = { pos, node }\n return false\n }\n return true\n })\n return found as Found | null\n }\n const before = find(a)\n const after = find(b)\n if (!before || !after) return false\n if (!a.slice(0, before.pos).eq(b.slice(0, after.pos))) return false\n if (!a.slice(endOf(before)).eq(b.slice(endOf(after)))) return false\n const [x, y] = [before.node.firstChild!, after.node.firstChild!]\n if (x.type !== y.type) return false\n if (restOf(x) !== restOf(y)) return false\n // the children of the block, if any\n if (before.node.childCount !== after.node.childCount) return false\n return before.node.childCount < 2 || before.node.child(1).eq(after.node.child(1))\n}\n"],"mappings":";;AAMA,IAAa,mBAAmB;;AAGhC,IAAa,eAAe;CAAE,KAAK;CAAK,KAAK;CAAM,MAAM;AAAG;;AAU5D,IAAM,WAAc,SAClB,MAAM,QAAQ,IAAI,IACb,KAAK,QAAQ,SAAS,QAAQ,OAAO,SAAS,YAAY,CAAC,MAAM,QAAQ,IAAI,CAAC,IAC/E,CAAC;;;;;;AAOP,SAAgB,QAAQ,OAA8B;CACpD,MAAM,SACJ,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACrD,QACD,CAAC;CACP,OAAO;EACL,GAAG;EACH,SAAS;EACT,OAAO,QAAQ,OAAO,KAAK;EAC3B,OAAO,QAAQ,OAAO,KAAK;CAC7B;AACF;AAEA,IAAa,eAAe,WAC1B,KAAK,MAAM,KAAK,IAAI,aAAa,KAAK,KAAK,IAAI,aAAa,KAAK,MAAM,CAAC,CAAC;;AAG3E,IAAa,YAAY,OAAgB,aACvC,OAAO,UAAU,YAAY,QAAQ,IAAI,YAAY,KAAK,IAAI;AAEhE,IAAM,YAAY,UAChB,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;;AAG9D,SAAgB,gBAAgB,OAAgC;CAC9D,MAAM,WAAgD,CAAC;CACvD,MAAM,EAAE,OAAO,WAAW;CAC1B,IAAI,SAAS,MAAM;EACjB,IAAI,CAAC,SAAS,KAAK,GACjB,SAAS,KAAK;GACZ,MAAM;GACN,SAAS;EACX,CAAC;OAED,KAAK,MAAM,QAAQ,CAAC,SAAS,OAAO,GAAY;GAC9C,MAAM,QAAQ,MAA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,OAAO;CAC9D,IAAI,CAAC,EAAE,MAAM,MAAM,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,MAAM,KAAK,CAAC,CAAC,GAAG,OAAO;CAC9D,MAAM,CAAC,GAAG,KAAK,CAAC,OAAO,KAAK,YAAa,MAAM,KAAK,UAAW;CAC/D,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO;CAC9B,IAAI,OAAO,CAAC,MAAM,OAAO,CAAC,GAAG,OAAO;CAEpC,IAAI,OAAO,KAAK,eAAe,MAAM,KAAK,YAAY,OAAO;CAC7D,OAAO,OAAO,KAAK,aAAa,KAAK,OAAO,KAAK,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,KAAK,MAAM,CAAC,CAAC;AAClF"}
1
+ {"version":3,"file":"board.js","names":[],"sources":["../../src/flow/board.ts"],"sourcesContent":["import type { FlowDocument, FlowExtension } from '@dou-ui/flow'\nimport type { Node as PMNode } from 'prosemirror-model'\nimport type { Label } from '../core/extension'\nimport type { FlowBlockEditorProps } from './index'\n\n/** Sent to a block's element to open its fullscreen editor (`Enter` on the selected block). */\nexport const BOARD_OPEN_EVENT = 'dou-editor-board-open'\n\n/** Heights a block may have in the document, in px. */\nexport const BOARD_HEIGHT = { min: 160, max: 1200, step: 40 }\n\nexport interface BoardBlockSettings {\n label: Label\n extensions: (FlowExtension | FlowExtension[])[]\n editorProps: FlowBlockEditorProps\n height: number\n /** When the extensions offer no node to add, offer one with ports (not on a whiteboard, which has its tools). */\n fallbackNode: boolean\n}\n\n/** The items of a list that are objects. */\nconst objects = <T>(list: unknown) =>\n Array.isArray(list)\n ? (list.filter((item) => item && typeof item === 'object' && !Array.isArray(item)) as T[])\n : []\n\n/**\n * A block's `board` prop as a flow document; one that is missing or not\n * shaped like one is read as an empty flow (nodes and edges that aren't\n * objects are left out).\n */\nexport function boardOf(value: unknown): FlowDocument {\n const source =\n value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Partial<FlowDocument>)\n : {}\n return {\n ...source,\n version: 1,\n nodes: objects(source.nodes),\n edges: objects(source.edges),\n } as FlowDocument\n}\n\nexport const clampHeight = (height: number) =>\n Math.round(Math.min(BOARD_HEIGHT.max, Math.max(BOARD_HEIGHT.min, height)))\n\n/** A block's `height` prop in px: the default when it isn't a positive number. */\nexport const heightOf = (value: unknown, fallback: number) =>\n typeof value === 'number' && value > 0 ? clampHeight(value) : fallback\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\n/** What `checkDocument` reports of a block's props: a board or height it would read differently. */\nexport function checkBoardProps(props: Record<string, unknown>) {\n const problems: { prop: string; message: string }[] = []\n const { board, height } = props\n if (board != null) {\n if (!isObject(board))\n problems.push({\n prop: 'board',\n message: 'The board is not a flow document; it would be shown empty',\n })\n else\n for (const list of ['nodes', 'edges'] as const) {\n const items = board[list]\n if (items === undefined) continue\n if (!Array.isArray(items))\n problems.push({\n prop: `board.${list}`,\n message: `\"${list}\" is not a list; it would be read as empty`,\n })\n else if (items.some((item) => !isObject(item)))\n problems.push({\n prop: `board.${list}`,\n message: `Some ${list} are not objects; they would be left out`,\n })\n }\n }\n if (height != null && !(typeof height === 'number' && height > 0))\n problems.push({\n prop: 'height',\n message: `The height ${JSON.stringify(height)} is not a positive number; the default would be used`,\n })\n else if (typeof height === 'number' && (height < BOARD_HEIGHT.min || height > BOARD_HEIGHT.max))\n problems.push({\n prop: 'height',\n message: `The height ${height} is outside ${BOARD_HEIGHT.min}–${BOARD_HEIGHT.max}; it would be clamped`,\n })\n return problems\n}\n\ninterface Found {\n pos: number\n node: PMNode\n}\n\nconst endOf = (at: Found) => at.pos + at.node.nodeSize\n/** A content node's attributes besides the board. */\nconst restOf = (node: PMNode) => JSON.stringify({ ...node.attrs, board: null })\n\n/**\n * Whether `a` and `b` differ only in the `board` prop of the block `id`:\n * an undo taken from the fullscreen editor must not change anything the\n * person can't see there.\n */\nexport function onlyBoardChanged(a: PMNode, b: PMNode, id: string): boolean {\n const find = (doc: PMNode) => {\n let found: Found | null = null\n doc.descendants((node, pos) => {\n if (found) return false\n if (node.type.name === 'block' && node.attrs.id === id) {\n found = { pos, node }\n return false\n }\n return true\n })\n return found as Found | null\n }\n const before = find(a)\n const after = find(b)\n if (!before || !after) return false\n if (!a.slice(0, before.pos).eq(b.slice(0, after.pos))) return false\n if (!a.slice(endOf(before)).eq(b.slice(endOf(after)))) return false\n const [x, y] = [before.node.firstChild!, after.node.firstChild!]\n if (x.type !== y.type) return false\n if (restOf(x) !== restOf(y)) return false\n // the children of the block, if any\n if (before.node.childCount !== after.node.childCount) return false\n return before.node.childCount < 2 || before.node.child(1).eq(after.node.child(1))\n}\n"],"mappings":";;AAMA,IAAa,mBAAmB;;AAGhC,IAAa,eAAe;CAAE,KAAK;CAAK,KAAK;CAAM,MAAM;AAAG;;AAY5D,IAAM,WAAc,SAClB,MAAM,QAAQ,IAAI,IACb,KAAK,QAAQ,SAAS,QAAQ,OAAO,SAAS,YAAY,CAAC,MAAM,QAAQ,IAAI,CAAC,IAC/E,CAAC;;;;;;AAOP,SAAgB,QAAQ,OAA8B;CACpD,MAAM,SACJ,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACrD,QACD,CAAC;CACP,OAAO;EACL,GAAG;EACH,SAAS;EACT,OAAO,QAAQ,OAAO,KAAK;EAC3B,OAAO,QAAQ,OAAO,KAAK;CAC7B;AACF;AAEA,IAAa,eAAe,WAC1B,KAAK,MAAM,KAAK,IAAI,aAAa,KAAK,KAAK,IAAI,aAAa,KAAK,MAAM,CAAC,CAAC;;AAG3E,IAAa,YAAY,OAAgB,aACvC,OAAO,UAAU,YAAY,QAAQ,IAAI,YAAY,KAAK,IAAI;AAEhE,IAAM,YAAY,UAChB,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;;AAG9D,SAAgB,gBAAgB,OAAgC;CAC9D,MAAM,WAAgD,CAAC;CACvD,MAAM,EAAE,OA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,CAAC;CACrB,MAAM,QAAQ,KAAK,CAAC;CACpB,IAAI,CAAC,UAAU,CAAC,OAAO,OAAO;CAC9B,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,CAAC,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,CAAC,GAAG,OAAO;CAC9D,IAAI,CAAC,EAAE,MAAM,MAAM,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,MAAM,KAAK,CAAC,CAAC,GAAG,OAAO;CAC9D,MAAM,CAAC,GAAG,KAAK,CAAC,OAAO,KAAK,YAAa,MAAM,KAAK,UAAW;CAC/D,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO;CAC9B,IAAI,OAAO,CAAC,MAAM,OAAO,CAAC,GAAG,OAAO;CAEpC,IAAI,OAAO,KAAK,eAAe,MAAM,KAAK,YAAY,OAAO;CAC7D,OAAO,OAAO,KAAK,aAAa,KAAK,OAAO,KAAK,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,KAAK,MAAM,CAAC,CAAC;AAClF"}
@@ -52,12 +52,16 @@ function readFences(root, type) {
52
52
  * Needs `@dou-ui/flow` and its styles. For a whiteboard, `whiteboardBlock()`.
53
53
  */
54
54
  function flowBlock(options) {
55
+ return boardBlock(options, true);
56
+ }
57
+ function boardBlock(options, fallbackNode) {
55
58
  const { type } = options;
56
59
  const settings = {
57
60
  label: options.label,
58
61
  extensions: options.extensions ?? [flowKit()],
59
62
  editorProps: options.editorProps ?? {},
60
- height: options.height ?? 360
63
+ height: options.height ?? 360,
64
+ fallbackNode
61
65
  };
62
66
  const View = defineComponent({
63
67
  name: "DouEditorFlowBlockView",
@@ -135,7 +139,7 @@ function flowBlock(options) {
135
139
  * ```
136
140
  */
137
141
  function whiteboardBlock(options = {}) {
138
- return flowBlock({
142
+ return boardBlock({
139
143
  type: "whiteboard",
140
144
  label: (m) => m.types.whiteboard,
141
145
  extensions: [flowKit(), whiteboardKit({
@@ -159,7 +163,7 @@ function whiteboardBlock(options = {}) {
159
163
  ],
160
164
  ...options.menu
161
165
  }
162
- });
166
+ }, false);
163
167
  }
164
168
  export { boardOf, flowBlock, whiteboardBlock };
165
169
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["BoardBlock"],"sources":["../../src/flow/index.ts"],"sourcesContent":["import { flowKit, type FlowDocument, type FlowEditorProps, type FlowExtension } from '@dou-ui/flow'\nimport { whiteboardKit, type WhiteboardKitOptions } from '@dou-ui/flow/whiteboard'\nimport { ShapesIcon, WorkflowIcon } from '@dou-ui/icons'\nimport { NodeSelection, type Command } from 'prosemirror-state'\nimport { defineComponent, h } from 'vue'\nimport { labelOf, type BlockOption, type EditorExtension, type Label } from '../core/extension'\nimport { escapeHTML } from '../core/output'\nimport { defineBlock } from '../define-block'\nimport { editorLocales } from '../locale'\nimport BoardBlock from './board-block.vue'\nimport {\n boardOf,\n BOARD_OPEN_EVENT,\n checkBoardProps,\n clampHeight,\n heightOf,\n type BoardBlockSettings,\n} from './board'\n\nexport { boardOf } from './board'\n\n/** The props of the fullscreen editor that a flow block may set. */\nexport type FlowBlockEditorProps = Omit<\n FlowEditorProps,\n 'extensions' | 'readonly' | 'fitView' | 'comments' | 'author' | 'activeComment' | 'commentable'\n>\n\nexport interface FlowBlockOptions {\n /** The block type, e.g. `approvalFlow`; unique among the editor's blocks. */\n type: string\n /** What the flow is made of, as the editor's `extensions`. `[flowKit()]` by default. */\n extensions?: (FlowExtension | FlowExtension[])[]\n /** More props for the flow editors, e.g. `nodeTypes`, `portTypes` or `direction`. */\n editorProps?: FlowBlockEditorProps\n /** The block's name: the title of the fullscreen editor, and of its slash menu entry. */\n label: Label\n /** The slash menu entry, or `false` to leave it out (blocks then come from code or pasting). */\n menu?: (Omit<BlockOption, 'key' | 'type' | 'label'> & { key?: string; label?: Label }) | false\n /** The height of a new block in the document, in px. Defaults to `360`. */\n height?: number\n /**\n * How a block is written in `blocksToHTML`, e.g. an `<img>` of a picture\n * of it the app keeps. By default a `<figure>` with its name, which\n * pasting reads back as the block.\n */\n html?: (board: FlowDocument, block: { id: string; props: Record<string, unknown> }) => string\n}\n\nconst fence = (type: string) => `dou-${type}`\n\nfunction attrsOf(dom: HTMLElement, height: number) {\n let board: unknown = null\n try {\n board = JSON.parse(dom.getAttribute('data-prop-board') ?? 'null')\n } catch {\n // a board that can't be read is an empty one\n }\n // `320`, or written by hand `320px`\n const stored = Number.parseFloat(dom.getAttribute('data-prop-height') ?? '')\n return { board: board ? boardOf(board) : null, height: stored > 0 ? clampHeight(stored) : height }\n}\n\n/** Turns ```dou-<type> fences from Markdown back into blocks. */\nfunction readFences(root: HTMLElement, type: string) {\n for (const code of root.querySelectorAll<HTMLElement>(`pre > code.language-${fence(type)}`)) {\n let written: unknown\n try {\n written = JSON.parse(code.textContent ?? '')\n } catch {\n continue\n }\n // `{ height, board }`, or the board alone\n const wrapped = !!written && typeof written === 'object' && 'board' in written\n const { board, height } = (wrapped ? written : { board: written }) as {\n board: unknown\n height?: unknown\n }\n const element = root.ownerDocument.createElement('div')\n element.dataset.contentType = type\n element.setAttribute('data-prop-board', JSON.stringify(boardOf(board)))\n if (typeof height === 'number') element.setAttribute('data-prop-height', String(height))\n code.parentElement!.replaceWith(element)\n }\n}\n\n/**\n * A block that holds a flow, drawn with `@dou-ui/flow`: the document shows\n * it whole, and it is edited in a fullscreen editor (double-click, the\n * “Edit” button, or `Enter` while the block is selected). The flow is the\n * block's `board` prop; collaboration merges it node by node.\n *\n * ```ts\n * extensions: [editorKit(), flowBlock({ type: 'approvalFlow', label: '审批流程', extensions: [flowKit(), approval()] })]\n * ```\n *\n * Needs `@dou-ui/flow` and its styles. For a whiteboard, `whiteboardBlock()`.\n */\nexport function flowBlock(options: FlowBlockOptions): EditorExtension {\n const { type } = options\n const settings: BoardBlockSettings = {\n label: options.label,\n extensions: options.extensions ?? [flowKit()],\n editorProps: options.editorProps ?? {},\n height: options.height ?? 360,\n }\n const View = defineComponent({\n name: 'DouEditorFlowBlockView',\n inheritAttrs: false,\n setup(_props, { attrs }) {\n return () => h(BoardBlock, { ...attrs, settings } as never)\n },\n })\n const menu = options.menu === false ? undefined : options.menu\n const block = defineBlock({\n type,\n props: { board: null, height: settings.height },\n content: 'none',\n component: View,\n menu:\n options.menu === false\n ? undefined\n : { icon: WorkflowIcon, ...menu, label: menu?.label ?? options.label },\n spec: {\n mergeProps: { board: { lists: ['nodes', 'edges'], objects: ['data'] } },\n // for `checkDocument`: what the block would read differently\n checkProps: checkBoardProps,\n // what is copied, and what `blocksToHTML` writes\n parseDOM: [`div[data-content-type=\"${type}\"]`, `figure[data-content-type=\"${type}\"]`].map(\n (tag) => ({\n tag,\n // before the figures of images, whatever the app's HTML puts inside\n priority: 70,\n getAttrs: (dom: HTMLElement) => attrsOf(dom, settings.height),\n }),\n ),\n },\n })\n /** `Enter` on the selected block opens it. */\n const open: Command = (state, dispatch, view) => {\n const { selection } = state\n if (!(selection instanceof NodeSelection) || selection.node.type.name !== type) return false\n if (dispatch && view) {\n const dom = view.nodeDOM(selection.from) as HTMLElement | null\n dom?.querySelector('.dou-editor-board')?.dispatchEvent(new CustomEvent(BOARD_OPEN_EVENT))\n }\n return true\n }\n return {\n ...block,\n name: `flow:${type}`,\n keymap: () => ({ enter: open }),\n prepareHTML: (root) => readFences(root, type),\n output: {\n blocks: {\n [type]: {\n html: (node, { children }) => {\n const board = boardOf(node.props.board)\n // written outside an editor: in Chinese, as the other output\n const inside = options.html\n ? options.html(board, node)\n : `<figcaption>${escapeHTML(labelOf(options.label, editorLocales['zh-CN']!))}</figcaption>`\n // the board stays on the figure, so pasting it reads back the block\n return `<figure data-content-type=\"${escapeHTML(type)}\" data-prop-board=\"${escapeHTML(JSON.stringify(board))}\" data-prop-height=\"${heightOf(node.props.height, settings.height)}\">${inside}</figure>${children}`\n },\n markdown: (node, { children }) => {\n const value = {\n height: heightOf(node.props.height, settings.height),\n board: boardOf(node.props.board),\n }\n const written = `\\`\\`\\`${fence(type)}\\n${JSON.stringify(value)}\\n\\`\\`\\``\n return children ? `${written}\\n\\n${children}` : written\n },\n },\n },\n },\n }\n}\n\nexport interface WhiteboardBlockOptions\n extends\n Pick<WhiteboardKitOptions, 'upload' | 'onUploadError'>,\n Pick<FlowBlockOptions, 'height' | 'html' | 'editorProps'> {\n /** The slash menu entry, or `false` to leave it out. */\n menu?: FlowBlockOptions['menu']\n}\n\n/**\n * A whiteboard block: shapes, sticky notes, text, pen strokes, images and\n * connectors, drawn in a fullscreen editor. Pass the `upload` of `image()`\n * so pictures on the board are uploaded too, not kept in the document.\n *\n * ```ts\n * extensions: [editorKit(), whiteboardBlock({ upload })]\n * ```\n */\nexport function whiteboardBlock(options: WhiteboardBlockOptions = {}): EditorExtension {\n return flowBlock({\n type: 'whiteboard',\n label: (m) => m.types.whiteboard,\n extensions: [\n flowKit(),\n whiteboardKit({ upload: options.upload, onUploadError: options.onUploadError }),\n ],\n editorProps: options.editorProps,\n height: options.height,\n html: options.html,\n menu:\n options.menu === false\n ? false\n : {\n icon: ShapesIcon,\n hint: (m) => m.hints.whiteboard,\n keywords: ['whiteboard', 'board', 'draw', 'flowchart', 'baiban', 'huatu', 'liuchengtu'],\n ...options.menu,\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;AAgDA,IAAM,SAAS,SAAiB,OAAO;AAEvC,SAAS,QAAQ,KAAkB,QAAgB;CACjD,IAAI,QAAiB;CACrB,IAAI;EACF,QAAQ,KAAK,MAAM,IAAI,aAAa,iBAAiB,KAAK,MAAM;CAClE,QAAQ,CAER;CAEA,MAAM,SAAS,OAAO,WAAW,IAAI,aAAa,kBAAkB,KAAK,EAAE;CAC3E,OAAO;EAAE,OAAO,QAAQ,QAAQ,KAAK,IAAI;EAAM,QAAQ,SAAS,IAAI,YAAY,MAAM,IAAI;CAAO;AACnG;;AAGA,SAAS,WAAW,MAAmB,MAAc;CACnD,KAAK,MAAM,QAAQ,KAAK,iBAA8B,uBAAuB,MAAM,IAAI,GAAG,GAAG;EAC3F,IAAI;EACJ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U;EACf,MAAM;EACN,QAAQ,MAAM,EAAE,MAAM;EACtB,YAAY,CACV,QAAQ,GACR,cAAc;GAAE,QAAQ,QAAQ;GAAQ,eAAe,QAAQ;EAAc,CAAC,CAChF;EACA,aAAa,QAAQ;EACrB,QAAQ,QAAQ;EAChB,MAAM,QAAQ;EACd,MACE,QAAQ,SAAS,QACb,QACA;GACE,MAAM;GACN,OAAO,MAAM,EAAE,MAAM;GACrB,UAAU;IAAC;IAAc;IAAS;IAAQ;IAAa;IAAU;IAAS;GAAY;GACtF,GAAG,QAAQ;EACb;CACR,CAAC;AACH"}
1
+ {"version":3,"file":"index.js","names":["BoardBlock"],"sources":["../../src/flow/index.ts"],"sourcesContent":["import { flowKit, type FlowDocument, type FlowEditorProps, type FlowExtension } from '@dou-ui/flow'\nimport { whiteboardKit, type WhiteboardKitOptions } from '@dou-ui/flow/whiteboard'\nimport { ShapesIcon, WorkflowIcon } from '@dou-ui/icons'\nimport { NodeSelection, type Command } from 'prosemirror-state'\nimport { defineComponent, h } from 'vue'\nimport { labelOf, type BlockOption, type EditorExtension, type Label } from '../core/extension'\nimport { escapeHTML } from '../core/output'\nimport { defineBlock } from '../define-block'\nimport { editorLocales } from '../locale'\nimport BoardBlock from './board-block.vue'\nimport {\n boardOf,\n BOARD_OPEN_EVENT,\n checkBoardProps,\n clampHeight,\n heightOf,\n type BoardBlockSettings,\n} from './board'\n\nexport { boardOf } from './board'\n\n/** The props of the fullscreen editor that a flow block may set. */\nexport type FlowBlockEditorProps = Omit<\n FlowEditorProps,\n 'extensions' | 'readonly' | 'fitView' | 'comments' | 'author' | 'activeComment' | 'commentable'\n>\n\nexport interface FlowBlockOptions {\n /** The block type, e.g. `approvalFlow`; unique among the editor's blocks. */\n type: string\n /** What the flow is made of, as the editor's `extensions`. `[flowKit()]` by default. */\n extensions?: (FlowExtension | FlowExtension[])[]\n /** More props for the flow editors, e.g. `nodeTypes`, `portTypes` or `direction`. */\n editorProps?: FlowBlockEditorProps\n /** The block's name: the title of the fullscreen editor, and of its slash menu entry. */\n label: Label\n /** The slash menu entry, or `false` to leave it out (blocks then come from code or pasting). */\n menu?: (Omit<BlockOption, 'key' | 'type' | 'label'> & { key?: string; label?: Label }) | false\n /** The height of a new block in the document, in px. Defaults to `360`. */\n height?: number\n /**\n * How a block is written in `blocksToHTML`, e.g. an `<img>` of a picture\n * of it the app keeps. By default a `<figure>` with its name, which\n * pasting reads back as the block.\n */\n html?: (board: FlowDocument, block: { id: string; props: Record<string, unknown> }) => string\n}\n\nconst fence = (type: string) => `dou-${type}`\n\nfunction attrsOf(dom: HTMLElement, height: number) {\n let board: unknown = null\n try {\n board = JSON.parse(dom.getAttribute('data-prop-board') ?? 'null')\n } catch {\n // a board that can't be read is an empty one\n }\n // `320`, or written by hand `320px`\n const stored = Number.parseFloat(dom.getAttribute('data-prop-height') ?? '')\n return { board: board ? boardOf(board) : null, height: stored > 0 ? clampHeight(stored) : height }\n}\n\n/** Turns ```dou-<type> fences from Markdown back into blocks. */\nfunction readFences(root: HTMLElement, type: string) {\n for (const code of root.querySelectorAll<HTMLElement>(`pre > code.language-${fence(type)}`)) {\n let written: unknown\n try {\n written = JSON.parse(code.textContent ?? '')\n } catch {\n continue\n }\n // `{ height, board }`, or the board alone\n const wrapped = !!written && typeof written === 'object' && 'board' in written\n const { board, height } = (wrapped ? written : { board: written }) as {\n board: unknown\n height?: unknown\n }\n const element = root.ownerDocument.createElement('div')\n element.dataset.contentType = type\n element.setAttribute('data-prop-board', JSON.stringify(boardOf(board)))\n if (typeof height === 'number') element.setAttribute('data-prop-height', String(height))\n code.parentElement!.replaceWith(element)\n }\n}\n\n/**\n * A block that holds a flow, drawn with `@dou-ui/flow`: the document shows\n * it whole, and it is edited in a fullscreen editor (double-click, the\n * “Edit” button, or `Enter` while the block is selected). The flow is the\n * block's `board` prop; collaboration merges it node by node.\n *\n * ```ts\n * extensions: [editorKit(), flowBlock({ type: 'approvalFlow', label: '审批流程', extensions: [flowKit(), approval()] })]\n * ```\n *\n * Needs `@dou-ui/flow` and its styles. For a whiteboard, `whiteboardBlock()`.\n */\nexport function flowBlock(options: FlowBlockOptions): EditorExtension {\n return boardBlock(options, true)\n}\n\nfunction boardBlock(options: FlowBlockOptions, fallbackNode: boolean): EditorExtension {\n const { type } = options\n const settings: BoardBlockSettings = {\n label: options.label,\n extensions: options.extensions ?? [flowKit()],\n editorProps: options.editorProps ?? {},\n height: options.height ?? 360,\n fallbackNode,\n }\n const View = defineComponent({\n name: 'DouEditorFlowBlockView',\n inheritAttrs: false,\n setup(_props, { attrs }) {\n return () => h(BoardBlock, { ...attrs, settings } as never)\n },\n })\n const menu = options.menu === false ? undefined : options.menu\n const block = defineBlock({\n type,\n props: { board: null, height: settings.height },\n content: 'none',\n component: View,\n menu:\n options.menu === false\n ? undefined\n : { icon: WorkflowIcon, ...menu, label: menu?.label ?? options.label },\n spec: {\n mergeProps: { board: { lists: ['nodes', 'edges'], objects: ['data'] } },\n // for `checkDocument`: what the block would read differently\n checkProps: checkBoardProps,\n // what is copied, and what `blocksToHTML` writes\n parseDOM: [`div[data-content-type=\"${type}\"]`, `figure[data-content-type=\"${type}\"]`].map(\n (tag) => ({\n tag,\n // before the figures of images, whatever the app's HTML puts inside\n priority: 70,\n getAttrs: (dom: HTMLElement) => attrsOf(dom, settings.height),\n }),\n ),\n },\n })\n /** `Enter` on the selected block opens it. */\n const open: Command = (state, dispatch, view) => {\n const { selection } = state\n if (!(selection instanceof NodeSelection) || selection.node.type.name !== type) return false\n if (dispatch && view) {\n const dom = view.nodeDOM(selection.from) as HTMLElement | null\n dom?.querySelector('.dou-editor-board')?.dispatchEvent(new CustomEvent(BOARD_OPEN_EVENT))\n }\n return true\n }\n return {\n ...block,\n name: `flow:${type}`,\n keymap: () => ({ enter: open }),\n prepareHTML: (root) => readFences(root, type),\n output: {\n blocks: {\n [type]: {\n html: (node, { children }) => {\n const board = boardOf(node.props.board)\n // written outside an editor: in Chinese, as the other output\n const inside = options.html\n ? options.html(board, node)\n : `<figcaption>${escapeHTML(labelOf(options.label, editorLocales['zh-CN']!))}</figcaption>`\n // the board stays on the figure, so pasting it reads back the block\n return `<figure data-content-type=\"${escapeHTML(type)}\" data-prop-board=\"${escapeHTML(JSON.stringify(board))}\" data-prop-height=\"${heightOf(node.props.height, settings.height)}\">${inside}</figure>${children}`\n },\n markdown: (node, { children }) => {\n const value = {\n height: heightOf(node.props.height, settings.height),\n board: boardOf(node.props.board),\n }\n const written = `\\`\\`\\`${fence(type)}\\n${JSON.stringify(value)}\\n\\`\\`\\``\n return children ? `${written}\\n\\n${children}` : written\n },\n },\n },\n },\n }\n}\n\nexport interface WhiteboardBlockOptions\n extends\n Pick<WhiteboardKitOptions, 'upload' | 'onUploadError'>,\n Pick<FlowBlockOptions, 'height' | 'html' | 'editorProps'> {\n /** The slash menu entry, or `false` to leave it out. */\n menu?: FlowBlockOptions['menu']\n}\n\n/**\n * A whiteboard block: shapes, sticky notes, text, pen strokes, images and\n * connectors, drawn in a fullscreen editor. Pass the `upload` of `image()`\n * so pictures on the board are uploaded too, not kept in the document.\n *\n * ```ts\n * extensions: [editorKit(), whiteboardBlock({ upload })]\n * ```\n */\nexport function whiteboardBlock(options: WhiteboardBlockOptions = {}): EditorExtension {\n return boardBlock(\n {\n type: 'whiteboard',\n label: (m) => m.types.whiteboard,\n extensions: [\n flowKit(),\n whiteboardKit({ upload: options.upload, onUploadError: options.onUploadError }),\n ],\n editorProps: options.editorProps,\n height: options.height,\n html: options.html,\n menu:\n options.menu === false\n ? false\n : {\n icon: ShapesIcon,\n hint: (m) => m.hints.whiteboard,\n keywords: [\n 'whiteboard',\n 'board',\n 'draw',\n 'flowchart',\n 'baiban',\n 'huatu',\n 'liuchengtu',\n ],\n ...options.menu,\n },\n },\n false,\n )\n}\n"],"mappings":";;;;;;;;;;;;AAgDA,IAAM,SAAS,SAAiB,OAAO;AAEvC,SAAS,QAAQ,KAAkB,QAAgB;CACjD,IAAI,QAAiB;CACrB,IAAI;EACF,QAA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