@dou-ui/editor 0.1.0-alpha.13 → 0.1.0-alpha.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collaboration/binding.js +32 -10
- package/dist/collaboration/binding.js.map +1 -1
- package/dist/collaboration/index.js +3 -0
- package/dist/collaboration/index.js.map +1 -1
- package/dist/collaboration/merged-props.js +152 -0
- package/dist/collaboration/merged-props.js.map +1 -0
- package/dist/components/block-handle.js.map +1 -1
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js +55 -5
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/core/extension.js.map +1 -1
- package/dist/core/model.js +2 -1
- package/dist/core/model.js.map +1 -1
- package/dist/core/transaction.js +7 -1
- package/dist/core/transaction.js.map +1 -1
- package/dist/define-block.js +2 -1
- package/dist/define-block.js.map +1 -1
- package/dist/document.js +20 -1
- package/dist/document.js.map +1 -1
- package/dist/dom.js +12 -1
- package/dist/dom.js.map +1 -1
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.js.map +1 -1
- package/dist/flow/board-block.js +6 -0
- package/dist/flow/board-block.js.map +1 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js +437 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/flow/board.js +102 -0
- package/dist/flow/board.js.map +1 -0
- package/dist/flow/index.js +166 -0
- package/dist/flow/index.js.map +1 -0
- package/dist/locale.js +33 -6
- package/dist/locale.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/style.js +1 -0
- package/dist/types/collaboration/binding.d.ts +4 -0
- package/dist/types/collaboration/merged-props.d.ts +20 -0
- package/dist/types/core/extension.d.ts +5 -2
- package/dist/types/core/transaction.d.ts +6 -0
- package/dist/types/document.d.ts +3 -2
- package/dist/types/dom.d.ts +7 -0
- package/dist/types/editor.vue.d.ts +9 -0
- package/dist/types/flow/board-block.vue.d.ts +16 -0
- package/dist/types/flow/board.d.ts +38 -0
- package/dist/types/flow/index.d.ts +59 -0
- package/dist/types/index.d.ts +9 -0
- package/dist/types/locale.d.ts +10 -0
- package/package.json +14 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createElementBlock","_normalizeClass","_unref","_createVNode","SearchBar","_createCommentVNode","_createElementVNode","_Fragment","BlockHandle","SlashMenu","BubbleToolbar","_renderList","_createBlock","_resolveDynamicComponent","_toDisplayString","CommentButton","CommentCard"],"sources":["../src/editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { isApplePlatform, useGlobalConfig, useNamespace } from 'dou-ui'\nimport { keymap } from 'prosemirror-keymap'\nimport { Plugin, type EditorState, type Transaction } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport {\n computed,\n getCurrentInstance,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n ref,\n shallowRef,\n toRaw,\n useTemplateRef,\n watch,\n h,\n useId,\n type Component,\n} from 'vue'\nimport BlockHandle from './components/block-handle.vue'\nimport BubbleToolbar from './components/bubble-toolbar.vue'\nimport SearchBar from './components/search-bar.vue'\nimport CommentButton from './components/comment-button.vue'\nimport CommentCard from './components/comment-card.vue'\nimport SlashMenu from './components/slash-menu.vue'\nimport { setFallbackHighlighter, type CodeHighlighter } from './core/highlight'\nimport { comparePlugin, compareKey } from './core/compare'\nimport {\n createEditorView,\n getBlocks,\n historyCommands,\n originKey,\n replaceBlocks,\n restoreBlocks,\n runCommand,\n setEditable,\n} from './core/editor'\nimport { diffBlocks } from './core/changes'\nimport { isRemote } from './core/plugins'\nimport { selectionOf, sameSelection } from './core/selection'\nimport { selectBlocks } from './core/block-selection'\nimport { applyEditorTransaction, EditorTransaction } from './core/transaction'\nimport {\n blocksToDoc,\n docToBlocks,\n type Block,\n type EditorDocument,\n type PartialBlock,\n} from './core/model'\nimport { resolveEditorExtensions } from './core/extension'\nimport {\n previewMatch,\n searchKey,\n searchPlugin,\n setSearch,\n type EditorSearchQuery,\n} from './core/search'\nimport { slashPlugin, type SlashState } from './core/slash'\nimport { writeHTML } from './core/output'\nimport { parseHTML } from './core/prepare'\nimport { componentMounter, vueNodeView } from './define-block'\nimport { editorKit } from './extensions/editor-kit'\nimport { readBlocks } from './document'\nimport {\n editorKey,\n type EditorEmits,\n type EditorExpose,\n type EditorProps,\n type EditorOrigin,\n type EditorLinkOpenEvent,\n type EditorSelection,\n type EditorTransactionResult,\n} from './editor'\nimport { useEditorMessages } from './locale'\nimport { useEditorComments } from './use-comments'\n\ndefineOptions({ name: 'DouEditor' })\n\nconst props = withDefaults(defineProps<EditorProps>(), {\n modelValue: undefined,\n extensions: undefined,\n readonly: false,\n searchable: true,\n placeholder: undefined,\n messages: undefined,\n ariaLabel: undefined,\n autofocus: false,\n plugins: undefined,\n history: true,\n undo: undefined,\n redo: undefined,\n selection: undefined,\n comments: undefined,\n author: undefined,\n activeComment: undefined,\n commentable: true,\n compare: undefined,\n})\nconst emit = defineEmits<EditorEmits>()\n\n// read once: changing the schema of a live editor would invalidate its document\nconst messages = useEditorMessages(() => props.messages)\nconst kit = resolveEditorExtensions(props.extensions ?? [editorKit()], () => messages.value)\n// say so once, instead of silently keeping the old extensions\nconst stopWatchingExtensions = watch(\n () => props.extensions,\n () => {\n console.warn(\n '[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.',\n )\n stopWatchingExtensions()\n },\n)\n\nconst ns = useNamespace('editor')\nconst config = useGlobalConfig()\nconst root = useTemplateRef<HTMLElement>('root')\nconst mount = useTemplateRef<HTMLElement>('mount')\nconst view = shallowRef<EditorView | null>(null)\nconst state = shallowRef<EditorState | null>(null)\nconst focused = shallowRef(false)\nconst dragging = shallowRef(false)\n/** Showing what changed since an older version: read-only, without comments. */\nconst comparing = computed(() => !!props.compare)\n/**\n * The older version as whole blocks, matched to the current ones by id. A\n * block saved without an id gets a new one, so it shows as removed.\n */\nconst compareBlocks = computed(() => {\n const blocks = props.compare?.blocks\n return Array.isArray(blocks) ? docToBlocks(blocksToDoc(kit.schema, blocks)) : null\n})\nconst editable = computed(() => !props.readonly && !comparing.value)\n\nconst {\n comments,\n plugin: commentPlugin,\n anchors,\n} = useEditorComments({\n props,\n emit,\n view,\n provider: kit.comments,\n})\n\nconst context = { view, state, focused, dragging, editable, messages, root, kit, comments }\nprovide(editorKey, context)\n\n// block components render outside this component's tree: hand them the context\nconst appContext = getCurrentInstance()?.appContext ?? null\nconst mountComponent = componentMounter(appContext, [[editorKey, context]])\nconst componentViews = {\n ...Object.fromEntries(\n Object.entries(kit.schema.nodes)\n .filter(([, type]) => type.spec.component)\n .map(([name, type]) => [\n name,\n vueNodeView(type.spec.component as Component, appContext, [[editorKey, context]]),\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(kit.componentViews).map(([name, create]) => [name, create(mountComponent)]),\n ),\n}\n\n// find and replace: the panel over the text, the matches marked in it\nconst searchOpen = ref(false)\nconst searchReplacing = ref(false)\nconst searchBar = useTemplateRef<InstanceType<typeof SearchBar>>('searchBar')\n/** Blocks that draw their own text, such as a code block in the code editor, are not searched. */\nconst searchSkip = (node: { type: { name: string } }) => node.type.name in kit.componentViews\n\n/** Opens the panel, with the replace box for `replace`. A selection on one line becomes the search. */\nfunction openSearch(replace = false, given?: Partial<EditorSearchQuery>) {\n const v = view.value\n if (!v || !props.searchable) return false\n const old = searchKey.getState(v.state)?.query ?? { search: '' }\n const query = { ...old, ...given }\n const { from, to, empty } = v.state.selection\n if (given?.search === undefined && !empty) {\n const text = v.state.doc.textBetween(from, to, '\\n')\n if (text && !text.includes('\\n')) query.search = text\n }\n if ((replace || given?.replace !== undefined) && editable.value) searchReplacing.value = true\n searchOpen.value = true\n v.dispatch(setSearch(v.state.tr, { query, active: true }))\n const preview = previewMatch(v.state)\n if (preview) v.dispatch(preview)\n void nextTick(() => searchBar.value?.focus(replace && editable.value ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n const v = view.value\n if (!searchOpen.value || !v) return false\n searchOpen.value = false\n v.dispatch(setSearch(v.state.tr, { active: false }))\n v.focus()\n return true\n}\n\n/** Goes to the next (or previous) match; with the panel shut, opens it on the last search. */\nfunction findAgain(step: 1 | -1) {\n if (!searchOpen.value) {\n const v = view.value\n if (!v || !searchKey.getState(v.state)?.query.search || !openSearch()) return false\n }\n void nextTick(() => (step > 0 ? searchBar.value?.next() : searchBar.value?.previous()))\n return true\n}\n\nconst replaceKey = isApplePlatform() ? 'Mod-Alt-f' : 'Mod-h'\nconst searchKeys = keymap({\n 'Mod-f': () => openSearch(),\n [replaceKey]: () => openSearch(true),\n F3: () => findAgain(1),\n 'Mod-g': () => findAgain(1),\n 'Shift-F3': () => findAgain(-1),\n 'Mod-Shift-g': () => findAgain(-1),\n Escape: () => closeSearch(),\n})\n\nconst slash = shallowRef<SlashState | null>(null)\nconst slashMenu = useTemplateRef<InstanceType<typeof SlashMenu>>('slashMenu')\nconst bubble = useTemplateRef<InstanceType<typeof BubbleToolbar>>('bubble')\n\n// The document last sent through `v-model`: when the same object comes back,\n// it is not loaded again (that would move the cursor).\nlet emitted: EditorDocument | undefined\n\n// the result of the last change, for `transact` to hand back\nlet lastResult: EditorTransactionResult | null = null\n\nfunction onChange(current: EditorView, tr: Transaction, before: EditorState) {\n const blocks = getBlocks(current)\n const doc: EditorDocument = { version: 1, blocks }\n emitted = doc\n const history = tr.getMeta('history$') as { redo: boolean } | undefined\n const origin =\n (tr.getMeta(originKey) as EditorOrigin | undefined) ??\n (history ? (history.redo ? 'redo' : 'undo') : isRemote(tr) ? 'remote' : undefined)\n const meta: EditorTransactionResult['meta'] = {\n history:\n tr.getMeta('addToHistory') !== false &&\n origin !== 'remote' &&\n origin !== 'undo' &&\n origin !== 'redo',\n }\n if (origin !== undefined) meta.origin = origin\n lastResult = { blocks, changes: diffBlocks(before.doc, current.state.doc), meta }\n emit('transaction', lastResult)\n emit('update:modelValue', doc)\n emit('change', doc)\n}\n\nlet selection: EditorSelection = { block: null, blocks: [] }\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\nconst lacksId = (blocks: PartialBlock[]): boolean =>\n blocks.some((block) => !block.id || lacksId(block.children ?? []))\n// until the editor is focused (or a block is, by the program) its selection is no cursor\nlet cursorKnown = false\n\nfunction onUpdate(current: EditorView) {\n state.value = current.state\n if (!cursorKnown) {\n if (!focused.value) return\n cursorKnown = true\n }\n const next = selectionOf(current.state)\n if (sameSelection(next, selection)) return\n selection = next\n emit('update:selection', next)\n}\n\n// a click on a link places the cursor; with Ctrl or ⌘ held, or while read-only, it opens the link\nconst openLinks = new Plugin({\n props: {\n handleDOMEvents: {\n click(clicked, event) {\n const link = (event.target as HTMLElement).closest<HTMLAnchorElement>('a.dou-editor__link')\n if (!link?.href || !(event.metaKey || event.ctrlKey || !clicked.editable)) return false\n event.preventDefault()\n const $pos = clicked.state.doc.resolve(clicked.posAtDOM(link, 0))\n let block = ''\n for (let depth = $pos.depth; depth > 0; depth--)\n if ($pos.node(depth).type.name === 'block') {\n block = $pos.node(depth).attrs.id as string\n break\n }\n const opening: EditorLinkOpenEvent = {\n link: link.getAttribute('href') ?? link.href,\n block,\n defaultPrevented: false,\n preventDefault() {\n this.defaultPrevented = true\n },\n }\n emit('linkOpen', opening)\n if (!opening.defaultPrevented) window.open(link.href, '_blank', 'noopener,noreferrer')\n return true\n },\n },\n },\n})\n\nonMounted(() => {\n const instance = createEditorView({\n element: mount.value!,\n kit,\n nodeViews: componentViews,\n // with collaboration the document comes from the shared document\n blocks: kit.externalDocument ? [] : readBlocks(props.modelValue),\n editable: editable.value,\n placeholder: {\n text: () => props.placeholder ?? messages.value.placeholder,\n heading: () => messages.value.headingPlaceholder,\n empty: () => props.placeholder ?? messages.value.emptyPlaceholder,\n },\n plugins: [\n ...(props.plugins ?? []),\n slashPlugin({\n onChange: (value) => (slash.value = value),\n onKey: (event) => slashMenu.value?.onKey(event) ?? false,\n }),\n keymap({\n 'Mod-k': () => bubble.value?.editLink() ?? false,\n 'Mod-Alt-m': () => comments.start(),\n // with the thread card open, Escape in the text closes it, and only that\n Escape: () => {\n if (!comments.pending.value && !comments.active.value) return false\n comments.close()\n return true\n },\n }),\n commentPlugin,\n comparePlugin({\n before: () => compareBlocks.value,\n label: () => messages.value.removedBlock,\n }),\n openLinks,\n searchPlugin({ skip: searchSkip }),\n ],\n keymaps: [searchKeys],\n history: props.history,\n undo: props.undo,\n redo: props.redo,\n attributes: () => {\n const attrs: Record<string, string> = {}\n if (props.ariaLabel) attrs['aria-label'] = props.ariaLabel\n if (!editable.value) attrs['aria-readonly'] = 'true'\n return attrs\n },\n onChange,\n onUpdate,\n })\n view.value = instance\n state.value = instance.state\n // code blocks without their own highlighter use the one DouCodeBlock uses\n watch(\n () =>\n (config.value.defaults as { DouCodeBlock?: { highlight?: CodeHighlighter } }).DouCodeBlock\n ?.highlight ?? null,\n (highlight) => setFallbackHighlighter(instance, highlight),\n { immediate: true },\n )\n instance.dom.addEventListener('focus', onFocus)\n instance.dom.addEventListener('blur', onBlur)\n if (props.autofocus) instance.focus()\n // blocks given without ids got them now: hand those back, so events' ids can be looked up\n const given = kit.externalDocument ? undefined : readBlocks(props.modelValue)\n if (given && lacksId(given)) {\n const doc: EditorDocument = { version: 1, blocks: getBlocks(instance) }\n emitted = doc\n emit('update:modelValue', doc)\n }\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n if (!cursorKnown && view.value) {\n cursorKnown = true\n const next = selectionOf(view.value.state)\n if (!sameSelection(next, selection)) {\n selection = next\n emit('update:selection', next)\n }\n }\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n focused.value = false\n emit('blur', event)\n}\n\nonBeforeUnmount(() => {\n view.value?.destroy()\n view.value = null\n})\n\nwatch(\n () => props.modelValue,\n (value) => {\n const current = view.value\n if (!current || value === undefined || kit.externalDocument || toRaw(value) === emitted) return\n replaceBlocks(current, readBlocks(value) ?? [])\n },\n)\n\nwatch(editable, (value) => view.value && setEditable(view.value, value))\nwatch(compareBlocks, () => view.value?.dispatch(view.value.state.tr.setMeta(compareKey, true)))\n\n/** The change last scrolled to, by its place among them. */\nlet changeIndex = -1\nwatch(\n () => props.compare,\n () => (changeIndex = -1),\n)\nfunction goToChange(step: 1 | -1) {\n const dom = view.value?.dom\n if (!dom || !props.compare) return false\n // a block's own mark, or the first piece of text changed in it\n const marks = [\n ...dom.querySelectorAll<HTMLElement>(\n '.dou-editor__diff-added, .dou-editor__diff-changed, .dou-editor__diff-removed-block, .dou-editor__diff-added-text, .dou-editor__diff-removed',\n ),\n ].filter((el, index, list) => {\n const block = el.closest('[data-block-id]')\n const previous = list[index - 1]\n return !previous || previous.closest('[data-block-id]') !== block || !block\n })\n const next = changeIndex + step\n const target = marks[next]\n if (!target) return false\n changeIndex = next\n target.scrollIntoView({ block: 'center' })\n const m = messages.value\n // a block added or removed, or one whose text or kind changed\n const kind = target.matches('.dou-editor__diff-added')\n ? m.changeAdded\n : target.matches('.dou-editor__diff-removed-block')\n ? m.changeRemoved\n : m.changeChanged\n announce(`${kind} ${changeText(target)}`)\n return true\n}\n\n/** The text of a change: what was removed, or its block as it is now. */\nfunction changeText(target: HTMLElement) {\n if (target.matches('.dou-editor__diff-removed-block')) return target.textContent ?? ''\n const block = (target.closest('[data-block-id]') ?? target).cloneNode(true) as HTMLElement\n for (const el of block.querySelectorAll('[data-diff=\"removed\"]')) el.remove()\n return block.textContent ?? ''\n}\n\n/** What the live region reads out: a version restored, the change gone to. */\nconst spoken = ref('')\nfunction announce(text: string) {\n // the same words twice still get read\n spoken.value = ''\n void nextTick(() => (spoken.value = text))\n}\n\nfunction restore(doc: EditorDocument<PartialBlock>) {\n // like the other methods it works while `readonly`, and it is the change comparing allows\n if (!view.value || !restoreBlocks(view.value, readBlocks(doc) ?? [])) return false\n announce(messages.value.restored)\n return true\n}\n\n// a selection from outside: the cursor goes to the block, or the blocks are selected\nwatch(\n () => props.selection,\n (value) => {\n const current = view.value\n if (!current || !value || sameSelection(value, selection)) return\n const known = cursorKnown\n cursorKnown = true\n let applied = false\n if (value.blocks.length > 1) {\n applied = selectBlocks(value.blocks[0]!, value.blocks.at(-1)!)(\n current.state,\n current.dispatch,\n )\n if (!applied) warn('`selection.blocks` must be sibling blocks that exist in the document')\n } else {\n const id = value.block ?? value.blocks[0]\n const transaction = new EditorTransaction(current.state)\n if (id && transaction.focusBlock(id)) {\n current.dispatch(transaction.tr)\n applied = true\n } else if (!id) warn('a selection without blocks cannot be set; the cursor stays where it is')\n }\n if (applied) return\n cursorKnown = known\n // hand back where the selection really is, so the binding doesn't keep a value that never applied\n emit('update:selection', { ...selection, blocks: [...selection.blocks] })\n },\n)\n\nfunction transact(\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransaction['meta'],\n): EditorTransactionResult | null {\n const current = view.value\n // comparing shows a version: nothing changes it but `restore`\n if (!current || props.compare) return null\n const transaction = new EditorTransaction(current.state, meta, cursorKnown)\n fn(transaction)\n lastResult = null\n // `focusBlock` places the cursor\n if (transaction.focused) cursorKnown = true\n applyEditorTransaction(current, transaction)\n if (transaction.focused) current.focus()\n const result = lastResult\n lastResult = null\n return result\n}\n\nconst history = (action: 'undo' | 'redo', dispatch: boolean) => {\n const current = view.value\n if (!current || props.compare) return false\n const command = historyCommands(current.state)[action]\n return dispatch ? runCommand(current, command) : command(current.state)\n}\n\ndefineExpose<EditorExpose>({\n get view() {\n return view.value\n },\n focus: () => view.value?.focus(),\n blur: () => (view.value?.dom as HTMLElement | undefined)?.blur(),\n getBlocks: () => (view.value ? getBlocks(view.value) : []),\n setBlocks: (blocks: PartialBlock[]) => view.value && replaceBlocks(view.value, blocks),\n getHTML: () => (view.value ? writeHTML(getBlocks(view.value), kit) : ''),\n setHTML: (html: string) => view.value && replaceBlocks(view.value, parseHTML(html, kit)),\n run: (command) => (view.value ? runCommand(view.value, command) : false),\n openSearch: (query) => openSearch(query?.replace !== undefined, query),\n closeSearch,\n transact,\n getBlock: (id) => (view.value ? new EditorTransaction(view.value.state).getBlock(id) : null),\n insertBlocks: (blocks, placement) => {\n let ids: string[] = []\n transact((tr) => (ids = tr.insertBlocks(blocks, placement)))\n return ids\n },\n updateBlock: (id, patch) => {\n let ok = false\n transact((tr) => (ok = tr.updateBlock(id, patch)))\n return ok\n },\n removeBlocks: (ids) => {\n let ok = false\n transact((tr) => (ok = tr.removeBlocks(ids)))\n return ok\n },\n moveBlocks: (ids, placement) => {\n let ok = false\n transact((tr) => (ok = tr.moveBlocks(ids, placement)))\n return ok\n },\n focusBlock: (id, edge) => {\n let ok = false\n transact((tr) => (ok = tr.focusBlock(id, edge)))\n return ok\n },\n getSelection: () => ({ ...selection, blocks: [...selection.blocks] }),\n undo: () => history('undo', true),\n redo: () => history('redo', true),\n get canUndo() {\n return !!state.value && history('undo', false)\n },\n get canRedo() {\n return !!state.value && history('redo', false)\n },\n comment: () => comments.start(),\n getCommentAnchors: anchors,\n restore,\n nextChange: () => goToChange(1),\n previousChange: () => goToChange(-1),\n})\n\n/*\n * Highlights for the threads that are open: by thread id, in one rule,\n * so a thread resolved or opened restyles its text without redrawing it.\n */\nconst scope = useId()\n/** An id as a CSS identifier: no quotes or `<`, which server rendering would escape. */\nconst ident = (id: string) =>\n id.replace(/[^a-zA-Z0-9_]|^[\\d-]/gu, (char) => `\\\\${char.codePointAt(0)!.toString(16)} `)\nconst highlighted = (id: string) => `[data-dou-editor=${ident(scope)}] [data-comment=${ident(id)}]`\nconst highlightCSS = computed(() => {\n if (!comments.enabled.value) return ''\n const open = comments.threads.value.filter((thread) => !thread.resolved)\n if (!open.length) return ''\n let css = `${open.map((thread) => highlighted(thread.id)).join(',')}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line)}`\n const active = comments.active.value\n if (active && open.some((thread) => thread.id === active))\n css += `${highlighted(active)}{background-color:var(--dou-editor-comment-bg-active)}`\n return css\n})\nconst HighlightStyle = () => (highlightCSS.value ? h('style', highlightCSS.value) : null)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n {\n // comparing keeps the editor's own gutter, so the text doesn't move\n 'is-readonly': readonly,\n 'is-comparing': comparing,\n 'is-focused': focused,\n 'is-dragging': dragging,\n },\n ]\"\n :data-dou-editor=\"scope\"\n >\n <div v-if=\"searchOpen && view\" :class=\"ns.e('search')\">\n <SearchBar\n ref=\"searchBar\"\n v-model:replacing=\"searchReplacing\"\n :readonly=\"!editable\"\n :skip=\"searchSkip\"\n @close=\"closeSearch\"\n />\n </div>\n <HighlightStyle />\n <div ref=\"mount\" :class=\"ns.e('mount')\" />\n <template v-if=\"editable && view\">\n <BlockHandle />\n <SlashMenu ref=\"slashMenu\" :slash=\"slash\" />\n <BubbleToolbar ref=\"bubble\" />\n <component :is=\"overlay\" v-for=\"(overlay, index) in kit.overlays\" :key=\"index\" />\n </template>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ spoken }}</div>\n <template v-if=\"view && comments.enabled.value && !comparing\">\n <CommentButton v-if=\"readonly\" />\n <CommentCard />\n </template>\n </div>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgFA,MAAM,QAAQ;EAoBd,MAAM,OAAO;EAGb,MAAM,WAAW,wBAAwB,MAAM,QAAQ;EACvD,MAAM,MAAM,wBAAwB,MAAM,cAAc,CAAC,UAAU,CAAC,SAAS,SAAS,KAAK;EAE3F,MAAM,yBAAyB,YACvB,MAAM,kBACN;GACJ,QAAQ,KACN,6KACF;GACA,uBAAuB;EACzB,CACF;EAEA,MAAM,KAAK,aAAa,QAAQ;EAChC,MAAM,SAAS,gBAAgB;EAC/B,MAAM,OAAO,eAA4B,MAAM;EAC/C,MAAM,QAAQ,eAA4B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EAAA,CAAE,CAAC,EAAC,OAAA,CAAA;;IACb,SAAA,SAAY,KAAA,SAA5BH,UAAA,GAAAC,mBAKWO,UAAA,EAAA,KAAA,EAAA,GAAA;KAJTJ,YAAeK,oBAAA;KACfL,YAA4CM,oBAAA;MAA7B,SAAA;MAAJ,KAAI;MAAa,OAAO,MAAA;;KACnCN,YAA8BO,wBAAA;MAAX,SAAA;MAAJ,KAAI;;MACnBX,UAAA,IAAA,GAAAC,mBAAiFO,UAAA,MAAAI,WAA7BT,MAAA,GAAA,CAAG,CAAC,WAAvB,SAAS,UAAK;MAA/C,OAAAH,UAAA,GAAAa,YAAiFC,wBAAjE,OAAO,GAAA,EAA4C,KAAK,MAAK,CAAA;;;IAE/EP,mBAAgE,OAAA;KAA1D,OAAKL,eAAEC,MAAA,EAAA,CAAE,CAAC,EAAC,MAAA,CAAA;KAAU,aAAU;IAAY,GAAAY,gBAAA,OAAA,KAAM,GAAA,CAAA;IACvC,KAAA,SAAQZ,MAAA,QAAA,CAAQ,CAAC,QAAQ,SAAK,CAAK,UAAA,SAAnDH,UAAA,GAAAC,mBAGWO,UAAA,EAAA,KAAA,EAAA,GAAA,CAFY,QAAA,YAArBR,UAAA,GAAAa,YAAiCG,wBAAA,EAAA,KAAA,EAAA,CAAA,K,8BACjCZ,YAAea,oBAAA,C"}
|
|
1
|
+
{"version":3,"file":"editor.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createElementBlock","_normalizeClass","_unref","_createVNode","SearchBar","_createCommentVNode","_createElementVNode","_Fragment","BlockHandle","SlashMenu","BubbleToolbar","_renderList","_createBlock","_resolveDynamicComponent","_toDisplayString","CommentButton","CommentCard"],"sources":["../src/editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { isApplePlatform, useGlobalConfig, useNamespace } from 'dou-ui'\nimport { keymap } from 'prosemirror-keymap'\nimport { Plugin, type EditorState, type Transaction } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport {\n computed,\n getCurrentInstance,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n ref,\n shallowRef,\n toRaw,\n useTemplateRef,\n watch,\n h,\n useId,\n type Component,\n} from 'vue'\nimport BlockHandle from './components/block-handle.vue'\nimport BubbleToolbar from './components/bubble-toolbar.vue'\nimport SearchBar from './components/search-bar.vue'\nimport CommentButton from './components/comment-button.vue'\nimport CommentCard from './components/comment-card.vue'\nimport SlashMenu from './components/slash-menu.vue'\nimport { setFallbackHighlighter, type CodeHighlighter } from './core/highlight'\nimport { comparePlugin, compareKey } from './core/compare'\nimport {\n createEditorView,\n getBlocks,\n historyCommands,\n originKey,\n replaceBlocks,\n restoreBlocks,\n runCommand,\n setEditable,\n} from './core/editor'\nimport { diffBlocks } from './core/changes'\nimport { isRemote } from './core/plugins'\nimport { selectionOf, sameSelection } from './core/selection'\nimport { selectBlocks } from './core/block-selection'\nimport { applyEditorTransaction, EditorTransaction } from './core/transaction'\nimport {\n blocksToDoc,\n docToBlocks,\n type Block,\n type EditorDocument,\n type PartialBlock,\n} from './core/model'\nimport { resolveEditorExtensions } from './core/extension'\nimport {\n previewMatch,\n searchKey,\n searchPlugin,\n setSearch,\n type EditorSearchQuery,\n} from './core/search'\nimport { slashPlugin, type SlashState } from './core/slash'\nimport { writeHTML } from './core/output'\nimport { parseHTML } from './core/prepare'\nimport { componentMounter, vueNodeView } from './define-block'\nimport { editorKit } from './extensions/editor-kit'\nimport { readBlocks } from './document'\nimport {\n editorKey,\n type EditorEmits,\n type EditorExpose,\n type EditorProps,\n type EditorOrigin,\n type EditorLinkOpenEvent,\n type EditorSelection,\n type EditorTransactionResult,\n} from './editor'\nimport { useEditorMessages } from './locale'\nimport { useEditorComments } from './use-comments'\n\ndefineOptions({ name: 'DouEditor' })\n\nconst props = withDefaults(defineProps<EditorProps>(), {\n modelValue: undefined,\n extensions: undefined,\n readonly: false,\n searchable: true,\n placeholder: undefined,\n messages: undefined,\n ariaLabel: undefined,\n autofocus: false,\n plugins: undefined,\n history: true,\n undo: undefined,\n redo: undefined,\n selection: undefined,\n comments: undefined,\n author: undefined,\n activeComment: undefined,\n commentable: true,\n compare: undefined,\n})\nconst emit = defineEmits<EditorEmits>()\n\n// read once: changing the schema of a live editor would invalidate its document\nconst messages = useEditorMessages(() => props.messages)\nconst kit = resolveEditorExtensions(props.extensions ?? [editorKit()], () => messages.value)\n// say so once, instead of silently keeping the old extensions\nconst stopWatchingExtensions = watch(\n () => props.extensions,\n () => {\n console.warn(\n '[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.',\n )\n stopWatchingExtensions()\n },\n)\n\nconst ns = useNamespace('editor')\nconst config = useGlobalConfig()\nconst root = useTemplateRef<HTMLElement>('root')\nconst mount = useTemplateRef<HTMLElement>('mount')\nconst view = shallowRef<EditorView | null>(null)\nconst state = shallowRef<EditorState | null>(null)\nconst focused = shallowRef(false)\nconst dragging = shallowRef(false)\n/** Showing what changed since an older version: read-only, without comments. */\nconst comparing = computed(() => !!props.compare)\n/**\n * The older version as whole blocks, matched to the current ones by id. A\n * block saved without an id gets a new one, so it shows as removed.\n */\nconst compareBlocks = computed(() => {\n const blocks = props.compare?.blocks\n return Array.isArray(blocks) ? docToBlocks(blocksToDoc(kit.schema, blocks)) : null\n})\nconst editable = computed(() => !props.readonly && !comparing.value)\n\nconst {\n comments,\n plugin: commentPlugin,\n anchors,\n} = useEditorComments({\n props,\n emit,\n view,\n provider: kit.comments,\n})\n\nconst context = { view, state, focused, dragging, editable, messages, root, kit, comments }\nprovide(editorKey, context)\n\n// block components render outside this component's tree: hand them the context\nconst appContext = getCurrentInstance()?.appContext ?? null\nconst mountComponent = componentMounter(appContext, [[editorKey, context]])\nconst componentViews = {\n ...Object.fromEntries(\n Object.entries(kit.schema.nodes)\n .filter(([, type]) => type.spec.component)\n .map(([name, type]) => [\n name,\n vueNodeView(type.spec.component as Component, appContext, [[editorKey, context]]),\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(kit.componentViews).map(([name, create]) => [name, create(mountComponent)]),\n ),\n}\n\n// find and replace: the panel over the text, the matches marked in it\nconst searchOpen = ref(false)\nconst searchReplacing = ref(false)\nconst searchBar = useTemplateRef<InstanceType<typeof SearchBar>>('searchBar')\n/** Blocks that draw their own text, such as a code block in the code editor, are not searched. */\nconst searchSkip = (node: { type: { name: string } }) => node.type.name in kit.componentViews\n\n/** Opens the panel, with the replace box for `replace`. A selection on one line becomes the search. */\nfunction openSearch(replace = false, given?: Partial<EditorSearchQuery>) {\n const v = view.value\n if (!v || !props.searchable) return false\n const old = searchKey.getState(v.state)?.query ?? { search: '' }\n const query = { ...old, ...given }\n const { from, to, empty } = v.state.selection\n if (given?.search === undefined && !empty) {\n const text = v.state.doc.textBetween(from, to, '\\n')\n if (text && !text.includes('\\n')) query.search = text\n }\n if ((replace || given?.replace !== undefined) && editable.value) searchReplacing.value = true\n searchOpen.value = true\n v.dispatch(setSearch(v.state.tr, { query, active: true }))\n const preview = previewMatch(v.state)\n if (preview) v.dispatch(preview)\n void nextTick(() => searchBar.value?.focus(replace && editable.value ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n const v = view.value\n if (!searchOpen.value || !v) return false\n searchOpen.value = false\n v.dispatch(setSearch(v.state.tr, { active: false }))\n v.focus()\n return true\n}\n\n/** Goes to the next (or previous) match; with the panel shut, opens it on the last search. */\nfunction findAgain(step: 1 | -1) {\n if (!searchOpen.value) {\n const v = view.value\n if (!v || !searchKey.getState(v.state)?.query.search || !openSearch()) return false\n }\n void nextTick(() => (step > 0 ? searchBar.value?.next() : searchBar.value?.previous()))\n return true\n}\n\nconst replaceKey = isApplePlatform() ? 'Mod-Alt-f' : 'Mod-h'\nconst searchKeys = keymap({\n 'Mod-f': () => openSearch(),\n [replaceKey]: () => openSearch(true),\n F3: () => findAgain(1),\n 'Mod-g': () => findAgain(1),\n 'Shift-F3': () => findAgain(-1),\n 'Mod-Shift-g': () => findAgain(-1),\n Escape: () => closeSearch(),\n})\n\nconst slash = shallowRef<SlashState | null>(null)\nconst slashMenu = useTemplateRef<InstanceType<typeof SlashMenu>>('slashMenu')\nconst bubble = useTemplateRef<InstanceType<typeof BubbleToolbar>>('bubble')\n\n// The document last sent through `v-model`: when the same object comes back,\n// it is not loaded again (that would move the cursor).\nlet emitted: EditorDocument | undefined\n\n// the result of the last change, for `transact` to hand back\nlet lastResult: EditorTransactionResult | null = null\n\nfunction onChange(current: EditorView, tr: Transaction, before: EditorState) {\n const blocks = getBlocks(current)\n const doc: EditorDocument = { version: 1, blocks }\n emitted = doc\n const history = tr.getMeta('history$') as { redo: boolean } | undefined\n const origin =\n (tr.getMeta(originKey) as EditorOrigin | undefined) ??\n (history ? (history.redo ? 'redo' : 'undo') : isRemote(tr) ? 'remote' : undefined)\n const meta: EditorTransactionResult['meta'] = {\n history:\n tr.getMeta('addToHistory') !== false &&\n origin !== 'remote' &&\n origin !== 'undo' &&\n origin !== 'redo',\n }\n if (origin !== undefined) meta.origin = origin\n lastResult = { blocks, changes: diffBlocks(before.doc, current.state.doc), meta }\n emit('transaction', lastResult)\n emit('update:modelValue', doc)\n emit('change', doc)\n}\n\nlet selection: EditorSelection = { block: null, blocks: [] }\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\nconst lacksId = (blocks: PartialBlock[]): boolean =>\n blocks.some((block) => !block.id || lacksId(block.children ?? []))\n// until the editor is focused (or a block is, by the program) its selection is no cursor\nlet cursorKnown = false\n\nfunction onUpdate(current: EditorView) {\n state.value = current.state\n if (!cursorKnown) {\n if (!focused.value) return\n cursorKnown = true\n }\n const next = selectionOf(current.state)\n if (sameSelection(next, selection)) return\n selection = next\n emit('update:selection', next)\n}\n\n// a click on a link places the cursor; with Ctrl or ⌘ held, or while read-only, it opens the link\nconst openLinks = new Plugin({\n props: {\n handleDOMEvents: {\n click(clicked, event) {\n const link = (event.target as HTMLElement).closest<HTMLAnchorElement>('a.dou-editor__link')\n if (!link?.href || !(event.metaKey || event.ctrlKey || !clicked.editable)) return false\n event.preventDefault()\n const $pos = clicked.state.doc.resolve(clicked.posAtDOM(link, 0))\n let block = ''\n for (let depth = $pos.depth; depth > 0; depth--)\n if ($pos.node(depth).type.name === 'block') {\n block = $pos.node(depth).attrs.id as string\n break\n }\n const opening: EditorLinkOpenEvent = {\n link: link.getAttribute('href') ?? link.href,\n block,\n defaultPrevented: false,\n preventDefault() {\n this.defaultPrevented = true\n },\n }\n emit('linkOpen', opening)\n if (!opening.defaultPrevented) window.open(link.href, '_blank', 'noopener,noreferrer')\n return true\n },\n },\n },\n})\n\nonMounted(() => {\n const instance = createEditorView({\n element: mount.value!,\n kit,\n nodeViews: componentViews,\n // with collaboration the document comes from the shared document\n blocks: kit.externalDocument ? [] : readBlocks(props.modelValue),\n editable: editable.value,\n placeholder: {\n text: () => props.placeholder ?? messages.value.placeholder,\n heading: () => messages.value.headingPlaceholder,\n empty: () => props.placeholder ?? messages.value.emptyPlaceholder,\n },\n plugins: [\n ...(props.plugins ?? []),\n slashPlugin({\n onChange: (value) => (slash.value = value),\n onKey: (event) => slashMenu.value?.onKey(event) ?? false,\n }),\n keymap({\n 'Mod-k': () => bubble.value?.editLink() ?? false,\n 'Mod-Alt-m': () => comments.start(),\n // with the thread card open, Escape in the text closes it, and only that\n Escape: () => {\n if (!comments.pending.value && !comments.active.value) return false\n comments.close()\n return true\n },\n }),\n commentPlugin,\n comparePlugin({\n before: () => compareBlocks.value,\n label: () => messages.value.removedBlock,\n }),\n openLinks,\n searchPlugin({ skip: searchSkip }),\n ],\n keymaps: [searchKeys],\n history: props.history,\n undo: props.undo,\n redo: props.redo,\n attributes: () => {\n const attrs: Record<string, string> = {}\n if (props.ariaLabel) attrs['aria-label'] = props.ariaLabel\n if (!editable.value) attrs['aria-readonly'] = 'true'\n return attrs\n },\n onChange,\n onUpdate,\n })\n view.value = instance\n state.value = instance.state\n // code blocks without their own highlighter use the one DouCodeBlock uses\n watch(\n () =>\n (config.value.defaults as { DouCodeBlock?: { highlight?: CodeHighlighter } }).DouCodeBlock\n ?.highlight ?? null,\n (highlight) => setFallbackHighlighter(instance, highlight),\n { immediate: true },\n )\n instance.dom.addEventListener('focus', onFocus)\n instance.dom.addEventListener('blur', onBlur)\n if (props.autofocus) instance.focus()\n // blocks given without ids got them now: hand those back, so events' ids can be looked up\n const given = kit.externalDocument ? undefined : readBlocks(props.modelValue)\n if (given && lacksId(given)) {\n const doc: EditorDocument = { version: 1, blocks: getBlocks(instance) }\n emitted = doc\n emit('update:modelValue', doc)\n }\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n if (!cursorKnown && view.value) {\n cursorKnown = true\n const next = selectionOf(view.value.state)\n if (!sameSelection(next, selection)) {\n selection = next\n emit('update:selection', next)\n }\n }\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n focused.value = false\n emit('blur', event)\n}\n\nonBeforeUnmount(() => {\n view.value?.destroy()\n view.value = null\n})\n\nwatch(\n () => props.modelValue,\n (value) => {\n const current = view.value\n if (!current || value === undefined || kit.externalDocument || toRaw(value) === emitted) return\n replaceBlocks(current, readBlocks(value) ?? [])\n },\n)\n\nwatch(editable, (value) => view.value && setEditable(view.value, value))\nwatch(compareBlocks, () => view.value?.dispatch(view.value.state.tr.setMeta(compareKey, true)))\n\n/** The change last scrolled to, by its place among them. */\nlet changeIndex = -1\nwatch(\n () => props.compare,\n () => (changeIndex = -1),\n)\nfunction goToChange(step: 1 | -1) {\n const dom = view.value?.dom\n if (!dom || !props.compare) return false\n // a block's own mark, or the first piece of text changed in it\n const marks = [\n ...dom.querySelectorAll<HTMLElement>(\n '.dou-editor__diff-added, .dou-editor__diff-changed, .dou-editor__diff-removed-block, .dou-editor__diff-added-text, .dou-editor__diff-removed',\n ),\n ].filter((el, index, list) => {\n const block = el.closest('[data-block-id]')\n const previous = list[index - 1]\n return !previous || previous.closest('[data-block-id]') !== block || !block\n })\n const next = changeIndex + step\n const target = marks[next]\n if (!target) return false\n changeIndex = next\n target.scrollIntoView({ block: 'center' })\n const m = messages.value\n // a block added or removed, or one whose text or kind changed\n const kind = target.matches('.dou-editor__diff-added')\n ? m.changeAdded\n : target.matches('.dou-editor__diff-removed-block')\n ? m.changeRemoved\n : m.changeChanged\n announce(`${kind} ${changeText(target)}`)\n return true\n}\n\n/** The text of a change: what was removed, or its block as it is now. */\nfunction changeText(target: HTMLElement) {\n if (target.matches('.dou-editor__diff-removed-block')) return target.textContent ?? ''\n const block = (target.closest('[data-block-id]') ?? target).cloneNode(true) as HTMLElement\n for (const el of block.querySelectorAll('[data-diff=\"removed\"]')) el.remove()\n return block.textContent ?? ''\n}\n\n/** What the live region reads out: a version restored, the change gone to. */\nconst spoken = ref('')\nfunction announce(text: string) {\n // the same words twice still get read\n spoken.value = ''\n void nextTick(() => (spoken.value = text))\n}\n\nfunction restore(doc: EditorDocument<PartialBlock>) {\n // like the other methods it works while `readonly`, and it is the change comparing allows\n if (!view.value || !restoreBlocks(view.value, readBlocks(doc) ?? [])) return false\n announce(messages.value.restored)\n return true\n}\n\n// a selection from outside: the cursor goes to the block, or the blocks are selected\nwatch(\n () => props.selection,\n (value) => {\n const current = view.value\n if (!current || !value || sameSelection(value, selection)) return\n const known = cursorKnown\n cursorKnown = true\n let applied = false\n if (value.blocks.length > 1) {\n applied = selectBlocks(value.blocks[0]!, value.blocks.at(-1)!)(\n current.state,\n current.dispatch,\n )\n if (!applied) warn('`selection.blocks` must be sibling blocks that exist in the document')\n } else {\n const id = value.block ?? value.blocks[0]\n const transaction = new EditorTransaction(current.state)\n if (id && transaction.focusBlock(id)) {\n current.dispatch(transaction.tr)\n applied = true\n } else if (!id) warn('a selection without blocks cannot be set; the cursor stays where it is')\n }\n if (applied) return\n cursorKnown = known\n // hand back where the selection really is, so the binding doesn't keep a value that never applied\n emit('update:selection', { ...selection, blocks: [...selection.blocks] })\n },\n)\n\nfunction transact(\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransaction['meta'],\n): EditorTransactionResult | null {\n const current = view.value\n // comparing shows a version: nothing changes it but `restore`\n if (!current || props.compare) return null\n const transaction = new EditorTransaction(current.state, meta, cursorKnown)\n fn(transaction)\n lastResult = null\n // `focusBlock` places the cursor\n if (transaction.focused) cursorKnown = true\n applyEditorTransaction(current, transaction)\n if (transaction.focused) current.focus()\n const result = lastResult\n lastResult = null\n return result\n}\n\nconst history = (action: 'undo' | 'redo', dispatch: boolean) => {\n const current = view.value\n if (!current || props.compare) return false\n const command = historyCommands(current.state)[action]\n return dispatch ? runCommand(current, command) : command(current.state)\n}\n\ndefineExpose<EditorExpose>({\n get view() {\n return view.value\n },\n focus: () => view.value?.focus(),\n blur: () => (view.value?.dom as HTMLElement | undefined)?.blur(),\n getBlocks: () => (view.value ? getBlocks(view.value) : []),\n setBlocks: (blocks: PartialBlock[]) => view.value && replaceBlocks(view.value, blocks),\n getHTML: () => (view.value ? writeHTML(getBlocks(view.value), kit) : ''),\n setHTML: (html: string) => view.value && replaceBlocks(view.value, parseHTML(html, kit)),\n run: (command) => (view.value ? runCommand(view.value, command) : false),\n openSearch: (query) => openSearch(query?.replace !== undefined, query),\n closeSearch,\n transact,\n getBlock: (id) => (view.value ? new EditorTransaction(view.value.state).getBlock(id) : null),\n insertBlocks: (blocks, placement) => {\n let ids: string[] = []\n transact((tr) => (ids = tr.insertBlocks(blocks, placement)))\n return ids\n },\n updateBlock: (id, patch) => {\n let ok = false\n transact((tr) => (ok = tr.updateBlock(id, patch)))\n return ok\n },\n removeBlocks: (ids) => {\n let ok = false\n transact((tr) => (ok = tr.removeBlocks(ids)))\n return ok\n },\n moveBlocks: (ids, placement) => {\n let ok = false\n transact((tr) => (ok = tr.moveBlocks(ids, placement)))\n return ok\n },\n focusBlock: (id, edge) => {\n let ok = false\n transact((tr) => (ok = tr.focusBlock(id, edge)))\n return ok\n },\n getSelection: () => ({ ...selection, blocks: [...selection.blocks] }),\n undo: () => history('undo', true),\n redo: () => history('redo', true),\n get canUndo() {\n return !!state.value && history('undo', false)\n },\n get canRedo() {\n return !!state.value && history('redo', false)\n },\n comment: () => comments.start(),\n getCommentAnchors: anchors,\n restore,\n nextChange: () => goToChange(1),\n previousChange: () => goToChange(-1),\n})\n\n/*\n * Highlights for the threads that are open: by thread id, in one rule,\n * so a thread resolved or opened restyles its text without redrawing it.\n */\nconst scope = useId()\n/** An id as a CSS identifier: no quotes or `<`, which server rendering would escape. */\nconst ident = (id: string) =>\n id.replace(/[^a-zA-Z0-9_]|^[\\d-]/gu, (char) => `\\\\${char.codePointAt(0)!.toString(16)} `)\nconst highlighted = (id: string) => `[data-dou-editor=${ident(scope)}] [data-comment=${ident(id)}]`\nconst highlightCSS = computed(() => {\n if (!comments.enabled.value) return ''\n const open = comments.threads.value.filter((thread) => !thread.resolved)\n if (!open.length) return ''\n let css = `${open.map((thread) => highlighted(thread.id)).join(',')}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line)}`\n const active = comments.active.value\n if (active && open.some((thread) => thread.id === active))\n css += `${highlighted(active)}{background-color:var(--dou-editor-comment-bg-active)}`\n return css\n})\nconst HighlightStyle = () => (highlightCSS.value ? h('style', highlightCSS.value) : null)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n {\n // comparing takes a narrow gutter for the bars beside changed blocks\n 'is-readonly': readonly,\n 'is-comparing': comparing,\n 'is-focused': focused,\n 'is-dragging': dragging,\n },\n ]\"\n :data-dou-editor=\"scope\"\n >\n <div v-if=\"searchOpen && view\" :class=\"ns.e('search')\">\n <SearchBar\n ref=\"searchBar\"\n v-model:replacing=\"searchReplacing\"\n :readonly=\"!editable\"\n :skip=\"searchSkip\"\n @close=\"closeSearch\"\n />\n </div>\n <HighlightStyle />\n <div ref=\"mount\" :class=\"ns.e('mount')\" />\n <template v-if=\"editable && view\">\n <BlockHandle />\n <SlashMenu ref=\"slashMenu\" :slash=\"slash\" />\n <BubbleToolbar ref=\"bubble\" />\n <component :is=\"overlay\" v-for=\"(overlay, index) in kit.overlays\" :key=\"index\" />\n </template>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ spoken }}</div>\n <template v-if=\"view && comments.enabled.value && !comparing\">\n <CommentButton v-if=\"readonly\" />\n <CommentCard />\n </template>\n </div>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgFA,MAAM,QAAQ;EAoBd,MAAM,OAAO;EAGb,MAAM,WAAW,wBAAwB,MAAM,QAAQ;EACvD,MAAM,MAAM,wBAAwB,MAAM,cAAc,CAAC,UAAU,CAAC,SAAS,SAAS,KAAK;EAE3F,MAAM,yBAAyB,YACvB,MAAM,kBACN;GACJ,QAAQ,KACN,6KACF;GACA,uBAAuB;EACzB,CACF;EAEA,MAAM,KAAK,aAAa,QAAQ;EAChC,MAAM,SAAS,gBAAgB;EAC/B,MAAM,OAAO,eAA4B,MAAM;EAC/C,MAAM,QAAQ,eAA4B,OAAO;EACjD,MAAM,OAAO,WAA8B,IAAI;EAC/C,MAAM,QAAQ,WAA+B,IAAI;EACjD,MAAM,UAAU,WAAW,KAAK;EAChC,MAAM,WAAW,WAAW,KAAK;;EAEjC,MAAM,YAAY,eAAe,CAAC,CAAC,MAAM,OAAO;;;;;EAKhD,MAAM,gBAAgB,eAAe;GACnC,MAAM,SAAS,MAAM,SAAS;GAC9B,OAAO,MAAM,QAAQ,MAAM,IAAI,YAAY,YAAY,IAAI,QAAQ,MAAM,CAAC,IAAI;EAChF,CAAC;EACD,MAAM,WAAW,eAAe,CAAC,MAAM,YAAY,CAAC,UAAU,KAAK;EAEnE,MAAM,EACJ,UACA,QAAQ,eACR,YACE,kBAAkB;GACpB;GACA;GACA;GACA,UAAU,IAAI;EAChB,CAAC;EAED,MAAM,UAAU;GAAE;GAAM;GAAO;GAAS;GAAU;GAAU;GAAU;GAAM;GAAK;EAAS;EAC1F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,GAAA,CAAA;IACvC,KAAA,SAAQZ,MAAA,QAAA,CAAQ,CAAC,QAAQ,SAAK,CAAK,UAAA,SAAnDH,UAAA,GAAAC,mBAGWO,UAAA,EAAA,KAAA,EAAA,GAAA,CAFY,QAAA,YAArBR,UAAA,GAAAa,YAAiCG,wBAAA,EAAA,KAAA,EAAA,CAAA,K,8BACjCZ,YAAea,oBAAA,C"}
|
package/dist/editor2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor2.js","names":["_sfc_main"],"sources":["../src/editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { isApplePlatform, useGlobalConfig, useNamespace } from 'dou-ui'\nimport { keymap } from 'prosemirror-keymap'\nimport { Plugin, type EditorState, type Transaction } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport {\n computed,\n getCurrentInstance,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n ref,\n shallowRef,\n toRaw,\n useTemplateRef,\n watch,\n h,\n useId,\n type Component,\n} from 'vue'\nimport BlockHandle from './components/block-handle.vue'\nimport BubbleToolbar from './components/bubble-toolbar.vue'\nimport SearchBar from './components/search-bar.vue'\nimport CommentButton from './components/comment-button.vue'\nimport CommentCard from './components/comment-card.vue'\nimport SlashMenu from './components/slash-menu.vue'\nimport { setFallbackHighlighter, type CodeHighlighter } from './core/highlight'\nimport { comparePlugin, compareKey } from './core/compare'\nimport {\n createEditorView,\n getBlocks,\n historyCommands,\n originKey,\n replaceBlocks,\n restoreBlocks,\n runCommand,\n setEditable,\n} from './core/editor'\nimport { diffBlocks } from './core/changes'\nimport { isRemote } from './core/plugins'\nimport { selectionOf, sameSelection } from './core/selection'\nimport { selectBlocks } from './core/block-selection'\nimport { applyEditorTransaction, EditorTransaction } from './core/transaction'\nimport {\n blocksToDoc,\n docToBlocks,\n type Block,\n type EditorDocument,\n type PartialBlock,\n} from './core/model'\nimport { resolveEditorExtensions } from './core/extension'\nimport {\n previewMatch,\n searchKey,\n searchPlugin,\n setSearch,\n type EditorSearchQuery,\n} from './core/search'\nimport { slashPlugin, type SlashState } from './core/slash'\nimport { writeHTML } from './core/output'\nimport { parseHTML } from './core/prepare'\nimport { componentMounter, vueNodeView } from './define-block'\nimport { editorKit } from './extensions/editor-kit'\nimport { readBlocks } from './document'\nimport {\n editorKey,\n type EditorEmits,\n type EditorExpose,\n type EditorProps,\n type EditorOrigin,\n type EditorLinkOpenEvent,\n type EditorSelection,\n type EditorTransactionResult,\n} from './editor'\nimport { useEditorMessages } from './locale'\nimport { useEditorComments } from './use-comments'\n\ndefineOptions({ name: 'DouEditor' })\n\nconst props = withDefaults(defineProps<EditorProps>(), {\n modelValue: undefined,\n extensions: undefined,\n readonly: false,\n searchable: true,\n placeholder: undefined,\n messages: undefined,\n ariaLabel: undefined,\n autofocus: false,\n plugins: undefined,\n history: true,\n undo: undefined,\n redo: undefined,\n selection: undefined,\n comments: undefined,\n author: undefined,\n activeComment: undefined,\n commentable: true,\n compare: undefined,\n})\nconst emit = defineEmits<EditorEmits>()\n\n// read once: changing the schema of a live editor would invalidate its document\nconst messages = useEditorMessages(() => props.messages)\nconst kit = resolveEditorExtensions(props.extensions ?? [editorKit()], () => messages.value)\n// say so once, instead of silently keeping the old extensions\nconst stopWatchingExtensions = watch(\n () => props.extensions,\n () => {\n console.warn(\n '[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.',\n )\n stopWatchingExtensions()\n },\n)\n\nconst ns = useNamespace('editor')\nconst config = useGlobalConfig()\nconst root = useTemplateRef<HTMLElement>('root')\nconst mount = useTemplateRef<HTMLElement>('mount')\nconst view = shallowRef<EditorView | null>(null)\nconst state = shallowRef<EditorState | null>(null)\nconst focused = shallowRef(false)\nconst dragging = shallowRef(false)\n/** Showing what changed since an older version: read-only, without comments. */\nconst comparing = computed(() => !!props.compare)\n/**\n * The older version as whole blocks, matched to the current ones by id. A\n * block saved without an id gets a new one, so it shows as removed.\n */\nconst compareBlocks = computed(() => {\n const blocks = props.compare?.blocks\n return Array.isArray(blocks) ? docToBlocks(blocksToDoc(kit.schema, blocks)) : null\n})\nconst editable = computed(() => !props.readonly && !comparing.value)\n\nconst {\n comments,\n plugin: commentPlugin,\n anchors,\n} = useEditorComments({\n props,\n emit,\n view,\n provider: kit.comments,\n})\n\nconst context = { view, state, focused, dragging, editable, messages, root, kit, comments }\nprovide(editorKey, context)\n\n// block components render outside this component's tree: hand them the context\nconst appContext = getCurrentInstance()?.appContext ?? null\nconst mountComponent = componentMounter(appContext, [[editorKey, context]])\nconst componentViews = {\n ...Object.fromEntries(\n Object.entries(kit.schema.nodes)\n .filter(([, type]) => type.spec.component)\n .map(([name, type]) => [\n name,\n vueNodeView(type.spec.component as Component, appContext, [[editorKey, context]]),\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(kit.componentViews).map(([name, create]) => [name, create(mountComponent)]),\n ),\n}\n\n// find and replace: the panel over the text, the matches marked in it\nconst searchOpen = ref(false)\nconst searchReplacing = ref(false)\nconst searchBar = useTemplateRef<InstanceType<typeof SearchBar>>('searchBar')\n/** Blocks that draw their own text, such as a code block in the code editor, are not searched. */\nconst searchSkip = (node: { type: { name: string } }) => node.type.name in kit.componentViews\n\n/** Opens the panel, with the replace box for `replace`. A selection on one line becomes the search. */\nfunction openSearch(replace = false, given?: Partial<EditorSearchQuery>) {\n const v = view.value\n if (!v || !props.searchable) return false\n const old = searchKey.getState(v.state)?.query ?? { search: '' }\n const query = { ...old, ...given }\n const { from, to, empty } = v.state.selection\n if (given?.search === undefined && !empty) {\n const text = v.state.doc.textBetween(from, to, '\\n')\n if (text && !text.includes('\\n')) query.search = text\n }\n if ((replace || given?.replace !== undefined) && editable.value) searchReplacing.value = true\n searchOpen.value = true\n v.dispatch(setSearch(v.state.tr, { query, active: true }))\n const preview = previewMatch(v.state)\n if (preview) v.dispatch(preview)\n void nextTick(() => searchBar.value?.focus(replace && editable.value ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n const v = view.value\n if (!searchOpen.value || !v) return false\n searchOpen.value = false\n v.dispatch(setSearch(v.state.tr, { active: false }))\n v.focus()\n return true\n}\n\n/** Goes to the next (or previous) match; with the panel shut, opens it on the last search. */\nfunction findAgain(step: 1 | -1) {\n if (!searchOpen.value) {\n const v = view.value\n if (!v || !searchKey.getState(v.state)?.query.search || !openSearch()) return false\n }\n void nextTick(() => (step > 0 ? searchBar.value?.next() : searchBar.value?.previous()))\n return true\n}\n\nconst replaceKey = isApplePlatform() ? 'Mod-Alt-f' : 'Mod-h'\nconst searchKeys = keymap({\n 'Mod-f': () => openSearch(),\n [replaceKey]: () => openSearch(true),\n F3: () => findAgain(1),\n 'Mod-g': () => findAgain(1),\n 'Shift-F3': () => findAgain(-1),\n 'Mod-Shift-g': () => findAgain(-1),\n Escape: () => closeSearch(),\n})\n\nconst slash = shallowRef<SlashState | null>(null)\nconst slashMenu = useTemplateRef<InstanceType<typeof SlashMenu>>('slashMenu')\nconst bubble = useTemplateRef<InstanceType<typeof BubbleToolbar>>('bubble')\n\n// The document last sent through `v-model`: when the same object comes back,\n// it is not loaded again (that would move the cursor).\nlet emitted: EditorDocument | undefined\n\n// the result of the last change, for `transact` to hand back\nlet lastResult: EditorTransactionResult | null = null\n\nfunction onChange(current: EditorView, tr: Transaction, before: EditorState) {\n const blocks = getBlocks(current)\n const doc: EditorDocument = { version: 1, blocks }\n emitted = doc\n const history = tr.getMeta('history$') as { redo: boolean } | undefined\n const origin =\n (tr.getMeta(originKey) as EditorOrigin | undefined) ??\n (history ? (history.redo ? 'redo' : 'undo') : isRemote(tr) ? 'remote' : undefined)\n const meta: EditorTransactionResult['meta'] = {\n history:\n tr.getMeta('addToHistory') !== false &&\n origin !== 'remote' &&\n origin !== 'undo' &&\n origin !== 'redo',\n }\n if (origin !== undefined) meta.origin = origin\n lastResult = { blocks, changes: diffBlocks(before.doc, current.state.doc), meta }\n emit('transaction', lastResult)\n emit('update:modelValue', doc)\n emit('change', doc)\n}\n\nlet selection: EditorSelection = { block: null, blocks: [] }\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\nconst lacksId = (blocks: PartialBlock[]): boolean =>\n blocks.some((block) => !block.id || lacksId(block.children ?? []))\n// until the editor is focused (or a block is, by the program) its selection is no cursor\nlet cursorKnown = false\n\nfunction onUpdate(current: EditorView) {\n state.value = current.state\n if (!cursorKnown) {\n if (!focused.value) return\n cursorKnown = true\n }\n const next = selectionOf(current.state)\n if (sameSelection(next, selection)) return\n selection = next\n emit('update:selection', next)\n}\n\n// a click on a link places the cursor; with Ctrl or ⌘ held, or while read-only, it opens the link\nconst openLinks = new Plugin({\n props: {\n handleDOMEvents: {\n click(clicked, event) {\n const link = (event.target as HTMLElement).closest<HTMLAnchorElement>('a.dou-editor__link')\n if (!link?.href || !(event.metaKey || event.ctrlKey || !clicked.editable)) return false\n event.preventDefault()\n const $pos = clicked.state.doc.resolve(clicked.posAtDOM(link, 0))\n let block = ''\n for (let depth = $pos.depth; depth > 0; depth--)\n if ($pos.node(depth).type.name === 'block') {\n block = $pos.node(depth).attrs.id as string\n break\n }\n const opening: EditorLinkOpenEvent = {\n link: link.getAttribute('href') ?? link.href,\n block,\n defaultPrevented: false,\n preventDefault() {\n this.defaultPrevented = true\n },\n }\n emit('linkOpen', opening)\n if (!opening.defaultPrevented) window.open(link.href, '_blank', 'noopener,noreferrer')\n return true\n },\n },\n },\n})\n\nonMounted(() => {\n const instance = createEditorView({\n element: mount.value!,\n kit,\n nodeViews: componentViews,\n // with collaboration the document comes from the shared document\n blocks: kit.externalDocument ? [] : readBlocks(props.modelValue),\n editable: editable.value,\n placeholder: {\n text: () => props.placeholder ?? messages.value.placeholder,\n heading: () => messages.value.headingPlaceholder,\n empty: () => props.placeholder ?? messages.value.emptyPlaceholder,\n },\n plugins: [\n ...(props.plugins ?? []),\n slashPlugin({\n onChange: (value) => (slash.value = value),\n onKey: (event) => slashMenu.value?.onKey(event) ?? false,\n }),\n keymap({\n 'Mod-k': () => bubble.value?.editLink() ?? false,\n 'Mod-Alt-m': () => comments.start(),\n // with the thread card open, Escape in the text closes it, and only that\n Escape: () => {\n if (!comments.pending.value && !comments.active.value) return false\n comments.close()\n return true\n },\n }),\n commentPlugin,\n comparePlugin({\n before: () => compareBlocks.value,\n label: () => messages.value.removedBlock,\n }),\n openLinks,\n searchPlugin({ skip: searchSkip }),\n ],\n keymaps: [searchKeys],\n history: props.history,\n undo: props.undo,\n redo: props.redo,\n attributes: () => {\n const attrs: Record<string, string> = {}\n if (props.ariaLabel) attrs['aria-label'] = props.ariaLabel\n if (!editable.value) attrs['aria-readonly'] = 'true'\n return attrs\n },\n onChange,\n onUpdate,\n })\n view.value = instance\n state.value = instance.state\n // code blocks without their own highlighter use the one DouCodeBlock uses\n watch(\n () =>\n (config.value.defaults as { DouCodeBlock?: { highlight?: CodeHighlighter } }).DouCodeBlock\n ?.highlight ?? null,\n (highlight) => setFallbackHighlighter(instance, highlight),\n { immediate: true },\n )\n instance.dom.addEventListener('focus', onFocus)\n instance.dom.addEventListener('blur', onBlur)\n if (props.autofocus) instance.focus()\n // blocks given without ids got them now: hand those back, so events' ids can be looked up\n const given = kit.externalDocument ? undefined : readBlocks(props.modelValue)\n if (given && lacksId(given)) {\n const doc: EditorDocument = { version: 1, blocks: getBlocks(instance) }\n emitted = doc\n emit('update:modelValue', doc)\n }\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n if (!cursorKnown && view.value) {\n cursorKnown = true\n const next = selectionOf(view.value.state)\n if (!sameSelection(next, selection)) {\n selection = next\n emit('update:selection', next)\n }\n }\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n focused.value = false\n emit('blur', event)\n}\n\nonBeforeUnmount(() => {\n view.value?.destroy()\n view.value = null\n})\n\nwatch(\n () => props.modelValue,\n (value) => {\n const current = view.value\n if (!current || value === undefined || kit.externalDocument || toRaw(value) === emitted) return\n replaceBlocks(current, readBlocks(value) ?? [])\n },\n)\n\nwatch(editable, (value) => view.value && setEditable(view.value, value))\nwatch(compareBlocks, () => view.value?.dispatch(view.value.state.tr.setMeta(compareKey, true)))\n\n/** The change last scrolled to, by its place among them. */\nlet changeIndex = -1\nwatch(\n () => props.compare,\n () => (changeIndex = -1),\n)\nfunction goToChange(step: 1 | -1) {\n const dom = view.value?.dom\n if (!dom || !props.compare) return false\n // a block's own mark, or the first piece of text changed in it\n const marks = [\n ...dom.querySelectorAll<HTMLElement>(\n '.dou-editor__diff-added, .dou-editor__diff-changed, .dou-editor__diff-removed-block, .dou-editor__diff-added-text, .dou-editor__diff-removed',\n ),\n ].filter((el, index, list) => {\n const block = el.closest('[data-block-id]')\n const previous = list[index - 1]\n return !previous || previous.closest('[data-block-id]') !== block || !block\n })\n const next = changeIndex + step\n const target = marks[next]\n if (!target) return false\n changeIndex = next\n target.scrollIntoView({ block: 'center' })\n const m = messages.value\n // a block added or removed, or one whose text or kind changed\n const kind = target.matches('.dou-editor__diff-added')\n ? m.changeAdded\n : target.matches('.dou-editor__diff-removed-block')\n ? m.changeRemoved\n : m.changeChanged\n announce(`${kind} ${changeText(target)}`)\n return true\n}\n\n/** The text of a change: what was removed, or its block as it is now. */\nfunction changeText(target: HTMLElement) {\n if (target.matches('.dou-editor__diff-removed-block')) return target.textContent ?? ''\n const block = (target.closest('[data-block-id]') ?? target).cloneNode(true) as HTMLElement\n for (const el of block.querySelectorAll('[data-diff=\"removed\"]')) el.remove()\n return block.textContent ?? ''\n}\n\n/** What the live region reads out: a version restored, the change gone to. */\nconst spoken = ref('')\nfunction announce(text: string) {\n // the same words twice still get read\n spoken.value = ''\n void nextTick(() => (spoken.value = text))\n}\n\nfunction restore(doc: EditorDocument<PartialBlock>) {\n // like the other methods it works while `readonly`, and it is the change comparing allows\n if (!view.value || !restoreBlocks(view.value, readBlocks(doc) ?? [])) return false\n announce(messages.value.restored)\n return true\n}\n\n// a selection from outside: the cursor goes to the block, or the blocks are selected\nwatch(\n () => props.selection,\n (value) => {\n const current = view.value\n if (!current || !value || sameSelection(value, selection)) return\n const known = cursorKnown\n cursorKnown = true\n let applied = false\n if (value.blocks.length > 1) {\n applied = selectBlocks(value.blocks[0]!, value.blocks.at(-1)!)(\n current.state,\n current.dispatch,\n )\n if (!applied) warn('`selection.blocks` must be sibling blocks that exist in the document')\n } else {\n const id = value.block ?? value.blocks[0]\n const transaction = new EditorTransaction(current.state)\n if (id && transaction.focusBlock(id)) {\n current.dispatch(transaction.tr)\n applied = true\n } else if (!id) warn('a selection without blocks cannot be set; the cursor stays where it is')\n }\n if (applied) return\n cursorKnown = known\n // hand back where the selection really is, so the binding doesn't keep a value that never applied\n emit('update:selection', { ...selection, blocks: [...selection.blocks] })\n },\n)\n\nfunction transact(\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransaction['meta'],\n): EditorTransactionResult | null {\n const current = view.value\n // comparing shows a version: nothing changes it but `restore`\n if (!current || props.compare) return null\n const transaction = new EditorTransaction(current.state, meta, cursorKnown)\n fn(transaction)\n lastResult = null\n // `focusBlock` places the cursor\n if (transaction.focused) cursorKnown = true\n applyEditorTransaction(current, transaction)\n if (transaction.focused) current.focus()\n const result = lastResult\n lastResult = null\n return result\n}\n\nconst history = (action: 'undo' | 'redo', dispatch: boolean) => {\n const current = view.value\n if (!current || props.compare) return false\n const command = historyCommands(current.state)[action]\n return dispatch ? runCommand(current, command) : command(current.state)\n}\n\ndefineExpose<EditorExpose>({\n get view() {\n return view.value\n },\n focus: () => view.value?.focus(),\n blur: () => (view.value?.dom as HTMLElement | undefined)?.blur(),\n getBlocks: () => (view.value ? getBlocks(view.value) : []),\n setBlocks: (blocks: PartialBlock[]) => view.value && replaceBlocks(view.value, blocks),\n getHTML: () => (view.value ? writeHTML(getBlocks(view.value), kit) : ''),\n setHTML: (html: string) => view.value && replaceBlocks(view.value, parseHTML(html, kit)),\n run: (command) => (view.value ? runCommand(view.value, command) : false),\n openSearch: (query) => openSearch(query?.replace !== undefined, query),\n closeSearch,\n transact,\n getBlock: (id) => (view.value ? new EditorTransaction(view.value.state).getBlock(id) : null),\n insertBlocks: (blocks, placement) => {\n let ids: string[] = []\n transact((tr) => (ids = tr.insertBlocks(blocks, placement)))\n return ids\n },\n updateBlock: (id, patch) => {\n let ok = false\n transact((tr) => (ok = tr.updateBlock(id, patch)))\n return ok\n },\n removeBlocks: (ids) => {\n let ok = false\n transact((tr) => (ok = tr.removeBlocks(ids)))\n return ok\n },\n moveBlocks: (ids, placement) => {\n let ok = false\n transact((tr) => (ok = tr.moveBlocks(ids, placement)))\n return ok\n },\n focusBlock: (id, edge) => {\n let ok = false\n transact((tr) => (ok = tr.focusBlock(id, edge)))\n return ok\n },\n getSelection: () => ({ ...selection, blocks: [...selection.blocks] }),\n undo: () => history('undo', true),\n redo: () => history('redo', true),\n get canUndo() {\n return !!state.value && history('undo', false)\n },\n get canRedo() {\n return !!state.value && history('redo', false)\n },\n comment: () => comments.start(),\n getCommentAnchors: anchors,\n restore,\n nextChange: () => goToChange(1),\n previousChange: () => goToChange(-1),\n})\n\n/*\n * Highlights for the threads that are open: by thread id, in one rule,\n * so a thread resolved or opened restyles its text without redrawing it.\n */\nconst scope = useId()\n/** An id as a CSS identifier: no quotes or `<`, which server rendering would escape. */\nconst ident = (id: string) =>\n id.replace(/[^a-zA-Z0-9_]|^[\\d-]/gu, (char) => `\\\\${char.codePointAt(0)!.toString(16)} `)\nconst highlighted = (id: string) => `[data-dou-editor=${ident(scope)}] [data-comment=${ident(id)}]`\nconst highlightCSS = computed(() => {\n if (!comments.enabled.value) return ''\n const open = comments.threads.value.filter((thread) => !thread.resolved)\n if (!open.length) return ''\n let css = `${open.map((thread) => highlighted(thread.id)).join(',')}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line)}`\n const active = comments.active.value\n if (active && open.some((thread) => thread.id === active))\n css += `${highlighted(active)}{background-color:var(--dou-editor-comment-bg-active)}`\n return css\n})\nconst HighlightStyle = () => (highlightCSS.value ? h('style', highlightCSS.value) : null)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n {\n // comparing keeps the editor's own gutter, so the text doesn't move\n 'is-readonly': readonly,\n 'is-comparing': comparing,\n 'is-focused': focused,\n 'is-dragging': dragging,\n },\n ]\"\n :data-dou-editor=\"scope\"\n >\n <div v-if=\"searchOpen && view\" :class=\"ns.e('search')\">\n <SearchBar\n ref=\"searchBar\"\n v-model:replacing=\"searchReplacing\"\n :readonly=\"!editable\"\n :skip=\"searchSkip\"\n @close=\"closeSearch\"\n />\n </div>\n <HighlightStyle />\n <div ref=\"mount\" :class=\"ns.e('mount')\" />\n <template v-if=\"editable && view\">\n <BlockHandle />\n <SlashMenu ref=\"slashMenu\" :slash=\"slash\" />\n <BubbleToolbar ref=\"bubble\" />\n <component :is=\"overlay\" v-for=\"(overlay, index) in kit.overlays\" :key=\"index\" />\n </template>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ spoken }}</div>\n <template v-if=\"view && comments.enabled.value && !comparing\">\n <CommentButton v-if=\"readonly\" />\n <CommentCard />\n </template>\n </div>\n</template>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"editor2.js","names":["_sfc_main"],"sources":["../src/editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { isApplePlatform, useGlobalConfig, useNamespace } from 'dou-ui'\nimport { keymap } from 'prosemirror-keymap'\nimport { Plugin, type EditorState, type Transaction } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport {\n computed,\n getCurrentInstance,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n ref,\n shallowRef,\n toRaw,\n useTemplateRef,\n watch,\n h,\n useId,\n type Component,\n} from 'vue'\nimport BlockHandle from './components/block-handle.vue'\nimport BubbleToolbar from './components/bubble-toolbar.vue'\nimport SearchBar from './components/search-bar.vue'\nimport CommentButton from './components/comment-button.vue'\nimport CommentCard from './components/comment-card.vue'\nimport SlashMenu from './components/slash-menu.vue'\nimport { setFallbackHighlighter, type CodeHighlighter } from './core/highlight'\nimport { comparePlugin, compareKey } from './core/compare'\nimport {\n createEditorView,\n getBlocks,\n historyCommands,\n originKey,\n replaceBlocks,\n restoreBlocks,\n runCommand,\n setEditable,\n} from './core/editor'\nimport { diffBlocks } from './core/changes'\nimport { isRemote } from './core/plugins'\nimport { selectionOf, sameSelection } from './core/selection'\nimport { selectBlocks } from './core/block-selection'\nimport { applyEditorTransaction, EditorTransaction } from './core/transaction'\nimport {\n blocksToDoc,\n docToBlocks,\n type Block,\n type EditorDocument,\n type PartialBlock,\n} from './core/model'\nimport { resolveEditorExtensions } from './core/extension'\nimport {\n previewMatch,\n searchKey,\n searchPlugin,\n setSearch,\n type EditorSearchQuery,\n} from './core/search'\nimport { slashPlugin, type SlashState } from './core/slash'\nimport { writeHTML } from './core/output'\nimport { parseHTML } from './core/prepare'\nimport { componentMounter, vueNodeView } from './define-block'\nimport { editorKit } from './extensions/editor-kit'\nimport { readBlocks } from './document'\nimport {\n editorKey,\n type EditorEmits,\n type EditorExpose,\n type EditorProps,\n type EditorOrigin,\n type EditorLinkOpenEvent,\n type EditorSelection,\n type EditorTransactionResult,\n} from './editor'\nimport { useEditorMessages } from './locale'\nimport { useEditorComments } from './use-comments'\n\ndefineOptions({ name: 'DouEditor' })\n\nconst props = withDefaults(defineProps<EditorProps>(), {\n modelValue: undefined,\n extensions: undefined,\n readonly: false,\n searchable: true,\n placeholder: undefined,\n messages: undefined,\n ariaLabel: undefined,\n autofocus: false,\n plugins: undefined,\n history: true,\n undo: undefined,\n redo: undefined,\n selection: undefined,\n comments: undefined,\n author: undefined,\n activeComment: undefined,\n commentable: true,\n compare: undefined,\n})\nconst emit = defineEmits<EditorEmits>()\n\n// read once: changing the schema of a live editor would invalidate its document\nconst messages = useEditorMessages(() => props.messages)\nconst kit = resolveEditorExtensions(props.extensions ?? [editorKit()], () => messages.value)\n// say so once, instead of silently keeping the old extensions\nconst stopWatchingExtensions = watch(\n () => props.extensions,\n () => {\n console.warn(\n '[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.',\n )\n stopWatchingExtensions()\n },\n)\n\nconst ns = useNamespace('editor')\nconst config = useGlobalConfig()\nconst root = useTemplateRef<HTMLElement>('root')\nconst mount = useTemplateRef<HTMLElement>('mount')\nconst view = shallowRef<EditorView | null>(null)\nconst state = shallowRef<EditorState | null>(null)\nconst focused = shallowRef(false)\nconst dragging = shallowRef(false)\n/** Showing what changed since an older version: read-only, without comments. */\nconst comparing = computed(() => !!props.compare)\n/**\n * The older version as whole blocks, matched to the current ones by id. A\n * block saved without an id gets a new one, so it shows as removed.\n */\nconst compareBlocks = computed(() => {\n const blocks = props.compare?.blocks\n return Array.isArray(blocks) ? docToBlocks(blocksToDoc(kit.schema, blocks)) : null\n})\nconst editable = computed(() => !props.readonly && !comparing.value)\n\nconst {\n comments,\n plugin: commentPlugin,\n anchors,\n} = useEditorComments({\n props,\n emit,\n view,\n provider: kit.comments,\n})\n\nconst context = { view, state, focused, dragging, editable, messages, root, kit, comments }\nprovide(editorKey, context)\n\n// block components render outside this component's tree: hand them the context\nconst appContext = getCurrentInstance()?.appContext ?? null\nconst mountComponent = componentMounter(appContext, [[editorKey, context]])\nconst componentViews = {\n ...Object.fromEntries(\n Object.entries(kit.schema.nodes)\n .filter(([, type]) => type.spec.component)\n .map(([name, type]) => [\n name,\n vueNodeView(type.spec.component as Component, appContext, [[editorKey, context]]),\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(kit.componentViews).map(([name, create]) => [name, create(mountComponent)]),\n ),\n}\n\n// find and replace: the panel over the text, the matches marked in it\nconst searchOpen = ref(false)\nconst searchReplacing = ref(false)\nconst searchBar = useTemplateRef<InstanceType<typeof SearchBar>>('searchBar')\n/** Blocks that draw their own text, such as a code block in the code editor, are not searched. */\nconst searchSkip = (node: { type: { name: string } }) => node.type.name in kit.componentViews\n\n/** Opens the panel, with the replace box for `replace`. A selection on one line becomes the search. */\nfunction openSearch(replace = false, given?: Partial<EditorSearchQuery>) {\n const v = view.value\n if (!v || !props.searchable) return false\n const old = searchKey.getState(v.state)?.query ?? { search: '' }\n const query = { ...old, ...given }\n const { from, to, empty } = v.state.selection\n if (given?.search === undefined && !empty) {\n const text = v.state.doc.textBetween(from, to, '\\n')\n if (text && !text.includes('\\n')) query.search = text\n }\n if ((replace || given?.replace !== undefined) && editable.value) searchReplacing.value = true\n searchOpen.value = true\n v.dispatch(setSearch(v.state.tr, { query, active: true }))\n const preview = previewMatch(v.state)\n if (preview) v.dispatch(preview)\n void nextTick(() => searchBar.value?.focus(replace && editable.value ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n const v = view.value\n if (!searchOpen.value || !v) return false\n searchOpen.value = false\n v.dispatch(setSearch(v.state.tr, { active: false }))\n v.focus()\n return true\n}\n\n/** Goes to the next (or previous) match; with the panel shut, opens it on the last search. */\nfunction findAgain(step: 1 | -1) {\n if (!searchOpen.value) {\n const v = view.value\n if (!v || !searchKey.getState(v.state)?.query.search || !openSearch()) return false\n }\n void nextTick(() => (step > 0 ? searchBar.value?.next() : searchBar.value?.previous()))\n return true\n}\n\nconst replaceKey = isApplePlatform() ? 'Mod-Alt-f' : 'Mod-h'\nconst searchKeys = keymap({\n 'Mod-f': () => openSearch(),\n [replaceKey]: () => openSearch(true),\n F3: () => findAgain(1),\n 'Mod-g': () => findAgain(1),\n 'Shift-F3': () => findAgain(-1),\n 'Mod-Shift-g': () => findAgain(-1),\n Escape: () => closeSearch(),\n})\n\nconst slash = shallowRef<SlashState | null>(null)\nconst slashMenu = useTemplateRef<InstanceType<typeof SlashMenu>>('slashMenu')\nconst bubble = useTemplateRef<InstanceType<typeof BubbleToolbar>>('bubble')\n\n// The document last sent through `v-model`: when the same object comes back,\n// it is not loaded again (that would move the cursor).\nlet emitted: EditorDocument | undefined\n\n// the result of the last change, for `transact` to hand back\nlet lastResult: EditorTransactionResult | null = null\n\nfunction onChange(current: EditorView, tr: Transaction, before: EditorState) {\n const blocks = getBlocks(current)\n const doc: EditorDocument = { version: 1, blocks }\n emitted = doc\n const history = tr.getMeta('history$') as { redo: boolean } | undefined\n const origin =\n (tr.getMeta(originKey) as EditorOrigin | undefined) ??\n (history ? (history.redo ? 'redo' : 'undo') : isRemote(tr) ? 'remote' : undefined)\n const meta: EditorTransactionResult['meta'] = {\n history:\n tr.getMeta('addToHistory') !== false &&\n origin !== 'remote' &&\n origin !== 'undo' &&\n origin !== 'redo',\n }\n if (origin !== undefined) meta.origin = origin\n lastResult = { blocks, changes: diffBlocks(before.doc, current.state.doc), meta }\n emit('transaction', lastResult)\n emit('update:modelValue', doc)\n emit('change', doc)\n}\n\nlet selection: EditorSelection = { block: null, blocks: [] }\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\nconst lacksId = (blocks: PartialBlock[]): boolean =>\n blocks.some((block) => !block.id || lacksId(block.children ?? []))\n// until the editor is focused (or a block is, by the program) its selection is no cursor\nlet cursorKnown = false\n\nfunction onUpdate(current: EditorView) {\n state.value = current.state\n if (!cursorKnown) {\n if (!focused.value) return\n cursorKnown = true\n }\n const next = selectionOf(current.state)\n if (sameSelection(next, selection)) return\n selection = next\n emit('update:selection', next)\n}\n\n// a click on a link places the cursor; with Ctrl or ⌘ held, or while read-only, it opens the link\nconst openLinks = new Plugin({\n props: {\n handleDOMEvents: {\n click(clicked, event) {\n const link = (event.target as HTMLElement).closest<HTMLAnchorElement>('a.dou-editor__link')\n if (!link?.href || !(event.metaKey || event.ctrlKey || !clicked.editable)) return false\n event.preventDefault()\n const $pos = clicked.state.doc.resolve(clicked.posAtDOM(link, 0))\n let block = ''\n for (let depth = $pos.depth; depth > 0; depth--)\n if ($pos.node(depth).type.name === 'block') {\n block = $pos.node(depth).attrs.id as string\n break\n }\n const opening: EditorLinkOpenEvent = {\n link: link.getAttribute('href') ?? link.href,\n block,\n defaultPrevented: false,\n preventDefault() {\n this.defaultPrevented = true\n },\n }\n emit('linkOpen', opening)\n if (!opening.defaultPrevented) window.open(link.href, '_blank', 'noopener,noreferrer')\n return true\n },\n },\n },\n})\n\nonMounted(() => {\n const instance = createEditorView({\n element: mount.value!,\n kit,\n nodeViews: componentViews,\n // with collaboration the document comes from the shared document\n blocks: kit.externalDocument ? [] : readBlocks(props.modelValue),\n editable: editable.value,\n placeholder: {\n text: () => props.placeholder ?? messages.value.placeholder,\n heading: () => messages.value.headingPlaceholder,\n empty: () => props.placeholder ?? messages.value.emptyPlaceholder,\n },\n plugins: [\n ...(props.plugins ?? []),\n slashPlugin({\n onChange: (value) => (slash.value = value),\n onKey: (event) => slashMenu.value?.onKey(event) ?? false,\n }),\n keymap({\n 'Mod-k': () => bubble.value?.editLink() ?? false,\n 'Mod-Alt-m': () => comments.start(),\n // with the thread card open, Escape in the text closes it, and only that\n Escape: () => {\n if (!comments.pending.value && !comments.active.value) return false\n comments.close()\n return true\n },\n }),\n commentPlugin,\n comparePlugin({\n before: () => compareBlocks.value,\n label: () => messages.value.removedBlock,\n }),\n openLinks,\n searchPlugin({ skip: searchSkip }),\n ],\n keymaps: [searchKeys],\n history: props.history,\n undo: props.undo,\n redo: props.redo,\n attributes: () => {\n const attrs: Record<string, string> = {}\n if (props.ariaLabel) attrs['aria-label'] = props.ariaLabel\n if (!editable.value) attrs['aria-readonly'] = 'true'\n return attrs\n },\n onChange,\n onUpdate,\n })\n view.value = instance\n state.value = instance.state\n // code blocks without their own highlighter use the one DouCodeBlock uses\n watch(\n () =>\n (config.value.defaults as { DouCodeBlock?: { highlight?: CodeHighlighter } }).DouCodeBlock\n ?.highlight ?? null,\n (highlight) => setFallbackHighlighter(instance, highlight),\n { immediate: true },\n )\n instance.dom.addEventListener('focus', onFocus)\n instance.dom.addEventListener('blur', onBlur)\n if (props.autofocus) instance.focus()\n // blocks given without ids got them now: hand those back, so events' ids can be looked up\n const given = kit.externalDocument ? undefined : readBlocks(props.modelValue)\n if (given && lacksId(given)) {\n const doc: EditorDocument = { version: 1, blocks: getBlocks(instance) }\n emitted = doc\n emit('update:modelValue', doc)\n }\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n if (!cursorKnown && view.value) {\n cursorKnown = true\n const next = selectionOf(view.value.state)\n if (!sameSelection(next, selection)) {\n selection = next\n emit('update:selection', next)\n }\n }\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n focused.value = false\n emit('blur', event)\n}\n\nonBeforeUnmount(() => {\n view.value?.destroy()\n view.value = null\n})\n\nwatch(\n () => props.modelValue,\n (value) => {\n const current = view.value\n if (!current || value === undefined || kit.externalDocument || toRaw(value) === emitted) return\n replaceBlocks(current, readBlocks(value) ?? [])\n },\n)\n\nwatch(editable, (value) => view.value && setEditable(view.value, value))\nwatch(compareBlocks, () => view.value?.dispatch(view.value.state.tr.setMeta(compareKey, true)))\n\n/** The change last scrolled to, by its place among them. */\nlet changeIndex = -1\nwatch(\n () => props.compare,\n () => (changeIndex = -1),\n)\nfunction goToChange(step: 1 | -1) {\n const dom = view.value?.dom\n if (!dom || !props.compare) return false\n // a block's own mark, or the first piece of text changed in it\n const marks = [\n ...dom.querySelectorAll<HTMLElement>(\n '.dou-editor__diff-added, .dou-editor__diff-changed, .dou-editor__diff-removed-block, .dou-editor__diff-added-text, .dou-editor__diff-removed',\n ),\n ].filter((el, index, list) => {\n const block = el.closest('[data-block-id]')\n const previous = list[index - 1]\n return !previous || previous.closest('[data-block-id]') !== block || !block\n })\n const next = changeIndex + step\n const target = marks[next]\n if (!target) return false\n changeIndex = next\n target.scrollIntoView({ block: 'center' })\n const m = messages.value\n // a block added or removed, or one whose text or kind changed\n const kind = target.matches('.dou-editor__diff-added')\n ? m.changeAdded\n : target.matches('.dou-editor__diff-removed-block')\n ? m.changeRemoved\n : m.changeChanged\n announce(`${kind} ${changeText(target)}`)\n return true\n}\n\n/** The text of a change: what was removed, or its block as it is now. */\nfunction changeText(target: HTMLElement) {\n if (target.matches('.dou-editor__diff-removed-block')) return target.textContent ?? ''\n const block = (target.closest('[data-block-id]') ?? target).cloneNode(true) as HTMLElement\n for (const el of block.querySelectorAll('[data-diff=\"removed\"]')) el.remove()\n return block.textContent ?? ''\n}\n\n/** What the live region reads out: a version restored, the change gone to. */\nconst spoken = ref('')\nfunction announce(text: string) {\n // the same words twice still get read\n spoken.value = ''\n void nextTick(() => (spoken.value = text))\n}\n\nfunction restore(doc: EditorDocument<PartialBlock>) {\n // like the other methods it works while `readonly`, and it is the change comparing allows\n if (!view.value || !restoreBlocks(view.value, readBlocks(doc) ?? [])) return false\n announce(messages.value.restored)\n return true\n}\n\n// a selection from outside: the cursor goes to the block, or the blocks are selected\nwatch(\n () => props.selection,\n (value) => {\n const current = view.value\n if (!current || !value || sameSelection(value, selection)) return\n const known = cursorKnown\n cursorKnown = true\n let applied = false\n if (value.blocks.length > 1) {\n applied = selectBlocks(value.blocks[0]!, value.blocks.at(-1)!)(\n current.state,\n current.dispatch,\n )\n if (!applied) warn('`selection.blocks` must be sibling blocks that exist in the document')\n } else {\n const id = value.block ?? value.blocks[0]\n const transaction = new EditorTransaction(current.state)\n if (id && transaction.focusBlock(id)) {\n current.dispatch(transaction.tr)\n applied = true\n } else if (!id) warn('a selection without blocks cannot be set; the cursor stays where it is')\n }\n if (applied) return\n cursorKnown = known\n // hand back where the selection really is, so the binding doesn't keep a value that never applied\n emit('update:selection', { ...selection, blocks: [...selection.blocks] })\n },\n)\n\nfunction transact(\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransaction['meta'],\n): EditorTransactionResult | null {\n const current = view.value\n // comparing shows a version: nothing changes it but `restore`\n if (!current || props.compare) return null\n const transaction = new EditorTransaction(current.state, meta, cursorKnown)\n fn(transaction)\n lastResult = null\n // `focusBlock` places the cursor\n if (transaction.focused) cursorKnown = true\n applyEditorTransaction(current, transaction)\n if (transaction.focused) current.focus()\n const result = lastResult\n lastResult = null\n return result\n}\n\nconst history = (action: 'undo' | 'redo', dispatch: boolean) => {\n const current = view.value\n if (!current || props.compare) return false\n const command = historyCommands(current.state)[action]\n return dispatch ? runCommand(current, command) : command(current.state)\n}\n\ndefineExpose<EditorExpose>({\n get view() {\n return view.value\n },\n focus: () => view.value?.focus(),\n blur: () => (view.value?.dom as HTMLElement | undefined)?.blur(),\n getBlocks: () => (view.value ? getBlocks(view.value) : []),\n setBlocks: (blocks: PartialBlock[]) => view.value && replaceBlocks(view.value, blocks),\n getHTML: () => (view.value ? writeHTML(getBlocks(view.value), kit) : ''),\n setHTML: (html: string) => view.value && replaceBlocks(view.value, parseHTML(html, kit)),\n run: (command) => (view.value ? runCommand(view.value, command) : false),\n openSearch: (query) => openSearch(query?.replace !== undefined, query),\n closeSearch,\n transact,\n getBlock: (id) => (view.value ? new EditorTransaction(view.value.state).getBlock(id) : null),\n insertBlocks: (blocks, placement) => {\n let ids: string[] = []\n transact((tr) => (ids = tr.insertBlocks(blocks, placement)))\n return ids\n },\n updateBlock: (id, patch) => {\n let ok = false\n transact((tr) => (ok = tr.updateBlock(id, patch)))\n return ok\n },\n removeBlocks: (ids) => {\n let ok = false\n transact((tr) => (ok = tr.removeBlocks(ids)))\n return ok\n },\n moveBlocks: (ids, placement) => {\n let ok = false\n transact((tr) => (ok = tr.moveBlocks(ids, placement)))\n return ok\n },\n focusBlock: (id, edge) => {\n let ok = false\n transact((tr) => (ok = tr.focusBlock(id, edge)))\n return ok\n },\n getSelection: () => ({ ...selection, blocks: [...selection.blocks] }),\n undo: () => history('undo', true),\n redo: () => history('redo', true),\n get canUndo() {\n return !!state.value && history('undo', false)\n },\n get canRedo() {\n return !!state.value && history('redo', false)\n },\n comment: () => comments.start(),\n getCommentAnchors: anchors,\n restore,\n nextChange: () => goToChange(1),\n previousChange: () => goToChange(-1),\n})\n\n/*\n * Highlights for the threads that are open: by thread id, in one rule,\n * so a thread resolved or opened restyles its text without redrawing it.\n */\nconst scope = useId()\n/** An id as a CSS identifier: no quotes or `<`, which server rendering would escape. */\nconst ident = (id: string) =>\n id.replace(/[^a-zA-Z0-9_]|^[\\d-]/gu, (char) => `\\\\${char.codePointAt(0)!.toString(16)} `)\nconst highlighted = (id: string) => `[data-dou-editor=${ident(scope)}] [data-comment=${ident(id)}]`\nconst highlightCSS = computed(() => {\n if (!comments.enabled.value) return ''\n const open = comments.threads.value.filter((thread) => !thread.resolved)\n if (!open.length) return ''\n let css = `${open.map((thread) => highlighted(thread.id)).join(',')}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line)}`\n const active = comments.active.value\n if (active && open.some((thread) => thread.id === active))\n css += `${highlighted(active)}{background-color:var(--dou-editor-comment-bg-active)}`\n return css\n})\nconst HighlightStyle = () => (highlightCSS.value ? h('style', highlightCSS.value) : null)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n {\n // comparing takes a narrow gutter for the bars beside changed blocks\n 'is-readonly': readonly,\n 'is-comparing': comparing,\n 'is-focused': focused,\n 'is-dragging': dragging,\n },\n ]\"\n :data-dou-editor=\"scope\"\n >\n <div v-if=\"searchOpen && view\" :class=\"ns.e('search')\">\n <SearchBar\n ref=\"searchBar\"\n v-model:replacing=\"searchReplacing\"\n :readonly=\"!editable\"\n :skip=\"searchSkip\"\n @close=\"closeSearch\"\n />\n </div>\n <HighlightStyle />\n <div ref=\"mount\" :class=\"ns.e('mount')\" />\n <template v-if=\"editable && view\">\n <BlockHandle />\n <SlashMenu ref=\"slashMenu\" :slash=\"slash\" />\n <BubbleToolbar ref=\"bubble\" />\n <component :is=\"overlay\" v-for=\"(overlay, index) in kit.overlays\" :key=\"index\" />\n </template>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ spoken }}</div>\n <template v-if=\"view && comments.enabled.value && !comparing\">\n <CommentButton v-if=\"readonly\" />\n <CommentCard />\n </template>\n </div>\n</template>\n"],"mappings":""}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import board_block_vue_vue_type_script_setup_true_lang_default from "./board-block.vue_vue_type_script_setup_true_lang.js";
|
|
2
|
+
// src/flow/board-block.vue
|
|
3
|
+
var board_block_default = board_block_vue_vue_type_script_setup_true_lang_default;
|
|
4
|
+
export { board_block_default as default };
|
|
5
|
+
|
|
6
|
+
//# sourceMappingURL=board-block.js.map
|
|
@@ -0,0 +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":""}
|