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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/collaboration/binding.js +32 -10
  2. package/dist/collaboration/binding.js.map +1 -1
  3. package/dist/collaboration/index.js +3 -0
  4. package/dist/collaboration/index.js.map +1 -1
  5. package/dist/collaboration/merged-props.js +152 -0
  6. package/dist/collaboration/merged-props.js.map +1 -0
  7. package/dist/components/block-handle.js.map +1 -1
  8. package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js +55 -5
  9. package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
  10. package/dist/core/extension.js.map +1 -1
  11. package/dist/core/model.js +2 -1
  12. package/dist/core/model.js.map +1 -1
  13. package/dist/core/transaction.js +7 -1
  14. package/dist/core/transaction.js.map +1 -1
  15. package/dist/define-block.js +2 -1
  16. package/dist/define-block.js.map +1 -1
  17. package/dist/document.js +20 -1
  18. package/dist/document.js.map +1 -1
  19. package/dist/dom.js +12 -1
  20. package/dist/dom.js.map +1 -1
  21. package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
  22. package/dist/editor2.js.map +1 -1
  23. package/dist/flow/board-block.js +6 -0
  24. package/dist/flow/board-block.js.map +1 -0
  25. package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js +437 -0
  26. package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js.map +1 -0
  27. package/dist/flow/board.js +102 -0
  28. package/dist/flow/board.js.map +1 -0
  29. package/dist/flow/index.js +166 -0
  30. package/dist/flow/index.js.map +1 -0
  31. package/dist/locale.js +33 -6
  32. package/dist/locale.js.map +1 -1
  33. package/dist/style.css +1 -1
  34. package/dist/style.js +1 -0
  35. package/dist/types/collaboration/binding.d.ts +4 -0
  36. package/dist/types/collaboration/merged-props.d.ts +20 -0
  37. package/dist/types/core/extension.d.ts +5 -2
  38. package/dist/types/core/transaction.d.ts +6 -0
  39. package/dist/types/document.d.ts +3 -2
  40. package/dist/types/dom.d.ts +7 -0
  41. package/dist/types/editor.vue.d.ts +9 -0
  42. package/dist/types/flow/board-block.vue.d.ts +16 -0
  43. package/dist/types/flow/board.d.ts +38 -0
  44. package/dist/types/flow/index.d.ts +59 -0
  45. package/dist/types/index.d.ts +9 -0
  46. package/dist/types/locale.d.ts +10 -0
  47. package/package.json +14 -5
@@ -1 +1 @@
1
- {"version":3,"file":"block-handle.js","names":["_sfc_main"],"sources":["../../src/components/block-handle.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n CheckIcon,\n CopyIcon,\n GripVerticalIcon,\n PlusIcon,\n TrashIcon,\n} from '@dou-ui/icons'\nimport { DouDropdown, DouDropdownItem, DouDropdownSub } from 'dou-ui'\nimport { TextSelection } from 'prosemirror-state'\nimport { computed, inject, onBeforeUnmount, onMounted, shallowRef, watch } from 'vue'\nimport { isCurrent } from '../catalog'\nimport { labelOf, type BlockOption } from '../core/extension'\nimport {\n blockSelectionKey,\n blockSelectionRange,\n getBlockSelection,\n selectBlocks,\n} from '../core/block-selection'\nimport {\n blockAround,\n blocksIn,\n findBlockById,\n siblingRangeBetween,\n type SiblingRange,\n} from '../core/blocks'\nimport {\n duplicateBlocks,\n insertBlockAfter,\n swapBlocks,\n moveRangeTo,\n moveRangeToNewColumn,\n deleteBlocks,\n setBlockType,\n} from '../core/commands'\nimport { blockFromNode } from '../core/model'\nimport { slashKey } from '../core/slash'\nimport {\n blockElementOf,\n childBlocks,\n COLUMN_GROUP,\n contentAt,\n contentSpan,\n firstLine,\n handleLeft,\n scrollParent,\n sideBySide,\n} from '../dom'\nimport { editorKey } from '../editor'\nimport { useMenuEscape } from './menu-escape'\n\nconst { view, state, focused, messages, root, dragging, kit } = inject(editorKey)!\n\n/**\n * Touch screens have no hover: there the handle shows only the grip, next\n * to the block with the cursor (or the selected blocks) while the editor\n * has focus. A tap on it opens the menu, a press and drag moves the block.\n */\nconst touch = shallowRef(false)\nlet media: MediaQueryList | null = null\nconst onMedia = () => (touch.value = !!media?.matches)\n\n/** The block the handle is next to, by id. */\nconst hovered = shallowRef<string | null>(null)\nconst position = shallowRef<{ top: number; left: number; height: number } | null>(null)\n/** In a column the handle is only the grip, in the gap before it, leaving room for the resize bar. */\nconst compact = shallowRef(false)\nconst menuOpen = shallowRef(false)\nuseMenuEscape(menuOpen, () => (menuOpen.value = false))\n\n/**\n * Where a drag would drop: before or after a block (a line across), or\n * beside a column, into a new column (a line down, `column` set).\n */\ninterface Drop {\n pos: number\n top: number\n left: number\n width: number\n height?: number\n column?: { row: string; index: number }\n}\nconst drop = shallowRef<Drop | null>(null)\n// typing hides the handle until the pointer moves again\nconst resting = shallowRef(false)\n\nconst visible = computed(() => {\n if (!position.value) return false\n if (menuOpen.value || dragging.value) return true\n if (touch.value) return focused.value || (!!state.value && !!getBlockSelection(state.value))\n return !resting.value\n})\n\nfunction place(content: HTMLElement) {\n const block = blockElementOf(content)\n const id = block?.dataset.blockId\n const host = root.value\n if (!id || !host) return\n const box = host.getBoundingClientRect()\n const line = firstLine(content)\n hovered.value = id\n compact.value = !!content.closest(COLUMN_GROUP)\n position.value = {\n top: line.top - box.top,\n left: handleLeft(content) - box.left,\n height: line.height,\n }\n}\n\nlet frame = 0\nlet lastY = 0\nlet lastX = 0\n\nfunction track(event: PointerEvent) {\n // a finger only moves the handle by moving the cursor; a drag reports itself\n if (event.pointerType === 'touch') return\n lastY = event.clientY\n lastX = event.clientX\n resting.value = false\n if (menuOpen.value || frame) return\n frame = requestAnimationFrame(() => {\n frame = 0\n if (dragging.value) return updateDrop()\n const current = view.value\n if (!current || menuOpen.value) return\n const content = contentAt(current, lastY, lastX)\n if (content) place(content)\n })\n}\n\n/** A wide table scrolled sideways: the handle next to it follows its left edge. */\nfunction onScroll(event: Event) {\n const content = event.target\n if (\n !(content instanceof HTMLElement) ||\n !content.classList.contains('dou-editor__content--table')\n )\n return\n if (position.value && hovered.value && blockElementOf(content)?.dataset.blockId === hovered.value)\n place(content)\n}\n\nfunction leave(event: PointerEvent) {\n if (menuOpen.value || dragging.value || event.pointerType === 'touch') return\n position.value = null\n hovered.value = null\n}\n\n/** On touch screens: put the handle next to the block with the cursor. */\nfunction follow() {\n const current = view.value\n if (!current || dragging.value) return\n const selected = blockSelectionRange(current.state)\n const info = selected ? blocksIn(selected)[0] : blockAround(current.state.selection.$from)\n const element = info\n ? (current.nodeDOM(info.pos) as HTMLElement | null)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__content',\n )\n : null\n if (element) place(element)\n else {\n position.value = null\n hovered.value = null\n }\n}\n\nlet followFrame = 0\nfunction scheduleFollow() {\n if (!touch.value || followFrame) return\n followFrame = requestAnimationFrame(() => {\n followFrame = 0\n if (touch.value && !menuOpen.value) follow()\n })\n}\n\nwatch([state, focused, touch], scheduleFollow)\n\nonMounted(() => {\n media = window.matchMedia('(pointer: coarse)')\n onMedia()\n media.addEventListener('change', onMedia)\n window.addEventListener('resize', scheduleFollow)\n root.value?.addEventListener('pointermove', track)\n root.value?.addEventListener('pointerleave', leave)\n root.value?.addEventListener('scroll', onScroll, true)\n})\nonBeforeUnmount(() => {\n media?.removeEventListener('change', onMedia)\n window.removeEventListener('resize', scheduleFollow)\n if (followFrame) cancelAnimationFrame(followFrame)\n root.value?.removeEventListener('pointermove', track)\n root.value?.removeEventListener('pointerleave', leave)\n root.value?.removeEventListener('scroll', onScroll, true)\n if (frame) cancelAnimationFrame(frame)\n stopDrag()\n})\n\n// follow edits: keep the handle on its block, or hide it while typing\nwatch(state, (next, previous) => {\n if (touch.value || !next || !previous || next.doc === previous.doc || dragging.value) return\n if (!menuOpen.value) resting.value = true\n requestAnimationFrame(() => {\n const current = view.value\n if (!current || !hovered.value) return\n const element = current.dom.querySelector<HTMLElement>(\n `[data-block-id=\"${CSS.escape(hovered.value)}\"] > .dou-editor__content`,\n )\n if (element) place(element)\n else position.value = null\n })\n})\n\nconst target = computed(() => {\n const doc = state.value?.doc\n return doc && hovered.value ? findBlockById(doc, hovered.value) : null\n})\n\n/** The hovered block, or every selected block when it is one of them. */\nfunction rangeForHovered(): SiblingRange | null {\n const current = view.value\n const info = target.value\n if (!current || !info) return null\n const selected = blockSelectionRange(current.state)\n if (selected && info.pos >= selected.start && info.pos < selected.end) return selected\n return siblingRangeBetween(current.state.doc, info.pos + 1, info.pos + 1)\n}\n\n/** Select the blocks the menu or a drag acts on. */\nfunction selectTarget(): SiblingRange | null {\n const current = view.value\n const range = rangeForHovered()\n if (!current || !range) return null\n const blocks = blocksIn(range)\n selectBlocks(blocks[0]!.node.attrs.id, blocks.at(-1)!.node.attrs.id)(\n current.state,\n current.dispatch,\n )\n return blockSelectionRange(current.state)\n}\n\n/* the + button */\n\nfunction add(event: MouseEvent) {\n const current = view.value\n const info = target.value\n if (!current || !info) return\n const empty = info.content.isTextblock && info.content.content.size === 0\n if (!empty || info.content.type.name !== 'paragraph') {\n insertBlockAfter(info.pos)(current.state, current.dispatch)\n // Alt+click adds the block above instead\n if (event.altKey) swapBlocks(-1)(current.state, current.dispatch)\n } else {\n const tr = current.state.tr.setSelection(\n TextSelection.create(current.state.doc, info.contentPos + 1),\n )\n current.dispatch(tr)\n }\n const from = current.state.selection.from\n current.dispatch(current.state.tr.insertText('/').setMeta(slashKey, { from, query: '' }))\n current.focus()\n}\n\n/* the block menu */\n\nconst turnOptions = kit.blockOptions.filter(\n (option) => !!kit.schema.nodes[option.type]?.isTextblock,\n)\nconst current = computed(() => {\n const info = target.value\n return info ? blockFromNode(info.node) : null\n})\n\nfunction after(action: () => void) {\n action()\n // the menu gives focus back to the handle; the editor takes it after\n requestAnimationFrame(() => view.value?.focus())\n}\n\nfunction keep(run: (current: NonNullable<typeof view.value>) => void) {\n after(() => {\n const instance = view.value\n if (!instance) return\n const selection = getBlockSelection(instance.state)\n run(instance)\n if (selection) selectBlocks(selection.anchor, selection.head)(instance.state, instance.dispatch)\n })\n}\n\nconst turnInto = (option: BlockOption) =>\n keep((instance) => setBlockType(option.type, option.props)(instance.state, instance.dispatch))\nconst duplicate = () => keep((instance) => duplicateBlocks(instance.state, instance.dispatch))\nconst move = (direction: -1 | 1) =>\n keep((instance) => swapBlocks(direction)(instance.state, instance.dispatch))\n\nfunction remove() {\n after(() => {\n const instance = view.value\n const range = instance && blockSelectionRange(instance.state)\n if (!instance || !range) return\n const tr = deleteBlocks(instance.state.tr, blocksIn(range)).setMeta(blockSelectionKey, null)\n instance.dispatch(tr.scrollIntoView())\n position.value = null\n })\n}\n\nconst canMove = (direction: -1 | 1) => {\n const instance = view.value\n return !!instance && !!state.value && swapBlocks(direction)(instance.state)\n}\n\n/* dragging */\n\nlet start: { x: number; y: number; pointer: number; touch: boolean } | null = null\nlet range: SiblingRange | null = null\nlet scroller: HTMLElement | null = null\nlet scrollFrame = 0\n/** A copy of the dragged blocks that follows the pointer. */\nlet ghost: HTMLElement | null = null\n\nfunction showGhost(moving: SiblingRange) {\n const instance = view.value\n const host = root.value\n if (!instance || !host) return\n ghost = document.createElement('div')\n ghost.className = 'dou-editor__surface dou-editor__ghost'\n ghost.setAttribute('aria-hidden', 'true')\n let width = 0\n for (const block of blocksIn(moving)) {\n const element = instance.nodeDOM(block.pos) as HTMLElement | null\n if (!element) continue\n width = Math.max(width, element.getBoundingClientRect().width)\n const copy = element.cloneNode(true) as HTMLElement\n copy.classList.remove('is-selected')\n for (const node of [copy, ...copy.querySelectorAll('[id], .is-selected')]) {\n node.removeAttribute('id')\n node.classList.remove('is-selected')\n }\n ghost.append(copy)\n }\n ghost.style.width = `${Math.min(width, 360)}px`\n host.append(ghost)\n moveGhost()\n}\n\nfunction moveGhost() {\n if (!ghost) return\n // above a finger, which would hide it; below and right of a mouse pointer\n const y = start?.touch ? lastY - ghost.offsetHeight - 24 : lastY + 12\n ghost.style.transform = `translate(${lastX + 12}px, ${y}px)`\n}\n\nfunction onGripDown(event: PointerEvent) {\n if (event.button !== 0) return\n start = {\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n touch: event.pointerType === 'touch',\n }\n ;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)\n}\n\nfunction onGripMove(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n lastX = event.clientX\n lastY = event.clientY\n if (!dragging.value) {\n // a finger wobbles more than a mouse while tapping\n const slop = start.touch ? 8 : 4\n if (Math.hypot(event.clientX - start.x, event.clientY - start.y) < slop) return\n range = selectTarget()\n if (!range) return stopDrag()\n dragging.value = true\n scroller = root.value && scrollParent(root.value)\n window.addEventListener('keydown', onDragKey, true)\n showGhost(range)\n autoScroll()\n }\n moveGhost()\n updateDrop()\n}\n\nfunction onGripUp(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n if (dragging.value) finishDrag()\n else if (menuOpen.value) menuOpen.value = false\n else {\n selectTarget()\n menuOpen.value = true\n }\n start = null\n}\n\nfunction onDragKey(event: KeyboardEvent) {\n if (event.key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n stopDrag()\n}\n\n/** Beside a column, past its edge: a new column there, when the set takes one more. */\n/** How far into the last column a drop still makes a new column after it. */\nconst LAST_COLUMN_EDGE = 16\n\nfunction columnDrop(content: HTMLElement, moving: SiblingRange, box: DOMRect): Drop | null {\n const instance = view.value\n const group = content.closest<HTMLElement>(COLUMN_GROUP)\n const column = group?.parentElement\n const rowGroup = column?.parentElement\n const rowId = rowGroup?.parentElement?.dataset.blockId\n if (!instance || !column || !rowGroup || !rowId) return null\n const columns = childBlocks(rowGroup)\n const index = columns.indexOf(column)\n if (index < 0 || !sideBySide(columns)) return null\n const rect = column.getBoundingClientRect()\n // right of the last column there may be no room (the editor's edge): its last strip counts\n const right = index === columns.length - 1 ? rect.right - LAST_COLUMN_EDGE : rect.right\n const at = lastX < rect.left ? index : lastX > right ? index + 1 : -1\n if (at < 0) return null\n const row = findBlockById(instance.state.doc, rowId)\n if (!row || !moveRangeToNewColumn(moving, row.pos, at)(instance.state)) return null\n const gap =\n columns.length > 1\n ? columns[1]!.getBoundingClientRect().left - columns[0]!.getBoundingClientRect().right\n : 0\n const x =\n at === 0\n ? columns[0]!.getBoundingClientRect().left - gap / 2\n : at === columns.length\n ? columns.at(-1)!.getBoundingClientRect().right - 1\n : (columns[at - 1]!.getBoundingClientRect().right +\n columns[at]!.getBoundingClientRect().left) /\n 2\n const rowRect = rowGroup.getBoundingClientRect()\n return {\n pos: row.pos,\n top: rowRect.top - box.top,\n left: x - box.left,\n width: 0,\n height: rowRect.height,\n column: { row: rowId, index: at },\n }\n}\n\nfunction updateDrop() {\n const instance = view.value\n const host = root.value\n if (!instance || !host || !range) return\n const content = contentAt(instance, lastY, lastX)\n const id = content && blockElementOf(content)?.dataset.blockId\n const info = id ? findBlockById(instance.state.doc, id) : null\n if (!content || !info) return (drop.value = null)\n const box = host.getBoundingClientRect()\n const beside = columnDrop(content, range, box)\n if (beside) return (drop.value = beside)\n const rect = content.getBoundingClientRect()\n const span = contentSpan(content)\n const below = lastY > rect.top + rect.height / 2\n let pos: number\n let y: number\n let left = span.left\n if (!below) {\n pos = info.pos\n y = rect.top\n } else if (info.group) {\n // the lower half of a block with children: in front of its first child\n pos = info.contentPos + info.content.nodeSize + 1\n y = rect.bottom\n const child = blockElementOf(content)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__group > .dou-editor__block > .dou-editor__content',\n )\n left = child ? contentSpan(child).left : span.left\n } else {\n pos = info.pos + info.node.nodeSize\n y = blockElementOf(content)!.getBoundingClientRect().bottom\n }\n if (!moveRangeTo(range, pos)(instance.state)) return (drop.value = null)\n // to the end of the text column, which a reading width can end before the editor\n drop.value = { pos, top: y - box.top, left: left - box.left, width: span.right - left }\n}\n\nfunction autoScroll() {\n scrollFrame = requestAnimationFrame(() => {\n if (!dragging.value) return\n const edge = 48\n const top = scroller ? scroller.getBoundingClientRect().top : 0\n const bottom = scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight\n let speed = 0\n if (lastY < top + edge) speed = -Math.ceil(((top + edge - lastY) / edge) * 16)\n else if (lastY > bottom - edge) speed = Math.ceil(((lastY - bottom + edge) / edge) * 16)\n if (speed) {\n if (scroller) scroller.scrollTop += speed\n else window.scrollBy(0, speed)\n updateDrop()\n }\n autoScroll()\n })\n}\n\nfunction finishDrag() {\n const instance = view.value\n const spot = drop.value\n const moving = range\n stopDrag()\n if (!instance || !spot || !moving) return\n const ids = blocksIn(moving).map((block) => block.node.attrs.id as string)\n const row = spot.column && findBlockById(instance.state.doc, spot.column.row)\n const command = spot.column\n ? row && moveRangeToNewColumn(moving, row.pos, spot.column.index)\n : moveRangeTo(moving, spot.pos)\n if (!command || !command(instance.state, instance.dispatch)) return\n selectBlocks(ids[0]!, ids.at(-1)!)(instance.state, instance.dispatch)\n instance.focus()\n}\n\nfunction stopDrag() {\n dragging.value = false\n drop.value = null\n range = null\n start = null\n ghost?.remove()\n ghost = null\n if (scrollFrame) cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n window.removeEventListener('keydown', onDragKey, true)\n}\n\nwatch(menuOpen, (value) => {\n if (value) return\n if (touch.value) scheduleFollow()\n else if (!root.value?.matches(':hover')) position.value = null\n})\n</script>\n\n<template>\n <div\n v-show=\"visible\"\n :class=\"['dou-editor__handle', { 'is-compact': compact }]\"\n :style=\"\n position\n ? {\n top: `${position.top}px`,\n left: `${position.left}px`,\n '--dou-editor-line': `${position.height}px`,\n }\n : undefined\n \"\n @mousedown.prevent\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__add\"\n :aria-label=\"messages.addBlock\"\n :title=\"messages.addBlock\"\n @click=\"add\"\n >\n <PlusIcon />\n </button>\n <DouDropdown\n v-model:open=\"menuOpen\"\n trigger=\"manual\"\n placement=\"bottom-start\"\n class=\"dou-editor-menu\"\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__grip\"\n :aria-label=\"messages.dragHandle\"\n :title=\"messages.dragHandle\"\n @pointerdown=\"onGripDown\"\n @pointermove=\"onGripMove\"\n @pointerup=\"onGripUp\"\n @pointercancel=\"stopDrag\"\n >\n <GripVerticalIcon />\n </button>\n <template #menu>\n <DouDropdownSub :title=\"messages.turnInto\">\n <DouDropdownItem\n v-for=\"option in turnOptions\"\n :key=\"option.key\"\n @click=\"turnInto(option)\"\n >\n <template #prefix><component :is=\"option.icon\" /></template>\n {{ labelOf(option.label, messages) }}\n <template v-if=\"current && isCurrent(option, current.type, current.props)\" #suffix>\n <CheckIcon />\n </template>\n </DouDropdownItem>\n </DouDropdownSub>\n <template v-if=\"current\">\n <component\n :is=\"entry\"\n v-for=\"(entry, index) in kit.blockMenu\"\n :key=\"index\"\n :block=\"current\"\n />\n </template>\n <DouDropdownItem :shortcut=\"touch ? undefined : 'mod+d'\" @click=\"duplicate\">\n <template #prefix><CopyIcon /></template>\n {{ messages.duplicate }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(-1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+up'\"\n @click=\"move(-1)\"\n >\n <template #prefix><ArrowUpIcon /></template>\n {{ messages.moveUp }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+down'\"\n @click=\"move(1)\"\n >\n <template #prefix><ArrowDownIcon /></template>\n {{ messages.moveDown }}\n </DouDropdownItem>\n <DouDropdownItem\n divided\n tone=\"danger\"\n :shortcut=\"touch ? undefined : 'delete'\"\n @click=\"remove\"\n >\n <template #prefix><TrashIcon /></template>\n {{ messages.delete }}\n </DouDropdownItem>\n </template>\n </DouDropdown>\n </div>\n <div\n v-if=\"drop\"\n :class=\"['dou-editor__drop', { 'is-vertical': drop.column }]\"\n :style=\"\n drop.column\n ? { top: `${drop.top}px`, left: `${drop.left}px`, height: `${drop.height}px` }\n : { top: `${drop.top}px`, left: `${drop.left}px`, width: `${drop.width}px` }\n \"\n />\n</template>\n"],"mappings":""}
1
+ {"version":3,"file":"block-handle.js","names":["_sfc_main"],"sources":["../../src/components/block-handle.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n CheckIcon,\n CopyIcon,\n GripVerticalIcon,\n PlusIcon,\n TrashIcon,\n} from '@dou-ui/icons'\nimport { DouDropdown, DouDropdownItem, DouDropdownSub } from 'dou-ui'\nimport { TextSelection } from 'prosemirror-state'\nimport {\n computed,\n inject,\n onBeforeUnmount,\n onMounted,\n shallowRef,\n useTemplateRef,\n watch,\n} from 'vue'\nimport { isCurrent } from '../catalog'\nimport { labelOf, type BlockOption } from '../core/extension'\nimport {\n blockSelectionKey,\n blockSelectionRange,\n getBlockSelection,\n selectBlocks,\n} from '../core/block-selection'\nimport {\n blockAround,\n blocksIn,\n findBlockById,\n siblingRangeBetween,\n type SiblingRange,\n} from '../core/blocks'\nimport {\n duplicateBlocks,\n insertBlockAfter,\n swapBlocks,\n moveRangeTo,\n moveRangeToNewColumn,\n deleteBlocks,\n setBlockType,\n} from '../core/commands'\nimport { blockFromNode } from '../core/model'\nimport { slashKey } from '../core/slash'\nimport {\n blockElementOf,\n bubbleShift,\n childBlocks,\n COLUMN_GROUP,\n contentAt,\n contentSpan,\n firstLine,\n handleLeft,\n scrollParent,\n sideBySide,\n} from '../dom'\nimport { editorKey } from '../editor'\nimport { useMenuEscape } from './menu-escape'\n\nconst { view, state, focused, messages, root, dragging, kit } = inject(editorKey)!\n\n/**\n * Touch screens have no hover: there the handle shows only the grip, next\n * to the block with the cursor (or the selected blocks) while the editor\n * has focus. A tap on it opens the menu, a press and drag moves the block.\n */\nconst touch = shallowRef(false)\nlet media: MediaQueryList | null = null\n/** A mouse: \"+\" comes out of the bubble while the pointer is on it. */\nlet fine: MediaQueryList | null = null\nconst onMedia = () => (touch.value = !!media?.matches)\n\n/** The block the handle is next to, by id. */\nconst hovered = shallowRef<string | null>(null)\nconst position = shallowRef<{ top: number; left: number; height: number } | null>(null)\n/** In a column the handle is only the grip, in the gap before it, leaving room for the resize bar. */\nconst compact = shallowRef(false)\n/** Next to a table: further out, clear of its row handles. */\nconst table = shallowRef(false)\nconst menuOpen = shallowRef(false)\nuseMenuEscape(menuOpen, () => {\n menuOpen.value = false\n // the menu had the focus; the selected blocks still answer Delete and copy\n requestAnimationFrame(() => view.value?.focus())\n})\n\n/**\n * Where a drag would drop: before or after a block (a line across), or\n * beside a column, into a new column (a line down, `column` set).\n */\ninterface Drop {\n pos: number\n top: number\n left: number\n width: number\n height?: number\n column?: { row: string; index: number }\n}\nconst drop = shallowRef<Drop | null>(null)\n// typing hides the handle until the pointer moves again\nconst resting = shallowRef(false)\n\nconst visible = computed(() => {\n if (!position.value) return false\n if (menuOpen.value || dragging.value) return true\n if (touch.value) return focused.value || (!!state.value && !!getBlockSelection(state.value))\n return !resting.value\n})\n\nfunction place(content: HTMLElement) {\n const block = blockElementOf(content)\n const id = block?.dataset.blockId\n const host = root.value\n if (!id || !host) return\n const box = host.getBoundingClientRect()\n const line = firstLine(content)\n hovered.value = id\n compact.value = !!content.closest(COLUMN_GROUP)\n table.value = content.classList.contains('dou-editor__content--table')\n position.value = {\n top: line.top - box.top,\n left: handleLeft(content) - box.left,\n height: line.height,\n }\n}\n\nlet frame = 0\nlet lastY = 0\nlet lastX = 0\n\nfunction track(event: PointerEvent) {\n // a finger only moves the handle by moving the cursor; a drag reports itself\n if (event.pointerType === 'touch') return\n lastY = event.clientY\n lastX = event.clientX\n resting.value = false\n if (menuOpen.value || frame) return\n frame = requestAnimationFrame(() => {\n frame = 0\n if (dragging.value) return updateDrop()\n const current = view.value\n if (!current || menuOpen.value) return\n const content = contentAt(current, lastY, lastX)\n if (content) place(content)\n })\n}\n\n/** A wide table scrolled sideways: the handle next to it follows its left edge. */\nfunction onScroll(event: Event) {\n const content = event.target\n if (\n !(content instanceof HTMLElement) ||\n !content.classList.contains('dou-editor__content--table')\n )\n return\n if (position.value && hovered.value && blockElementOf(content)?.dataset.blockId === hovered.value)\n place(content)\n}\n\nfunction leave(event: PointerEvent) {\n if (menuOpen.value || dragging.value || event.pointerType === 'touch') return\n position.value = null\n hovered.value = null\n}\n\n/** On touch screens: put the handle next to the block with the cursor. */\nfunction follow() {\n const current = view.value\n if (!current || dragging.value) return\n const selected = blockSelectionRange(current.state)\n const info = selected ? blocksIn(selected)[0] : blockAround(current.state.selection.$from)\n const element = info\n ? (current.nodeDOM(info.pos) as HTMLElement | null)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__content',\n )\n : null\n if (element) place(element)\n else {\n position.value = null\n hovered.value = null\n }\n}\n\nlet followFrame = 0\nfunction scheduleFollow() {\n if (!touch.value || followFrame) return\n followFrame = requestAnimationFrame(() => {\n followFrame = 0\n if (touch.value && !menuOpen.value) follow()\n })\n}\n\nwatch([state, focused, touch], scheduleFollow)\n\nonMounted(() => {\n media = window.matchMedia('(pointer: coarse)')\n fine = window.matchMedia('(hover: hover) and (pointer: fine)')\n onMedia()\n media.addEventListener('change', onMedia)\n window.addEventListener('resize', scheduleFollow)\n root.value?.addEventListener('pointermove', track)\n root.value?.addEventListener('pointerleave', leave)\n root.value?.addEventListener('scroll', onScroll, true)\n})\nonBeforeUnmount(() => {\n media?.removeEventListener('change', onMedia)\n window.removeEventListener('resize', scheduleFollow)\n if (followFrame) cancelAnimationFrame(followFrame)\n root.value?.removeEventListener('pointermove', track)\n root.value?.removeEventListener('pointerleave', leave)\n root.value?.removeEventListener('scroll', onScroll, true)\n if (frame) cancelAnimationFrame(frame)\n stopDrag()\n})\n\n// follow edits: keep the handle on its block, or hide it while typing\nwatch(state, (next, previous) => {\n if (touch.value || !next || !previous || next.doc === previous.doc || dragging.value) return\n if (!menuOpen.value) resting.value = true\n requestAnimationFrame(() => {\n const current = view.value\n if (!current || !hovered.value) return\n const element = current.dom.querySelector<HTMLElement>(\n `[data-block-id=\"${CSS.escape(hovered.value)}\"] > .dou-editor__content`,\n )\n if (element) place(element)\n else position.value = null\n })\n})\n\n/*\n * The bubble floats outside the text. When the editor's container cuts off\n * the room there (it clips, or the screen ends), the bubble moves in by as\n * much as it lacks, counting the \"+\" that comes out on hover, so the grip\n * stays under the pointer when it does, and a finger's reach on touch screens.\n */\nconst handle = useTemplateRef<HTMLElement>('handle')\n/** The width \"+\" adds to the bubble (its button, see the styles). */\nconst ADD_WIDTH = 20\n/** How far a finger's reach goes left of the bubble (the grip's ::before, past the bubble's border and padding). */\nconst TOUCH_REACH = 12\nconst shift = shallowRef(0)\n\nfunction clipLeft(from: HTMLElement): number {\n for (let node = from.parentElement; node; node = node.parentElement) {\n if (getComputedStyle(node).overflowX !== 'visible') return node.getBoundingClientRect().left\n }\n return 0\n}\n\nfunction fit() {\n const element = handle.value\n const host = root.value\n if (!element || !host || !visible.value) return\n let left = element.getBoundingClientRect().left - shift.value\n const plus = element.querySelector<HTMLElement>('.dou-editor__add')\n if (fine?.matches && !compact.value && plus && !plus.offsetWidth) left -= ADD_WIDTH\n const style = getComputedStyle(element)\n const clear =\n table.value && position.value\n ? host.getBoundingClientRect().left +\n position.value.left +\n Number.parseFloat(style.getPropertyValue('--dou-editor-handle-offset')) -\n 1\n : undefined\n const edge = clipLeft(host)\n /*\n * A finger's reach moves the bubble in too, but only as far as plain text\n * lets it: next to a table, a cut-off reach stays cut off rather than\n * pushing the bubble onto the row handles or past them.\n */\n const next = Math.max(\n bubbleShift(left, edge, clear),\n touch.value && !table.value ? bubbleShift(left - TOUCH_REACH, edge) : 0,\n )\n if (next !== shift.value) shift.value = next\n}\n\nwatch([position, visible, compact, table], fit, { flush: 'post' })\nlet sizes: ResizeObserver | null = null\nonMounted(() => {\n sizes = new ResizeObserver(fit)\n if (handle.value) sizes.observe(handle.value)\n})\nonBeforeUnmount(() => sizes?.disconnect())\n\nconst target = computed(() => {\n const doc = state.value?.doc\n return doc && hovered.value ? findBlockById(doc, hovered.value) : null\n})\n\n/** The hovered block, or every selected block when it is one of them. */\nfunction rangeForHovered(): SiblingRange | null {\n const current = view.value\n const info = target.value\n if (!current || !info) return null\n const selected = blockSelectionRange(current.state)\n if (selected && info.pos >= selected.start && info.pos < selected.end) return selected\n return siblingRangeBetween(current.state.doc, info.pos + 1, info.pos + 1)\n}\n\n/** Select the blocks the menu or a drag acts on. */\nfunction selectTarget(): SiblingRange | null {\n const current = view.value\n const range = rangeForHovered()\n if (!current || !range) return null\n const blocks = blocksIn(range)\n selectBlocks(blocks[0]!.node.attrs.id, blocks.at(-1)!.node.attrs.id)(\n current.state,\n current.dispatch,\n )\n return blockSelectionRange(current.state)\n}\n\n/* the + button */\n\nfunction add(event: MouseEvent) {\n const current = view.value\n const info = target.value\n if (!current || !info) return\n const empty = info.content.isTextblock && info.content.content.size === 0\n if (!empty || info.content.type.name !== 'paragraph') {\n insertBlockAfter(info.pos)(current.state, current.dispatch)\n // Alt+click adds the block above instead\n if (event.altKey) swapBlocks(-1)(current.state, current.dispatch)\n } else {\n const tr = current.state.tr.setSelection(\n TextSelection.create(current.state.doc, info.contentPos + 1),\n )\n current.dispatch(tr)\n }\n const from = current.state.selection.from\n current.dispatch(current.state.tr.insertText('/').setMeta(slashKey, { from, query: '' }))\n current.focus()\n}\n\n/* the block menu */\n\nconst turnOptions = kit.blockOptions.filter(\n (option) => !!kit.schema.nodes[option.type]?.isTextblock,\n)\nconst current = computed(() => {\n const info = target.value\n return info ? blockFromNode(info.node) : null\n})\n\nfunction after(action: () => void) {\n action()\n // the menu gives focus back to the handle; the editor takes it after\n requestAnimationFrame(() => view.value?.focus())\n}\n\nfunction keep(run: (current: NonNullable<typeof view.value>) => void) {\n after(() => {\n const instance = view.value\n if (!instance) return\n const selection = getBlockSelection(instance.state)\n run(instance)\n if (selection) selectBlocks(selection.anchor, selection.head)(instance.state, instance.dispatch)\n })\n}\n\nconst turnInto = (option: BlockOption) =>\n keep((instance) => setBlockType(option.type, option.props)(instance.state, instance.dispatch))\nconst duplicate = () => keep((instance) => duplicateBlocks(instance.state, instance.dispatch))\nconst move = (direction: -1 | 1) =>\n keep((instance) => swapBlocks(direction)(instance.state, instance.dispatch))\n\nfunction remove() {\n after(() => {\n const instance = view.value\n const range = instance && blockSelectionRange(instance.state)\n if (!instance || !range) return\n const tr = deleteBlocks(instance.state.tr, blocksIn(range)).setMeta(blockSelectionKey, null)\n instance.dispatch(tr.scrollIntoView())\n position.value = null\n })\n}\n\nconst canMove = (direction: -1 | 1) => {\n const instance = view.value\n return !!instance && !!state.value && swapBlocks(direction)(instance.state)\n}\n\n/* dragging */\n\nlet start: { x: number; y: number; pointer: number; touch: boolean } | null = null\nlet range: SiblingRange | null = null\nlet scroller: HTMLElement | null = null\nlet scrollFrame = 0\n/** A copy of the dragged blocks that follows the pointer. */\nlet ghost: HTMLElement | null = null\n\nfunction showGhost(moving: SiblingRange) {\n const instance = view.value\n const host = root.value\n if (!instance || !host) return\n ghost = document.createElement('div')\n ghost.className = 'dou-editor__surface dou-editor__ghost'\n ghost.setAttribute('aria-hidden', 'true')\n let width = 0\n for (const block of blocksIn(moving)) {\n const element = instance.nodeDOM(block.pos) as HTMLElement | null\n if (!element) continue\n width = Math.max(width, element.getBoundingClientRect().width)\n const copy = element.cloneNode(true) as HTMLElement\n copy.classList.remove('is-selected')\n for (const node of [copy, ...copy.querySelectorAll('[id], .is-selected')]) {\n node.removeAttribute('id')\n node.classList.remove('is-selected')\n }\n ghost.append(copy)\n }\n ghost.style.width = `${Math.min(width, 360)}px`\n host.append(ghost)\n moveGhost()\n}\n\nfunction moveGhost() {\n if (!ghost) return\n // above a finger, which would hide it; below and right of a mouse pointer\n const y = start?.touch ? lastY - ghost.offsetHeight - 24 : lastY + 12\n ghost.style.transform = `translate(${lastX + 12}px, ${y}px)`\n}\n\nfunction onGripDown(event: PointerEvent) {\n if (event.button !== 0) return\n start = {\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n touch: event.pointerType === 'touch',\n }\n ;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)\n}\n\nfunction onGripMove(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n lastX = event.clientX\n lastY = event.clientY\n if (!dragging.value) {\n // a finger wobbles more than a mouse while tapping\n const slop = start.touch ? 8 : 4\n if (Math.hypot(event.clientX - start.x, event.clientY - start.y) < slop) return\n range = selectTarget()\n if (!range) return stopDrag()\n dragging.value = true\n scroller = root.value && scrollParent(root.value)\n window.addEventListener('keydown', onDragKey, true)\n showGhost(range)\n autoScroll()\n }\n moveGhost()\n updateDrop()\n}\n\nfunction onGripUp(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n if (dragging.value) finishDrag()\n else if (menuOpen.value) menuOpen.value = false\n else {\n selectTarget()\n menuOpen.value = true\n }\n start = null\n}\n\nfunction onDragKey(event: KeyboardEvent) {\n if (event.key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n stopDrag()\n}\n\n/** Beside a column, past its edge: a new column there, when the set takes one more. */\n/** How far into the last column a drop still makes a new column after it. */\nconst LAST_COLUMN_EDGE = 16\n\nfunction columnDrop(content: HTMLElement, moving: SiblingRange, box: DOMRect): Drop | null {\n const instance = view.value\n const group = content.closest<HTMLElement>(COLUMN_GROUP)\n const column = group?.parentElement\n const rowGroup = column?.parentElement\n const rowId = rowGroup?.parentElement?.dataset.blockId\n if (!instance || !column || !rowGroup || !rowId) return null\n const columns = childBlocks(rowGroup)\n const index = columns.indexOf(column)\n if (index < 0 || !sideBySide(columns)) return null\n const rect = column.getBoundingClientRect()\n // right of the last column there may be no room (the editor's edge): its last strip counts\n const right = index === columns.length - 1 ? rect.right - LAST_COLUMN_EDGE : rect.right\n const at = lastX < rect.left ? index : lastX > right ? index + 1 : -1\n if (at < 0) return null\n const row = findBlockById(instance.state.doc, rowId)\n if (!row || !moveRangeToNewColumn(moving, row.pos, at)(instance.state)) return null\n const gap =\n columns.length > 1\n ? columns[1]!.getBoundingClientRect().left - columns[0]!.getBoundingClientRect().right\n : 0\n const x =\n at === 0\n ? columns[0]!.getBoundingClientRect().left - gap / 2\n : at === columns.length\n ? columns.at(-1)!.getBoundingClientRect().right - 1\n : (columns[at - 1]!.getBoundingClientRect().right +\n columns[at]!.getBoundingClientRect().left) /\n 2\n const rowRect = rowGroup.getBoundingClientRect()\n return {\n pos: row.pos,\n top: rowRect.top - box.top,\n left: x - box.left,\n width: 0,\n height: rowRect.height,\n column: { row: rowId, index: at },\n }\n}\n\nfunction updateDrop() {\n const instance = view.value\n const host = root.value\n if (!instance || !host || !range) return\n const content = contentAt(instance, lastY, lastX)\n const id = content && blockElementOf(content)?.dataset.blockId\n const info = id ? findBlockById(instance.state.doc, id) : null\n if (!content || !info) return (drop.value = null)\n const box = host.getBoundingClientRect()\n const beside = columnDrop(content, range, box)\n if (beside) return (drop.value = beside)\n const rect = content.getBoundingClientRect()\n const span = contentSpan(content)\n const below = lastY > rect.top + rect.height / 2\n let pos: number\n let y: number\n let left = span.left\n if (!below) {\n pos = info.pos\n y = rect.top\n } else if (info.group) {\n // the lower half of a block with children: in front of its first child\n pos = info.contentPos + info.content.nodeSize + 1\n y = rect.bottom\n const child = blockElementOf(content)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__group > .dou-editor__block > .dou-editor__content',\n )\n left = child ? contentSpan(child).left : span.left\n } else {\n pos = info.pos + info.node.nodeSize\n y = blockElementOf(content)!.getBoundingClientRect().bottom\n }\n if (!moveRangeTo(range, pos)(instance.state)) return (drop.value = null)\n // to the end of the text column, which a reading width can end before the editor\n drop.value = { pos, top: y - box.top, left: left - box.left, width: span.right - left }\n}\n\nfunction autoScroll() {\n scrollFrame = requestAnimationFrame(() => {\n if (!dragging.value) return\n const edge = 48\n const top = scroller ? scroller.getBoundingClientRect().top : 0\n const bottom = scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight\n let speed = 0\n if (lastY < top + edge) speed = -Math.ceil(((top + edge - lastY) / edge) * 16)\n else if (lastY > bottom - edge) speed = Math.ceil(((lastY - bottom + edge) / edge) * 16)\n if (speed) {\n if (scroller) scroller.scrollTop += speed\n else window.scrollBy(0, speed)\n updateDrop()\n }\n autoScroll()\n })\n}\n\nfunction finishDrag() {\n const instance = view.value\n const spot = drop.value\n const moving = range\n stopDrag()\n if (!instance || !spot || !moving) return\n const ids = blocksIn(moving).map((block) => block.node.attrs.id as string)\n const row = spot.column && findBlockById(instance.state.doc, spot.column.row)\n const command = spot.column\n ? row && moveRangeToNewColumn(moving, row.pos, spot.column.index)\n : moveRangeTo(moving, spot.pos)\n if (!command || !command(instance.state, instance.dispatch)) return\n selectBlocks(ids[0]!, ids.at(-1)!)(instance.state, instance.dispatch)\n instance.focus()\n}\n\nfunction stopDrag() {\n dragging.value = false\n drop.value = null\n range = null\n start = null\n ghost?.remove()\n ghost = null\n if (scrollFrame) cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n window.removeEventListener('keydown', onDragKey, true)\n}\n\nwatch(menuOpen, (value) => {\n if (value) return\n if (touch.value) scheduleFollow()\n else if (!root.value?.matches(':hover')) position.value = null\n})\n</script>\n\n<template>\n <div\n v-show=\"visible\"\n ref=\"handle\"\n :class=\"['dou-editor__handle', { 'is-compact': compact, 'is-table': table }]\"\n :style=\"\n position\n ? {\n top: `${position.top}px`,\n left: `${position.left}px`,\n '--dou-editor-line': `${position.height}px`,\n '--dou-editor-handle-shift': `${shift}px`,\n }\n : undefined\n \"\n @mousedown.prevent\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__add\"\n :aria-label=\"messages.addBlock\"\n :title=\"messages.addBlock\"\n @click=\"add\"\n >\n <PlusIcon />\n </button>\n <DouDropdown\n v-model:open=\"menuOpen\"\n trigger=\"manual\"\n placement=\"bottom-start\"\n class=\"dou-editor-menu\"\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__grip\"\n :aria-label=\"messages.dragHandle\"\n :title=\"messages.dragHandle\"\n @pointerdown=\"onGripDown\"\n @pointermove=\"onGripMove\"\n @pointerup=\"onGripUp\"\n @pointercancel=\"stopDrag\"\n >\n <GripVerticalIcon />\n </button>\n <template #menu>\n <DouDropdownSub :title=\"messages.turnInto\">\n <DouDropdownItem\n v-for=\"option in turnOptions\"\n :key=\"option.key\"\n @click=\"turnInto(option)\"\n >\n <template #prefix><component :is=\"option.icon\" /></template>\n {{ labelOf(option.label, messages) }}\n <template v-if=\"current && isCurrent(option, current.type, current.props)\" #suffix>\n <CheckIcon />\n </template>\n </DouDropdownItem>\n </DouDropdownSub>\n <template v-if=\"current\">\n <component\n :is=\"entry\"\n v-for=\"(entry, index) in kit.blockMenu\"\n :key=\"index\"\n :block=\"current\"\n />\n </template>\n <DouDropdownItem :shortcut=\"touch ? undefined : 'mod+d'\" @click=\"duplicate\">\n <template #prefix><CopyIcon /></template>\n {{ messages.duplicate }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(-1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+up'\"\n @click=\"move(-1)\"\n >\n <template #prefix><ArrowUpIcon /></template>\n {{ messages.moveUp }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+down'\"\n @click=\"move(1)\"\n >\n <template #prefix><ArrowDownIcon /></template>\n {{ messages.moveDown }}\n </DouDropdownItem>\n <DouDropdownItem\n divided\n tone=\"danger\"\n :shortcut=\"touch ? undefined : 'delete'\"\n @click=\"remove\"\n >\n <template #prefix><TrashIcon /></template>\n {{ messages.delete }}\n </DouDropdownItem>\n </template>\n </DouDropdown>\n </div>\n <div\n v-if=\"drop\"\n :class=\"['dou-editor__drop', { 'is-vertical': drop.column }]\"\n :style=\"\n drop.column\n ? { top: `${drop.top}px`, left: `${drop.left}px`, height: `${drop.height}px` }\n : { top: `${drop.top}px`, left: `${drop.left}px`, width: `${drop.width}px` }\n \"\n />\n</template>\n"],"mappings":""}
@@ -5,16 +5,19 @@ import { blockAround, blocksIn, findBlockById, siblingRangeBetween } from "../co
5
5
  import { deleteBlocks, duplicateBlocks, insertBlockAfter, moveRangeTo, moveRangeToNewColumn, setBlockType, swapBlocks } from "../core/commands.js";
6
6
  import { blockSelectionKey, blockSelectionRange, getBlockSelection, selectBlocks } from "../core/block-selection.js";
7
7
  import { slashKey } from "../core/slash.js";
8
- import { COLUMN_GROUP, blockElementOf, childBlocks, contentAt, contentSpan, firstLine, handleLeft, scrollParent, sideBySide } from "../dom.js";
8
+ import { COLUMN_GROUP, blockElementOf, bubbleShift, childBlocks, contentAt, contentSpan, firstLine, handleLeft, scrollParent, sideBySide } from "../dom.js";
9
9
  import { editorKey } from "../editor.js";
10
10
  import { useMenuEscape } from "./menu-escape.js";
11
11
  import { DouDropdown, DouDropdownItem, DouDropdownSub } from "dou-ui";
12
- import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, inject, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, renderList, resolveDynamicComponent, shallowRef, toDisplayString, unref, vShow, watch, withCtx, withDirectives, withModifiers } from "vue";
12
+ import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, inject, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, renderList, resolveDynamicComponent, shallowRef, toDisplayString, unref, useTemplateRef, vShow, watch, withCtx, withDirectives, withModifiers } from "vue";
13
13
  import { TextSelection } from "prosemirror-state";
14
14
  import { ArrowDownIcon, ArrowUpIcon, CheckIcon, CopyIcon, GripVerticalIcon, PlusIcon, TrashIcon } from "@dou-ui/icons";
15
15
  // src/components/block-handle.vue?vue&type=script&setup=true&lang.ts
16
16
  var _hoisted_1 = ["aria-label", "title"];
17
17
  var _hoisted_2 = ["aria-label", "title"];
18
+ var ADD_WIDTH = 20;
19
+ /** How far a finger's reach goes left of the bubble (the grip's ::before, past the bubble's border and padding). */
20
+ var TOUCH_REACH = 12;
18
21
  var LAST_COLUMN_EDGE = 16;
19
22
  var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({
20
23
  __name: "block-handle",
@@ -27,14 +30,21 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
27
30
  */
28
31
  const touch = shallowRef(false);
29
32
  let media = null;
33
+ /** A mouse: "+" comes out of the bubble while the pointer is on it. */
34
+ let fine = null;
30
35
  const onMedia = () => touch.value = !!media?.matches;
31
36
  /** The block the handle is next to, by id. */
32
37
  const hovered = shallowRef(null);
33
38
  const position = shallowRef(null);
34
39
  /** In a column the handle is only the grip, in the gap before it, leaving room for the resize bar. */
35
40
  const compact = shallowRef(false);
41
+ /** Next to a table: further out, clear of its row handles. */
42
+ const table = shallowRef(false);
36
43
  const menuOpen = shallowRef(false);
37
- useMenuEscape(menuOpen, () => menuOpen.value = false);
44
+ useMenuEscape(menuOpen, () => {
45
+ menuOpen.value = false;
46
+ requestAnimationFrame(() => view.value?.focus());
47
+ });
38
48
  /**
39
49
  * Where a drag would drop: before or after a block (a line across), or
40
50
  * beside a column, into a new column (a line down, `column` set).
@@ -55,6 +65,7 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
55
65
  const line = firstLine(content);
56
66
  hovered.value = id;
57
67
  compact.value = !!content.closest(COLUMN_GROUP);
68
+ table.value = content.classList.contains("dou-editor__content--table");
58
69
  position.value = {
59
70
  top: line.top - box.top,
60
71
  left: handleLeft(content) - box.left,
@@ -118,6 +129,7 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
118
129
  ], scheduleFollow);
119
130
  onMounted(() => {
120
131
  media = window.matchMedia("(pointer: coarse)");
132
+ fine = window.matchMedia("(hover: hover) and (pointer: fine)");
121
133
  onMedia();
122
134
  media.addEventListener("change", onMedia);
123
135
  window.addEventListener("resize", scheduleFollow);
@@ -146,6 +158,38 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
146
158
  else position.value = null;
147
159
  });
148
160
  });
161
+ const handle = useTemplateRef("handle");
162
+ /** The width "+" adds to the bubble (its button, see the styles). */
163
+ const shift = shallowRef(0);
164
+ function clipLeft(from) {
165
+ for (let node = from.parentElement; node; node = node.parentElement) if (getComputedStyle(node).overflowX !== "visible") return node.getBoundingClientRect().left;
166
+ return 0;
167
+ }
168
+ function fit() {
169
+ const element = handle.value;
170
+ const host = root.value;
171
+ if (!element || !host || !visible.value) return;
172
+ let left = element.getBoundingClientRect().left - shift.value;
173
+ const plus = element.querySelector(".dou-editor__add");
174
+ if (fine?.matches && !compact.value && plus && !plus.offsetWidth) left -= ADD_WIDTH;
175
+ const style = getComputedStyle(element);
176
+ const clear = table.value && position.value ? host.getBoundingClientRect().left + position.value.left + Number.parseFloat(style.getPropertyValue("--dou-editor-handle-offset")) - 1 : void 0;
177
+ const edge = clipLeft(host);
178
+ const next = Math.max(bubbleShift(left, edge, clear), touch.value && !table.value ? bubbleShift(left - TOUCH_REACH, edge) : 0);
179
+ if (next !== shift.value) shift.value = next;
180
+ }
181
+ watch([
182
+ position,
183
+ visible,
184
+ compact,
185
+ table
186
+ ], fit, { flush: "post" });
187
+ let sizes = null;
188
+ onMounted(() => {
189
+ sizes = new ResizeObserver(fit);
190
+ if (handle.value) sizes.observe(handle.value);
191
+ });
192
+ onBeforeUnmount(() => sizes?.disconnect());
149
193
  const target = computed(() => {
150
194
  const doc = state.value?.doc;
151
195
  return doc && hovered.value ? findBlockById(doc, hovered.value) : null;
@@ -417,11 +461,17 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
417
461
  });
418
462
  return (_ctx, _cache) => {
419
463
  return openBlock(), createElementBlock(Fragment, null, [withDirectives(createElementVNode("div", {
420
- class: normalizeClass(["dou-editor__handle", { "is-compact": compact.value }]),
464
+ ref_key: "handle",
465
+ ref: handle,
466
+ class: normalizeClass(["dou-editor__handle", {
467
+ "is-compact": compact.value,
468
+ "is-table": table.value
469
+ }]),
421
470
  style: normalizeStyle(position.value ? {
422
471
  top: `${position.value.top}px`,
423
472
  left: `${position.value.left}px`,
424
- "--dou-editor-line": `${position.value.height}px`
473
+ "--dou-editor-line": `${position.value.height}px`,
474
+ "--dou-editor-handle-shift": `${shift.value}px`
425
475
  } : void 0),
426
476
  onMousedown: _cache[3] || (_cache[3] = withModifiers(() => {}, ["prevent"]))
427
477
  }, [createElementVNode("button", {
@@ -1 +1 @@
1
- {"version":3,"file":"block-handle.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createElementBlock","_Fragment","_withDirectives","_createElementVNode","_normalizeClass","_normalizeStyle","_withModifiers","_unref","_createVNode","_withCtx","_renderList","_createBlock","_createSlots","_resolveDynamicComponent","_createTextVNode","_toDisplayString","_createCommentVNode","_vShow"],"sources":["../../src/components/block-handle.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n CheckIcon,\n CopyIcon,\n GripVerticalIcon,\n PlusIcon,\n TrashIcon,\n} from '@dou-ui/icons'\nimport { DouDropdown, DouDropdownItem, DouDropdownSub } from 'dou-ui'\nimport { TextSelection } from 'prosemirror-state'\nimport { computed, inject, onBeforeUnmount, onMounted, shallowRef, watch } from 'vue'\nimport { isCurrent } from '../catalog'\nimport { labelOf, type BlockOption } from '../core/extension'\nimport {\n blockSelectionKey,\n blockSelectionRange,\n getBlockSelection,\n selectBlocks,\n} from '../core/block-selection'\nimport {\n blockAround,\n blocksIn,\n findBlockById,\n siblingRangeBetween,\n type SiblingRange,\n} from '../core/blocks'\nimport {\n duplicateBlocks,\n insertBlockAfter,\n swapBlocks,\n moveRangeTo,\n moveRangeToNewColumn,\n deleteBlocks,\n setBlockType,\n} from '../core/commands'\nimport { blockFromNode } from '../core/model'\nimport { slashKey } from '../core/slash'\nimport {\n blockElementOf,\n childBlocks,\n COLUMN_GROUP,\n contentAt,\n contentSpan,\n firstLine,\n handleLeft,\n scrollParent,\n sideBySide,\n} from '../dom'\nimport { editorKey } from '../editor'\nimport { useMenuEscape } from './menu-escape'\n\nconst { view, state, focused, messages, root, dragging, kit } = inject(editorKey)!\n\n/**\n * Touch screens have no hover: there the handle shows only the grip, next\n * to the block with the cursor (or the selected blocks) while the editor\n * has focus. A tap on it opens the menu, a press and drag moves the block.\n */\nconst touch = shallowRef(false)\nlet media: MediaQueryList | null = null\nconst onMedia = () => (touch.value = !!media?.matches)\n\n/** The block the handle is next to, by id. */\nconst hovered = shallowRef<string | null>(null)\nconst position = shallowRef<{ top: number; left: number; height: number } | null>(null)\n/** In a column the handle is only the grip, in the gap before it, leaving room for the resize bar. */\nconst compact = shallowRef(false)\nconst menuOpen = shallowRef(false)\nuseMenuEscape(menuOpen, () => (menuOpen.value = false))\n\n/**\n * Where a drag would drop: before or after a block (a line across), or\n * beside a column, into a new column (a line down, `column` set).\n */\ninterface Drop {\n pos: number\n top: number\n left: number\n width: number\n height?: number\n column?: { row: string; index: number }\n}\nconst drop = shallowRef<Drop | null>(null)\n// typing hides the handle until the pointer moves again\nconst resting = shallowRef(false)\n\nconst visible = computed(() => {\n if (!position.value) return false\n if (menuOpen.value || dragging.value) return true\n if (touch.value) return focused.value || (!!state.value && !!getBlockSelection(state.value))\n return !resting.value\n})\n\nfunction place(content: HTMLElement) {\n const block = blockElementOf(content)\n const id = block?.dataset.blockId\n const host = root.value\n if (!id || !host) return\n const box = host.getBoundingClientRect()\n const line = firstLine(content)\n hovered.value = id\n compact.value = !!content.closest(COLUMN_GROUP)\n position.value = {\n top: line.top - box.top,\n left: handleLeft(content) - box.left,\n height: line.height,\n }\n}\n\nlet frame = 0\nlet lastY = 0\nlet lastX = 0\n\nfunction track(event: PointerEvent) {\n // a finger only moves the handle by moving the cursor; a drag reports itself\n if (event.pointerType === 'touch') return\n lastY = event.clientY\n lastX = event.clientX\n resting.value = false\n if (menuOpen.value || frame) return\n frame = requestAnimationFrame(() => {\n frame = 0\n if (dragging.value) return updateDrop()\n const current = view.value\n if (!current || menuOpen.value) return\n const content = contentAt(current, lastY, lastX)\n if (content) place(content)\n })\n}\n\n/** A wide table scrolled sideways: the handle next to it follows its left edge. */\nfunction onScroll(event: Event) {\n const content = event.target\n if (\n !(content instanceof HTMLElement) ||\n !content.classList.contains('dou-editor__content--table')\n )\n return\n if (position.value && hovered.value && blockElementOf(content)?.dataset.blockId === hovered.value)\n place(content)\n}\n\nfunction leave(event: PointerEvent) {\n if (menuOpen.value || dragging.value || event.pointerType === 'touch') return\n position.value = null\n hovered.value = null\n}\n\n/** On touch screens: put the handle next to the block with the cursor. */\nfunction follow() {\n const current = view.value\n if (!current || dragging.value) return\n const selected = blockSelectionRange(current.state)\n const info = selected ? blocksIn(selected)[0] : blockAround(current.state.selection.$from)\n const element = info\n ? (current.nodeDOM(info.pos) as HTMLElement | null)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__content',\n )\n : null\n if (element) place(element)\n else {\n position.value = null\n hovered.value = null\n }\n}\n\nlet followFrame = 0\nfunction scheduleFollow() {\n if (!touch.value || followFrame) return\n followFrame = requestAnimationFrame(() => {\n followFrame = 0\n if (touch.value && !menuOpen.value) follow()\n })\n}\n\nwatch([state, focused, touch], scheduleFollow)\n\nonMounted(() => {\n media = window.matchMedia('(pointer: coarse)')\n onMedia()\n media.addEventListener('change', onMedia)\n window.addEventListener('resize', scheduleFollow)\n root.value?.addEventListener('pointermove', track)\n root.value?.addEventListener('pointerleave', leave)\n root.value?.addEventListener('scroll', onScroll, true)\n})\nonBeforeUnmount(() => {\n media?.removeEventListener('change', onMedia)\n window.removeEventListener('resize', scheduleFollow)\n if (followFrame) cancelAnimationFrame(followFrame)\n root.value?.removeEventListener('pointermove', track)\n root.value?.removeEventListener('pointerleave', leave)\n root.value?.removeEventListener('scroll', onScroll, true)\n if (frame) cancelAnimationFrame(frame)\n stopDrag()\n})\n\n// follow edits: keep the handle on its block, or hide it while typing\nwatch(state, (next, previous) => {\n if (touch.value || !next || !previous || next.doc === previous.doc || dragging.value) return\n if (!menuOpen.value) resting.value = true\n requestAnimationFrame(() => {\n const current = view.value\n if (!current || !hovered.value) return\n const element = current.dom.querySelector<HTMLElement>(\n `[data-block-id=\"${CSS.escape(hovered.value)}\"] > .dou-editor__content`,\n )\n if (element) place(element)\n else position.value = null\n })\n})\n\nconst target = computed(() => {\n const doc = state.value?.doc\n return doc && hovered.value ? findBlockById(doc, hovered.value) : null\n})\n\n/** The hovered block, or every selected block when it is one of them. */\nfunction rangeForHovered(): SiblingRange | null {\n const current = view.value\n const info = target.value\n if (!current || !info) return null\n const selected = blockSelectionRange(current.state)\n if (selected && info.pos >= selected.start && info.pos < selected.end) return selected\n return siblingRangeBetween(current.state.doc, info.pos + 1, info.pos + 1)\n}\n\n/** Select the blocks the menu or a drag acts on. */\nfunction selectTarget(): SiblingRange | null {\n const current = view.value\n const range = rangeForHovered()\n if (!current || !range) return null\n const blocks = blocksIn(range)\n selectBlocks(blocks[0]!.node.attrs.id, blocks.at(-1)!.node.attrs.id)(\n current.state,\n current.dispatch,\n )\n return blockSelectionRange(current.state)\n}\n\n/* the + button */\n\nfunction add(event: MouseEvent) {\n const current = view.value\n const info = target.value\n if (!current || !info) return\n const empty = info.content.isTextblock && info.content.content.size === 0\n if (!empty || info.content.type.name !== 'paragraph') {\n insertBlockAfter(info.pos)(current.state, current.dispatch)\n // Alt+click adds the block above instead\n if (event.altKey) swapBlocks(-1)(current.state, current.dispatch)\n } else {\n const tr = current.state.tr.setSelection(\n TextSelection.create(current.state.doc, info.contentPos + 1),\n )\n current.dispatch(tr)\n }\n const from = current.state.selection.from\n current.dispatch(current.state.tr.insertText('/').setMeta(slashKey, { from, query: '' }))\n current.focus()\n}\n\n/* the block menu */\n\nconst turnOptions = kit.blockOptions.filter(\n (option) => !!kit.schema.nodes[option.type]?.isTextblock,\n)\nconst current = computed(() => {\n const info = target.value\n return info ? blockFromNode(info.node) : null\n})\n\nfunction after(action: () => void) {\n action()\n // the menu gives focus back to the handle; the editor takes it after\n requestAnimationFrame(() => view.value?.focus())\n}\n\nfunction keep(run: (current: NonNullable<typeof view.value>) => void) {\n after(() => {\n const instance = view.value\n if (!instance) return\n const selection = getBlockSelection(instance.state)\n run(instance)\n if (selection) selectBlocks(selection.anchor, selection.head)(instance.state, instance.dispatch)\n })\n}\n\nconst turnInto = (option: BlockOption) =>\n keep((instance) => setBlockType(option.type, option.props)(instance.state, instance.dispatch))\nconst duplicate = () => keep((instance) => duplicateBlocks(instance.state, instance.dispatch))\nconst move = (direction: -1 | 1) =>\n keep((instance) => swapBlocks(direction)(instance.state, instance.dispatch))\n\nfunction remove() {\n after(() => {\n const instance = view.value\n const range = instance && blockSelectionRange(instance.state)\n if (!instance || !range) return\n const tr = deleteBlocks(instance.state.tr, blocksIn(range)).setMeta(blockSelectionKey, null)\n instance.dispatch(tr.scrollIntoView())\n position.value = null\n })\n}\n\nconst canMove = (direction: -1 | 1) => {\n const instance = view.value\n return !!instance && !!state.value && swapBlocks(direction)(instance.state)\n}\n\n/* dragging */\n\nlet start: { x: number; y: number; pointer: number; touch: boolean } | null = null\nlet range: SiblingRange | null = null\nlet scroller: HTMLElement | null = null\nlet scrollFrame = 0\n/** A copy of the dragged blocks that follows the pointer. */\nlet ghost: HTMLElement | null = null\n\nfunction showGhost(moving: SiblingRange) {\n const instance = view.value\n const host = root.value\n if (!instance || !host) return\n ghost = document.createElement('div')\n ghost.className = 'dou-editor__surface dou-editor__ghost'\n ghost.setAttribute('aria-hidden', 'true')\n let width = 0\n for (const block of blocksIn(moving)) {\n const element = instance.nodeDOM(block.pos) as HTMLElement | null\n if (!element) continue\n width = Math.max(width, element.getBoundingClientRect().width)\n const copy = element.cloneNode(true) as HTMLElement\n copy.classList.remove('is-selected')\n for (const node of [copy, ...copy.querySelectorAll('[id], .is-selected')]) {\n node.removeAttribute('id')\n node.classList.remove('is-selected')\n }\n ghost.append(copy)\n }\n ghost.style.width = `${Math.min(width, 360)}px`\n host.append(ghost)\n moveGhost()\n}\n\nfunction moveGhost() {\n if (!ghost) return\n // above a finger, which would hide it; below and right of a mouse pointer\n const y = start?.touch ? lastY - ghost.offsetHeight - 24 : lastY + 12\n ghost.style.transform = `translate(${lastX + 12}px, ${y}px)`\n}\n\nfunction onGripDown(event: PointerEvent) {\n if (event.button !== 0) return\n start = {\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n touch: event.pointerType === 'touch',\n }\n ;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)\n}\n\nfunction onGripMove(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n lastX = event.clientX\n lastY = event.clientY\n if (!dragging.value) {\n // a finger wobbles more than a mouse while tapping\n const slop = start.touch ? 8 : 4\n if (Math.hypot(event.clientX - start.x, event.clientY - start.y) < slop) return\n range = selectTarget()\n if (!range) return stopDrag()\n dragging.value = true\n scroller = root.value && scrollParent(root.value)\n window.addEventListener('keydown', onDragKey, true)\n showGhost(range)\n autoScroll()\n }\n moveGhost()\n updateDrop()\n}\n\nfunction onGripUp(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n if (dragging.value) finishDrag()\n else if (menuOpen.value) menuOpen.value = false\n else {\n selectTarget()\n menuOpen.value = true\n }\n start = null\n}\n\nfunction onDragKey(event: KeyboardEvent) {\n if (event.key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n stopDrag()\n}\n\n/** Beside a column, past its edge: a new column there, when the set takes one more. */\n/** How far into the last column a drop still makes a new column after it. */\nconst LAST_COLUMN_EDGE = 16\n\nfunction columnDrop(content: HTMLElement, moving: SiblingRange, box: DOMRect): Drop | null {\n const instance = view.value\n const group = content.closest<HTMLElement>(COLUMN_GROUP)\n const column = group?.parentElement\n const rowGroup = column?.parentElement\n const rowId = rowGroup?.parentElement?.dataset.blockId\n if (!instance || !column || !rowGroup || !rowId) return null\n const columns = childBlocks(rowGroup)\n const index = columns.indexOf(column)\n if (index < 0 || !sideBySide(columns)) return null\n const rect = column.getBoundingClientRect()\n // right of the last column there may be no room (the editor's edge): its last strip counts\n const right = index === columns.length - 1 ? rect.right - LAST_COLUMN_EDGE : rect.right\n const at = lastX < rect.left ? index : lastX > right ? index + 1 : -1\n if (at < 0) return null\n const row = findBlockById(instance.state.doc, rowId)\n if (!row || !moveRangeToNewColumn(moving, row.pos, at)(instance.state)) return null\n const gap =\n columns.length > 1\n ? columns[1]!.getBoundingClientRect().left - columns[0]!.getBoundingClientRect().right\n : 0\n const x =\n at === 0\n ? columns[0]!.getBoundingClientRect().left - gap / 2\n : at === columns.length\n ? columns.at(-1)!.getBoundingClientRect().right - 1\n : (columns[at - 1]!.getBoundingClientRect().right +\n columns[at]!.getBoundingClientRect().left) /\n 2\n const rowRect = rowGroup.getBoundingClientRect()\n return {\n pos: row.pos,\n top: rowRect.top - box.top,\n left: x - box.left,\n width: 0,\n height: rowRect.height,\n column: { row: rowId, index: at },\n }\n}\n\nfunction updateDrop() {\n const instance = view.value\n const host = root.value\n if (!instance || !host || !range) return\n const content = contentAt(instance, lastY, lastX)\n const id = content && blockElementOf(content)?.dataset.blockId\n const info = id ? findBlockById(instance.state.doc, id) : null\n if (!content || !info) return (drop.value = null)\n const box = host.getBoundingClientRect()\n const beside = columnDrop(content, range, box)\n if (beside) return (drop.value = beside)\n const rect = content.getBoundingClientRect()\n const span = contentSpan(content)\n const below = lastY > rect.top + rect.height / 2\n let pos: number\n let y: number\n let left = span.left\n if (!below) {\n pos = info.pos\n y = rect.top\n } else if (info.group) {\n // the lower half of a block with children: in front of its first child\n pos = info.contentPos + info.content.nodeSize + 1\n y = rect.bottom\n const child = blockElementOf(content)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__group > .dou-editor__block > .dou-editor__content',\n )\n left = child ? contentSpan(child).left : span.left\n } else {\n pos = info.pos + info.node.nodeSize\n y = blockElementOf(content)!.getBoundingClientRect().bottom\n }\n if (!moveRangeTo(range, pos)(instance.state)) return (drop.value = null)\n // to the end of the text column, which a reading width can end before the editor\n drop.value = { pos, top: y - box.top, left: left - box.left, width: span.right - left }\n}\n\nfunction autoScroll() {\n scrollFrame = requestAnimationFrame(() => {\n if (!dragging.value) return\n const edge = 48\n const top = scroller ? scroller.getBoundingClientRect().top : 0\n const bottom = scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight\n let speed = 0\n if (lastY < top + edge) speed = -Math.ceil(((top + edge - lastY) / edge) * 16)\n else if (lastY > bottom - edge) speed = Math.ceil(((lastY - bottom + edge) / edge) * 16)\n if (speed) {\n if (scroller) scroller.scrollTop += speed\n else window.scrollBy(0, speed)\n updateDrop()\n }\n autoScroll()\n })\n}\n\nfunction finishDrag() {\n const instance = view.value\n const spot = drop.value\n const moving = range\n stopDrag()\n if (!instance || !spot || !moving) return\n const ids = blocksIn(moving).map((block) => block.node.attrs.id as string)\n const row = spot.column && findBlockById(instance.state.doc, spot.column.row)\n const command = spot.column\n ? row && moveRangeToNewColumn(moving, row.pos, spot.column.index)\n : moveRangeTo(moving, spot.pos)\n if (!command || !command(instance.state, instance.dispatch)) return\n selectBlocks(ids[0]!, ids.at(-1)!)(instance.state, instance.dispatch)\n instance.focus()\n}\n\nfunction stopDrag() {\n dragging.value = false\n drop.value = null\n range = null\n start = null\n ghost?.remove()\n ghost = null\n if (scrollFrame) cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n window.removeEventListener('keydown', onDragKey, true)\n}\n\nwatch(menuOpen, (value) => {\n if (value) return\n if (touch.value) scheduleFollow()\n else if (!root.value?.matches(':hover')) position.value = null\n})\n</script>\n\n<template>\n <div\n v-show=\"visible\"\n :class=\"['dou-editor__handle', { 'is-compact': compact }]\"\n :style=\"\n position\n ? {\n top: `${position.top}px`,\n left: `${position.left}px`,\n '--dou-editor-line': `${position.height}px`,\n }\n : undefined\n \"\n @mousedown.prevent\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__add\"\n :aria-label=\"messages.addBlock\"\n :title=\"messages.addBlock\"\n @click=\"add\"\n >\n <PlusIcon />\n </button>\n <DouDropdown\n v-model:open=\"menuOpen\"\n trigger=\"manual\"\n placement=\"bottom-start\"\n class=\"dou-editor-menu\"\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__grip\"\n :aria-label=\"messages.dragHandle\"\n :title=\"messages.dragHandle\"\n @pointerdown=\"onGripDown\"\n @pointermove=\"onGripMove\"\n @pointerup=\"onGripUp\"\n @pointercancel=\"stopDrag\"\n >\n <GripVerticalIcon />\n </button>\n <template #menu>\n <DouDropdownSub :title=\"messages.turnInto\">\n <DouDropdownItem\n v-for=\"option in turnOptions\"\n :key=\"option.key\"\n @click=\"turnInto(option)\"\n >\n <template #prefix><component :is=\"option.icon\" /></template>\n {{ labelOf(option.label, messages) }}\n <template v-if=\"current && isCurrent(option, current.type, current.props)\" #suffix>\n <CheckIcon />\n </template>\n </DouDropdownItem>\n </DouDropdownSub>\n <template v-if=\"current\">\n <component\n :is=\"entry\"\n v-for=\"(entry, index) in kit.blockMenu\"\n :key=\"index\"\n :block=\"current\"\n />\n </template>\n <DouDropdownItem :shortcut=\"touch ? undefined : 'mod+d'\" @click=\"duplicate\">\n <template #prefix><CopyIcon /></template>\n {{ messages.duplicate }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(-1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+up'\"\n @click=\"move(-1)\"\n >\n <template #prefix><ArrowUpIcon /></template>\n {{ messages.moveUp }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+down'\"\n @click=\"move(1)\"\n >\n <template #prefix><ArrowDownIcon /></template>\n {{ messages.moveDown }}\n </DouDropdownItem>\n <DouDropdownItem\n divided\n tone=\"danger\"\n :shortcut=\"touch ? undefined : 'delete'\"\n @click=\"remove\"\n >\n <template #prefix><TrashIcon /></template>\n {{ messages.delete }}\n </DouDropdownItem>\n </template>\n </DouDropdown>\n </div>\n <div\n v-if=\"drop\"\n :class=\"['dou-editor__drop', { 'is-vertical': drop.column }]\"\n :style=\"\n drop.column\n ? { top: `${drop.top}px`, left: `${dr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AC1CC,gBAAGR,MAAA,QAAA,CAAQ,CAAC,MAAM,GAAA,CAAA,C;;;;IA9DtB,SAAAE,cAYS,CAZTN,mBAYS,UAAA;KAXP,MAAK;KACL,UAAS;KACT,OAAM;KACL,cAAYI,MAAA,QAAA,CAAQ,CAAC;KACrB,OAAOA,MAAA,QAAA,CAAQ,CAAC;KAChB,eAAa;KACb,eAAa;KACb,aAAW;KACX,iBAAe;I,IAEhBC,YAAoBD,MAAA,gBAAA,CAAA,C;;G,wBAxChB,CAAAU,OAAA,QAAA,KAAO,C,IAiGT,KAAA,SADRlB,UAAA,GAAAC,mBAQE,OAAA;;IANC,OAAKI,eAAA,CAAA,oBAAA,EAAA,eAAwC,KAAA,MAAK,OAAM,CAAA,CAAA;IACxD,OAAKC,eAAS,KAAA,MAAK,SAA2B;KAAA,KAAA,GAAA,KAAA,MAAK,IAAG;KAAA,MAAA,GAAe,KAAA,MAAK,KAAI;KAAA,QAAA,GAAiB,KAAA,MAAK,OAAM;IAAA,IAA2B;KAAA,KAAA,GAAA,KAAA,MAAK,IAAG;KAAA,MAAA,GAAe,KAAA,MAAK,KAAI;KAAA,OAAA,GAAgB,KAAA,MAAK,MAAK;IAAA,C"}
1
+ {"version":3,"file":"block-handle.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createElementBlock","_Fragment","_withDirectives","_createElementVNode","_normalizeClass","_normalizeStyle","_withModifiers","_unref","_createVNode","_withCtx","_renderList","_createBlock","_createSlots","_resolveDynamicComponent","_createTextVNode","_toDisplayString","_createCommentVNode","_vShow"],"sources":["../../src/components/block-handle.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n CheckIcon,\n CopyIcon,\n GripVerticalIcon,\n PlusIcon,\n TrashIcon,\n} from '@dou-ui/icons'\nimport { DouDropdown, DouDropdownItem, DouDropdownSub } from 'dou-ui'\nimport { TextSelection } from 'prosemirror-state'\nimport {\n computed,\n inject,\n onBeforeUnmount,\n onMounted,\n shallowRef,\n useTemplateRef,\n watch,\n} from 'vue'\nimport { isCurrent } from '../catalog'\nimport { labelOf, type BlockOption } from '../core/extension'\nimport {\n blockSelectionKey,\n blockSelectionRange,\n getBlockSelection,\n selectBlocks,\n} from '../core/block-selection'\nimport {\n blockAround,\n blocksIn,\n findBlockById,\n siblingRangeBetween,\n type SiblingRange,\n} from '../core/blocks'\nimport {\n duplicateBlocks,\n insertBlockAfter,\n swapBlocks,\n moveRangeTo,\n moveRangeToNewColumn,\n deleteBlocks,\n setBlockType,\n} from '../core/commands'\nimport { blockFromNode } from '../core/model'\nimport { slashKey } from '../core/slash'\nimport {\n blockElementOf,\n bubbleShift,\n childBlocks,\n COLUMN_GROUP,\n contentAt,\n contentSpan,\n firstLine,\n handleLeft,\n scrollParent,\n sideBySide,\n} from '../dom'\nimport { editorKey } from '../editor'\nimport { useMenuEscape } from './menu-escape'\n\nconst { view, state, focused, messages, root, dragging, kit } = inject(editorKey)!\n\n/**\n * Touch screens have no hover: there the handle shows only the grip, next\n * to the block with the cursor (or the selected blocks) while the editor\n * has focus. A tap on it opens the menu, a press and drag moves the block.\n */\nconst touch = shallowRef(false)\nlet media: MediaQueryList | null = null\n/** A mouse: \"+\" comes out of the bubble while the pointer is on it. */\nlet fine: MediaQueryList | null = null\nconst onMedia = () => (touch.value = !!media?.matches)\n\n/** The block the handle is next to, by id. */\nconst hovered = shallowRef<string | null>(null)\nconst position = shallowRef<{ top: number; left: number; height: number } | null>(null)\n/** In a column the handle is only the grip, in the gap before it, leaving room for the resize bar. */\nconst compact = shallowRef(false)\n/** Next to a table: further out, clear of its row handles. */\nconst table = shallowRef(false)\nconst menuOpen = shallowRef(false)\nuseMenuEscape(menuOpen, () => {\n menuOpen.value = false\n // the menu had the focus; the selected blocks still answer Delete and copy\n requestAnimationFrame(() => view.value?.focus())\n})\n\n/**\n * Where a drag would drop: before or after a block (a line across), or\n * beside a column, into a new column (a line down, `column` set).\n */\ninterface Drop {\n pos: number\n top: number\n left: number\n width: number\n height?: number\n column?: { row: string; index: number }\n}\nconst drop = shallowRef<Drop | null>(null)\n// typing hides the handle until the pointer moves again\nconst resting = shallowRef(false)\n\nconst visible = computed(() => {\n if (!position.value) return false\n if (menuOpen.value || dragging.value) return true\n if (touch.value) return focused.value || (!!state.value && !!getBlockSelection(state.value))\n return !resting.value\n})\n\nfunction place(content: HTMLElement) {\n const block = blockElementOf(content)\n const id = block?.dataset.blockId\n const host = root.value\n if (!id || !host) return\n const box = host.getBoundingClientRect()\n const line = firstLine(content)\n hovered.value = id\n compact.value = !!content.closest(COLUMN_GROUP)\n table.value = content.classList.contains('dou-editor__content--table')\n position.value = {\n top: line.top - box.top,\n left: handleLeft(content) - box.left,\n height: line.height,\n }\n}\n\nlet frame = 0\nlet lastY = 0\nlet lastX = 0\n\nfunction track(event: PointerEvent) {\n // a finger only moves the handle by moving the cursor; a drag reports itself\n if (event.pointerType === 'touch') return\n lastY = event.clientY\n lastX = event.clientX\n resting.value = false\n if (menuOpen.value || frame) return\n frame = requestAnimationFrame(() => {\n frame = 0\n if (dragging.value) return updateDrop()\n const current = view.value\n if (!current || menuOpen.value) return\n const content = contentAt(current, lastY, lastX)\n if (content) place(content)\n })\n}\n\n/** A wide table scrolled sideways: the handle next to it follows its left edge. */\nfunction onScroll(event: Event) {\n const content = event.target\n if (\n !(content instanceof HTMLElement) ||\n !content.classList.contains('dou-editor__content--table')\n )\n return\n if (position.value && hovered.value && blockElementOf(content)?.dataset.blockId === hovered.value)\n place(content)\n}\n\nfunction leave(event: PointerEvent) {\n if (menuOpen.value || dragging.value || event.pointerType === 'touch') return\n position.value = null\n hovered.value = null\n}\n\n/** On touch screens: put the handle next to the block with the cursor. */\nfunction follow() {\n const current = view.value\n if (!current || dragging.value) return\n const selected = blockSelectionRange(current.state)\n const info = selected ? blocksIn(selected)[0] : blockAround(current.state.selection.$from)\n const element = info\n ? (current.nodeDOM(info.pos) as HTMLElement | null)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__content',\n )\n : null\n if (element) place(element)\n else {\n position.value = null\n hovered.value = null\n }\n}\n\nlet followFrame = 0\nfunction scheduleFollow() {\n if (!touch.value || followFrame) return\n followFrame = requestAnimationFrame(() => {\n followFrame = 0\n if (touch.value && !menuOpen.value) follow()\n })\n}\n\nwatch([state, focused, touch], scheduleFollow)\n\nonMounted(() => {\n media = window.matchMedia('(pointer: coarse)')\n fine = window.matchMedia('(hover: hover) and (pointer: fine)')\n onMedia()\n media.addEventListener('change', onMedia)\n window.addEventListener('resize', scheduleFollow)\n root.value?.addEventListener('pointermove', track)\n root.value?.addEventListener('pointerleave', leave)\n root.value?.addEventListener('scroll', onScroll, true)\n})\nonBeforeUnmount(() => {\n media?.removeEventListener('change', onMedia)\n window.removeEventListener('resize', scheduleFollow)\n if (followFrame) cancelAnimationFrame(followFrame)\n root.value?.removeEventListener('pointermove', track)\n root.value?.removeEventListener('pointerleave', leave)\n root.value?.removeEventListener('scroll', onScroll, true)\n if (frame) cancelAnimationFrame(frame)\n stopDrag()\n})\n\n// follow edits: keep the handle on its block, or hide it while typing\nwatch(state, (next, previous) => {\n if (touch.value || !next || !previous || next.doc === previous.doc || dragging.value) return\n if (!menuOpen.value) resting.value = true\n requestAnimationFrame(() => {\n const current = view.value\n if (!current || !hovered.value) return\n const element = current.dom.querySelector<HTMLElement>(\n `[data-block-id=\"${CSS.escape(hovered.value)}\"] > .dou-editor__content`,\n )\n if (element) place(element)\n else position.value = null\n })\n})\n\n/*\n * The bubble floats outside the text. When the editor's container cuts off\n * the room there (it clips, or the screen ends), the bubble moves in by as\n * much as it lacks, counting the \"+\" that comes out on hover, so the grip\n * stays under the pointer when it does, and a finger's reach on touch screens.\n */\nconst handle = useTemplateRef<HTMLElement>('handle')\n/** The width \"+\" adds to the bubble (its button, see the styles). */\nconst ADD_WIDTH = 20\n/** How far a finger's reach goes left of the bubble (the grip's ::before, past the bubble's border and padding). */\nconst TOUCH_REACH = 12\nconst shift = shallowRef(0)\n\nfunction clipLeft(from: HTMLElement): number {\n for (let node = from.parentElement; node; node = node.parentElement) {\n if (getComputedStyle(node).overflowX !== 'visible') return node.getBoundingClientRect().left\n }\n return 0\n}\n\nfunction fit() {\n const element = handle.value\n const host = root.value\n if (!element || !host || !visible.value) return\n let left = element.getBoundingClientRect().left - shift.value\n const plus = element.querySelector<HTMLElement>('.dou-editor__add')\n if (fine?.matches && !compact.value && plus && !plus.offsetWidth) left -= ADD_WIDTH\n const style = getComputedStyle(element)\n const clear =\n table.value && position.value\n ? host.getBoundingClientRect().left +\n position.value.left +\n Number.parseFloat(style.getPropertyValue('--dou-editor-handle-offset')) -\n 1\n : undefined\n const edge = clipLeft(host)\n /*\n * A finger's reach moves the bubble in too, but only as far as plain text\n * lets it: next to a table, a cut-off reach stays cut off rather than\n * pushing the bubble onto the row handles or past them.\n */\n const next = Math.max(\n bubbleShift(left, edge, clear),\n touch.value && !table.value ? bubbleShift(left - TOUCH_REACH, edge) : 0,\n )\n if (next !== shift.value) shift.value = next\n}\n\nwatch([position, visible, compact, table], fit, { flush: 'post' })\nlet sizes: ResizeObserver | null = null\nonMounted(() => {\n sizes = new ResizeObserver(fit)\n if (handle.value) sizes.observe(handle.value)\n})\nonBeforeUnmount(() => sizes?.disconnect())\n\nconst target = computed(() => {\n const doc = state.value?.doc\n return doc && hovered.value ? findBlockById(doc, hovered.value) : null\n})\n\n/** The hovered block, or every selected block when it is one of them. */\nfunction rangeForHovered(): SiblingRange | null {\n const current = view.value\n const info = target.value\n if (!current || !info) return null\n const selected = blockSelectionRange(current.state)\n if (selected && info.pos >= selected.start && info.pos < selected.end) return selected\n return siblingRangeBetween(current.state.doc, info.pos + 1, info.pos + 1)\n}\n\n/** Select the blocks the menu or a drag acts on. */\nfunction selectTarget(): SiblingRange | null {\n const current = view.value\n const range = rangeForHovered()\n if (!current || !range) return null\n const blocks = blocksIn(range)\n selectBlocks(blocks[0]!.node.attrs.id, blocks.at(-1)!.node.attrs.id)(\n current.state,\n current.dispatch,\n )\n return blockSelectionRange(current.state)\n}\n\n/* the + button */\n\nfunction add(event: MouseEvent) {\n const current = view.value\n const info = target.value\n if (!current || !info) return\n const empty = info.content.isTextblock && info.content.content.size === 0\n if (!empty || info.content.type.name !== 'paragraph') {\n insertBlockAfter(info.pos)(current.state, current.dispatch)\n // Alt+click adds the block above instead\n if (event.altKey) swapBlocks(-1)(current.state, current.dispatch)\n } else {\n const tr = current.state.tr.setSelection(\n TextSelection.create(current.state.doc, info.contentPos + 1),\n )\n current.dispatch(tr)\n }\n const from = current.state.selection.from\n current.dispatch(current.state.tr.insertText('/').setMeta(slashKey, { from, query: '' }))\n current.focus()\n}\n\n/* the block menu */\n\nconst turnOptions = kit.blockOptions.filter(\n (option) => !!kit.schema.nodes[option.type]?.isTextblock,\n)\nconst current = computed(() => {\n const info = target.value\n return info ? blockFromNode(info.node) : null\n})\n\nfunction after(action: () => void) {\n action()\n // the menu gives focus back to the handle; the editor takes it after\n requestAnimationFrame(() => view.value?.focus())\n}\n\nfunction keep(run: (current: NonNullable<typeof view.value>) => void) {\n after(() => {\n const instance = view.value\n if (!instance) return\n const selection = getBlockSelection(instance.state)\n run(instance)\n if (selection) selectBlocks(selection.anchor, selection.head)(instance.state, instance.dispatch)\n })\n}\n\nconst turnInto = (option: BlockOption) =>\n keep((instance) => setBlockType(option.type, option.props)(instance.state, instance.dispatch))\nconst duplicate = () => keep((instance) => duplicateBlocks(instance.state, instance.dispatch))\nconst move = (direction: -1 | 1) =>\n keep((instance) => swapBlocks(direction)(instance.state, instance.dispatch))\n\nfunction remove() {\n after(() => {\n const instance = view.value\n const range = instance && blockSelectionRange(instance.state)\n if (!instance || !range) return\n const tr = deleteBlocks(instance.state.tr, blocksIn(range)).setMeta(blockSelectionKey, null)\n instance.dispatch(tr.scrollIntoView())\n position.value = null\n })\n}\n\nconst canMove = (direction: -1 | 1) => {\n const instance = view.value\n return !!instance && !!state.value && swapBlocks(direction)(instance.state)\n}\n\n/* dragging */\n\nlet start: { x: number; y: number; pointer: number; touch: boolean } | null = null\nlet range: SiblingRange | null = null\nlet scroller: HTMLElement | null = null\nlet scrollFrame = 0\n/** A copy of the dragged blocks that follows the pointer. */\nlet ghost: HTMLElement | null = null\n\nfunction showGhost(moving: SiblingRange) {\n const instance = view.value\n const host = root.value\n if (!instance || !host) return\n ghost = document.createElement('div')\n ghost.className = 'dou-editor__surface dou-editor__ghost'\n ghost.setAttribute('aria-hidden', 'true')\n let width = 0\n for (const block of blocksIn(moving)) {\n const element = instance.nodeDOM(block.pos) as HTMLElement | null\n if (!element) continue\n width = Math.max(width, element.getBoundingClientRect().width)\n const copy = element.cloneNode(true) as HTMLElement\n copy.classList.remove('is-selected')\n for (const node of [copy, ...copy.querySelectorAll('[id], .is-selected')]) {\n node.removeAttribute('id')\n node.classList.remove('is-selected')\n }\n ghost.append(copy)\n }\n ghost.style.width = `${Math.min(width, 360)}px`\n host.append(ghost)\n moveGhost()\n}\n\nfunction moveGhost() {\n if (!ghost) return\n // above a finger, which would hide it; below and right of a mouse pointer\n const y = start?.touch ? lastY - ghost.offsetHeight - 24 : lastY + 12\n ghost.style.transform = `translate(${lastX + 12}px, ${y}px)`\n}\n\nfunction onGripDown(event: PointerEvent) {\n if (event.button !== 0) return\n start = {\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n touch: event.pointerType === 'touch',\n }\n ;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)\n}\n\nfunction onGripMove(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n lastX = event.clientX\n lastY = event.clientY\n if (!dragging.value) {\n // a finger wobbles more than a mouse while tapping\n const slop = start.touch ? 8 : 4\n if (Math.hypot(event.clientX - start.x, event.clientY - start.y) < slop) return\n range = selectTarget()\n if (!range) return stopDrag()\n dragging.value = true\n scroller = root.value && scrollParent(root.value)\n window.addEventListener('keydown', onDragKey, true)\n showGhost(range)\n autoScroll()\n }\n moveGhost()\n updateDrop()\n}\n\nfunction onGripUp(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n if (dragging.value) finishDrag()\n else if (menuOpen.value) menuOpen.value = false\n else {\n selectTarget()\n menuOpen.value = true\n }\n start = null\n}\n\nfunction onDragKey(event: KeyboardEvent) {\n if (event.key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n stopDrag()\n}\n\n/** Beside a column, past its edge: a new column there, when the set takes one more. */\n/** How far into the last column a drop still makes a new column after it. */\nconst LAST_COLUMN_EDGE = 16\n\nfunction columnDrop(content: HTMLElement, moving: SiblingRange, box: DOMRect): Drop | null {\n const instance = view.value\n const group = content.closest<HTMLElement>(COLUMN_GROUP)\n const column = group?.parentElement\n const rowGroup = column?.parentElement\n const rowId = rowGroup?.parentElement?.dataset.blockId\n if (!instance || !column || !rowGroup || !rowId) return null\n const columns = childBlocks(rowGroup)\n const index = columns.indexOf(column)\n if (index < 0 || !sideBySide(columns)) return null\n const rect = column.getBoundingClientRect()\n // right of the last column there may be no room (the editor's edge): its last strip counts\n const right = index === columns.length - 1 ? rect.right - LAST_COLUMN_EDGE : rect.right\n const at = lastX < rect.left ? index : lastX > right ? index + 1 : -1\n if (at < 0) return null\n const row = findBlockById(instance.state.doc, rowId)\n if (!row || !moveRangeToNewColumn(moving, row.pos, at)(instance.state)) return null\n const gap =\n columns.length > 1\n ? columns[1]!.getBoundingClientRect().left - columns[0]!.getBoundingClientRect().right\n : 0\n const x =\n at === 0\n ? columns[0]!.getBoundingClientRect().left - gap / 2\n : at === columns.length\n ? columns.at(-1)!.getBoundingClientRect().right - 1\n : (columns[at - 1]!.getBoundingClientRect().right +\n columns[at]!.getBoundingClientRect().left) /\n 2\n const rowRect = rowGroup.getBoundingClientRect()\n return {\n pos: row.pos,\n top: rowRect.top - box.top,\n left: x - box.left,\n width: 0,\n height: rowRect.height,\n column: { row: rowId, index: at },\n }\n}\n\nfunction updateDrop() {\n const instance = view.value\n const host = root.value\n if (!instance || !host || !range) return\n const content = contentAt(instance, lastY, lastX)\n const id = content && blockElementOf(content)?.dataset.blockId\n const info = id ? findBlockById(instance.state.doc, id) : null\n if (!content || !info) return (drop.value = null)\n const box = host.getBoundingClientRect()\n const beside = columnDrop(content, range, box)\n if (beside) return (drop.value = beside)\n const rect = content.getBoundingClientRect()\n const span = contentSpan(content)\n const below = lastY > rect.top + rect.height / 2\n let pos: number\n let y: number\n let left = span.left\n if (!below) {\n pos = info.pos\n y = rect.top\n } else if (info.group) {\n // the lower half of a block with children: in front of its first child\n pos = info.contentPos + info.content.nodeSize + 1\n y = rect.bottom\n const child = blockElementOf(content)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__group > .dou-editor__block > .dou-editor__content',\n )\n left = child ? contentSpan(child).left : span.left\n } else {\n pos = info.pos + info.node.nodeSize\n y = blockElementOf(content)!.getBoundingClientRect().bottom\n }\n if (!moveRangeTo(range, pos)(instance.state)) return (drop.value = null)\n // to the end of the text column, which a reading width can end before the editor\n drop.value = { pos, top: y - box.top, left: left - box.left, width: span.right - left }\n}\n\nfunction autoScroll() {\n scrollFrame = requestAnimationFrame(() => {\n if (!dragging.value) return\n const edge = 48\n const top = scroller ? scroller.getBoundingClientRect().top : 0\n const bottom = scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight\n let speed = 0\n if (lastY < top + edge) speed = -Math.ceil(((top + edge - lastY) / edge) * 16)\n else if (lastY > bottom - edge) speed = Math.ceil(((lastY - bottom + edge) / edge) * 16)\n if (speed) {\n if (scroller) scroller.scrollTop += speed\n else window.scrollBy(0, speed)\n updateDrop()\n }\n autoScroll()\n })\n}\n\nfunction finishDrag() {\n const instance = view.value\n const spot = drop.value\n const moving = range\n stopDrag()\n if (!instance || !spot || !moving) return\n const ids = blocksIn(moving).map((block) => block.node.attrs.id as string)\n const row = spot.column && findBlockById(instance.state.doc, spot.column.row)\n const command = spot.column\n ? row && moveRangeToNewColumn(moving, row.pos, spot.column.index)\n : moveRangeTo(moving, spot.pos)\n if (!command || !command(instance.state, instance.dispatch)) return\n selectBlocks(ids[0]!, ids.at(-1)!)(instance.state, instance.dispatch)\n instance.focus()\n}\n\nfunction stopDrag() {\n dragging.value = false\n drop.value = null\n range = null\n start = null\n ghost?.remove()\n ghost = null\n if (scrollFrame) cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n window.removeEventListener('keydown', onDragKey, true)\n}\n\nwatch(menuOpen, (value) => {\n if (value) return\n if (touch.value) scheduleFollow()\n else if (!root.value?.matches(':hover')) position.value = null\n})\n</script>\n\n<template>\n <div\n v-show=\"visible\"\n ref=\"handle\"\n :class=\"['dou-editor__handle', { 'is-compact': compact, 'is-table': table }]\"\n :style=\"\n position\n ? {\n top: `${position.top}px`,\n left: `${position.left}px`,\n '--dou-editor-line': `${position.height}px`,\n '--dou-editor-handle-shift': `${shift}px`,\n }\n : undefined\n \"\n @mousedown.prevent\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__add\"\n :aria-label=\"messages.addBlock\"\n :title=\"messages.addBlock\"\n @click=\"add\"\n >\n <PlusIcon />\n </button>\n <DouDropdown\n v-model:open=\"menuOpen\"\n trigger=\"manual\"\n placement=\"bottom-start\"\n class=\"dou-editor-menu\"\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__grip\"\n :aria-label=\"messages.dragHandle\"\n :title=\"messages.dragHandle\"\n @pointerdown=\"onGripDown\"\n @pointermove=\"onGripMove\"\n @pointerup=\"onGripUp\"\n @pointercancel=\"stopDrag\"\n >\n <GripVerticalIcon />\n </button>\n <template #menu>\n <DouDropdownSub :title=\"messages.turnInto\">\n <DouDropdownItem\n v-for=\"option in turnOptions\"\n :key=\"option.key\"\n @click=\"turnInto(option)\"\n >\n <template #prefix><component :is=\"option.icon\" /></template>\n {{ labelOf(option.label, messages) }}\n <template v-if=\"current && isCurrent(option, current.type, current.props)\" #suffix>\n <CheckIcon />\n </template>\n </DouDropdownItem>\n </DouDropdownSub>\n <template v-if=\"current\">\n <component\n :is=\"entry\"\n v-for=\"(entry, index) in kit.blockMenu\"\n :key=\"index\"\n :block=\"current\"\n />\n </template>\n <DouDropdownItem :shortcut=\"touch ? undefined : 'mod+d'\" @click=\"duplicate\">\n <template #prefix><CopyIcon /></template>\n {{ messages.duplicate }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(-1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+up'\"\n @click=\"move(-1)\"\n >\n <template #prefix><ArrowUpIcon /></template>\n {{ messages.moveUp }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+down'\"\n @click=\"move(1)\"\n >\n <template #prefix><ArrowDownIcon /></template>\n {{ messages.moveDown }}\n </DouDropdownItem>\n <DouDropdownItem\n divided\n tone=\"danger\"\n :shortcut=\"touch ? undefined : 'delete'\"\n @click=\"remove\"\n >\n <template #prefix><TrashIcon /></template>\n {{ messages.delete }}\n </DouDropdownItem>\n </template>\n </DouDropdown>\n </div>\n <div\n v-if=\"drop\"\n :class=\"['dou-editor__drop', { 'is-vertical': drop.column }]\"\n :style=\"\n drop.column\n ? { top: `${drop.top}px`, left: `${drop.left}px`, height: `${drop.height}px` }\n : { top: `${drop.top}px`, left: `${drop.left}px`, width: `${drop.width}px` }\n \"\n />\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;AAiPA,IAAM,YAAY;;AAElB,IAAM,cAAc;AA4OpB,IAAM,mBAAmB;;;;EAjazB,MAAM,EAAE,MAAM,OAAO,SAAS,UAAU,MAAM,UAAU,QAAQ,OAAO,SAAS;;;;;;EAOhF,MAAM,QAAQ,WAAW,KAAK;EAC9B,IAAI,QAA+B;;EAEnC,IAAI,OAA8B;EAClC,MAAM,gBAAiB,MAAM,QAAQ,CAAC,CAAC,OAAO;;EAG9C,MAAM,UAAU,WAA0B,IAAI;EAC9C,MAAM,WAAW,WAAiE,IAAI;;EAEtF,MAAM,UAAU,WAAW,KAAK;;EAEhC,MAAM,QAAQ,W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Ae;I,IAEhBC,YAAoBD,MAAA,gBAAA,CAAA,C;;G,wBA1ChB,CAAAU,OAAA,QAAA,KAAO,C,IAmGT,KAAA,SADRlB,UAAA,GAAAC,mBAQE,OAAA;;IANC,OAAKI,eAAA,CAAA,oBAAA,EAAA,eAAwC,KAAA,MAAK,OAAM,CAAA,CAAA;IACxD,OAAKC,eAAS,KAAA,MAAK,SAA2B;KAAA,KAAA,GAAA,KAAA,MAAK,IAAG;KAAA,MAAA,GAAe,KAAA,MAAK,KAAI;KAAA,QAAA,GAAiB,KAAA,MAAK,OAAM;IAAA,IAA2B;KAAA,KAAA,GAAA,KAAA,MAAK,IAAG;KAAA,MAAA,GAAe,KAAA,MAAK,KAAI;KAAA,OAAA,GAAgB,KAAA,MAAK,MAAK;IAAA,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"extension.js","names":[],"sources":["../../src/core/extension.ts"],"sourcesContent":["import type { InputRule } from 'prosemirror-inputrules'\nimport type { MarkSpec, NodeSpec, Schema } from 'prosemirror-model'\nimport type { Command, Plugin } from 'prosemirror-state'\nimport type { NodeViewConstructor } from 'prosemirror-view'\nimport { parseHotkey, type CommentAction, type CommentThread } from 'dou-ui'\nimport type { Component, Ref } from 'vue'\nimport { editorLocales, type EditorMessages } from '../locale'\nimport type { BlockProps } from './model'\nimport type { EditorExtensionOutput } from './output'\nimport { createSchema } from './schema'\n\n/** Text shown in a menu: fixed, or read from the editor's messages so it follows the locale. */\nexport type Label = string | ((messages: EditorMessages) => string)\n\nexport const labelOf = (label: Label | undefined, messages: EditorMessages) =>\n typeof label === 'function' ? label(messages) : (label ?? '')\n\n/** An entry of the slash menu and of the “turn into” menus. */\nexport interface BlockOption {\n /** Unique among the options. */\n key: string\n /** The block type it inserts or turns blocks into. */\n type: string\n props?: BlockProps\n label: Label\n /** A short description under the label in the slash menu. */\n hint?: Label\n icon: Component\n /** Extra words the slash menu matches, besides the label (pinyin works well). */\n keywords?: string[]\n /** The Markdown shortcut, shown as a hint. */\n shortcut?: string\n /**\n * Variants to pick from in a panel beside the option in the slash menu,\n * e.g. how many columns. Choosing the option itself inserts the first.\n */\n choices?: BlockOptionChoices\n}\n\n/** One variant of a slash menu option. */\nexport interface BlockOptionChoice {\n /** The props it inserts with, over the option's own. */\n props: BlockProps\n /** Its name, also read out by screen readers. */\n label: Label\n}\n\n/** The variants of a slash menu option, picked in a panel beside it. */\nexport interface BlockOptionChoices {\n /** The panel's title, e.g. “Number of columns”; also the name screen readers give the panel. */\n title: Label\n items: BlockOptionChoice[]\n /**\n * Draws the variants (the panel around them and its title are drawn by\n * the menu). It gets the props in `BlockOptionChoicesProps` and emits\n * `hover` and `choose` with an index, as in `BlockOptionChoicesEmits`.\n * Without it, the panel lists their names.\n */\n component?: Component<BlockOptionChoicesProps>\n}\n\n/** What the `component` of `BlockOptionChoices` gets. */\nexport interface BlockOptionChoicesProps {\n items: BlockOptionChoice[]\n /** The index of the highlighted variant; -1 while the option itself is highlighted. */\n active: number\n messages: EditorMessages\n /**\n * For screen readers: give the element of variant `index` the id\n * `${idPrefix}-${index}` and `role=\"option\"` (with `aria-selected`), so\n * the editor can point at the highlighted one.\n */\n idPrefix: string\n}\n\n/** What the `component` of `BlockOptionChoices` emits. */\nexport interface BlockOptionChoicesEmits {\n /** The pointer is on variant `index`. */\n hover: [index: number]\n /** Variant `index` is picked: the menu inserts it. */\n choose: [index: number]\n}\n\n/** A toggle in the formatting toolbar for a mark. */\nexport interface FormatOption {\n mark: string\n label: Label\n icon: Component\n /** The shortcut shown in its tooltip, written as in `useHotkey`, e.g. `mod+b`. */\n hotkey?: string\n}\n\n/** Where the comment threads live, when not in `v-model:comments`. */\nexport interface CommentsProvider {\n /** The threads, kept up to date. */\n threads: Readonly<Ref<readonly CommentThread[]>>\n /** Make a change this user asked for. */\n apply: (action: CommentAction) => void\n}\n\nexport interface EditorExtensionContext {\n schema: Schema\n /**\n * The editor's messages, in its current locale, for text a plugin puts\n * in the document's markup (e.g. a name for screen readers). Outside an\n * editor (converting documents) the Chinese ones.\n */\n messages: () => EditorMessages\n}\n\n/** What the extension replacing the undo history provides (e.g. collaboration). */\nexport interface HistoryProvider {\n plugins: Plugin[]\n undo: Command\n redo: Command\n}\n\n/**\n * A piece of the editor: block types, marks, behaviour and menu entries.\n * The built-in blocks are extensions too (see `editorKit`).\n */\nexport interface EditorExtension {\n name: string\n /** Higher runs first: its keys, input rules and plugins win. Defaults to 100. */\n priority?: number\n /**\n * Content node specs for new block types, by type name. They join the\n * `blockContent` group. Extra spec fields the editor reads:\n * `continues` (Enter continues the same type, like a list) and\n * `component` (a Vue component that renders the block).\n */\n blocks?: Record<string, NodeSpec>\n /**\n * Nodes that only live inside the extension's blocks, e.g. a table's\n * rows and cells. They join no group.\n */\n nodes?: Record<string, NodeSpec>\n /** Inline nodes, e.g. a mention. */\n inlines?: Record<string, NodeSpec>\n marks?: Record<string, MarkSpec>\n nodeViews?: Record<string, NodeViewConstructor>\n /**\n * Node views that draw Vue components, by node type. Each is made with\n * `mount`, which renders a component into an element inside the editor's\n * app, so it can call `useEditor()` and follows the ConfigProvider.\n */\n componentViews?: Record<string, (mount: MountComponent) => NodeViewConstructor>\n inputRules?: (context: EditorExtensionContext) => InputRule[]\n /**\n * Keys, written as in `useHotkey` (e.g. `mod+shift+h`, `shift+tab`,\n * `enter`), while the editor has focus. A command returning `false` lets\n * the key through to the next extension.\n */\n keymap?: (context: EditorExtensionContext) => Record<string, Command>\n plugins?: (context: EditorExtensionContext) => Plugin[]\n /**\n * The document lives outside the editor (e.g. in a Yjs document): the\n * initial `modelValue` and later outside changes to it are ignored, and\n * `v-model` only mirrors the document.\n */\n externalDocument?: boolean\n /** Replace the built-in undo history. Only one extension may. */\n history?: (context: EditorExtensionContext) => HistoryProvider\n /**\n * Keep the comment threads somewhere else than `v-model:comments`, e.g.\n * in a shared document. `v-model:comments` then only mirrors them.\n * Only one extension may.\n */\n comments?: (context: EditorExtensionContext) => CommentsProvider\n /** Entries for the slash menu and the “turn into” menus. */\n blockOptions?: BlockOption[]\n /** Toggles for the formatting toolbar. */\n formats?: FormatOption[]\n /**\n * Components rendered next to the editing area while it is editable,\n * e.g. a popup of suggestions. They can call `useEditor()`.\n */\n overlays?: Component[]\n /**\n * Controls added to the formatting toolbar, after the marks (e.g. a\n * color menu). They can call `useEditor()`.\n */\n toolbar?: Component[]\n /**\n * Entries added to the block menu of the handle, usually a\n * `DouDropdownSub` or `DouDropdownItem`s. Each gets the block the menu is\n * for as the `block` prop (a `Block`) and can call `useEditor()`.\n */\n blockMenu?: Component[]\n /**\n * How the extension's blocks, inline nodes and marks are written as HTML\n * and Markdown (`blocksToHTML`, `blocksToMarkdown`).\n */\n output?: EditorExtensionOutput\n /**\n * Rewrite HTML before it is read as blocks (when pasting, and in\n * `htmlToBlocks` and `markdownToBlocks`), e.g. turn a `<details>`\n * element into a toggle with its children. `blockElement` and\n * `splitContainer` help build the editor's markup.\n */\n prepareHTML?: (root: HTMLElement) => void\n}\n\n/**\n * Renders `component` into `element` with `props` (a reactive object stays\n * live), inside the editor's app. Returns a function that removes it.\n */\nexport type MountComponent = (\n component: Component,\n props: Record<string, unknown>,\n element: HTMLElement,\n) => () => void\n\n/** Declare an extension; only gives it a type. */\nexport function defineEditorExtension(extension: EditorExtension): EditorExtension {\n return extension\n}\n\n/** Everything the extensions contribute, gathered once per list of extensions. */\nexport interface ResolvedEditorExtensions {\n extensions: EditorExtension[]\n schema: Schema\n context: EditorExtensionContext\n nodeViews: Record<string, NodeViewConstructor>\n componentViews: Record<string, (mount: MountComponent) => NodeViewConstructor>\n blockOptions: BlockOption[]\n formats: FormatOption[]\n overlays: Component[]\n toolbar: Component[]\n blockMenu: Component[]\n inputRules: InputRule[]\n keymaps: Record<string, Command>[]\n plugins: Plugin[]\n history: HistoryProvider | null\n comments: CommentsProvider | null\n externalDocument: boolean\n}\n\nconst PM_KEYS: Record<string, string> = {\n ' ': 'Space',\n arrowup: 'ArrowUp',\n arrowdown: 'ArrowDown',\n arrowleft: 'ArrowLeft',\n arrowright: 'ArrowRight',\n pageup: 'PageUp',\n pagedown: 'PageDown',\n}\nconst PM_MODIFIERS: Record<string, string> = {\n mod: 'Mod',\n ctrl: 'Ctrl',\n alt: 'Alt',\n meta: 'Meta',\n shift: 'Shift',\n}\n\n/** `mod+shift+h` → `Mod-Shift-h`, the way the ProseMirror keymap names keys. */\nexport function toEditorKey(hotkey: string): string {\n const steps = parseHotkey(hotkey)\n if (steps.length !== 1)\n throw new Error(`[@dou-ui/editor] key sequences aren't supported in a keymap: \"${hotkey}\"`)\n const keys = steps[0]!\n const modifiers = Object.keys(PM_MODIFIERS)\n .filter((name) => keys.includes(name))\n .map((name) => PM_MODIFIERS[name])\n const key = keys.find((name) => !(name in PM_MODIFIERS)) ?? ''\n const name = PM_KEYS[key] ?? (key.length > 1 ? key[0]!.toUpperCase() + key.slice(1) : key)\n return [...modifiers, name].join('-')\n}\n\nconst toEditorKeymap = (bindings: Record<string, Command>) =>\n Object.fromEntries(Object.entries(bindings).map(([key, command]) => [toEditorKey(key), command]))\n\nfunction flatten(list: readonly (EditorExtension | EditorExtension[])[]): EditorExtension[] {\n const result: EditorExtension[] = []\n for (const item of list) {\n if (Array.isArray(item)) result.push(...flatten(item))\n else result.push(item)\n }\n return result\n}\n\nfunction merge<T>(\n target: Record<string, T>,\n source: Record<string, T> | undefined,\n what: string,\n owner: string,\n) {\n for (const [name, value] of Object.entries(source ?? {})) {\n if (name in target)\n throw new Error(`[@dou-ui/editor] ${what} \"${name}\" from \"${owner}\" is already defined`)\n target[name] = value\n }\n}\n\n/** Sort the extensions by priority, build the schema and collect what they add. */\nexport function resolveEditorExtensions(\n list: readonly (EditorExtension | EditorExtension[])[],\n messages: () => EditorMessages = () => editorLocales['zh-CN']!,\n): ResolvedEditorExtensions {\n const extensions = flatten(list)\n .map((extension, index) => ({ extension, index }))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n .sort(\n (a, b) => (b.extension.priority ?? 100) - (a.extension.priority ?? 100) || a.index - b.index,\n )\n .map((entry) => entry.extension)\n\n const names = new Set<string>()\n const blocks: Record<string, NodeSpec> = {}\n const nodes: Record<string, NodeSpec> = {}\n const inlines: Record<string, NodeSpec> = {}\n const marks: Record<string, MarkSpec> = {}\n for (const extension of extensions) {\n if (names.has(extension.name))\n throw new Error(`[@dou-ui/editor] the extension \"${extension.name}\" is added twice`)\n names.add(extension.name)\n merge(blocks, extension.blocks, 'block type', extension.name)\n merge(nodes, extension.nodes, 'node', extension.name)\n merge(inlines, extension.inlines, 'inline node', extension.name)\n merge(marks, extension.marks, 'mark', extension.name)\n }\n const schema = createSchema({ blocks, nodes, inlines, marks })\n const context: EditorExtensionContext = { schema, messages }\n\n const providers = extensions.filter((extension) => extension.history)\n if (providers.length > 1)\n throw new Error('[@dou-ui/editor] only one extension may replace the undo history')\n\n const keepers = extensions.filter((extension) => extension.comments)\n if (keepers.length > 1)\n throw new Error('[@dou-ui/editor] only one extension may keep the comment threads')\n\n return {\n extensions,\n schema,\n context,\n nodeViews: Object.assign({}, ...extensions.map((extension) => extension.nodeViews ?? {})),\n componentViews: Object.assign(\n {},\n ...extensions.map((extension) => extension.componentViews ?? {}),\n ),\n blockOptions: extensions.flatMap((extension) => extension.blockOptions ?? []),\n formats: extensions.flatMap((extension) => extension.formats ?? []),\n overlays: extensions.flatMap((extension) => extension.overlays ?? []),\n toolbar: extensions.flatMap((extension) => extension.toolbar ?? []),\n blockMenu: extensions.flatMap((extension) => extension.blockMenu ?? []),\n inputRules: extensions.flatMap((extension) => extension.inputRules?.(context) ?? []),\n keymaps: extensions.flatMap((extension) =>\n extension.keymap ? [toEditorKeymap(extension.keymap(context))] : [],\n ),\n plugins: extensions.flatMap((extension) => extension.plugins?.(context) ?? []),\n history: providers[0]?.history?.(context) ?? null,\n comments: keepers[0]?.comments?.(context) ?? null,\n externalDocument: extensions.some((extension) => extension.externalDocument),\n }\n}\n"],"mappings":";;;;AAcA,IAAa,WAAW,OAA0B,aAChD,OAAO,UAA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,OAAO,CAAC,GAAG,GAAG,WAAW,KAAK,cAAc,UAAU,aAAa,CAAC,CAAC,CAAC;EACxF,gBAAgB,OAAO,OACrB,CAAC,GACD,GAAG,WAAW,KAAK,cAAc,UAAU,kBAAkB,CAAC,CAAC,CACjE;EACA,cAAc,WAAW,SAAS,cAAc,UAAU,gBAAgB,CAAC,CAAC;EAC5E,SAAS,WAAW,SAAS,cAAc,UAAU,WAAW,CAAC,CAAC;EAClE,UAAU,WAAW,SAAS,cAAc,UAAU,YAAY,CAAC,CAAC;EACpE,SAAS,WAAW,SAAS,cAAc,UAAU,WAAW,CAAC,CAAC;EAClE,WAAW,WAAW,SAAS,cAAc,UAAU,aAAa,CAAC,CAAC;EACtE,YAAY,WAAW,SAAS,cAAc,UAAU,aAAa,OAAO,KAAK,CAAC,CAAC;EACnF,SAAS,WAAW,SAAS,cAC3B,UAAU,SAAS,CAAC,eAAe,UAAU,OAAO,OAAO,CAAC,CAAC,IAAI,CAAC,CACpE;EACA,SAAS,WAAW,SAAS,cAAc,UAAU,UAAU,OAAO,KAAK,CAAC,CAAC;EAC7E,SAAS,UAAU,EAAE,EAAE,UAAU,OAAO,KAAK;EAC7C,UAAU,QAAQ,EAAE,EAAE,WAAW,OAAO,KAAK;EAC7C,kBAAkB,WAAW,MAAM,cAAc,UAAU,gBAAgB;CAC7E;AACF"}
1
+ {"version":3,"file":"extension.js","names":[],"sources":["../../src/core/extension.ts"],"sourcesContent":["import type { InputRule } from 'prosemirror-inputrules'\nimport type { MarkSpec, NodeSpec, Schema } from 'prosemirror-model'\nimport type { Command, Plugin } from 'prosemirror-state'\nimport type { NodeViewConstructor } from 'prosemirror-view'\nimport { parseHotkey, type CommentAction, type CommentThread } from 'dou-ui'\nimport type { Component, Ref } from 'vue'\nimport { editorLocales, type EditorMessages } from '../locale'\nimport type { BlockProps } from './model'\nimport type { EditorExtensionOutput } from './output'\nimport { createSchema } from './schema'\n\n/** Text shown in a menu: fixed, or read from the editor's messages so it follows the locale. */\nexport type Label = string | ((messages: EditorMessages) => string)\n\nexport const labelOf = (label: Label | undefined, messages: EditorMessages) =>\n typeof label === 'function' ? label(messages) : (label ?? '')\n\n/** An entry of the slash menu and of the “turn into” menus. */\nexport interface BlockOption {\n /** Unique among the options. */\n key: string\n /** The block type it inserts or turns blocks into. */\n type: string\n props?: BlockProps\n label: Label\n /** A short description under the label in the slash menu. */\n hint?: Label\n icon: Component\n /** Extra words the slash menu matches, besides the label (pinyin works well). */\n keywords?: string[]\n /** The Markdown shortcut, shown as a hint. */\n shortcut?: string\n /**\n * Variants to pick from in a panel beside the option in the slash menu,\n * e.g. how many columns. Choosing the option itself inserts the first.\n */\n choices?: BlockOptionChoices\n}\n\n/** One variant of a slash menu option. */\nexport interface BlockOptionChoice {\n /** The props it inserts with, over the option's own. */\n props: BlockProps\n /** Its name, also read out by screen readers. */\n label: Label\n}\n\n/** The variants of a slash menu option, picked in a panel beside it. */\nexport interface BlockOptionChoices {\n /** The panel's title, e.g. “Number of columns”; also the name screen readers give the panel. */\n title: Label\n items: BlockOptionChoice[]\n /**\n * Draws the variants (the panel around them and its title are drawn by\n * the menu). It gets the props in `BlockOptionChoicesProps` and emits\n * `hover` and `choose` with an index, as in `BlockOptionChoicesEmits`.\n * Without it, the panel lists their names.\n */\n component?: Component<BlockOptionChoicesProps>\n}\n\n/** What the `component` of `BlockOptionChoices` gets. */\nexport interface BlockOptionChoicesProps {\n items: BlockOptionChoice[]\n /** The index of the highlighted variant; -1 while the option itself is highlighted. */\n active: number\n messages: EditorMessages\n /**\n * For screen readers: give the element of variant `index` the id\n * `${idPrefix}-${index}` and `role=\"option\"` (with `aria-selected`), so\n * the editor can point at the highlighted one.\n */\n idPrefix: string\n}\n\n/** What the `component` of `BlockOptionChoices` emits. */\nexport interface BlockOptionChoicesEmits {\n /** The pointer is on variant `index`. */\n hover: [index: number]\n /** Variant `index` is picked: the menu inserts it. */\n choose: [index: number]\n}\n\n/** A toggle in the formatting toolbar for a mark. */\nexport interface FormatOption {\n mark: string\n label: Label\n icon: Component\n /** The shortcut shown in its tooltip, written as in `useHotkey`, e.g. `mod+b`. */\n hotkey?: string\n}\n\n/** Where the comment threads live, when not in `v-model:comments`. */\nexport interface CommentsProvider {\n /** The threads, kept up to date. */\n threads: Readonly<Ref<readonly CommentThread[]>>\n /** Make a change this user asked for. */\n apply: (action: CommentAction) => void\n}\n\nexport interface EditorExtensionContext {\n schema: Schema\n /**\n * The editor's messages, in its current locale, for text a plugin puts\n * in the document's markup (e.g. a name for screen readers). Outside an\n * editor (converting documents) the Chinese ones.\n */\n messages: () => EditorMessages\n}\n\n/** What the extension replacing the undo history provides (e.g. collaboration). */\nexport interface HistoryProvider {\n plugins: Plugin[]\n undo: Command\n redo: Command\n}\n\n/**\n * A piece of the editor: block types, marks, behaviour and menu entries.\n * The built-in blocks are extensions too (see `editorKit`).\n */\nexport interface EditorExtension {\n name: string\n /** Higher runs first: its keys, input rules and plugins win. Defaults to 100. */\n priority?: number\n /**\n * Content node specs for new block types, by type name. They join the\n * `blockContent` group. Extra spec fields the editor reads:\n * `continues` (Enter continues the same type, like a list),\n * `component` (a Vue component that renders the block) and\n * `mergeProps` (props holding lists of `{ id }` items that collaboration\n * merges item by item, by prop name: the fields that are such lists,\n * e.g. `{ board: ['nodes', 'edges'] }`).\n */\n blocks?: Record<string, NodeSpec>\n /**\n * Nodes that only live inside the extension's blocks, e.g. a table's\n * rows and cells. They join no group.\n */\n nodes?: Record<string, NodeSpec>\n /** Inline nodes, e.g. a mention. */\n inlines?: Record<string, NodeSpec>\n marks?: Record<string, MarkSpec>\n nodeViews?: Record<string, NodeViewConstructor>\n /**\n * Node views that draw Vue components, by node type. Each is made with\n * `mount`, which renders a component into an element inside the editor's\n * app, so it can call `useEditor()` and follows the ConfigProvider.\n */\n componentViews?: Record<string, (mount: MountComponent) => NodeViewConstructor>\n inputRules?: (context: EditorExtensionContext) => InputRule[]\n /**\n * Keys, written as in `useHotkey` (e.g. `mod+shift+h`, `shift+tab`,\n * `enter`), while the editor has focus. A command returning `false` lets\n * the key through to the next extension.\n */\n keymap?: (context: EditorExtensionContext) => Record<string, Command>\n plugins?: (context: EditorExtensionContext) => Plugin[]\n /**\n * The document lives outside the editor (e.g. in a Yjs document): the\n * initial `modelValue` and later outside changes to it are ignored, and\n * `v-model` only mirrors the document.\n */\n externalDocument?: boolean\n /** Replace the built-in undo history. Only one extension may. */\n history?: (context: EditorExtensionContext) => HistoryProvider\n /**\n * Keep the comment threads somewhere else than `v-model:comments`, e.g.\n * in a shared document. `v-model:comments` then only mirrors them.\n * Only one extension may.\n */\n comments?: (context: EditorExtensionContext) => CommentsProvider\n /** Entries for the slash menu and the “turn into” menus. */\n blockOptions?: BlockOption[]\n /** Toggles for the formatting toolbar. */\n formats?: FormatOption[]\n /**\n * Components rendered next to the editing area while it is editable,\n * e.g. a popup of suggestions. They can call `useEditor()`.\n */\n overlays?: Component[]\n /**\n * Controls added to the formatting toolbar, after the marks (e.g. a\n * color menu). They can call `useEditor()`.\n */\n toolbar?: Component[]\n /**\n * Entries added to the block menu of the handle, usually a\n * `DouDropdownSub` or `DouDropdownItem`s. Each gets the block the menu is\n * for as the `block` prop (a `Block`) and can call `useEditor()`.\n */\n blockMenu?: Component[]\n /**\n * How the extension's blocks, inline nodes and marks are written as HTML\n * and Markdown (`blocksToHTML`, `blocksToMarkdown`).\n */\n output?: EditorExtensionOutput\n /**\n * Rewrite HTML before it is read as blocks (when pasting, and in\n * `htmlToBlocks` and `markdownToBlocks`), e.g. turn a `<details>`\n * element into a toggle with its children. `blockElement` and\n * `splitContainer` help build the editor's markup.\n */\n prepareHTML?: (root: HTMLElement) => void\n}\n\n/**\n * Renders `component` into `element` with `props` (a reactive object stays\n * live), inside the editor's app. Returns a function that removes it.\n */\nexport type MountComponent = (\n component: Component,\n props: Record<string, unknown>,\n element: HTMLElement,\n) => () => void\n\n/** Declare an extension; only gives it a type. */\nexport function defineEditorExtension(extension: EditorExtension): EditorExtension {\n return extension\n}\n\n/** Everything the extensions contribute, gathered once per list of extensions. */\nexport interface ResolvedEditorExtensions {\n extensions: EditorExtension[]\n schema: Schema\n context: EditorExtensionContext\n nodeViews: Record<string, NodeViewConstructor>\n componentViews: Record<string, (mount: MountComponent) => NodeViewConstructor>\n blockOptions: BlockOption[]\n formats: FormatOption[]\n overlays: Component[]\n toolbar: Component[]\n blockMenu: Component[]\n inputRules: InputRule[]\n keymaps: Record<string, Command>[]\n plugins: Plugin[]\n history: HistoryProvider | null\n comments: CommentsProvider | null\n externalDocument: boolean\n}\n\nconst PM_KEYS: Record<string, string> = {\n ' ': 'Space',\n arrowup: 'ArrowUp',\n arrowdown: 'ArrowDown',\n arrowleft: 'ArrowLeft',\n arrowright: 'ArrowRight',\n pageup: 'PageUp',\n pagedown: 'PageDown',\n}\nconst PM_MODIFIERS: Record<string, string> = {\n mod: 'Mod',\n ctrl: 'Ctrl',\n alt: 'Alt',\n meta: 'Meta',\n shift: 'Shift',\n}\n\n/** `mod+shift+h` → `Mod-Shift-h`, the way the ProseMirror keymap names keys. */\nexport function toEditorKey(hotkey: string): string {\n const steps = parseHotkey(hotkey)\n if (steps.length !== 1)\n throw new Error(`[@dou-ui/editor] key sequences aren't supported in a keymap: \"${hotkey}\"`)\n const keys = steps[0]!\n const modifiers = Object.keys(PM_MODIFIERS)\n .filter((name) => keys.includes(name))\n .map((name) => PM_MODIFIERS[name])\n const key = keys.find((name) => !(name in PM_MODIFIERS)) ?? ''\n const name = PM_KEYS[key] ?? (key.length > 1 ? key[0]!.toUpperCase() + key.slice(1) : key)\n return [...modifiers, name].join('-')\n}\n\nconst toEditorKeymap = (bindings: Record<string, Command>) =>\n Object.fromEntries(Object.entries(bindings).map(([key, command]) => [toEditorKey(key), command]))\n\nfunction flatten(list: readonly (EditorExtension | EditorExtension[])[]): EditorExtension[] {\n const result: EditorExtension[] = []\n for (const item of list) {\n if (Array.isArray(item)) result.push(...flatten(item))\n else result.push(item)\n }\n return result\n}\n\nfunction merge<T>(\n target: Record<string, T>,\n source: Record<string, T> | undefined,\n what: string,\n owner: string,\n) {\n for (const [name, value] of Object.entries(source ?? {})) {\n if (name in target)\n throw new Error(`[@dou-ui/editor] ${what} \"${name}\" from \"${owner}\" is already defined`)\n target[name] = value\n }\n}\n\n/** Sort the extensions by priority, build the schema and collect what they add. */\nexport function resolveEditorExtensions(\n list: readonly (EditorExtension | EditorExtension[])[],\n messages: () => EditorMessages = () => editorLocales['zh-CN']!,\n): ResolvedEditorExtensions {\n const extensions = flatten(list)\n .map((extension, index) => ({ extension, index }))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n .sort(\n (a, b) => (b.extension.priority ?? 100) - (a.extension.priority ?? 100) || a.index - b.index,\n )\n .map((entry) => entry.extension)\n\n const names = new Set<string>()\n const blocks: Record<string, NodeSpec> = {}\n const nodes: Record<string, NodeSpec> = {}\n const inlines: Record<string, NodeSpec> = {}\n const marks: Record<string, MarkSpec> = {}\n for (const extension of extensions) {\n if (names.has(extension.name))\n throw new Error(`[@dou-ui/editor] the extension \"${extension.name}\" is added twice`)\n names.add(extension.name)\n merge(blocks, extension.blocks, 'block type', extension.name)\n merge(nodes, extension.nodes, 'node', extension.name)\n merge(inlines, extension.inlines, 'inline node', extension.name)\n merge(marks, extension.marks, 'mark', extension.name)\n }\n const schema = createSchema({ blocks, nodes, inlines, marks })\n const context: EditorExtensionContext = { schema, messages }\n\n const providers = extensions.filter((extension) => extension.history)\n if (providers.length > 1)\n throw new Error('[@dou-ui/editor] only one extension may replace the undo history')\n\n const keepers = extensions.filter((extension) => extension.comments)\n if (keepers.length > 1)\n throw new Error('[@dou-ui/editor] only one extension may keep the comment threads')\n\n return {\n extensions,\n schema,\n context,\n nodeViews: Object.assign({}, ...extensions.map((extension) => extension.nodeViews ?? {})),\n componentViews: Object.assign(\n {},\n ...extensions.map((extension) => extension.componentViews ?? {}),\n ),\n blockOptions: extensions.flatMap((extension) => extension.blockOptions ?? []),\n formats: extensions.flatMap((extension) => extension.formats ?? []),\n overlays: extensions.flatMap((extension) => extension.overlays ?? []),\n toolbar: extensions.flatMap((extension) => extension.toolbar ?? []),\n blockMenu: extensions.flatMap((extension) => extension.blockMenu ?? []),\n inputRules: extensions.flatMap((extension) => extension.inputRules?.(context) ?? []),\n keymaps: extensions.flatMap((extension) =>\n extension.keymap ? [toEditorKeymap(extension.keymap(context))] : [],\n ),\n plugins: extensions.flatMap((extension) => extension.plugins?.(context) ?? []),\n history: providers[0]?.history?.(context) ?? null,\n comments: keepers[0]?.comments?.(context) ?? null,\n externalDocument: extensions.some((extension) => extension.externalDocument),\n }\n}\n"],"mappings":";;;;AAcA,IAAa,WAAW,OAA0B,aAChD,OAAO,UAAU,aAAa,MAAM,QAAQ,IAAK,SAAS;;AA0M5D,SAAgB,sBAAsB,WAA6C;CACjF,OAAO;AACT;AAsBA,IAAM,UAAkC;CACtC,KAAK;CACL,SAAS;CACT,WAAW;CACX,WAAW;CACX,YAAY;CACZ,QAAQ;CACR,UAAU;AACZ;AACA,IAAM,eAAuC;CAC3C,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACN,OAAO;AACT;;AAGA,SAAgB,YAAY,QAAwB;CAClD,MAAM,QAAQ,YAAY,MAAM;CAChC,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,MAAM,iEAAiE,OAAO,EAAE;CAC5F,MAAM,OAAO,MAAM;CACnB,MAAM,YAAY,OAAO,KAAK,YAAY,CAAC,CACxC,QAAQ,SAAS,KAAK,SAAS,IAAI,CAAC,CAAC,CACrC,KAAK,SAAS,aAAa,KAAK;CACnC,MAAM,MAAM,KAAK,MAAM,SAAS,EAAE,QAAQ,aAAa,KAAK;CAC5D,MAAM,OAAO,QAAQ,SAAS,IAAI,SAAS,IAAI,IAAI,EAAE,CAAE,YAAY,IAAI,IAAI,MAAM,CAAC,IAAI;CACtF,OAAO,CAAC,GAAG,WAAW,IAAI,CAAC,CAAC,KAAK,GAAG;AACtC;AAEA,IAAM,kBAAkB,aACtB,O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cAAc,UAAU,gBAAgB;CAC7E;AACF"}
@@ -1,4 +1,5 @@
1
1
  import { isColor } from "./colors.js";
2
+ import { toRaw } from "vue";
2
3
  import { Mark } from "prosemirror-model";
3
4
  // src/core/model.ts
4
5
  var MARK_ORDER = [
@@ -162,7 +163,7 @@ function inlineNodes(schema, content, code) {
162
163
  */
163
164
  function contentAttrs(type, props = {}) {
164
165
  const attrs = {};
165
- for (const name of Object.keys(type.spec.attrs ?? {})) if (props[name] !== void 0) attrs[name] = props[name];
166
+ for (const name of Object.keys(type.spec.attrs ?? {})) if (props[name] !== void 0) attrs[name] = toRaw(props[name]);
166
167
  const normalize = type.spec.normalizeProps;
167
168
  return normalize ? normalize(attrs) : attrs;
168
169
  }