@dou-ui/editor 0.1.0-alpha.12 → 0.1.0-alpha.13
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/cursors.js +42 -10
- package/dist/collaboration/cursors.js.map +1 -1
- package/dist/collaboration/index.js +30 -3
- package/dist/collaboration/index.js.map +1 -1
- package/dist/components/block-handle.js.map +1 -1
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js +73 -15
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/slash-choices.js +6 -0
- package/dist/components/slash-choices.js.map +1 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js +56 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/components/slash-menu.js.map +1 -1
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js +185 -20
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/core/block-selection.js +32 -4
- package/dist/core/block-selection.js.map +1 -1
- package/dist/core/blocks.js +21 -3
- package/dist/core/blocks.js.map +1 -1
- package/dist/core/commands.js +125 -13
- package/dist/core/commands.js.map +1 -1
- package/dist/core/extension.js +6 -2
- package/dist/core/extension.js.map +1 -1
- package/dist/core/model.js +8 -2
- package/dist/core/model.js.map +1 -1
- package/dist/core/schema.js.map +1 -1
- package/dist/core/transaction.js +12 -3
- package/dist/core/transaction.js.map +1 -1
- package/dist/document.js +40 -4
- package/dist/document.js.map +1 -1
- package/dist/dom.js +96 -13
- package/dist/dom.js.map +1 -1
- package/dist/editor.vue_vue_type_script_setup_true_lang.js +3 -3
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.js.map +1 -1
- package/dist/extensions/columns/column-picker.js +6 -0
- package/dist/extensions/columns/column-picker.js.map +1 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js +57 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/columns-controls.js +6 -0
- package/dist/extensions/columns/columns-controls.js.map +1 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js +341 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/html.js +34 -0
- package/dist/extensions/columns/html.js.map +1 -0
- package/dist/extensions/columns/index.js +57 -0
- package/dist/extensions/columns/index.js.map +1 -0
- package/dist/extensions/columns/keys.js +53 -0
- package/dist/extensions/columns/keys.js.map +1 -0
- package/dist/extensions/columns/plugin.js +213 -0
- package/dist/extensions/columns/plugin.js.map +1 -0
- package/dist/extensions/columns/schema.js +58 -0
- package/dist/extensions/columns/schema.js.map +1 -0
- package/dist/extensions/columns/select-columns.js +6 -0
- package/dist/extensions/columns/select-columns.js.map +1 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js +71 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/editor-kit.js +3 -1
- package/dist/extensions/editor-kit.js.map +1 -1
- package/dist/extensions/table/plugin.js +33 -1
- package/dist/extensions/table/plugin.js.map +1 -1
- package/dist/extensions/table/table-controls.js.map +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/table/view.js +25 -1
- package/dist/extensions/table/view.js.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/locale.js +30 -0
- package/dist/locale.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/types/collaboration/cursors.d.ts +29 -1
- package/dist/types/collaboration/index.d.ts +17 -2
- package/dist/types/components/slash-choices.vue.d.ts +18 -0
- package/dist/types/core/blocks.d.ts +10 -0
- package/dist/types/core/commands.d.ts +17 -2
- package/dist/types/core/extension.d.ts +53 -2
- package/dist/types/core/model.d.ts +6 -1
- package/dist/types/core/schema.d.ts +1 -1
- package/dist/types/document.d.ts +4 -2
- package/dist/types/dom.d.ts +34 -4
- package/dist/types/editor.vue.d.ts +10 -0
- package/dist/types/extensions/columns/column-picker.vue.d.ts +10 -0
- package/dist/types/extensions/columns/columns-controls.vue.d.ts +3 -0
- package/dist/types/extensions/columns/html.d.ts +10 -0
- package/dist/types/extensions/columns/index.d.ts +9 -0
- package/dist/types/extensions/columns/keys.d.ts +6 -0
- package/dist/types/extensions/columns/plugin.d.ts +28 -0
- package/dist/types/extensions/columns/schema.d.ts +17 -0
- package/dist/types/extensions/columns/select-columns.vue.d.ts +13 -0
- package/dist/types/extensions/editor-kit.d.ts +4 -1
- package/dist/types/extensions/table/view.d.ts +8 -1
- package/dist/types/index.d.ts +12 -2
- package/dist/types/locale.d.ts +17 -0
- package/package.json +5 -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 kit = resolveEditorExtensions(props.extensions ?? [editorKit()])\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 messages = useEditorMessages(() => props.messages)\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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"}
|
|
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,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,CA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AA;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"}
|
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 kit = resolveEditorExtensions(props.extensions ?? [editorKit()])\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 messages = useEditorMessages(() => props.messages)\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 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":""}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import column_picker_vue_vue_type_script_setup_true_lang_default from "./column-picker.vue_vue_type_script_setup_true_lang.js";
|
|
2
|
+
// src/extensions/columns/column-picker.vue
|
|
3
|
+
var column_picker_default = column_picker_vue_vue_type_script_setup_true_lang_default;
|
|
4
|
+
export { column_picker_default as default };
|
|
5
|
+
|
|
6
|
+
//# sourceMappingURL=column-picker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"column-picker.js","names":["_sfc_main"],"sources":["../../../src/extensions/columns/column-picker.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport {\n labelOf,\n type BlockOptionChoicesEmits,\n type BlockOptionChoicesProps,\n} from '../../core/extension'\n\n/**\n * The column count picker beside “Columns” in the slash menu: a row of\n * bars, as many as the most columns; pointing at one lights the bars up to\n * it, the count a click inserts.\n */\nconst props = defineProps<BlockOptionChoicesProps>()\nconst emit = defineEmits<BlockOptionChoicesEmits>()\n\nconst counts = computed(() => props.items.map((item) => Number(item.props.count)))\nconst bars = computed(() => Math.max(...counts.value))\n/** Bars lit up to here; none while the option itself is highlighted. */\nconst lit = computed(() => (props.active < 0 ? 0 : (counts.value[props.active] ?? 0)))\n\n/** The choice a bar stands for: its count, or the fewest there can be. */\nconst indexOf = (bar: number) => {\n const index = counts.value.indexOf(Math.max(bar, counts.value[0]!))\n return index < 0 ? 0 : index\n}\n</script>\n\n<template>\n <div class=\"dou-editor-column-picker\">\n <div\n v-for=\"bar in bars\"\n :id=\"bar >= counts[0]! ? `${idPrefix}-${indexOf(bar)}` : undefined\"\n :key=\"bar\"\n :role=\"bar >= counts[0]! ? 'option' : 'presentation'\"\n :aria-selected=\"bar >= counts[0]! ? bar === lit : undefined\"\n :aria-label=\"bar >= counts[0]! ? labelOf(items[indexOf(bar)]!.label, messages) : undefined\"\n :class=\"['dou-editor-column-picker__bar', { 'is-lit': bar <= lit }]\"\n @pointermove=\"emit('hover', indexOf(bar))\"\n @click=\"emit('choose', indexOf(bar))\"\n />\n </div>\n</template>\n"],"mappings":""}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { labelOf } from "../../core/extension.js";
|
|
2
|
+
import { Fragment, computed, createElementBlock, defineComponent, normalizeClass, openBlock, renderList, unref } from "vue";
|
|
3
|
+
// src/extensions/columns/column-picker.vue?vue&type=script&setup=true&lang.ts
|
|
4
|
+
var _hoisted_1 = { class: "dou-editor-column-picker" };
|
|
5
|
+
var _hoisted_2 = [
|
|
6
|
+
"id",
|
|
7
|
+
"role",
|
|
8
|
+
"aria-selected",
|
|
9
|
+
"aria-label",
|
|
10
|
+
"onPointermove",
|
|
11
|
+
"onClick"
|
|
12
|
+
];
|
|
13
|
+
/**
|
|
14
|
+
* The column count picker beside “Columns” in the slash menu: a row of
|
|
15
|
+
* bars, as many as the most columns; pointing at one lights the bars up to
|
|
16
|
+
* it, the count a click inserts.
|
|
17
|
+
*/
|
|
18
|
+
var column_picker_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({
|
|
19
|
+
__name: "column-picker",
|
|
20
|
+
props: {
|
|
21
|
+
items: {},
|
|
22
|
+
active: {},
|
|
23
|
+
messages: {},
|
|
24
|
+
idPrefix: {}
|
|
25
|
+
},
|
|
26
|
+
emits: ["hover", "choose"],
|
|
27
|
+
setup(__props, { emit: __emit }) {
|
|
28
|
+
const props = __props;
|
|
29
|
+
const emit = __emit;
|
|
30
|
+
const counts = computed(() => props.items.map((item) => Number(item.props.count)));
|
|
31
|
+
const bars = computed(() => Math.max(...counts.value));
|
|
32
|
+
/** Bars lit up to here; none while the option itself is highlighted. */
|
|
33
|
+
const lit = computed(() => props.active < 0 ? 0 : counts.value[props.active] ?? 0);
|
|
34
|
+
/** The choice a bar stands for: its count, or the fewest there can be. */
|
|
35
|
+
const indexOf = (bar) => {
|
|
36
|
+
const index = counts.value.indexOf(Math.max(bar, counts.value[0]));
|
|
37
|
+
return index < 0 ? 0 : index;
|
|
38
|
+
};
|
|
39
|
+
return (_ctx, _cache) => {
|
|
40
|
+
return openBlock(), createElementBlock("div", _hoisted_1, [(openBlock(true), createElementBlock(Fragment, null, renderList(bars.value, (bar) => {
|
|
41
|
+
return openBlock(), createElementBlock("div", {
|
|
42
|
+
id: bar >= counts.value[0] ? `${__props.idPrefix}-${indexOf(bar)}` : void 0,
|
|
43
|
+
key: bar,
|
|
44
|
+
role: bar >= counts.value[0] ? "option" : "presentation",
|
|
45
|
+
"aria-selected": bar >= counts.value[0] ? bar === lit.value : void 0,
|
|
46
|
+
"aria-label": bar >= counts.value[0] ? unref(labelOf)(__props.items[indexOf(bar)].label, __props.messages) : void 0,
|
|
47
|
+
class: normalizeClass(["dou-editor-column-picker__bar", { "is-lit": bar <= lit.value }]),
|
|
48
|
+
onPointermove: ($event) => emit("hover", indexOf(bar)),
|
|
49
|
+
onClick: ($event) => emit("choose", indexOf(bar))
|
|
50
|
+
}, null, 42, _hoisted_2);
|
|
51
|
+
}), 128))]);
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
export { column_picker_vue_vue_type_script_setup_true_lang_default as default };
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=column-picker.vue_vue_type_script_setup_true_lang.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"column-picker.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createElementBlock","_Fragment","_renderList","_unref","_normalizeClass"],"sources":["../../../src/extensions/columns/column-picker.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport {\n labelOf,\n type BlockOptionChoicesEmits,\n type BlockOptionChoicesProps,\n} from '../../core/extension'\n\n/**\n * The column count picker beside “Columns” in the slash menu: a row of\n * bars, as many as the most columns; pointing at one lights the bars up to\n * it, the count a click inserts.\n */\nconst props = defineProps<BlockOptionChoicesProps>()\nconst emit = defineEmits<BlockOptionChoicesEmits>()\n\nconst counts = computed(() => props.items.map((item) => Number(item.props.count)))\nconst bars = computed(() => Math.max(...counts.value))\n/** Bars lit up to here; none while the option itself is highlighted. */\nconst lit = computed(() => (props.active < 0 ? 0 : (counts.value[props.active] ?? 0)))\n\n/** The choice a bar stands for: its count, or the fewest there can be. */\nconst indexOf = (bar: number) => {\n const index = counts.value.indexOf(Math.max(bar, counts.value[0]!))\n return index < 0 ? 0 : index\n}\n</script>\n\n<template>\n <div class=\"dou-editor-column-picker\">\n <div\n v-for=\"bar in bars\"\n :id=\"bar >= counts[0]! ? `${idPrefix}-${indexOf(bar)}` : undefined\"\n :key=\"bar\"\n :role=\"bar >= counts[0]! ? 'option' : 'presentation'\"\n :aria-selected=\"bar >= counts[0]! ? bar === lit : undefined\"\n :aria-label=\"bar >= counts[0]! ? labelOf(items[indexOf(bar)]!.label, messages) : undefined\"\n :class=\"['dou-editor-column-picker__bar', { 'is-lit': bar <= lit }]\"\n @pointermove=\"emit('hover', indexOf(bar))\"\n @click=\"emit('choose', indexOf(bar))\"\n />\n </div>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;EAaA,MAAM,QAAQ;EACd,MAAM,OAAO;EAEb,MAAM,SAAS,eAAe,MAAM,MAAM,KAAK,SAAS,OAAO,KAAK,MAAM,KAAK,CAAC,CAAC;EACjF,MAAM,OAAO,eAAe,KAAK,IAAI,GAAG,OAAO,KAAK,CAAC;;EAErD,MAAM,MAAM,eAAgB,MAAM,SAAS,IAAI,IAAK,OAAO,MAAM,MAAM,WAAW,CAAG;;EAGrF,MAAM,WAAW,QAAgB;GAC/B,MAAM,QAAQ,OAAO,MAAM,QAAQ,KAAK,IAAI,KAAK,OAAO,MAAM,EAAG,CAAC;GAClE,OAAO,QAAQ,IAAI,IAAI;EACzB;;GAIE,OAAAA,UAAA,GAAAC,mBAYM,OAZN,YAYM,EAXJD,UAAA,IAAA,GAAAC,mBAUEC,UAAA,MAAAC,WATc,KAAA,QAAP,QAAG;IADZ,OAAAH,UAAA,GAAAC,mBAUE,OAAA;KARC,IAAI,OAAO,OAAA,MAAM,KAAA,GAAU,QAAA,SAAQ,GAAI,QAAQ,GAAG,MAAM,KAAA;KACxD,KAAK;KACL,MAAM,OAAO,OAAA,MAAM,KAAA,WAAA;KACnB,iBAAe,OAAO,OAAA,MAAM,KAAO,QAAQ,IAAA,QAAM,KAAA;KACjD,cAAY,OAAO,OAAA,MAAM,KAAOG,MAAA,OAAA,CAAO,CAAC,QAAA,MAAM,QAAQ,GAAG,EAAA,CAAI,OAAO,QAAA,QAAQ,IAAI,KAAA;KAChF,OAAKC,eAAA,CAAA,iCAAA,EAAA,UAAgD,OAAO,IAAA,MAAG,CAAA,CAAA;KAC/D,gBAAW,WAAE,KAAI,SAAU,QAAQ,GAAG,CAAA;KACtC,UAAK,WAAE,KAAI,UAAW,QAAQ,GAAG,CAAA"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import columns_controls_vue_vue_type_script_setup_true_lang_default from "./columns-controls.vue_vue_type_script_setup_true_lang.js";
|
|
2
|
+
// src/extensions/columns/columns-controls.vue
|
|
3
|
+
var columns_controls_default = columns_controls_vue_vue_type_script_setup_true_lang_default;
|
|
4
|
+
export { columns_controls_default as default };
|
|
5
|
+
|
|
6
|
+
//# sourceMappingURL=columns-controls.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"columns-controls.js","names":["_sfc_main"],"sources":["../../../src/extensions/columns/columns-controls.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { computed, nextTick, onBeforeUnmount, onMounted, shallowRef, watch } from 'vue'\nimport { findBlockById, layoutOf, parentBlock, blockAround } from '../../core/blocks'\nimport { childBlocks, COLUMNS_GROUP, sideBySide } from '../../dom'\nimport { useEditor } from '../../editor'\nimport { previewColumns, refreshColumns, type ColumnPreview } from './plugin'\nimport { widthOf } from './schema'\n\n/**\n * The bars between columns. One shows when the pointer is in the middle of\n * the gap between two columns (on a touch screen, after a tap there);\n * dragging it moves width from one column to the other, `Esc` takes the\n * drag back, a double click makes all the columns of the set even. While\n * the cursor is in a set of columns, its bars can also be reached with\n * `Tab` and moved with `←` `→`. A drag is shown as it goes and written to\n * the document when it ends: one undo step.\n */\nconst { view, state, root, messages, dragging } = useEditor()\n\n/** How far from the middle of the gap the bar can be grabbed, and on a touch screen tapped. */\nconst REACH = 5\nconst TOUCH_REACH = 20\n/** The narrowest a column gets by resizing. */\nconst MIN_WIDTH = 96\n/** How much of the two columns' width a key press moves. */\nconst STEP = 0.05\n\ninterface Bar {\n /** The set of columns, by id, and the column left of the bar. */\n row: string\n index: number\n top: number\n left: number\n height: number\n /** The left column's share of the two, in percent, for screen readers. */\n value: number\n}\n\n/** The bar under the pointer. */\nconst bar = shallowRef<Bar | null>(null)\n/** The bars of the set of columns the cursor is in, for the keyboard. */\nconst keyBars = shallowRef<Bar[]>([])\nconst active = shallowRef(false)\n\n/** The column blocks of a set: where each block is, and its width. */\nfunction columnsInDoc(row: string) {\n const current = view.value\n const info = current && findBlockById(current.state.doc, row)\n if (!info?.group || layoutOf(info.node) !== 'row') return null\n const list: { pos: number; width: number }[] = []\n let pos = info.contentPos + info.content.nodeSize + 1\n info.group.forEach((column) => {\n list.push({ pos, width: widthOf(column.firstChild!.attrs.width) ?? 1 })\n pos += column.nodeSize\n })\n return list\n}\n\nfunction findGroup(row: string) {\n const block = view.value?.dom.querySelector(`[data-block-id=\"${CSS.escape(row)}\"]`)\n return block?.querySelector<HTMLElement>(`:scope > ${COLUMNS_GROUP}`) ?? null\n}\n\n/** The middle of the gap after column `index`, on the screen. */\nconst middleOf = (columns: HTMLElement[], index: number) =>\n (columns[index]!.getBoundingClientRect().right +\n columns[index + 1]!.getBoundingClientRect().left) /\n 2\n\nfunction barAt(group: HTMLElement, index: number): Bar | null {\n const host = root.value\n const columns = childBlocks(group)\n const id = (group.parentElement as HTMLElement | null)?.dataset.blockId\n const weights = id && columnsInDoc(id)\n if (!host || !id || !weights || !columns[index + 1]) return null\n const box = host.getBoundingClientRect()\n const rect = group.getBoundingClientRect()\n const left = weights[index]!.width\n const right = weights[index + 1]!.width\n return {\n row: id,\n index,\n top: rect.top - box.top,\n left: middleOf(columns, index) - box.left,\n height: rect.height,\n value: Math.round((left / (left + right)) * 100),\n }\n}\n\n/** The bar near `x` in the set of columns `target` is in, if any. */\nfunction barNear(target: Element, x: number, reach: number): Bar | null {\n const group = target.closest<HTMLElement>(COLUMNS_GROUP)\n const columns = group ? childBlocks(group) : []\n if (!group || !sideBySide(columns)) return null\n for (let index = 0; index < columns.length - 1; index++)\n if (Math.abs(x - middleOf(columns, index)) <= reach) return barAt(group, index)\n return null\n}\n\nfunction track(event: PointerEvent) {\n if (event.pointerType === 'touch' || resize || dragging.value) return\n const target = event.target as Element\n if (target.closest('.dou-editor-columns__bar')) return\n bar.value = barNear(target, event.clientX, REACH)\n}\n\n/** A tap in the middle of a gap shows the bar there, to drag next. */\nfunction tap(event: PointerEvent) {\n if (event.pointerType === 'mouse' || resize) return\n const target = event.target as Element\n if (target.closest('.dou-editor-columns__bar')) return\n bar.value = barNear(target, event.clientX, TOUCH_REACH)\n}\n\nfunction leave(event: PointerEvent) {\n if (!resize && event.pointerType === 'mouse') bar.value = null\n}\n\n/** The bars of the set of columns around the cursor. */\nfunction placeKeyBars() {\n const current = state.value\n const block = current && blockAround(current.selection.$from)\n let row = block && parentBlock(current.doc, block)\n while (row && layoutOf(row.node) !== 'row') row = parentBlock(current!.doc, row)\n const group = row && findGroup(row.node.attrs.id as string)\n const columns = group ? childBlocks(group) : []\n if (!group || !sideBySide(columns)) {\n keyBars.value = []\n return\n }\n keyBars.value = columns\n .slice(1)\n .map((_, index) => barAt(group, index))\n .filter((entry): entry is Bar => !!entry)\n}\n\nwatch(state, () => void nextTick(placeKeyBars), { flush: 'post' })\n// the columns' names follow the locale\nwatch(messages, () => {\n const current = view.value\n if (current) current.dispatch(refreshColumns(current.state.tr))\n})\n\n/* dragging */\n\nlet resize: {\n pointer: number\n bar: Bar\n /** The two columns' widths together, in pixels, and the gap between them. */\n start: number\n span: number\n gap: number\n /** Their weights together, shared out again. */\n total: number\n /** Where the two columns are in the document. */\n columns: [number, number]\n weights: [number, number]\n} | null = null\n\n/** The two columns beside a bar: where they are, their weights and their size on the screen. */\nfunction pairOf(current: Bar) {\n const group = findGroup(current.row)\n const columns = group ? childBlocks(group) : []\n const weights = columnsInDoc(current.row)\n const left = columns[current.index]\n const right = columns[current.index + 1]\n const a = weights?.[current.index]\n const b = weights?.[current.index + 1]\n if (!group || !left || !right || !a || !b) return null\n const first = left.getBoundingClientRect()\n const second = right.getBoundingClientRect()\n return {\n group,\n start: first.left,\n span: first.width + second.width,\n gap: second.left - first.right,\n columns: [a.pos, b.pos] as [number, number],\n weights: [a.width, b.width] as [number, number],\n }\n}\n\n/** The left column's weight for a width in pixels, the narrowest kept. */\nfunction share(total: number, span: number, width: number): [number, number] {\n const min = Math.min(MIN_WIDTH, span / 2)\n const clamped = Math.min(span - min, Math.max(min, width))\n const left = Math.round((total * clamped * 1000) / span) / 1000\n return [left, Math.round((total - left) * 1000) / 1000]\n}\n\nfunction show(preview: ColumnPreview[] | null) {\n const current = view.value\n if (current) current.dispatch(previewColumns(current.state.tr, preview))\n}\n\n/** Write the two columns' widths: one undo step. */\nfunction commit(columns: [number, number], weights: [number, number]) {\n const current = view.value\n if (!current) return\n const tr = previewColumns(current.state.tr, null).setMeta('addToHistory', true)\n columns.forEach((pos, offset) => {\n const weight = weights[offset]!\n tr.setNodeAttribute(pos + 1, 'width', weight === 1 ? null : widthOf(weight))\n })\n current.dispatch(tr)\n}\n\nfunction onDown(event: PointerEvent, current: Bar) {\n if (event.button !== 0) return\n const pair = pairOf(current)\n if (!pair) return\n event.preventDefault()\n ;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)\n resize = {\n pointer: event.pointerId,\n bar: current,\n start: pair.start,\n span: pair.span,\n gap: pair.gap,\n total: pair.weights[0] + pair.weights[1],\n columns: pair.columns,\n weights: pair.weights,\n }\n active.value = true\n window.addEventListener('keydown', onEscape, true)\n}\n\nfunction onMove(event: PointerEvent) {\n if (!resize || event.pointerId !== resize.pointer) return\n const { start, span, gap, total, columns } = resize\n resize.weights = share(total, span, event.clientX - gap / 2 - start)\n show(columns.map((pos, offset) => ({ pos, width: resize!.weights[offset]! })))\n const group = findGroup(resize.bar.row)\n const moved = group && barAt(group, resize.bar.index)\n if (moved) bar.value = moved\n}\n\nfunction end() {\n resize = null\n active.value = false\n window.removeEventListener('keydown', onEscape, true)\n}\n\nfunction onUp(event: PointerEvent) {\n if (!resize || event.pointerId !== resize.pointer) return\n const { columns, weights } = resize\n end()\n commit(columns, weights)\n}\n\n/** `Esc` or a cancelled pointer: the widths as they were. */\nfunction cancel() {\n if (!resize) return\n end()\n show(null)\n const current = bar.value\n const group = current && findGroup(current.row)\n if (current && group) bar.value = barAt(group, current.index)\n}\n\nfunction onEscape(event: KeyboardEvent) {\n if (event.key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n cancel()\n}\n\n/** `←` `→` on a bar: move a little width from one column to the other; `Esc` or `Shift+Tab` back to the text. */\nfunction onKey(event: KeyboardEvent, current: Bar) {\n if (event.key === 'Escape' || (event.key === 'Tab' && event.shiftKey)) {\n event.preventDefault()\n view.value?.focus()\n return\n }\n const direction = { ArrowLeft: -1, ArrowRight: 1 }[event.key]\n if (!direction) return\n event.preventDefault()\n const pair = pairOf(current)\n if (!pair) return\n const total = pair.weights[0] + pair.weights[1]\n const width = (pair.weights[0] / total) * pair.span + direction * STEP * pair.span\n commit(pair.columns, share(total, pair.span, width))\n void nextTick(placeKeyBars)\n}\n\n/** A double click: every column of the set as wide as the others. */\nfunction even(current: Bar) {\n const columns = columnsInDoc(current.row)\n const instance = view.value\n if (!columns || !instance) return\n const tr = instance.state.tr\n for (const column of columns)\n if (column.width !== 1) tr.setNodeAttribute(column.pos + 1, 'width', null)\n if (tr.docChanged) instance.dispatch(tr)\n}\n\n/** The bars to draw: the keyboard's, and the pointer's when it is at another gap. */\nconst bars = computed(() => {\n const list = keyBars.value.map((entry) => ({ ...entry, key: true, shown: false }))\n const pointed = bar.value\n if (!pointed) return list\n const same = list.findIndex((entry) => entry.row === pointed.row && entry.index === pointed.index)\n if (same < 0) return [...list, { ...pointed, key: false, shown: true }]\n list[same] = { ...pointed, key: true, shown: true }\n return list\n})\n\nconst onScroll = () => {\n if (!resize) bar.value = null\n}\n\n// the editor narrower or wider (a window resized, a tablet turned): the bars move with the columns\nlet observer: ResizeObserver | undefined\n\nonMounted(() => {\n if (typeof ResizeObserver !== 'undefined' && root.value) {\n observer = new ResizeObserver(() => {\n if (!resize) bar.value = null\n placeKeyBars()\n })\n observer.observe(root.value)\n }\n root.value?.addEventListener('pointermove', track)\n root.value?.addEventListener('pointerdown', tap)\n root.value?.addEventListener('pointerleave', leave)\n window.addEventListener('scroll', onScroll, true)\n placeKeyBars()\n})\nonBeforeUnmount(() => {\n observer?.disconnect()\n root.value?.removeEventListener('pointermove', track)\n root.value?.removeEventListener('pointerdown', tap)\n root.value?.removeEventListener('pointerleave', leave)\n window.removeEventListener('scroll', onScroll, true)\n window.removeEventListener('keydown', onEscape, true)\n})\n</script>\n\n<template>\n <div\n v-for=\"entry in bars\"\n :key=\"`${entry.row}-${entry.index}`\"\n :class=\"[\n 'dou-editor-columns__bar',\n { 'is-key': entry.key, 'is-shown': entry.shown, 'is-active': active && entry.shown },\n ]\"\n role=\"separator\"\n aria-orientation=\"vertical\"\n :tabindex=\"entry.key ? 0 : -1\"\n :aria-label=\"messages.columns.resize\"\n :aria-valuenow=\"entry.value\"\n aria-valuemin=\"0\"\n aria-valuemax=\"100\"\n :title=\"messages.columns.resize\"\n :style=\"{ top: `${entry.top}px`, left: `${entry.left}px`, height: `${entry.height}px` }\"\n @mousedown.prevent\n @pointerdown=\"onDown($event, entry)\"\n @pointermove=\"onMove\"\n @pointerup=\"onUp\"\n @pointercancel=\"cancel\"\n @lostpointercapture=\"cancel\"\n @keydown=\"onKey($event, entry)\"\n @focus=\"placeKeyBars\"\n @dblclick=\"even(entry)\"\n />\n</template>\n"],"mappings":""}
|