@dou-ui/code 0.1.0-alpha.21 → 0.1.0-alpha.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"code-diff.js","names":["_sfc_main"],"sources":["../src/code-diff.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n DiffSplitIcon,\n DiffUnifiedIcon,\n FoldVerticalIcon,\n UnfoldVerticalIcon,\n} from '@dou-ui/icons'\nimport { DouButton, DouTooltip, createScrollLink, useNamespace } from 'dou-ui'\nimport {\n type VNodeChild,\n computed,\n h,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n reactive,\n ref,\n watch,\n} from 'vue'\nimport CodeEditor from './code-editor.vue'\nimport RenderPart from './render-part'\nimport { type CodeDiffHunk, diffText, lineStarts } from './core/diff'\nimport type { CodeKeymap } from './core/keymap'\nimport type { CodeTransactionResult } from './core/transaction'\nimport { splitLines } from './core/text'\nimport {\n type CodeDecoration,\n type CodeExtension,\n type CodeGutterHoverMarker,\n type CodeGutterMarker,\n type CodeWidget,\n defineCodeExtension,\n WIDGET_HEIGHT_KEY,\n} from './extension'\nimport { format, useCodeMessages } from './locale'\nimport type {\n CodeDiffEmits,\n CodeDiffGutter,\n CodeDiffHoverMarker,\n CodeDiffProps,\n CodeDiffSide,\n CodeDiffWidget,\n CodeEditorExpose,\n} from './types'\n\n/**\n * Two texts compared: side by side, or the changes in one column. Changed\n * lines are tinted, the words that changed inside them marked, and long\n * runs of unchanged lines hidden behind a bar that shows them.\n */\ndefineOptions({ name: 'DouCodeDiff' })\n\nconst props = withDefaults(defineProps<CodeDiffProps>(), {\n original: '',\n modelValue: '',\n language: undefined,\n mode: 'auto',\n editable: false,\n collapseUnchanged: true,\n ignoreWhitespace: false,\n words: true,\n wrap: false,\n extensions: undefined,\n gutters: undefined,\n widgets: undefined,\n tabSize: 2,\n toolbar: true,\n bordered: true,\n messages: undefined,\n})\nconst emit = defineEmits<CodeDiffEmits>()\n\nconst ns = useNamespace('code-diff')\nconst messages = useCodeMessages(() => props.messages)\n\n// ---------------------------------------------------------------- view\n\nconst root = ref<HTMLElement>()\n/** Whether the box is wide enough for two columns. */\nconst roomy = ref(true)\n/** The view picked with the toggle, when `mode` isn't bound. */\nconst picked = ref<'split' | 'inline' | null>(null)\nwatch(\n () => props.mode,\n () => (picked.value = null),\n)\nconst view = computed<'split' | 'inline'>(() => {\n if (picked.value) return picked.value\n if (props.mode !== 'auto') return props.mode\n return roomy.value ? 'split' : 'inline'\n})\nfunction toggleView() {\n const other = view.value === 'split' ? 'inline' : 'split'\n picked.value = other\n emit('update:mode', other)\n}\n\n/** Below this, each side would show fewer than about 30 columns: one column reads better. */\nconst SPLIT_WIDTH = 560\n\nlet resize: ResizeObserver | undefined\nonMounted(() => {\n if (typeof ResizeObserver === 'undefined' || !root.value) return\n resize = new ResizeObserver(([entry]) => {\n if (entry) roomy.value = entry.contentRect.width >= SPLIT_WIDTH\n })\n resize.observe(root.value)\n})\nonBeforeUnmount(() => resize?.disconnect())\n\n// ---------------------------------------------------------------- texts and changes\n\n/** The modified text as edited here, ahead of the parent's copy. */\nconst modified = ref(props.modelValue)\nwatch(\n () => props.modelValue,\n (value) => (modified.value = value),\n)\nfunction onModifiedInput(value: string) {\n modified.value = value\n emit('update:modelValue', value)\n}\n\nconst hunks = computed<CodeDiffHunk[]>(() =>\n diffText(props.original, modified.value, {\n ignoreWhitespace: props.ignoreWhitespace,\n words: props.words,\n }),\n)\nconst originalLines = computed(() => splitLines(props.original))\nconst modifiedLines = computed(() => splitLines(modified.value))\n\nconst stats = computed(() => {\n let added = 0\n let removed = 0\n for (const hunk of hunks.value) {\n added += hunk.modifiedCount\n removed += hunk.originalCount\n }\n return { added, removed }\n})\n\n// ---------------------------------------------------------------- unchanged lines\n\ninterface Unchanged {\n /** First line on each side, from 1. */\n a: number\n b: number\n count: number\n /** Where its hidden part starts, from its first line, and how long it is (0 when nothing is hidden). */\n hideFrom: number\n hideCount: number\n /** Stays the same while the modified text is edited. */\n key: number\n}\n\nconst collapse = computed(() => {\n const option = props.collapseUnchanged\n if (!option) return null\n const own = option === true ? {} : option\n return {\n context: Math.max(1, Math.floor(own.context ?? 3)),\n minLines: Math.max(1, Math.floor(own.minLines ?? 4)),\n }\n})\n/** The runs of unchanged lines opened with their bar, by key; `true` for all of them. */\nconst opened = reactive(new Set<number>())\nconst allOpen = ref(false)\n\n/**\n * The lines with a marker or widget on each side, which collapsing leaves in\n * view. A marker shown only on hover is out of sight, so it doesn't count.\n */\nconst annotatedLines = computed(() => {\n const out = { a: new Set<number>(), b: new Set<number>() }\n const add = (side: CodeDiffSide, line: number) => out[side === 'original' ? 'a' : 'b'].add(line)\n for (const gutter of props.gutters ?? [])\n for (const marker of gutter.markers ?? [])\n if (marker.visible !== 'hover') add(marker.side, marker.line)\n for (const widget of props.widgets ?? []) add(widget.side, widget.line)\n return out\n})\n\nconst unchanged = computed<Unchanged[]>(() => {\n const list = hunks.value\n const total = originalLines.value.length\n const out: Unchanged[] = []\n const rule = collapse.value\n const push = (a: number, b: number, count: number, before: boolean, after: boolean) => {\n if (count <= 0) return\n let hideFrom = 0\n let hideCount = 0\n if (rule && list.length && !allOpen.value && !opened.has(a)) {\n const from = before ? rule.context : 0\n const to = count - (after ? rule.context : 0)\n if (to - from >= rule.minLines) {\n hideFrom = from\n hideCount = to - from\n }\n }\n out.push({ a, b, count, hideFrom, hideCount, key: a })\n }\n // A line with a marker or widget stays in view, with context around it, like a change.\n const kept = annotatedLines.value\n const cut = (a: number, b: number, count: number, before: boolean, after: boolean) => {\n let from = 0\n for (let i = 0; i < count; i++) {\n if (!kept.a.has(a + i) && !kept.b.has(b + i)) continue\n if (i > from) push(a + from, b + from, i - from, from > 0 || before, true)\n from = Math.max(from, i)\n }\n push(a + from, b + from, count - from, from > 0 || before, after)\n }\n let a = 1\n let b = 1\n for (let i = 0; i < list.length; i++) {\n const hunk = list[i]!\n cut(a, b, hunk.originalStart - a, i > 0, true)\n a = hunk.originalStart + hunk.originalCount\n b = hunk.modifiedStart + hunk.modifiedCount\n }\n cut(a, b, total - a + 1, list.length > 0, false)\n return out\n})\nconst hiddenCount = computed(() => unchanged.value.reduce((sum, run) => sum + run.hideCount, 0))\nconst anyHideable = computed(() => !!collapse.value && hunks.value.length > 0)\n\nfunction open(key: number) {\n opened.add(key)\n}\nfunction toggleAll() {\n if (hiddenCount.value) allOpen.value = true\n else {\n allOpen.value = false\n opened.clear()\n }\n}\n// A new pair of texts starts collapsed again.\nwatch(\n () => props.original,\n () => {\n allOpen.value = false\n opened.clear()\n },\n)\n\n/**\n * The bar over a run of hidden lines. Side by side, the original's bar\n * mirrors the modified one's: pressed with a pointer, but left out of the\n * keyboard order and of what is read out, so the run is one stop, not two.\n */\nfunction bar(run: Unchanged, mirror = false) {\n const label = format(messages.value.diffUnchanged, { count: run.hideCount })\n return h(\n 'button',\n {\n type: 'button',\n class: ns.e('bar'),\n 'aria-label': `${messages.value.unfold}:${label}`,\n 'aria-hidden': mirror ? 'true' : undefined,\n tabindex: mirror ? -1 : undefined,\n onClick: () => open(run.key),\n },\n [h(UnfoldVerticalIcon, { class: ns.e('bar-icon') }), h('span', label)],\n )\n}\nconst BAR_HEIGHT = 28\n\n// ---------------------------------------------------------------- side by side\n\ntype Side = 'a' | 'b'\n\n/** What one side of the split view draws: tints, marks, fillers, hidden lines and bars. */\nfunction sideExtension(side: Side): CodeExtension {\n const startOf = (hunk: CodeDiffHunk) => (side === 'a' ? hunk.originalStart : hunk.modifiedStart)\n const countOf = (hunk: CodeDiffHunk) => (side === 'a' ? hunk.originalCount : hunk.modifiedCount)\n const otherCountOf = (hunk: CodeDiffHunk) =>\n side === 'a' ? hunk.modifiedCount : hunk.originalCount\n const tone = side === 'a' ? 'removed' : 'added'\n\n return defineCodeExtension({\n name: 'diff',\n decorations({ visible }) {\n const out: CodeDecoration[] = []\n for (const hunk of hunks.value) {\n const start = startOf(hunk)\n const count = countOf(hunk)\n if (start > visible.to) break\n if (!count || start + count - 1 < visible.from) continue\n const from = Math.max(start, visible.from)\n const to = Math.min(start + count - 1, visible.to)\n for (let n = from; n <= to; n++)\n out.push({ type: 'line', line: n, class: `${ns.e('line')} is-${tone}` })\n for (const part of hunk.parts) {\n const range = side === 'a' ? part.original : part.modified\n if (range.to > range.from)\n out.push({\n type: 'mark',\n from: range.from,\n to: range.to,\n class: `${ns.e('word')} is-${tone}`,\n })\n }\n }\n return out\n },\n widgets() {\n const out: CodeWidget[] = []\n const fills = splitPlan.value[side].fills\n hunks.value.forEach((hunk, i) => {\n const missing = otherCountOf(hunk) - countOf(hunk)\n if (missing <= 0) return\n const last = startOf(hunk) - 1 + countOf(hunk)\n const blanks = fills.get(i) ?? []\n out.push({\n // the height in the id: the editor never keeps a size measured before blanks changed\n id: `fill-${i}-${missing}-${blanks.map((blank) => blank.height).join('.')}`,\n ...(last >= 1 ? { line: last } : { line: 1, position: 'above' as const }),\n height: missing * LINE + blanks.reduce((sum, blank) => sum + blank.height, 0),\n render: () => filler(missing, blanks),\n })\n })\n const total = side === 'a' ? originalLines.value.length : modifiedLines.value.length\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const first = (side === 'a' ? run.a : run.b) + run.hideFrom\n const last = first + run.hideCount - 1\n out.push({\n id: `bar-${run.key}`,\n ...(last < total ? { line: last + 1, position: 'above' as const } : { line: first - 1 }),\n height: BAR_HEIGHT,\n render: () => bar(run, side === 'a'),\n })\n }\n return out\n },\n hide() {\n const out: Array<{ from: number; to: number }> = []\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const first = (side === 'a' ? run.a : run.b) + run.hideFrom\n out.push({ from: first, to: first + run.hideCount - 1 })\n }\n return out\n },\n })\n}\n\n/** Rows of filler, or rows split by the blanks of widgets on the other side. */\nconst block = (count: number) =>\n h('div', {\n class: ns.e('filler'),\n style: { height: `calc(${count} * var(--dou-code-editor-line-height))` },\n })\nfunction filler(rows: number, blanks: Blank[]) {\n if (!blanks.length) return block(rows)\n const children = []\n let at = 0\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n for (const blank of [...blanks].sort((x, y) => x.offset - y.offset || +x.above - +y.above)) {\n if (blank.offset > at) children.push(block(blank.offset - at))\n children.push(spacer(blank.height, blank.span)())\n at = Math.max(at, blank.offset)\n }\n if (rows > at) children.push(block(rows - at))\n return h('div', children)\n}\n\n/**\n * The `+`/`−` column of one side. It goes after every other extension, so it\n * is always the gutter's last column, next to the text: its tint spreads\n * over the whole gutter row from there (see style.css).\n */\nfunction signExtension(side: Side): CodeExtension {\n const startOf = (hunk: CodeDiffHunk) => (side === 'a' ? hunk.originalStart : hunk.modifiedStart)\n const countOf = (hunk: CodeDiffHunk) => (side === 'a' ? hunk.originalCount : hunk.modifiedCount)\n const tone = side === 'a' ? 'removed' : 'added'\n return defineCodeExtension({\n name: 'diff-sign',\n gutters: [\n {\n name: 'diff',\n width: 16,\n markers({ visible }) {\n const out: CodeGutterMarker[] = []\n const title = side === 'a' ? messages.value.diffRemoved : messages.value.diffAdded\n for (const hunk of hunks.value) {\n const start = startOf(hunk)\n const count = countOf(hunk)\n if (start > visible.to) break\n for (let n = Math.max(start, visible.from); n < start + count && n <= visible.to; n++)\n out.push({\n line: n,\n text: side === 'a' ? '−' : '+',\n class: `${ns.e('sign')} is-${tone}`,\n title,\n })\n }\n return out\n },\n },\n ],\n })\n}\n\nconst modifiedOwn = sideExtension('b')\nconst signB = signExtension('b')\nconst modifiedExtensions = computed(() => [\n annotationsB,\n modifiedOwn,\n annotationsEndB,\n ...(props.extensions ?? []),\n signB,\n])\n\nconst editorA = ref<CodeEditorExpose>()\nconst editorB = ref<CodeEditorExpose>()\nconst sideA = ref<HTMLElement>()\nconst sideB = ref<HTMLElement>()\nconst extensionsA = [\n annotations('a'),\n sideExtension('a'),\n annotations('a', true),\n signExtension('a'),\n]\nconst annotationsB = annotations('b')\nconst annotationsEndB = annotations('b', true)\n\n// Both sides scroll together; they are the same height, line for line.\nconst link = createScrollLink()\nfunction onScroll(event: Event) {\n if (view.value !== 'split') return\n if (spans.value.length) schedulePlace()\n const from = (event.target as HTMLElement).closest(`.${ns.e('side')}`)\n const source = from?.querySelector<HTMLElement>('.dou-code-editor__scroller')\n if (!source || source !== event.target) return\n const other = (from === sideA.value ? sideB.value : sideA.value)?.querySelector<HTMLElement>(\n '.dou-code-editor__scroller',\n )\n if (other) link.follow(source, other)\n}\n\n// ---------------------------------------------------------------- inline\n\nconst enum Kind {\n Same,\n Removed,\n Added,\n}\n\ninterface Unified {\n text: string\n kinds: Uint8Array\n /** Line numbers on each side, 0 where the line isn't there. */\n aNums: Int32Array\n bNums: Int32Array\n /** Where each line of each side is, from 1, by its number. */\n aRows: Int32Array\n bRows: Int32Array\n /** Where each change starts, from 1. */\n hunkLines: number[]\n /** Where each unchanged run starts, from 1, by key. */\n runLines: Map<number, number>\n marks: Array<{ from: number; to: number; kind: Kind }>\n}\n\nconst unified = computed<Unified | null>(() => {\n if (view.value !== 'inline') return null\n const a = originalLines.value\n const b = modifiedLines.value\n const lines: string[] = []\n const kinds: number[] = []\n const aNums: number[] = []\n const bNums: number[] = []\n const hunkLines: number[] = []\n const runLines = new Map<number, number>()\n const marks: Unified['marks'] = []\n const aRows = new Int32Array(a.length + 1)\n const bRows = new Int32Array(b.length + 1)\n let pos = 0\n const push = (text: string, kind: Kind, an: number, bn: number) => {\n lines.push(text)\n kinds.push(kind)\n aNums.push(an)\n bNums.push(bn)\n if (an) aRows[an] = lines.length\n if (bn) bRows[bn] = lines.length\n pos += text.length + 1\n }\n const runs = unchanged.value\n let r = 0\n const sameUpTo = (aEnd: number) => {\n while (r < runs.length && runs[r]!.a < aEnd) {\n const run = runs[r++]!\n runLines.set(run.key, lines.length + 1)\n for (let i = 0; i < run.count; i++) push(b[run.b - 1 + i]!, Kind.Same, run.a + i, run.b + i)\n }\n }\n // Where each original and modified line starts, for moving the word marks.\n const aStarts = lineStarts(a)\n const bStarts = lineStarts(b)\n for (const hunk of hunks.value) {\n sameUpTo(hunk.originalStart)\n hunkLines.push(lines.length + 1)\n const removedAt = pos\n for (let i = 0; i < hunk.originalCount; i++)\n push(a[hunk.originalStart - 1 + i]!, Kind.Removed, hunk.originalStart + i, 0)\n const addedAt = pos\n for (let i = 0; i < hunk.modifiedCount; i++)\n push(b[hunk.modifiedStart - 1 + i]!, Kind.Added, 0, hunk.modifiedStart + i)\n const aBase = aStarts[hunk.originalStart - 1]!\n const bBase = bStarts[hunk.modifiedStart - 1]!\n for (const part of hunk.parts) {\n if (part.original.to > part.original.from)\n marks.push({\n from: removedAt + part.original.from - aBase,\n to: removedAt + part.original.to - aBase,\n kind: Kind.Removed,\n })\n if (part.modified.to > part.modified.from)\n marks.push({\n from: addedAt + part.modified.from - bBase,\n to: addedAt + part.modified.to - bBase,\n kind: Kind.Added,\n })\n }\n }\n sameUpTo(Infinity)\n return {\n text: lines.join('\\n'),\n kinds: Uint8Array.from(kinds),\n aNums: Int32Array.from(aNums),\n bNums: Int32Array.from(bNums),\n aRows,\n bRows,\n hunkLines,\n runLines,\n marks,\n }\n})\n\nconst digits = (n: number) => String(Math.max(1, n)).length\nconst numberWidth = (n: number) => digits(n) * 8 + 16\n\n/** The line numbers of one side, in the inline view's gutter. */\nconst numbersOf =\n (pick: 'aNums' | 'bNums') =>\n ({ visible }: { visible: { from: number; to: number } }) => {\n const u = unified.value\n if (!u) return []\n const out: CodeGutterMarker[] = []\n const list = u[pick]\n for (let n = visible.from; n <= visible.to && n <= list.length; n++) {\n const value = list[n - 1]!\n const kind = u.kinds[n - 1]\n const tone = kind === Kind.Removed ? ' is-removed' : kind === Kind.Added ? ' is-added' : ''\n out.push({ line: n, text: value ? String(value) : '', class: `${ns.e('number')}${tone}` })\n }\n return out\n }\n\nconst inlineExtension = defineCodeExtension({\n name: 'diff',\n decorations({ visible }) {\n const u = unified.value\n if (!u) return []\n const out: CodeDecoration[] = []\n for (let n = visible.from; n <= visible.to && n <= u.kinds.length; n++) {\n const kind = u.kinds[n - 1]\n if (kind === Kind.Removed)\n out.push({ type: 'line', line: n, class: `${ns.e('line')} is-removed` })\n else if (kind === Kind.Added)\n out.push({ type: 'line', line: n, class: `${ns.e('line')} is-added` })\n }\n for (const mark of u.marks)\n out.push({\n type: 'mark',\n from: mark.from,\n to: mark.to,\n class: `${ns.e('word')} ${mark.kind === Kind.Removed ? 'is-removed' : 'is-added'}`,\n })\n return out\n },\n get gutters() {\n return [\n {\n name: 'diff-original',\n width: numberWidth(originalLines.value.length),\n markers: numbersOf('aNums'),\n },\n {\n name: 'diff-modified',\n width: numberWidth(modifiedLines.value.length),\n markers: numbersOf('bNums'),\n },\n {\n name: 'diff',\n width: 16,\n markers: ({ visible }: { visible: { from: number; to: number } }) => {\n const u = unified.value\n if (!u) return []\n const out: CodeGutterMarker[] = []\n for (let n = visible.from; n <= visible.to && n <= u.kinds.length; n++) {\n const kind = u.kinds[n - 1]\n if (kind === Kind.Removed)\n out.push({\n line: n,\n text: '−',\n class: `${ns.e('sign')} is-removed`,\n title: messages.value.diffRemoved,\n })\n else if (kind === Kind.Added)\n out.push({\n line: n,\n text: '+',\n class: `${ns.e('sign')} is-added`,\n title: messages.value.diffAdded,\n })\n }\n return out\n },\n },\n ]\n },\n widgets() {\n const u = unified.value\n if (!u) return []\n const total = u.kinds.length\n const out: CodeWidget[] = []\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const first = u.runLines.get(run.key)! + run.hideFrom\n const last = first + run.hideCount - 1\n out.push({\n id: `bar-${run.key}`,\n ...(last < total ? { line: last + 1, position: 'above' as const } : { line: first - 1 }),\n height: BAR_HEIGHT,\n render: () => bar(run),\n })\n }\n return out\n },\n hide() {\n const u = unified.value\n if (!u) return []\n const out: Array<{ from: number; to: number }> = []\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const first = u.runLines.get(run.key)! + run.hideFrom\n out.push({ from: first, to: first + run.hideCount - 1 })\n }\n return out\n },\n})\nconst inlineExtensions = [inlineAnnotations(), inlineExtension, inlineAnnotations(true)]\nconst editorInline = ref<CodeEditorExpose>()\nconst inlineBox = ref<HTMLElement>()\n\n// ---------------------------------------------------------------- markers and widgets of both texts\n\n/** One line's height, before the editors have measured theirs. */\nconst LINE = 20\nconst sideName = (side: Side): CodeDiffSide => (side === 'a' ? 'original' : 'modified')\n\n/** The widgets' measured heights, by id, for the blank left beside each. */\nconst heights = reactive(new Map<string, number>())\nlet heightObserver: ResizeObserver | undefined\n/** The element each widget's content is drawn in now, by id, and back. */\nconst measuredEls = new Map<string, Element>()\nconst measuredIds = new Map<Element, string>()\nfunction readHeight(box: Element, entry?: ResizeObserverEntry) {\n const id = measuredIds.get(box)\n // The size the observer saw: by the time it says so, the editor may have\n // moved on and taken the widget away, which leaves nothing to measure.\n const size = entry?.borderBoxSize?.[0]?.blockSize ?? entry?.contentRect.height\n const height = size === undefined ? (box as HTMLElement).offsetHeight : Math.round(size)\n // Nothing measured means no layout (hidden): keep the guess.\n if (id && height && heights.get(id) !== height) heights.set(id, height)\n}\nfunction forget(box: Element) {\n heightObserver?.unobserve(box)\n measuredIds.delete(box)\n}\n/** Measures a widget across both sides as drawn, now and whenever it resizes; `null` once it is gone. */\nfunction measure(el: Element | null, id: string) {\n const had = measuredEls.get(id)\n if (!el) {\n // the old element going after a new one came, e.g. on switching views, keeps the new one\n if (had && !had.isConnected) {\n forget(had)\n measuredEls.delete(id)\n }\n return\n }\n if (had === el) return\n if (had) forget(had)\n measuredEls.set(id, el)\n measuredIds.set(el, id)\n readHeight(el)\n if (typeof ResizeObserver === 'undefined') return\n heightObserver ??= new ResizeObserver((entries) => {\n for (const entry of entries) readHeight(entry.target, entry)\n })\n heightObserver.observe(el)\n}\nonBeforeUnmount(() => heightObserver?.disconnect())\n\nconst heightOf = (widget: CodeDiffWidget) => heights.get(widget.id) ?? widget.height ?? LINE\n\n// The editors measure the widgets they draw and say so here: one height for the widget and its blank.\nconst widgetIds = computed(() => new Set((props.widgets ?? []).map((widget) => widget.id)))\nprovide(WIDGET_HEIGHT_KEY, (key, height) => {\n if (!key.startsWith('diff-widgets')) return\n const id = key.slice(key.indexOf('/') + 1)\n if (widgetIds.value.has(id) && heights.get(id) !== height) heights.set(id, height)\n})\n\n/** A widget's own content. */\nconst content = (widget: CodeDiffWidget) => () =>\n h('div', { class: ns.e('widget') }, [widget.render()])\n\n/** The blank across from a widget; `span` marks where a widget across both sides is drawn. */\nconst spacer = (height: number, span?: string) => () =>\n h('div', {\n class: ns.e('spacer'),\n style: { height: `${height}px` },\n 'data-diff-span': span,\n })\n\n/** A blank inside a filler: `offset` rows into it. */\ninterface Blank {\n offset: number\n above: boolean\n height: number\n span?: string\n}\ninterface SidePlan {\n /** Widgets below lines, drawn before the diff's own; above lines, after them. */\n below: CodeWidget[]\n above: CodeWidget[]\n /** Blanks inside the fillers, by change. */\n fills: Map<number, Blank[]>\n}\n\n/**\n * Where a spot beside line `line` of `side` is on the other side: beside\n * a line there, or inside the filler of a change.\n */\nfunction across(\n side: Side,\n line: number,\n above: boolean,\n): { line: number } | { fill: number; offset: number } | null {\n const list = hunks.value\n for (let i = 0; i < list.length; i++) {\n const hunk = list[i]!\n const start = side === 'a' ? hunk.originalStart : hunk.modifiedStart\n const count = side === 'a' ? hunk.originalCount : hunk.modifiedCount\n if (line < start) break\n if (line >= start + count) continue\n const otherStart = side === 'a' ? hunk.modifiedStart : hunk.originalStart\n const otherCount = side === 'a' ? hunk.modifiedCount : hunk.originalCount\n const index = line - start\n if (index < otherCount) return { line: otherStart + index }\n return { fill: i, offset: index - otherCount + (above ? 0 : 1) }\n }\n for (const run of unchanged.value) {\n const start = side === 'a' ? run.a : run.b\n if (line >= start && line < start + run.count)\n return { line: line - start + (side === 'a' ? run.b : run.a) }\n }\n return null\n}\n\n/** Side by side: each widget on its side, a blank of its height on the other. */\n// Heights are kept by id across both sides, so one id twice mixes them up.\nif (process.env.NODE_ENV !== 'production') {\n const warned = new Set<string>()\n watch(\n () => props.widgets,\n (widgets) => {\n const seen = new Set<string>()\n for (const widget of widgets ?? []) {\n if (seen.has(widget.id) && !warned.has(widget.id)) {\n warned.add(widget.id)\n console.warn(\n `[@dou-ui/code] DouCodeDiff: widget id \"${widget.id}\" is used more than once; ids must be unique across both sides.`,\n )\n }\n seen.add(widget.id)\n }\n },\n { immediate: true },\n )\n}\n\nconst splitPlan = computed(() => {\n const plan: Record<Side, SidePlan> = {\n a: { below: [], above: [], fills: new Map() },\n b: { below: [], above: [], fills: new Map() },\n }\n if (view.value !== 'split') return plan\n for (const widget of props.widgets ?? []) {\n const own: Side = widget.side === 'original' ? 'a' : 'b'\n const other: Side = own === 'a' ? 'b' : 'a'\n const lines = own === 'a' ? originalLines.value.length : modifiedLines.value.length\n if (!(widget.line >= 1 && widget.line <= lines)) continue\n const above = widget.position === 'above'\n const height = heightOf(widget)\n const span = widget.span === 'both' ? widget.id : undefined\n const put = (\n side: Side,\n line: number,\n render: () => VNodeChild,\n label?: string,\n blank = false,\n ) =>\n plan[side][above ? 'above' : 'below'].push({\n // A blank's height is known: in its id, so the editor never keeps one it measured before.\n id: blank ? `${widget.id}~${height}` : widget.id,\n line,\n position: above ? 'above' : 'below',\n height,\n label,\n render,\n })\n // Across both sides, the widget itself is drawn over the blanks, with its label.\n if (span) put(own, widget.line, spacer(height, span), widget.label, true)\n else put(own, widget.line, content(widget), widget.label)\n const spot = across(own, widget.line, above)\n if (!spot) continue\n if ('fill' in spot) {\n const fills = plan[other].fills\n const blanks = fills.get(spot.fill) ?? []\n blanks.push({ offset: spot.offset, above, height, span })\n fills.set(spot.fill, blanks)\n } else put(other, spot.line, spacer(height, span), undefined, true)\n }\n return plan\n})\n\n/** The widgets drawn across both sides, over them. */\nconst spans = computed(() =>\n view.value === 'split' ? (props.widgets ?? []).filter((widget) => widget.span === 'both') : [],\n)\n\n/** Whether a column's `hoverMarker` goes on the lines of `side`. */\nfunction hoversOn(gutter: CodeDiffGutter, side: CodeDiffSide) {\n return !!gutter.hoverMarker && (!gutter.hoverMarker.side || gutter.hoverMarker.side === side)\n}\n\n/** Whether a column has a marker of its own on line `line` of `side`. */\nfunction ownMarkerOn(gutter: CodeDiffGutter, side: CodeDiffSide, line: number) {\n return line > 0 && (gutter.markers ?? []).some((m) => m.side === side && m.line === line)\n}\n\n/**\n * Which line of which side a press on a column goes to, or `null` for none.\n * A column whose `hoverMarker` is on one side only answers presses on the\n * other side's own markers, not on its empty cells.\n */\nfunction pressedOn(gutter: CodeDiffGutter, side: CodeDiffSide, line: number): CodeDiffSide | null {\n if (!gutter.hoverMarker || hoversOn(gutter, side) || ownMarkerOn(gutter, side, line)) return side\n return null\n}\n\n/** The column's `hoverMarker` as the editor of one side takes it, named for that side. */\nfunction hoverMarkerOf(hover: CodeDiffHoverMarker, side: CodeDiffSide): CodeGutterHoverMarker {\n const { title } = hover\n return {\n icon: hover.icon,\n text: hover.text,\n class: hover.class,\n title: typeof title === 'function' ? (line: number) => title(line, side) : title,\n }\n}\n\n/** A column of `gutters` as one side's editor draws it. */\nfunction sideGutter(gutter: CodeDiffGutter, side: Side) {\n const name = sideName(side)\n return {\n name: gutter.name,\n width: gutter.width,\n markers: ({ visible }: { visible: { from: number; to: number } }) =>\n (gutter.markers ?? []).filter(\n (marker) =>\n marker.side === name && marker.line >= visible.from && marker.line <= visible.to,\n ),\n hoverMarker: hoversOn(gutter, name) ? hoverMarkerOf(gutter.hoverMarker!, name) : undefined,\n // on one side only, the other side's empty cells take no press\n pressOn: gutter.hoverMarker?.side ? ('markers' as const) : gutter.pressOn,\n onPress:\n gutter.onPress &&\n ((line: number, event: PointerEvent | KeyboardEvent) => {\n if (pressedOn(gutter, name, line)) gutter.onPress!(line, event, name)\n }),\n }\n}\n\n/**\n * The `gutters` and `widgets` of one side. Two of them go around the\n * diff's own: widgets below a line come before its filler or bar, those\n * above a line after them.\n */\nfunction annotations(side: Side, end = false): CodeExtension {\n return defineCodeExtension({\n name: end ? 'diff-widgets-end' : 'diff-widgets',\n get gutters() {\n return end ? [] : (props.gutters ?? []).map((gutter) => sideGutter(gutter, side))\n },\n widgets: () => splitPlan.value[side][end ? 'above' : 'below'],\n })\n}\n\n/** Where line `line` of `side` is inline, from 1; 0 when it isn't there. */\nfunction inlineRow(u: Unified, side: CodeDiffSide, line: number) {\n const rows = side === 'original' ? u.aRows : u.bRows\n return line >= 1 && line < rows.length ? rows[line]! : 0\n}\n\n/** The `gutters` and `widgets` inline, on the rows of their lines. */\nfunction inlineAnnotations(end = false): CodeExtension {\n return defineCodeExtension({\n name: end ? 'diff-widgets-end' : 'diff-widgets',\n get gutters() {\n if (end) return []\n return (props.gutters ?? []).map((gutter) => ({\n name: gutter.name,\n width: gutter.width,\n // on one side only, rows of just the other side take no press\n pressOn: gutter.hoverMarker?.side ? ('markers' as const) : gutter.pressOn,\n markers: ({ visible }: { visible: { from: number; to: number } }) => {\n const u = unified.value\n if (!u) return []\n const out: CodeGutterMarker[] = []\n const taken = new Set<number>()\n // The modified side's marker wins on a row both share.\n for (const side of ['modified', 'original'] as const)\n for (const marker of gutter.markers ?? []) {\n if (marker.side !== side) continue\n const row = inlineRow(u, side, marker.line)\n if (!row || row < visible.from || row > visible.to || taken.has(row)) continue\n out.push({ ...marker, line: row })\n taken.add(row)\n }\n if (gutter.hoverMarker)\n for (let row = visible.from; row <= visible.to && row <= u.kinds.length; row++) {\n if (taken.has(row)) continue\n const b = u.bNums[row - 1] ?? 0\n const a = u.aNums[row - 1] ?? 0\n // named for the line and side a press here goes to\n const at: [number, CodeDiffSide] | null =\n b && hoversOn(gutter, 'modified')\n ? [b, 'modified']\n : a && hoversOn(gutter, 'original')\n ? [a, 'original']\n : null\n if (!at) continue\n const { icon, text, class: className, title } = gutter.hoverMarker\n out.push({\n icon,\n text,\n class: className,\n title: typeof title === 'function' ? title(at[0], at[1]) : title,\n line: row,\n visible: 'hover',\n })\n }\n return out\n },\n onPress:\n gutter.onPress &&\n ((row: number, event: PointerEvent | KeyboardEvent) => {\n const u = unified.value\n if (!u) return\n const a = u.aNums[row - 1] ?? 0\n const b = u.bNums[row - 1] ?? 0\n const press = (side: CodeDiffSide, line: number) => gutter.onPress!(line, event, side)\n if (ownMarkerOn(gutter, 'modified', b)) return press('modified', b)\n if (ownMarkerOn(gutter, 'original', a)) return press('original', a)\n if (!gutter.hoverMarker) return b ? press('modified', b) : press('original', a)\n // with a hoverMarker on one side, an empty row of the other side isn't one to press\n if (b && hoversOn(gutter, 'modified')) press('modified', b)\n else if (a && hoversOn(gutter, 'original')) press('original', a)\n }),\n }))\n },\n widgets() {\n const u = unified.value\n if (!u) return []\n const out: CodeWidget[] = []\n for (const widget of props.widgets ?? []) {\n if ((widget.position === 'above') !== end) continue\n const row = inlineRow(u, widget.side, widget.line)\n if (!row) continue\n out.push({\n id: widget.id,\n line: row,\n position: widget.position,\n height: heightOf(widget),\n label: widget.label,\n render: content(widget),\n })\n }\n return out\n },\n })\n}\n\n// ---------------------------------------------------------------- widgets across both sides\n\nconst spanLayer = ref<HTMLElement>()\n/** Where the layer of widgets across both sides is: over the text of the sides. */\nconst spanBox = ref({ top: 0, height: 0 })\n/** Each widget's y in the layer, by id; left out while its blank isn't drawn. */\nconst spanTops = ref<Record<string, number>>({})\n\nlet placeFrame = 0\nfunction schedulePlace() {\n if (!placeFrame && typeof requestAnimationFrame !== 'undefined')\n placeFrame = requestAnimationFrame(placeSpans)\n}\n/** Puts each widget across both sides over its blank. */\nfunction placeSpans() {\n placeFrame = 0\n const body = spanLayer.value?.parentElement\n const scroller = sideA.value?.querySelector<HTMLElement>('.dou-code-editor__scroller')\n if (!body || !scroller) return\n const frame = scroller.getBoundingClientRect()\n const top = frame.top - body.getBoundingClientRect().top\n if (spanBox.value.top !== top || spanBox.value.height !== frame.height)\n spanBox.value = { top, height: frame.height }\n const tops: Record<string, number> = {}\n for (const box of [sideA.value, sideB.value])\n for (const el of box?.querySelectorAll<HTMLElement>('[data-diff-span]') ?? []) {\n const id = el.dataset.diffSpan!\n if (!(id in tops)) tops[id] = el.getBoundingClientRect().top - frame.top\n }\n const had = spanTops.value\n const keys = Object.keys(tops)\n if (keys.length !== Object.keys(had).length || keys.some((id) => had[id] !== tops[id]))\n spanTops.value = tops\n}\n\n// Blanks move when the text scrolls, a widget above grows, or the box resizes.\nlet stopPlacing: (() => void) | undefined\nfunction startPlacing() {\n stopPlacing?.()\n stopPlacing = undefined\n if (!spans.value.length || !sideA.value) return\n placeSpans()\n const moved = typeof MutationObserver === 'undefined' ? null : new MutationObserver(schedulePlace)\n for (const side of [sideA.value, sideB.value])\n if (side) moved?.observe(side, { subtree: true, childList: true, attributeFilter: ['style'] })\n const resized = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(schedulePlace)\n if (root.value) resized?.observe(root.value)\n stopPlacing = () => {\n moved?.disconnect()\n resized?.disconnect()\n if (placeFrame) cancelAnimationFrame(placeFrame)\n placeFrame = 0\n }\n}\nwatch(() => spans.value.length > 0 && view.value, startPlacing, { flush: 'post' })\nonMounted(startPlacing)\nonBeforeUnmount(() => stopPlacing?.())\n\n/**\n * While the text scrolls, the widgets across both sides are hidden: placed a\n * frame late, they would trail behind it. They come back once it rests.\n */\nconst spansScrolling = ref(false)\nlet restTimer: ReturnType<typeof setTimeout> | undefined\nfunction onSideScroll() {\n if (!spans.value.length) return\n spansScrolling.value = true\n clearTimeout(restTimer)\n restTimer = setTimeout(() => {\n spansScrolling.value = false\n placeSpans()\n }, 120)\n}\nonBeforeUnmount(() => clearTimeout(restTimer))\n\n/** A wheel over a widget across both sides scrolls the text under it. */\nfunction onSpanWheel(event: WheelEvent) {\n const scroller = sideB.value?.querySelector<HTMLElement>('.dou-code-editor__scroller')\n if (!scroller) return\n const unit = event.deltaMode === 1 ? LINE : event.deltaMode === 2 ? scroller.clientHeight : 1\n const dy = event.deltaY * unit\n const dx = event.deltaX * unit\n const canY =\n dy < 0\n ? scroller.scrollTop > 0\n : dy > 0 && scroller.scrollTop + scroller.clientHeight < scroller.scrollHeight - 1\n const canX =\n dx < 0\n ? scroller.scrollLeft > 0\n : dx > 0 && scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth - 1\n // At the end, the page scrolls on as it would over the text.\n if (!canY && !canX) return\n event.preventDefault()\n if (canY) scroller.scrollTop += dy\n if (canX) scroller.scrollLeft += dx\n}\n\n// ---------------------------------------------------------------- hidden lines a cursor reaches\n\n/** Shows the run of hidden lines a cursor moved into, e.g. with search. */\nfunction revealAt(side: Side | 'inline', result: CodeTransactionResult) {\n if (!hiddenCount.value) return\n const { doc, selection } = result.state\n const u = unified.value\n for (const range of selection.ranges) {\n const line = doc.lineAt(range.head).number\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const start =\n side === 'inline' ? (u?.runLines.get(run.key) ?? 0) : side === 'a' ? run.a : run.b\n const first = start + run.hideFrom\n if (line >= first && line < first + run.hideCount) open(run.key)\n }\n }\n}\n\n// ---------------------------------------------------------------- going from change to change\n\nconst live = ref('')\nconst current = ref(-1)\n\nfunction target(): { editor: CodeEditorExpose; box: HTMLElement; side: Side | 'inline' } | null {\n if (view.value === 'inline')\n return editorInline.value && inlineBox.value\n ? { editor: editorInline.value, box: inlineBox.value, side: 'inline' }\n : null\n const inA = !!sideA.value?.contains(document.activeElement)\n const editor = inA ? editorA.value : editorB.value\n const box = inA ? sideA.value : sideB.value\n return editor && box ? { editor, box, side: inA ? 'a' : 'b' } : null\n}\n\nfunction lineOf(index: number, side: Side | 'inline') {\n const hunk = hunks.value[index]!\n if (side === 'inline') return unified.value?.hunkLines[index] ?? 1\n return side === 'a' ? hunk.originalStart : hunk.modifiedStart\n}\n\nfunction go(step: 1 | -1) {\n const list = hunks.value\n const t = target()\n if (!list.length || !t) return false\n const doc = t.editor.doc\n const at = doc.lineAt(t.editor.selection.ranges[t.editor.selection.main]!.head).number\n let index = -1\n if (step > 0) {\n index = list.findIndex((_, i) => lineOf(i, t.side) > at)\n if (index < 0) index = 0\n } else {\n for (let i = list.length - 1; i >= 0; i--)\n if (lineOf(i, t.side) < at) {\n index = i\n break\n }\n if (index < 0) index = list.length - 1\n }\n const line = Math.min(doc.lines, Math.max(1, lineOf(index, t.side)))\n t.editor.select(doc.line(line).from)\n current.value = index\n const hunk = list[index]!\n live.value = format(messages.value.diffChangeAt, {\n index: index + 1,\n count: list.length,\n line: hunk.modifiedStart,\n removed: hunk.originalCount,\n added: hunk.modifiedCount,\n })\n // The editor may grow with the page instead of scrolling: bring the cursor into the window too.\n nextTick(() => t.box.querySelector('textarea')?.scrollIntoView({ block: 'nearest' }))\n return true\n}\n\nconst keymap: CodeKeymap = {\n f7: () => go(1),\n 'shift+f7': () => go(-1),\n}\n\nfunction next() {\n return go(1)\n}\nfunction previous() {\n return go(-1)\n}\n\nconst summary = computed(() =>\n hunks.value.length ? format(messages.value.diffStats, stats.value) : messages.value.diffNoChanges,\n)\n\ndefineExpose({\n /** The changes found now. */\n get hunks() {\n return hunks.value\n },\n /** Moves to the next change; `false` when there is none. */\n next,\n /** Moves to the previous change. */\n previous,\n /** Shows every unchanged line. */\n expandAll: () => (allOpen.value = true),\n /** Hides the runs of unchanged lines again. */\n collapseAll: () => {\n allOpen.value = false\n opened.clear()\n },\n /** The editors drawn now: both sides, or the inline one as `modified`. */\n get original() {\n return view.value === 'split' ? editorA.value : undefined\n },\n get modified() {\n return view.value === 'split' ? editorB.value : editorInline.value\n },\n})\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[ns.b(), ns.m(view), ns.is('bordered', bordered)]\"\n role=\"group\"\n :aria-label=\"messages.diff\"\n >\n <div v-if=\"toolbar\" :class=\"ns.e('toolbar')\">\n <span :class=\"ns.e('stats')\">\n <template v-if=\"hunks.length\">\n <span :class=\"[ns.e('count'), 'is-added']\" aria-hidden=\"true\">+{{ stats.added }}</span>\n <span :class=\"[ns.e('count'), 'is-removed']\" aria-hidden=\"true\"\n >−{{ stats.removed }}</span\n >\n <span :class=\"ns.e('hidden-text')\">{{ summary }}</span>\n </template>\n <span v-else :class=\"ns.e('summary')\">{{ summary }}</span>\n </span>\n <DouTooltip :content=\"messages.diffPrevious\" shortcut=\"shift+f7\">\n <DouButton\n variant=\"ghost\"\n size=\"sm\"\n :disabled=\"!hunks.length\"\n :aria-label=\"messages.diffPrevious\"\n @click=\"previous\"\n >\n <ArrowUpIcon />\n </DouButton>\n </DouTooltip>\n <DouTooltip :content=\"messages.diffNext\" shortcut=\"f7\">\n <DouButton\n variant=\"ghost\"\n size=\"sm\"\n :disabled=\"!hunks.length\"\n :aria-label=\"messages.diffNext\"\n @click=\"next\"\n >\n <ArrowDownIcon />\n </DouButton>\n </DouTooltip>\n <DouTooltip\n v-if=\"anyHideable\"\n :content=\"hiddenCount ? messages.diffExpandAll : messages.diffCollapse\"\n >\n <DouButton\n variant=\"ghost\"\n size=\"sm\"\n :aria-label=\"hiddenCount ? messages.diffExpandAll : messages.diffCollapse\"\n @click=\"toggleAll\"\n >\n <UnfoldVerticalIcon v-if=\"hiddenCount\" />\n <FoldVerticalIcon v-else />\n </DouButton>\n </DouTooltip>\n <DouTooltip :content=\"view === 'split' ? messages.diffInline : messages.diffSplit\">\n <DouButton\n variant=\"ghost\"\n size=\"sm\"\n :aria-label=\"view === 'split' ? messages.diffInline : messages.diffSplit\"\n @click=\"toggleView\"\n >\n <DiffUnifiedIcon v-if=\"view === 'split'\" />\n <DiffSplitIcon v-else />\n </DouButton>\n </DouTooltip>\n </div>\n <div v-if=\"view === 'split'\" :class=\"ns.e('body')\" @scroll.capture=\"onScroll\">\n <div :class=\"ns.e('label')\">{{ messages.diffOriginal }}</div>\n <div :class=\"ns.e('label')\">{{ messages.diffModified }}</div>\n <div\n ref=\"sideA\"\n @scroll.capture.passive=\"onSideScroll\"\n :class=\"[ns.e('side'), 'is-original']\"\n >\n <CodeEditor\n ref=\"editorA\"\n :model-value=\"original\"\n :language=\"language\"\n :extensions=\"extensionsA\"\n :tab-size=\"tabSize\"\n :messages=\"messages\"\n :keymap=\"keymap\"\n :aria-label=\"messages.diffOriginal\"\n :foldable=\"false\"\n :active-line=\"false\"\n :bordered=\"false\"\n readonly\n @transaction=\"revealAt('a', $event)\"\n />\n </div>\n <div\n ref=\"sideB\"\n @scroll.capture.passive=\"onSideScroll\"\n :class=\"[ns.e('side'), 'is-modified']\"\n >\n <CodeEditor\n ref=\"editorB\"\n :model-value=\"modified\"\n :language=\"language\"\n :extensions=\"modifiedExtensions\"\n :tab-size=\"tabSize\"\n :messages=\"messages\"\n :keymap=\"keymap\"\n :aria-label=\"messages.diffModified\"\n :foldable=\"false\"\n :active-line=\"false\"\n :bordered=\"false\"\n :readonly=\"!editable\"\n @update:model-value=\"onModifiedInput\"\n @transaction=\"revealAt('b', $event)\"\n />\n </div>\n <div\n v-if=\"spans.length\"\n ref=\"spanLayer\"\n :class=\"ns.e('spans')\"\n :style=\"{ top: `${spanBox.top}px`, height: `${spanBox.height}px` }\"\n >\n <div\n v-for=\"widget in spans\"\n :key=\"widget.id\"\n :ref=\"(el) => measure(el as Element | null, widget.id)\"\n :class=\"[ns.e('span'), ns.is('placed', widget.id in spanTops && !spansScrolling)]\"\n :style=\"{ transform: `translateY(${spanTops[widget.id] ?? 0}px)` }\"\n :role=\"widget.label ? 'group' : undefined\"\n :aria-label=\"widget.label\"\n @wheel=\"onSpanWheel\"\n >\n <RenderPart :render=\"widget.render\" />\n </div>\n </div>\n </div>\n <div v-else ref=\"inlineBox\" :class=\"ns.e('body')\">\n <CodeEditor\n ref=\"editorInline\"\n :model-value=\"unified?.text ?? ''\"\n :language=\"language\"\n :extensions=\"inlineExtensions\"\n :tab-size=\"tabSize\"\n :messages=\"messages\"\n :keymap=\"keymap\"\n :aria-label=\"messages.diff\"\n :line-numbers=\"false\"\n :foldable=\"false\"\n :active-line=\"false\"\n :bordered=\"false\"\n :wrap=\"wrap\"\n readonly\n @transaction=\"revealAt('inline', $event)\"\n />\n </div>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ live }}</div>\n </div>\n</template>\n"],"mappings":""}
1
+ {"version":3,"file":"code-diff.js","names":["_sfc_main"],"sources":["../src/code-diff.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n DiffSplitIcon,\n DiffUnifiedIcon,\n FoldVerticalIcon,\n UnfoldVerticalIcon,\n} from '@dou-ui/icons'\nimport { DouButton, DouTooltip, createScrollLink, useNamespace } from 'dou-ui'\nimport {\n type VNodeChild,\n computed,\n h,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n reactive,\n ref,\n watch,\n} from 'vue'\nimport CodeEditor from './code-editor.vue'\nimport RenderPart from './render-part'\nimport { type CodeDiffHunk, diffText, lineStarts } from './core/diff'\nimport type { CodeKeymap } from './core/keymap'\nimport type { CodeTransactionResult } from './core/transaction'\nimport { splitLines } from './core/text'\nimport {\n type CodeDecoration,\n type CodeExtension,\n type CodeGutterHoverMarker,\n type CodeGutterMarker,\n type CodeWidget,\n defineCodeExtension,\n WIDGET_HEIGHT_KEY,\n} from './extension'\nimport { format, useCodeMessages } from './locale'\nimport type {\n CodeDiffEmits,\n CodeDiffExpose,\n CodeDiffGutter,\n CodeDiffHoverMarker,\n CodeDiffProps,\n CodeDiffSide,\n CodeDiffSlots,\n CodeDiffWidget,\n CodeEditorExpose,\n} from './types'\n\n/**\n * Two texts compared: side by side, or the changes in one column. Changed\n * lines are tinted, the words that changed inside them marked, and long\n * runs of unchanged lines hidden behind a bar that shows them.\n */\ndefineOptions({ name: 'DouCodeDiff' })\n\nconst props = withDefaults(defineProps<CodeDiffProps>(), {\n original: '',\n modelValue: '',\n language: undefined,\n mode: 'auto',\n editable: false,\n collapseUnchanged: true,\n ignoreWhitespace: false,\n words: true,\n wrap: false,\n extensions: undefined,\n gutters: undefined,\n widgets: undefined,\n tabSize: 2,\n toolbar: true,\n stickyToolbar: false,\n bordered: true,\n scrollY: true,\n messages: undefined,\n})\nconst emit = defineEmits<CodeDiffEmits>()\nconst slots = defineSlots<CodeDiffSlots>()\n\nconst ns = useNamespace('code-diff')\nconst messages = useCodeMessages(() => props.messages)\n\n// ---------------------------------------------------------------- view\n\nconst root = ref<HTMLElement>()\n/** Whether the box is wide enough for two columns. */\nconst roomy = ref(true)\n/** The view picked with the toggle, when `mode` isn't bound. */\nconst picked = ref<'split' | 'inline' | null>(null)\nwatch(\n () => props.mode,\n () => (picked.value = null),\n)\nconst view = computed<'split' | 'inline'>(() => {\n if (picked.value) return picked.value\n if (props.mode !== 'auto') return props.mode\n return roomy.value ? 'split' : 'inline'\n})\nfunction toggleView() {\n const other = view.value === 'split' ? 'inline' : 'split'\n picked.value = other\n emit('update:mode', other)\n}\n\n/** Below this, each side would show fewer than about 30 columns: one column reads better. */\nconst SPLIT_WIDTH = 560\n\nlet resize: ResizeObserver | undefined\nonMounted(() => {\n if (typeof ResizeObserver === 'undefined' || !root.value) return\n resize = new ResizeObserver(([entry]) => {\n if (entry) roomy.value = entry.contentRect.width >= SPLIT_WIDTH\n })\n resize.observe(root.value)\n})\nonBeforeUnmount(() => resize?.disconnect())\n\n// ---------------------------------------------------------------- texts and changes\n\n/** The modified text as edited here, ahead of the parent's copy. */\nconst modified = ref(props.modelValue)\nwatch(\n () => props.modelValue,\n (value) => (modified.value = value),\n)\nfunction onModifiedInput(value: string) {\n modified.value = value\n emit('update:modelValue', value)\n}\n\nconst hunks = computed<CodeDiffHunk[]>(() =>\n diffText(props.original, modified.value, {\n ignoreWhitespace: props.ignoreWhitespace,\n words: props.words,\n }),\n)\nconst originalLines = computed(() => splitLines(props.original))\nconst modifiedLines = computed(() => splitLines(modified.value))\n\nconst stats = computed(() => {\n let added = 0\n let removed = 0\n for (const hunk of hunks.value) {\n added += hunk.modifiedCount\n removed += hunk.originalCount\n }\n return { added, removed }\n})\n\n// ---------------------------------------------------------------- unchanged lines\n\ninterface Unchanged {\n /** First line on each side, from 1. */\n a: number\n b: number\n count: number\n /** Whether this run is long enough to collapse under `collapseUnchanged`. */\n hideable: boolean\n /** Where its hidden part starts, from its first line, and how long it is (0 when nothing is hidden). */\n hideFrom: number\n hideCount: number\n /** Stays the same while the modified text is edited. */\n key: number\n}\n\nconst collapse = computed(() => {\n const option = props.collapseUnchanged\n if (!option) return null\n const own = option === true ? {} : option\n return {\n context: Math.max(1, Math.floor(own.context ?? 3)),\n minLines: Math.max(1, Math.floor(own.minLines ?? 4)),\n }\n})\n/** The runs of unchanged lines opened with their bar, by key; `true` for all of them. */\nconst opened = reactive(new Set<number>())\nconst allOpen = ref(false)\n\n/**\n * The lines with a marker or widget on each side, which collapsing leaves in\n * view. A marker shown only on hover is out of sight, so it doesn't count.\n */\nconst annotatedLines = computed(() => {\n const out = { a: new Set<number>(), b: new Set<number>() }\n const add = (side: CodeDiffSide, line: number) => out[side === 'original' ? 'a' : 'b'].add(line)\n for (const gutter of props.gutters ?? [])\n for (const marker of gutter.markers ?? [])\n if (marker.visible !== 'hover') add(marker.side, marker.line)\n for (const widget of props.widgets ?? []) add(widget.side, widget.line)\n return out\n})\n\nconst unchanged = computed<Unchanged[]>(() => {\n const list = hunks.value\n const total = originalLines.value.length\n const out: Unchanged[] = []\n const rule = collapse.value\n const push = (a: number, b: number, count: number, before: boolean, after: boolean) => {\n if (count <= 0) return\n let hideable = false\n let hideFrom = 0\n let hideCount = 0\n if (rule && list.length) {\n const from = before ? rule.context : 0\n const to = count - (after ? rule.context : 0)\n if (to - from >= rule.minLines) {\n hideable = true\n if (!allOpen.value && !opened.has(a)) {\n hideFrom = from\n hideCount = to - from\n }\n }\n }\n out.push({ a, b, count, hideable, hideFrom, hideCount, key: a })\n }\n // A line with a marker or widget stays in view, with context around it, like a change.\n const kept = annotatedLines.value\n const cut = (a: number, b: number, count: number, before: boolean, after: boolean) => {\n let from = 0\n for (let i = 0; i < count; i++) {\n if (!kept.a.has(a + i) && !kept.b.has(b + i)) continue\n if (i > from) push(a + from, b + from, i - from, from > 0 || before, true)\n from = Math.max(from, i)\n }\n push(a + from, b + from, count - from, from > 0 || before, after)\n }\n let a = 1\n let b = 1\n for (let i = 0; i < list.length; i++) {\n const hunk = list[i]!\n cut(a, b, hunk.originalStart - a, i > 0, true)\n a = hunk.originalStart + hunk.originalCount\n b = hunk.modifiedStart + hunk.modifiedCount\n }\n cut(a, b, total - a + 1, list.length > 0, false)\n return out\n})\nconst hiddenCount = computed(() => unchanged.value.reduce((sum, run) => sum + run.hideCount, 0))\nconst anyHideable = computed(() => unchanged.value.some((run) => run.hideable))\n\nfunction open(key: number) {\n opened.add(key)\n}\nfunction toggleAll() {\n if (hiddenCount.value) allOpen.value = true\n else {\n allOpen.value = false\n opened.clear()\n }\n}\n// A new pair of texts starts collapsed again.\nwatch(\n () => props.original,\n () => {\n allOpen.value = false\n opened.clear()\n },\n)\n\n/**\n * The bar over a run of hidden lines. Side by side, the original's bar\n * mirrors the modified one's: pressed with a pointer, but left out of the\n * keyboard order and of what is read out, so the run is one stop, not two.\n */\nfunction bar(run: Unchanged, mirror = false) {\n const label = format(messages.value.diffUnchanged, { count: run.hideCount })\n return h(\n 'button',\n {\n type: 'button',\n class: ns.e('bar'),\n 'aria-label': `${messages.value.unfold}:${label}`,\n 'aria-hidden': mirror ? 'true' : undefined,\n tabindex: mirror ? -1 : undefined,\n onClick: () => open(run.key),\n },\n [h(UnfoldVerticalIcon, { class: ns.e('bar-icon') }), h('span', label)],\n )\n}\nconst BAR_HEIGHT = 28\n\n// ---------------------------------------------------------------- side by side\n\ntype Side = 'a' | 'b'\n\n/** What one side of the split view draws: tints, marks, fillers, hidden lines and bars. */\nfunction sideExtension(side: Side): CodeExtension {\n const startOf = (hunk: CodeDiffHunk) => (side === 'a' ? hunk.originalStart : hunk.modifiedStart)\n const countOf = (hunk: CodeDiffHunk) => (side === 'a' ? hunk.originalCount : hunk.modifiedCount)\n const otherCountOf = (hunk: CodeDiffHunk) =>\n side === 'a' ? hunk.modifiedCount : hunk.originalCount\n const tone = side === 'a' ? 'removed' : 'added'\n\n return defineCodeExtension({\n name: 'diff',\n decorations({ visible }) {\n const out: CodeDecoration[] = []\n for (const hunk of hunks.value) {\n const start = startOf(hunk)\n const count = countOf(hunk)\n if (start > visible.to) break\n if (!count || start + count - 1 < visible.from) continue\n const from = Math.max(start, visible.from)\n const to = Math.min(start + count - 1, visible.to)\n for (let n = from; n <= to; n++)\n out.push({ type: 'line', line: n, class: `${ns.e('line')} is-${tone}` })\n for (const part of hunk.parts) {\n const range = side === 'a' ? part.original : part.modified\n if (range.to > range.from)\n out.push({\n type: 'mark',\n from: range.from,\n to: range.to,\n class: `${ns.e('word')} is-${tone}`,\n })\n }\n }\n return out\n },\n widgets() {\n const out: CodeWidget[] = []\n const fills = splitPlan.value[side].fills\n hunks.value.forEach((hunk, i) => {\n const missing = otherCountOf(hunk) - countOf(hunk)\n if (missing <= 0) return\n const last = startOf(hunk) - 1 + countOf(hunk)\n const blanks = fills.get(i) ?? []\n out.push({\n // the height in the id: the editor never keeps a size measured before blanks changed\n id: `fill-${i}-${missing}-${blanks.map((blank) => blank.height).join('.')}`,\n ...(last >= 1 ? { line: last } : { line: 1, position: 'above' as const }),\n height: missing * LINE + blanks.reduce((sum, blank) => sum + blank.height, 0),\n render: () => filler(missing, blanks),\n })\n })\n const total = side === 'a' ? originalLines.value.length : modifiedLines.value.length\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const first = (side === 'a' ? run.a : run.b) + run.hideFrom\n const last = first + run.hideCount - 1\n out.push({\n id: `bar-${run.key}`,\n ...(last < total ? { line: last + 1, position: 'above' as const } : { line: first - 1 }),\n height: BAR_HEIGHT,\n render: () => bar(run, side === 'a'),\n })\n }\n return out\n },\n hide() {\n const out: Array<{ from: number; to: number }> = []\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const first = (side === 'a' ? run.a : run.b) + run.hideFrom\n out.push({ from: first, to: first + run.hideCount - 1 })\n }\n return out\n },\n })\n}\n\n/** Rows of filler, or rows split by the blanks of widgets on the other side. */\nconst block = (count: number) =>\n h('div', {\n class: ns.e('filler'),\n style: { height: `calc(${count} * var(--dou-code-editor-line-height))` },\n })\nfunction filler(rows: number, blanks: Blank[]) {\n if (!blanks.length) return block(rows)\n const children = []\n let at = 0\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n for (const blank of [...blanks].sort((x, y) => x.offset - y.offset || +x.above - +y.above)) {\n if (blank.offset > at) children.push(block(blank.offset - at))\n children.push(spacer(blank.height, blank.span)())\n at = Math.max(at, blank.offset)\n }\n if (rows > at) children.push(block(rows - at))\n return h('div', children)\n}\n\n/**\n * The `+`/`−` column of one side. It goes after every other extension, so it\n * is always the gutter's last column, next to the text: its tint spreads\n * over the whole gutter row from there (see style.css).\n */\nfunction signExtension(side: Side): CodeExtension {\n const startOf = (hunk: CodeDiffHunk) => (side === 'a' ? hunk.originalStart : hunk.modifiedStart)\n const countOf = (hunk: CodeDiffHunk) => (side === 'a' ? hunk.originalCount : hunk.modifiedCount)\n const tone = side === 'a' ? 'removed' : 'added'\n return defineCodeExtension({\n name: 'diff-sign',\n gutters: [\n {\n name: 'diff',\n width: 16,\n markers({ visible }) {\n const out: CodeGutterMarker[] = []\n const title = side === 'a' ? messages.value.diffRemoved : messages.value.diffAdded\n for (const hunk of hunks.value) {\n const start = startOf(hunk)\n const count = countOf(hunk)\n if (start > visible.to) break\n for (let n = Math.max(start, visible.from); n < start + count && n <= visible.to; n++)\n out.push({\n line: n,\n text: side === 'a' ? '−' : '+',\n class: `${ns.e('sign')} is-${tone}`,\n title,\n })\n }\n return out\n },\n },\n ],\n })\n}\n\nconst modifiedOwn = sideExtension('b')\nconst signB = signExtension('b')\nconst modifiedExtensions = computed(() => [\n annotationsB,\n modifiedOwn,\n annotationsEndB,\n ...(props.extensions ?? []),\n signB,\n])\n\nconst editorA = ref<CodeEditorExpose>()\nconst editorB = ref<CodeEditorExpose>()\nconst sideA = ref<HTMLElement>()\nconst sideB = ref<HTMLElement>()\nconst extensionsA = [\n annotations('a'),\n sideExtension('a'),\n annotations('a', true),\n signExtension('a'),\n]\nconst annotationsB = annotations('b')\nconst annotationsEndB = annotations('b', true)\n\n// Both sides scroll together; they are the same height, line for line.\nconst linkXY = createScrollLink('xy')\nconst linkX = createScrollLink('x')\nfunction onScroll(event: Event) {\n if (view.value !== 'split') return\n if (spans.value.length) schedulePlace()\n const from = (event.target as HTMLElement).closest(`.${ns.e('side')}`)\n const source = from?.querySelector<HTMLElement>('.dou-code-editor__scroller')\n if (!source || source !== event.target) return\n const other = (from === sideA.value ? sideB.value : sideA.value)?.querySelector<HTMLElement>(\n '.dou-code-editor__scroller',\n )\n if (other) (props.scrollY ? linkXY : linkX).follow(source, other)\n}\n\n// ---------------------------------------------------------------- inline\n\nconst enum Kind {\n Same,\n Removed,\n Added,\n}\n\ninterface Unified {\n text: string\n kinds: Uint8Array\n /** Line numbers on each side, 0 where the line isn't there. */\n aNums: Int32Array\n bNums: Int32Array\n /** Where each line of each side is, from 1, by its number. */\n aRows: Int32Array\n bRows: Int32Array\n /** Where each change starts, from 1. */\n hunkLines: number[]\n /** Where each unchanged run starts, from 1, by key. */\n runLines: Map<number, number>\n marks: Array<{ from: number; to: number; kind: Kind }>\n}\n\nconst unified = computed<Unified | null>(() => {\n if (view.value !== 'inline') return null\n const a = originalLines.value\n const b = modifiedLines.value\n const lines: string[] = []\n const kinds: number[] = []\n const aNums: number[] = []\n const bNums: number[] = []\n const hunkLines: number[] = []\n const runLines = new Map<number, number>()\n const marks: Unified['marks'] = []\n const aRows = new Int32Array(a.length + 1)\n const bRows = new Int32Array(b.length + 1)\n let pos = 0\n const push = (text: string, kind: Kind, an: number, bn: number) => {\n lines.push(text)\n kinds.push(kind)\n aNums.push(an)\n bNums.push(bn)\n if (an) aRows[an] = lines.length\n if (bn) bRows[bn] = lines.length\n pos += text.length + 1\n }\n const runs = unchanged.value\n let r = 0\n const sameUpTo = (aEnd: number) => {\n while (r < runs.length && runs[r]!.a < aEnd) {\n const run = runs[r++]!\n runLines.set(run.key, lines.length + 1)\n for (let i = 0; i < run.count; i++) push(b[run.b - 1 + i]!, Kind.Same, run.a + i, run.b + i)\n }\n }\n // Where each original and modified line starts, for moving the word marks.\n const aStarts = lineStarts(a)\n const bStarts = lineStarts(b)\n for (const hunk of hunks.value) {\n sameUpTo(hunk.originalStart)\n hunkLines.push(lines.length + 1)\n const removedAt = pos\n for (let i = 0; i < hunk.originalCount; i++)\n push(a[hunk.originalStart - 1 + i]!, Kind.Removed, hunk.originalStart + i, 0)\n const addedAt = pos\n for (let i = 0; i < hunk.modifiedCount; i++)\n push(b[hunk.modifiedStart - 1 + i]!, Kind.Added, 0, hunk.modifiedStart + i)\n const aBase = aStarts[hunk.originalStart - 1]!\n const bBase = bStarts[hunk.modifiedStart - 1]!\n for (const part of hunk.parts) {\n if (part.original.to > part.original.from)\n marks.push({\n from: removedAt + part.original.from - aBase,\n to: removedAt + part.original.to - aBase,\n kind: Kind.Removed,\n })\n if (part.modified.to > part.modified.from)\n marks.push({\n from: addedAt + part.modified.from - bBase,\n to: addedAt + part.modified.to - bBase,\n kind: Kind.Added,\n })\n }\n }\n sameUpTo(Infinity)\n return {\n text: lines.join('\\n'),\n kinds: Uint8Array.from(kinds),\n aNums: Int32Array.from(aNums),\n bNums: Int32Array.from(bNums),\n aRows,\n bRows,\n hunkLines,\n runLines,\n marks,\n }\n})\n\nconst digits = (n: number) => String(Math.max(1, n)).length\nconst numberWidth = (n: number) => digits(n) * 8 + 16\n\n/** The line numbers of one side, in the inline view's gutter. */\nconst numbersOf =\n (pick: 'aNums' | 'bNums') =>\n ({ visible }: { visible: { from: number; to: number } }) => {\n const u = unified.value\n if (!u) return []\n const out: CodeGutterMarker[] = []\n const list = u[pick]\n for (let n = visible.from; n <= visible.to && n <= list.length; n++) {\n const value = list[n - 1]!\n const kind = u.kinds[n - 1]\n const tone = kind === Kind.Removed ? ' is-removed' : kind === Kind.Added ? ' is-added' : ''\n out.push({ line: n, text: value ? String(value) : '', class: `${ns.e('number')}${tone}` })\n }\n return out\n }\n\nconst inlineExtension = defineCodeExtension({\n name: 'diff',\n decorations({ visible }) {\n const u = unified.value\n if (!u) return []\n const out: CodeDecoration[] = []\n for (let n = visible.from; n <= visible.to && n <= u.kinds.length; n++) {\n const kind = u.kinds[n - 1]\n if (kind === Kind.Removed)\n out.push({ type: 'line', line: n, class: `${ns.e('line')} is-removed` })\n else if (kind === Kind.Added)\n out.push({ type: 'line', line: n, class: `${ns.e('line')} is-added` })\n }\n for (const mark of u.marks)\n out.push({\n type: 'mark',\n from: mark.from,\n to: mark.to,\n class: `${ns.e('word')} ${mark.kind === Kind.Removed ? 'is-removed' : 'is-added'}`,\n })\n return out\n },\n get gutters() {\n return [\n {\n name: 'diff-original',\n width: numberWidth(originalLines.value.length),\n markers: numbersOf('aNums'),\n },\n {\n name: 'diff-modified',\n width: numberWidth(modifiedLines.value.length),\n markers: numbersOf('bNums'),\n },\n {\n name: 'diff',\n width: 16,\n markers: ({ visible }: { visible: { from: number; to: number } }) => {\n const u = unified.value\n if (!u) return []\n const out: CodeGutterMarker[] = []\n for (let n = visible.from; n <= visible.to && n <= u.kinds.length; n++) {\n const kind = u.kinds[n - 1]\n if (kind === Kind.Removed)\n out.push({\n line: n,\n text: '−',\n class: `${ns.e('sign')} is-removed`,\n title: messages.value.diffRemoved,\n })\n else if (kind === Kind.Added)\n out.push({\n line: n,\n text: '+',\n class: `${ns.e('sign')} is-added`,\n title: messages.value.diffAdded,\n })\n }\n return out\n },\n },\n ]\n },\n widgets() {\n const u = unified.value\n if (!u) return []\n const total = u.kinds.length\n const out: CodeWidget[] = []\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const first = u.runLines.get(run.key)! + run.hideFrom\n const last = first + run.hideCount - 1\n out.push({\n id: `bar-${run.key}`,\n ...(last < total ? { line: last + 1, position: 'above' as const } : { line: first - 1 }),\n height: BAR_HEIGHT,\n render: () => bar(run),\n })\n }\n return out\n },\n hide() {\n const u = unified.value\n if (!u) return []\n const out: Array<{ from: number; to: number }> = []\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const first = u.runLines.get(run.key)! + run.hideFrom\n out.push({ from: first, to: first + run.hideCount - 1 })\n }\n return out\n },\n})\nconst inlineExtensions = [inlineAnnotations(), inlineExtension, inlineAnnotations(true)]\nconst editorInline = ref<CodeEditorExpose>()\nconst inlineBox = ref<HTMLElement>()\n\n// ---------------------------------------------------------------- markers and widgets of both texts\n\n/** One line's height, before the editors have measured theirs. */\nconst LINE = 20\nconst sideName = (side: Side): CodeDiffSide => (side === 'a' ? 'original' : 'modified')\n\n/** The widgets' measured heights, by id, for the blank left beside each. */\nconst heights = reactive(new Map<string, number>())\nlet heightObserver: ResizeObserver | undefined\n/** The element each widget's content is drawn in now, by id, and back. */\nconst measuredEls = new Map<string, Element>()\nconst measuredIds = new Map<Element, string>()\nfunction readHeight(box: Element, entry?: ResizeObserverEntry) {\n const id = measuredIds.get(box)\n // The size the observer saw: by the time it says so, the editor may have\n // moved on and taken the widget away, which leaves nothing to measure.\n const size = entry?.borderBoxSize?.[0]?.blockSize ?? entry?.contentRect.height\n const height = size === undefined ? (box as HTMLElement).offsetHeight : Math.round(size)\n // Nothing measured means no layout (hidden): keep the guess.\n if (id && height && heights.get(id) !== height) heights.set(id, height)\n}\nfunction forget(box: Element) {\n heightObserver?.unobserve(box)\n measuredIds.delete(box)\n}\n/** Measures a widget across both sides as drawn, now and whenever it resizes; `null` once it is gone. */\nfunction measure(el: Element | null, id: string) {\n const had = measuredEls.get(id)\n if (!el) {\n // the old element going after a new one came, e.g. on switching views, keeps the new one\n if (had && !had.isConnected) {\n forget(had)\n measuredEls.delete(id)\n }\n return\n }\n if (had === el) return\n if (had) forget(had)\n measuredEls.set(id, el)\n measuredIds.set(el, id)\n readHeight(el)\n if (typeof ResizeObserver === 'undefined') return\n heightObserver ??= new ResizeObserver((entries) => {\n for (const entry of entries) readHeight(entry.target, entry)\n })\n heightObserver.observe(el)\n}\nonBeforeUnmount(() => heightObserver?.disconnect())\n\nconst heightOf = (widget: CodeDiffWidget) => heights.get(widget.id) ?? widget.height ?? LINE\n\n// The editors measure the widgets they draw and say so here: one height for the widget and its blank.\nconst widgetIds = computed(() => new Set((props.widgets ?? []).map((widget) => widget.id)))\nprovide(WIDGET_HEIGHT_KEY, (key, height) => {\n if (!key.startsWith('diff-widgets')) return\n const id = key.slice(key.indexOf('/') + 1)\n if (widgetIds.value.has(id) && heights.get(id) !== height) heights.set(id, height)\n})\n\n/** A widget's own content. */\nconst content = (widget: CodeDiffWidget) => () =>\n h('div', { class: ns.e('widget') }, [widget.render()])\n\n/** The blank across from a widget; `span` marks where a widget across both sides is drawn. */\nconst spacer = (height: number, span?: string) => () =>\n h('div', {\n class: ns.e('spacer'),\n style: { height: `${height}px` },\n 'data-diff-span': span,\n })\n\n/** A blank inside a filler: `offset` rows into it. */\ninterface Blank {\n offset: number\n above: boolean\n height: number\n span?: string\n}\ninterface SidePlan {\n /** Widgets below lines, drawn before the diff's own; above lines, after them. */\n below: CodeWidget[]\n above: CodeWidget[]\n /** Blanks inside the fillers, by change. */\n fills: Map<number, Blank[]>\n}\n\n/**\n * Where a spot beside line `line` of `side` is on the other side: beside\n * a line there, or inside the filler of a change.\n */\nfunction across(\n side: Side,\n line: number,\n above: boolean,\n): { line: number } | { fill: number; offset: number } | null {\n const list = hunks.value\n for (let i = 0; i < list.length; i++) {\n const hunk = list[i]!\n const start = side === 'a' ? hunk.originalStart : hunk.modifiedStart\n const count = side === 'a' ? hunk.originalCount : hunk.modifiedCount\n if (line < start) break\n if (line >= start + count) continue\n const otherStart = side === 'a' ? hunk.modifiedStart : hunk.originalStart\n const otherCount = side === 'a' ? hunk.modifiedCount : hunk.originalCount\n const index = line - start\n if (index < otherCount) return { line: otherStart + index }\n return { fill: i, offset: index - otherCount + (above ? 0 : 1) }\n }\n for (const run of unchanged.value) {\n const start = side === 'a' ? run.a : run.b\n if (line >= start && line < start + run.count)\n return { line: line - start + (side === 'a' ? run.b : run.a) }\n }\n return null\n}\n\n/** Side by side: each widget on its side, a blank of its height on the other. */\n// Heights are kept by id across both sides, so one id twice mixes them up.\nif (process.env.NODE_ENV !== 'production') {\n const warned = new Set<string>()\n watch(\n () => props.widgets,\n (widgets) => {\n const seen = new Set<string>()\n for (const widget of widgets ?? []) {\n if (seen.has(widget.id) && !warned.has(widget.id)) {\n warned.add(widget.id)\n console.warn(\n `[@dou-ui/code] DouCodeDiff: widget id \"${widget.id}\" is used more than once; ids must be unique across both sides.`,\n )\n }\n seen.add(widget.id)\n }\n },\n { immediate: true },\n )\n}\n\nconst splitPlan = computed(() => {\n const plan: Record<Side, SidePlan> = {\n a: { below: [], above: [], fills: new Map() },\n b: { below: [], above: [], fills: new Map() },\n }\n if (view.value !== 'split') return plan\n for (const widget of props.widgets ?? []) {\n const own: Side = widget.side === 'original' ? 'a' : 'b'\n const other: Side = own === 'a' ? 'b' : 'a'\n const lines = own === 'a' ? originalLines.value.length : modifiedLines.value.length\n if (!(widget.line >= 1 && widget.line <= lines)) continue\n const above = widget.position === 'above'\n const height = heightOf(widget)\n const span = widget.span === 'both' ? widget.id : undefined\n const put = (\n side: Side,\n line: number,\n render: () => VNodeChild,\n label?: string,\n blank = false,\n ) =>\n plan[side][above ? 'above' : 'below'].push({\n // A blank's height is known: in its id, so the editor never keeps one it measured before.\n id: blank ? `${widget.id}~${height}` : widget.id,\n line,\n position: above ? 'above' : 'below',\n height,\n label,\n render,\n })\n // Across both sides, the widget itself is drawn over the blanks, with its label.\n if (span) put(own, widget.line, spacer(height, span), widget.label, true)\n else put(own, widget.line, content(widget), widget.label)\n const spot = across(own, widget.line, above)\n if (!spot) continue\n if ('fill' in spot) {\n const fills = plan[other].fills\n const blanks = fills.get(spot.fill) ?? []\n blanks.push({ offset: spot.offset, above, height, span })\n fills.set(spot.fill, blanks)\n } else put(other, spot.line, spacer(height, span), undefined, true)\n }\n return plan\n})\n\n/** The widgets drawn across both sides, over them. */\nconst spans = computed(() =>\n view.value === 'split' ? (props.widgets ?? []).filter((widget) => widget.span === 'both') : [],\n)\n\n/** Whether a column's `hoverMarker` goes on the lines of `side`. */\nfunction hoversOn(gutter: CodeDiffGutter, side: CodeDiffSide) {\n return !!gutter.hoverMarker && (!gutter.hoverMarker.side || gutter.hoverMarker.side === side)\n}\n\n/** Whether a column has a marker of its own on line `line` of `side`. */\nfunction ownMarkerOn(gutter: CodeDiffGutter, side: CodeDiffSide, line: number) {\n return line > 0 && (gutter.markers ?? []).some((m) => m.side === side && m.line === line)\n}\n\n/**\n * Which line of which side a press on a column goes to, or `null` for none.\n * A column whose `hoverMarker` is on one side only answers presses on the\n * other side's own markers, not on its empty cells.\n */\nfunction pressedOn(gutter: CodeDiffGutter, side: CodeDiffSide, line: number): CodeDiffSide | null {\n if (!gutter.hoverMarker || hoversOn(gutter, side) || ownMarkerOn(gutter, side, line)) return side\n return null\n}\n\n/** The column's `hoverMarker` as the editor of one side takes it, named for that side. */\nfunction hoverMarkerOf(hover: CodeDiffHoverMarker, side: CodeDiffSide): CodeGutterHoverMarker {\n const { title } = hover\n return {\n icon: hover.icon,\n text: hover.text,\n class: hover.class,\n title: typeof title === 'function' ? (line: number) => title(line, side) : title,\n }\n}\n\n/** A column of `gutters` as one side's editor draws it. */\nfunction sideGutter(gutter: CodeDiffGutter, side: Side) {\n const name = sideName(side)\n return {\n name: gutter.name,\n width: gutter.width,\n markers: ({ visible }: { visible: { from: number; to: number } }) =>\n (gutter.markers ?? []).filter(\n (marker) =>\n marker.side === name && marker.line >= visible.from && marker.line <= visible.to,\n ),\n hoverMarker: hoversOn(gutter, name) ? hoverMarkerOf(gutter.hoverMarker!, name) : undefined,\n // on one side only, the other side's empty cells take no press\n pressOn: gutter.hoverMarker?.side ? ('markers' as const) : gutter.pressOn,\n onPress:\n gutter.onPress &&\n ((line: number, event: PointerEvent | KeyboardEvent) => {\n if (pressedOn(gutter, name, line)) gutter.onPress!(line, event, name)\n }),\n }\n}\n\n/**\n * The `gutters` and `widgets` of one side. Two of them go around the\n * diff's own: widgets below a line come before its filler or bar, those\n * above a line after them.\n */\nfunction annotations(side: Side, end = false): CodeExtension {\n return defineCodeExtension({\n name: end ? 'diff-widgets-end' : 'diff-widgets',\n get gutters() {\n return end ? [] : (props.gutters ?? []).map((gutter) => sideGutter(gutter, side))\n },\n widgets: () => splitPlan.value[side][end ? 'above' : 'below'],\n })\n}\n\n/** Where line `line` of `side` is inline, from 1; 0 when it isn't there. */\nfunction inlineRow(u: Unified, side: CodeDiffSide, line: number) {\n const rows = side === 'original' ? u.aRows : u.bRows\n return line >= 1 && line < rows.length ? rows[line]! : 0\n}\n\n/** The `gutters` and `widgets` inline, on the rows of their lines. */\nfunction inlineAnnotations(end = false): CodeExtension {\n return defineCodeExtension({\n name: end ? 'diff-widgets-end' : 'diff-widgets',\n get gutters() {\n if (end) return []\n return (props.gutters ?? []).map((gutter) => ({\n name: gutter.name,\n width: gutter.width,\n // on one side only, rows of just the other side take no press\n pressOn: gutter.hoverMarker?.side ? ('markers' as const) : gutter.pressOn,\n markers: ({ visible }: { visible: { from: number; to: number } }) => {\n const u = unified.value\n if (!u) return []\n const out: CodeGutterMarker[] = []\n const taken = new Set<number>()\n // The modified side's marker wins on a row both share.\n for (const side of ['modified', 'original'] as const)\n for (const marker of gutter.markers ?? []) {\n if (marker.side !== side) continue\n const row = inlineRow(u, side, marker.line)\n if (!row || row < visible.from || row > visible.to || taken.has(row)) continue\n out.push({ ...marker, line: row })\n taken.add(row)\n }\n if (gutter.hoverMarker)\n for (let row = visible.from; row <= visible.to && row <= u.kinds.length; row++) {\n if (taken.has(row)) continue\n const b = u.bNums[row - 1] ?? 0\n const a = u.aNums[row - 1] ?? 0\n // named for the line and side a press here goes to\n const at: [number, CodeDiffSide] | null =\n b && hoversOn(gutter, 'modified')\n ? [b, 'modified']\n : a && hoversOn(gutter, 'original')\n ? [a, 'original']\n : null\n if (!at) continue\n const { icon, text, class: className, title } = gutter.hoverMarker\n out.push({\n icon,\n text,\n class: className,\n title: typeof title === 'function' ? title(at[0], at[1]) : title,\n line: row,\n visible: 'hover',\n })\n }\n return out\n },\n onPress:\n gutter.onPress &&\n ((row: number, event: PointerEvent | KeyboardEvent) => {\n const u = unified.value\n if (!u) return\n const a = u.aNums[row - 1] ?? 0\n const b = u.bNums[row - 1] ?? 0\n const press = (side: CodeDiffSide, line: number) => gutter.onPress!(line, event, side)\n if (ownMarkerOn(gutter, 'modified', b)) return press('modified', b)\n if (ownMarkerOn(gutter, 'original', a)) return press('original', a)\n if (!gutter.hoverMarker) return b ? press('modified', b) : press('original', a)\n // with a hoverMarker on one side, an empty row of the other side isn't one to press\n if (b && hoversOn(gutter, 'modified')) press('modified', b)\n else if (a && hoversOn(gutter, 'original')) press('original', a)\n }),\n }))\n },\n widgets() {\n const u = unified.value\n if (!u) return []\n const out: CodeWidget[] = []\n for (const widget of props.widgets ?? []) {\n if ((widget.position === 'above') !== end) continue\n const row = inlineRow(u, widget.side, widget.line)\n if (!row) continue\n out.push({\n id: widget.id,\n line: row,\n position: widget.position,\n height: heightOf(widget),\n label: widget.label,\n render: content(widget),\n })\n }\n return out\n },\n })\n}\n\n// ---------------------------------------------------------------- widgets across both sides\n\nconst spanLayer = ref<HTMLElement>()\n/** Where the layer of widgets across both sides is: over the text of the sides. */\nconst spanBox = ref({ top: 0, height: 0 })\n/** Each widget's y in the layer, by id; left out while its blank isn't drawn. */\nconst spanTops = ref<Record<string, number>>({})\n\nlet placeFrame = 0\nfunction schedulePlace() {\n if (!placeFrame && typeof requestAnimationFrame !== 'undefined')\n placeFrame = requestAnimationFrame(placeSpans)\n}\n/** Puts each widget across both sides over its blank. */\nfunction placeSpans() {\n placeFrame = 0\n const body = spanLayer.value?.parentElement\n const scroller = sideA.value?.querySelector<HTMLElement>('.dou-code-editor__scroller')\n if (!body || !scroller) return\n const frame = scroller.getBoundingClientRect()\n const top = frame.top - body.getBoundingClientRect().top\n if (spanBox.value.top !== top || spanBox.value.height !== frame.height)\n spanBox.value = { top, height: frame.height }\n const tops: Record<string, number> = {}\n for (const box of [sideA.value, sideB.value])\n for (const el of box?.querySelectorAll<HTMLElement>('[data-diff-span]') ?? []) {\n const id = el.dataset.diffSpan!\n if (!(id in tops)) tops[id] = el.getBoundingClientRect().top - frame.top\n }\n const had = spanTops.value\n const keys = Object.keys(tops)\n if (keys.length !== Object.keys(had).length || keys.some((id) => had[id] !== tops[id]))\n spanTops.value = tops\n}\n\n// Blanks move when the text scrolls, a widget above grows, or the box resizes.\nlet stopPlacing: (() => void) | undefined\nfunction startPlacing() {\n stopPlacing?.()\n stopPlacing = undefined\n if (!spans.value.length || !sideA.value) return\n placeSpans()\n const moved = typeof MutationObserver === 'undefined' ? null : new MutationObserver(schedulePlace)\n for (const side of [sideA.value, sideB.value])\n if (side) moved?.observe(side, { subtree: true, childList: true, attributeFilter: ['style'] })\n const resized = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(schedulePlace)\n if (root.value) resized?.observe(root.value)\n stopPlacing = () => {\n moved?.disconnect()\n resized?.disconnect()\n if (placeFrame) cancelAnimationFrame(placeFrame)\n placeFrame = 0\n }\n}\nwatch(() => spans.value.length > 0 && view.value, startPlacing, { flush: 'post' })\nonMounted(startPlacing)\nonBeforeUnmount(() => stopPlacing?.())\n\n/**\n * While the text scrolls, the widgets across both sides are hidden: placed a\n * frame late, they would trail behind it. They come back once it rests.\n */\nconst spansScrolling = ref(false)\nlet restTimer: ReturnType<typeof setTimeout> | undefined\nfunction onSideScroll() {\n if (!spans.value.length) return\n spansScrolling.value = true\n clearTimeout(restTimer)\n restTimer = setTimeout(() => {\n spansScrolling.value = false\n placeSpans()\n }, 120)\n}\nonBeforeUnmount(() => clearTimeout(restTimer))\n\n/** A wheel over a widget across both sides scrolls the text under it. */\nfunction onSpanWheel(event: WheelEvent) {\n const scroller = sideB.value?.querySelector<HTMLElement>('.dou-code-editor__scroller')\n if (!scroller) return\n const unit = event.deltaMode === 1 ? LINE : event.deltaMode === 2 ? scroller.clientHeight : 1\n const dy = event.deltaY * unit\n const dx = event.deltaX * unit\n const canY =\n props.scrollY &&\n (dy < 0\n ? scroller.scrollTop > 0\n : dy > 0 && scroller.scrollTop + scroller.clientHeight < scroller.scrollHeight - 1)\n const canX =\n dx < 0\n ? scroller.scrollLeft > 0\n : dx > 0 && scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth - 1\n // At the end, the page scrolls on as it would over the text.\n if (!canY && !canX) return\n event.preventDefault()\n if (canY) scroller.scrollTop += dy\n if (canX) scroller.scrollLeft += dx\n}\n\n// ---------------------------------------------------------------- hidden lines a cursor reaches\n\n/** Shows the run of hidden lines a cursor moved into, e.g. with search. */\nfunction revealAt(side: Side | 'inline', result: CodeTransactionResult) {\n if (!hiddenCount.value) return\n const { doc, selection } = result.state\n const u = unified.value\n for (const range of selection.ranges) {\n const line = doc.lineAt(range.head).number\n for (const run of unchanged.value) {\n if (!run.hideCount) continue\n const start =\n side === 'inline' ? (u?.runLines.get(run.key) ?? 0) : side === 'a' ? run.a : run.b\n const first = start + run.hideFrom\n if (line >= first && line < first + run.hideCount) open(run.key)\n }\n }\n}\n\n// ---------------------------------------------------------------- going from change to change\n\nconst live = ref('')\nconst current = ref(-1)\n\nfunction target(): { editor: CodeEditorExpose; box: HTMLElement; side: Side | 'inline' } | null {\n if (view.value === 'inline')\n return editorInline.value && inlineBox.value\n ? { editor: editorInline.value, box: inlineBox.value, side: 'inline' }\n : null\n const inA = !!sideA.value?.contains(document.activeElement)\n const editor = inA ? editorA.value : editorB.value\n const box = inA ? sideA.value : sideB.value\n return editor && box ? { editor, box, side: inA ? 'a' : 'b' } : null\n}\n\nfunction lineOf(index: number, side: Side | 'inline') {\n const hunk = hunks.value[index]!\n if (side === 'inline') return unified.value?.hunkLines[index] ?? 1\n return side === 'a' ? hunk.originalStart : hunk.modifiedStart\n}\n\nfunction go(step: 1 | -1) {\n const list = hunks.value\n const t = target()\n if (!list.length || !t) return false\n const doc = t.editor.doc\n const at = doc.lineAt(t.editor.selection.ranges[t.editor.selection.main]!.head).number\n let index = -1\n if (step > 0) {\n index = list.findIndex((_, i) => lineOf(i, t.side) > at)\n if (index < 0) index = 0\n } else {\n for (let i = list.length - 1; i >= 0; i--)\n if (lineOf(i, t.side) < at) {\n index = i\n break\n }\n if (index < 0) index = list.length - 1\n }\n const line = Math.min(doc.lines, Math.max(1, lineOf(index, t.side)))\n t.editor.select(doc.line(line).from)\n current.value = index\n const hunk = list[index]!\n live.value = format(messages.value.diffChangeAt, {\n index: index + 1,\n count: list.length,\n line: hunk.modifiedStart,\n removed: hunk.originalCount,\n added: hunk.modifiedCount,\n })\n // The editor may grow with the page instead of scrolling: bring the cursor into the window too.\n nextTick(() => t.box.querySelector('textarea')?.scrollIntoView({ block: 'nearest' }))\n return true\n}\n\nconst keymap: CodeKeymap = {\n f7: () => go(1),\n 'shift+f7': () => go(-1),\n}\n\nfunction next() {\n return go(1)\n}\nfunction previous() {\n return go(-1)\n}\n\nconst summary = computed(() =>\n hunks.value.length ? format(messages.value.diffStats, stats.value) : messages.value.diffNoChanges,\n)\n\ndefineExpose<CodeDiffExpose>({\n /** The changes found now. */\n get hunks() {\n return hunks.value\n },\n /** Whether any run of unchanged lines can be collapsed under the current settings. */\n get anyHideable() {\n return anyHideable.value\n },\n /** How many unchanged lines are currently hidden behind collapse bars. */\n get hiddenCount() {\n return hiddenCount.value\n },\n /** Moves to the next change; `false` when there is none. */\n next,\n /** Moves to the previous change. */\n previous,\n /** Shows every unchanged line. */\n expandAll: () => {\n allOpen.value = true\n },\n /** Hides the runs of unchanged lines again. */\n collapseAll: () => {\n allOpen.value = false\n opened.clear()\n },\n /** The editors drawn now: both sides, or the inline one as `modified`. */\n get original() {\n return view.value === 'split' ? editorA.value : undefined\n },\n get modified() {\n return view.value === 'split' ? editorB.value : editorInline.value\n },\n})\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[ns.b(), ns.m(view), ns.is('bordered', bordered), ns.is('scroll-y', scrollY)]\"\n role=\"group\"\n :aria-label=\"messages.diff\"\n >\n <div v-if=\"toolbar\" :class=\"[ns.e('toolbar'), ns.is('sticky', stickyToolbar)]\">\n <div v-if=\"slots.title\" :class=\"ns.e('title')\">\n <slot name=\"title\" />\n </div>\n <span :class=\"ns.e('stats')\">\n <template v-if=\"hunks.length\">\n <span :class=\"[ns.e('count'), 'is-added']\" aria-hidden=\"true\">+{{ stats.added }}</span>\n <span :class=\"[ns.e('count'), 'is-removed']\" aria-hidden=\"true\"\n >−{{ stats.removed }}</span\n >\n <span :class=\"ns.e('hidden-text')\">{{ summary }}</span>\n </template>\n <span v-else :class=\"ns.e('summary')\">{{ summary }}</span>\n </span>\n <DouTooltip :content=\"messages.diffPrevious\" shortcut=\"shift+f7\">\n <DouButton\n variant=\"ghost\"\n size=\"sm\"\n :disabled=\"!hunks.length\"\n :aria-label=\"messages.diffPrevious\"\n @click=\"previous\"\n >\n <ArrowUpIcon />\n </DouButton>\n </DouTooltip>\n <DouTooltip :content=\"messages.diffNext\" shortcut=\"f7\">\n <DouButton\n variant=\"ghost\"\n size=\"sm\"\n :disabled=\"!hunks.length\"\n :aria-label=\"messages.diffNext\"\n @click=\"next\"\n >\n <ArrowDownIcon />\n </DouButton>\n </DouTooltip>\n <DouTooltip\n v-if=\"anyHideable\"\n :content=\"hiddenCount ? messages.diffExpandAll : messages.diffCollapse\"\n >\n <DouButton\n variant=\"ghost\"\n size=\"sm\"\n :aria-label=\"hiddenCount ? messages.diffExpandAll : messages.diffCollapse\"\n @click=\"toggleAll\"\n >\n <UnfoldVerticalIcon v-if=\"hiddenCount\" />\n <FoldVerticalIcon v-else />\n </DouButton>\n </DouTooltip>\n <DouTooltip :content=\"view === 'split' ? messages.diffInline : messages.diffSplit\">\n <DouButton\n variant=\"ghost\"\n size=\"sm\"\n :aria-label=\"view === 'split' ? messages.diffInline : messages.diffSplit\"\n @click=\"toggleView\"\n >\n <DiffUnifiedIcon v-if=\"view === 'split'\" />\n <DiffSplitIcon v-else />\n </DouButton>\n </DouTooltip>\n </div>\n <div v-if=\"view === 'split'\" :class=\"ns.e('body')\" @scroll.capture=\"onScroll\">\n <div :class=\"ns.e('label')\">{{ messages.diffOriginal }}</div>\n <div :class=\"ns.e('label')\">{{ messages.diffModified }}</div>\n <div\n ref=\"sideA\"\n @scroll.capture.passive=\"onSideScroll\"\n :class=\"[ns.e('side'), 'is-original']\"\n >\n <CodeEditor\n ref=\"editorA\"\n :model-value=\"original\"\n :language=\"language\"\n :extensions=\"extensionsA\"\n :tab-size=\"tabSize\"\n :messages=\"messages\"\n :keymap=\"keymap\"\n :aria-label=\"messages.diffOriginal\"\n :foldable=\"false\"\n :active-line=\"false\"\n :bordered=\"false\"\n :scroll-y=\"scrollY\"\n readonly\n @transaction=\"revealAt('a', $event)\"\n />\n </div>\n <div\n ref=\"sideB\"\n @scroll.capture.passive=\"onSideScroll\"\n :class=\"[ns.e('side'), 'is-modified']\"\n >\n <CodeEditor\n ref=\"editorB\"\n :model-value=\"modified\"\n :language=\"language\"\n :extensions=\"modifiedExtensions\"\n :tab-size=\"tabSize\"\n :messages=\"messages\"\n :keymap=\"keymap\"\n :aria-label=\"messages.diffModified\"\n :foldable=\"false\"\n :active-line=\"false\"\n :bordered=\"false\"\n :scroll-y=\"scrollY\"\n :readonly=\"!editable\"\n @update:model-value=\"onModifiedInput\"\n @transaction=\"revealAt('b', $event)\"\n />\n </div>\n <div\n v-if=\"spans.length\"\n ref=\"spanLayer\"\n :class=\"ns.e('spans')\"\n :style=\"{ top: `${spanBox.top}px`, height: `${spanBox.height}px` }\"\n >\n <div\n v-for=\"widget in spans\"\n :key=\"widget.id\"\n :ref=\"(el) => measure(el as Element | null, widget.id)\"\n :class=\"[ns.e('span'), ns.is('placed', widget.id in spanTops && !spansScrolling)]\"\n :style=\"{ transform: `translateY(${spanTops[widget.id] ?? 0}px)` }\"\n :role=\"widget.label ? 'group' : undefined\"\n :aria-label=\"widget.label\"\n @wheel=\"onSpanWheel\"\n >\n <RenderPart :render=\"widget.render\" />\n </div>\n </div>\n </div>\n <div v-else ref=\"inlineBox\" :class=\"ns.e('body')\">\n <CodeEditor\n ref=\"editorInline\"\n :model-value=\"unified?.text ?? ''\"\n :language=\"language\"\n :extensions=\"inlineExtensions\"\n :tab-size=\"tabSize\"\n :messages=\"messages\"\n :keymap=\"keymap\"\n :aria-label=\"messages.diff\"\n :line-numbers=\"false\"\n :foldable=\"false\"\n :active-line=\"false\"\n :bordered=\"false\"\n :scroll-y=\"scrollY\"\n :wrap=\"wrap\"\n readonly\n @transaction=\"revealAt('inline', $event)\"\n />\n </div>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ live }}</div>\n </div>\n</template>\n"],"mappings":""}
@@ -5,7 +5,7 @@ import render_part_default from "./render-part.js";
5
5
  import code_editor_default from "./code-editor.js";
6
6
  import { diffText, lineStarts } from "./core/diff.js";
7
7
  import { DouButton, DouTooltip, createScrollLink, useNamespace } from "dou-ui";
8
- import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createVNode, defineComponent, h, nextTick, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, provide, reactive, ref, renderList, toDisplayString, unref, watch, withCtx } from "vue";
8
+ import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createVNode, defineComponent, h, nextTick, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, provide, reactive, ref, renderList, renderSlot, toDisplayString, unref, useSlots, watch, withCtx } from "vue";
9
9
  import { ArrowDownIcon, ArrowUpIcon, DiffSplitIcon, DiffUnifiedIcon, FoldVerticalIcon, UnfoldVerticalIcon } from "@dou-ui/icons";
10
10
  // src/code-diff.vue?vue&type=script&setup=true&lang.ts
11
11
  var _hoisted_1 = ["aria-label"];
@@ -65,16 +65,25 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
65
65
  type: Boolean,
66
66
  default: true
67
67
  },
68
+ stickyToolbar: {
69
+ type: Boolean,
70
+ default: false
71
+ },
68
72
  bordered: {
69
73
  type: Boolean,
70
74
  default: true
71
75
  },
76
+ scrollY: {
77
+ type: Boolean,
78
+ default: true
79
+ },
72
80
  messages: { default: void 0 }
73
81
  },
74
82
  emits: ["update:modelValue", "update:mode"],
75
83
  setup(__props, { expose: __expose, emit: __emit }) {
76
84
  const props = __props;
77
85
  const emit = __emit;
86
+ const slots = useSlots();
78
87
  const ns = useNamespace("code-diff");
79
88
  const messages = useCodeMessages(() => props.messages);
80
89
  const root = ref();
@@ -161,20 +170,25 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
161
170
  const rule = collapse.value;
162
171
  const push = (a, b, count, before, after) => {
163
172
  if (count <= 0) return;
173
+ let hideable = false;
164
174
  let hideFrom = 0;
165
175
  let hideCount = 0;
166
- if (rule && list.length && !allOpen.value && !opened.has(a)) {
176
+ if (rule && list.length) {
167
177
  const from = before ? rule.context : 0;
168
178
  const to = count - (after ? rule.context : 0);
169
179
  if (to - from >= rule.minLines) {
170
- hideFrom = from;
171
- hideCount = to - from;
180
+ hideable = true;
181
+ if (!allOpen.value && !opened.has(a)) {
182
+ hideFrom = from;
183
+ hideCount = to - from;
184
+ }
172
185
  }
173
186
  }
174
187
  out.push({
175
188
  a,
176
189
  b,
177
190
  count,
191
+ hideable,
178
192
  hideFrom,
179
193
  hideCount,
180
194
  key: a
@@ -202,7 +216,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
202
216
  return out;
203
217
  });
204
218
  const hiddenCount = computed(() => unchanged.value.reduce((sum, run) => sum + run.hideCount, 0));
205
- const anyHideable = computed(() => !!collapse.value && hunks.value.length > 0);
219
+ const anyHideable = computed(() => unchanged.value.some((run) => run.hideable));
206
220
  function open(key) {
207
221
  opened.add(key);
208
222
  }
@@ -386,7 +400,8 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
386
400
  ];
387
401
  const annotationsB = annotations("b");
388
402
  const annotationsEndB = annotations("b", true);
389
- const link = createScrollLink();
403
+ const linkXY = createScrollLink("xy");
404
+ const linkX = createScrollLink("x");
390
405
  function onScroll(event) {
391
406
  if (view.value !== "split") return;
392
407
  if (spans.value.length) schedulePlace();
@@ -394,7 +409,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
394
409
  const source = from?.querySelector(".dou-code-editor__scroller");
395
410
  if (!source || source !== event.target) return;
396
411
  const other = (from === sideA.value ? sideB.value : sideA.value)?.querySelector(".dou-code-editor__scroller");
397
- if (other) link.follow(source, other);
412
+ if (other) (props.scrollY ? linkXY : linkX).follow(source, other);
398
413
  }
399
414
  const unified = computed(() => {
400
415
  if (view.value !== "inline") return null;
@@ -955,7 +970,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
955
970
  const unit = event.deltaMode === 1 ? LINE : event.deltaMode === 2 ? scroller.clientHeight : 1;
956
971
  const dy = event.deltaY * unit;
957
972
  const dx = event.deltaX * unit;
958
- const canY = dy < 0 ? scroller.scrollTop > 0 : dy > 0 && scroller.scrollTop + scroller.clientHeight < scroller.scrollHeight - 1;
973
+ const canY = props.scrollY && (dy < 0 ? scroller.scrollTop > 0 : dy > 0 && scroller.scrollTop + scroller.clientHeight < scroller.scrollHeight - 1);
959
974
  const canX = dx < 0 ? scroller.scrollLeft > 0 : dx > 0 && scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth - 1;
960
975
  if (!canY && !canX) return;
961
976
  event.preventDefault();
@@ -1045,12 +1060,22 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1045
1060
  get hunks() {
1046
1061
  return hunks.value;
1047
1062
  },
1063
+ /** Whether any run of unchanged lines can be collapsed under the current settings. */
1064
+ get anyHideable() {
1065
+ return anyHideable.value;
1066
+ },
1067
+ /** How many unchanged lines are currently hidden behind collapse bars. */
1068
+ get hiddenCount() {
1069
+ return hiddenCount.value;
1070
+ },
1048
1071
  /** Moves to the next change; `false` when there is none. */
1049
1072
  next,
1050
1073
  /** Moves to the previous change. */
1051
1074
  previous,
1052
1075
  /** Shows every unchanged line. */
1053
- expandAll: () => allOpen.value = true,
1076
+ expandAll: () => {
1077
+ allOpen.value = true;
1078
+ },
1054
1079
  /** Hides the runs of unchanged lines again. */
1055
1080
  collapseAll: () => {
1056
1081
  allOpen.value = false;
@@ -1071,15 +1096,20 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1071
1096
  class: normalizeClass([
1072
1097
  unref(ns).b(),
1073
1098
  unref(ns).m(view.value),
1074
- unref(ns).is("bordered", __props.bordered)
1099
+ unref(ns).is("bordered", __props.bordered),
1100
+ unref(ns).is("scroll-y", __props.scrollY)
1075
1101
  ]),
1076
1102
  role: "group",
1077
1103
  "aria-label": unref(messages).diff
1078
1104
  }, [
1079
1105
  __props.toolbar ? (openBlock(), createElementBlock("div", {
1080
1106
  key: 0,
1081
- class: normalizeClass(unref(ns).e("toolbar"))
1107
+ class: normalizeClass([unref(ns).e("toolbar"), unref(ns).is("sticky", __props.stickyToolbar)])
1082
1108
  }, [
1109
+ slots.title ? (openBlock(), createElementBlock("div", {
1110
+ key: 0,
1111
+ class: normalizeClass(unref(ns).e("title"))
1112
+ }, [renderSlot(_ctx.$slots, "title")], 2)) : createCommentVNode("", true),
1083
1113
  createElementVNode("span", { class: normalizeClass(unref(ns).e("stats")) }, [hunks.value.length ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
1084
1114
  createElementVNode("span", {
1085
1115
  class: normalizeClass([unref(ns).e("count"), "is-added"]),
@@ -1127,7 +1157,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1127
1157
  _: 1
1128
1158
  }, 8, ["content"]),
1129
1159
  anyHideable.value ? (openBlock(), createBlock(unref(DouTooltip), {
1130
- key: 0,
1160
+ key: 1,
1131
1161
  content: hiddenCount.value ? unref(messages).diffExpandAll : unref(messages).diffCollapse
1132
1162
  }, {
1133
1163
  default: withCtx(() => [createVNode(unref(DouButton), {
@@ -1179,6 +1209,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1179
1209
  foldable: false,
1180
1210
  "active-line": false,
1181
1211
  bordered: false,
1212
+ "scroll-y": __props.scrollY,
1182
1213
  readonly: "",
1183
1214
  onTransaction: _cache[0] || (_cache[0] = ($event) => revealAt("a", $event))
1184
1215
  }, null, 8, [
@@ -1186,7 +1217,8 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1186
1217
  "language",
1187
1218
  "tab-size",
1188
1219
  "messages",
1189
- "aria-label"
1220
+ "aria-label",
1221
+ "scroll-y"
1190
1222
  ])], 34),
1191
1223
  createElementVNode("div", {
1192
1224
  ref_key: "sideB",
@@ -1206,6 +1238,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1206
1238
  foldable: false,
1207
1239
  "active-line": false,
1208
1240
  bordered: false,
1241
+ "scroll-y": __props.scrollY,
1209
1242
  readonly: !__props.editable,
1210
1243
  "onUpdate:modelValue": onModifiedInput,
1211
1244
  onTransaction: _cache[1] || (_cache[1] = ($event) => revealAt("b", $event))
@@ -1216,6 +1249,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1216
1249
  "tab-size",
1217
1250
  "messages",
1218
1251
  "aria-label",
1252
+ "scroll-y",
1219
1253
  "readonly"
1220
1254
  ])], 34),
1221
1255
  spans.value.length ? (openBlock(), createElementBlock("div", {
@@ -1258,6 +1292,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1258
1292
  foldable: false,
1259
1293
  "active-line": false,
1260
1294
  bordered: false,
1295
+ "scroll-y": __props.scrollY,
1261
1296
  wrap: __props.wrap,
1262
1297
  readonly: "",
1263
1298
  onTransaction: _cache[2] || (_cache[2] = ($event) => revealAt("inline", $event))
@@ -1267,6 +1302,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1267
1302
  "tab-size",
1268
1303
  "messages",
1269
1304
  "aria-label",
1305
+ "scroll-y",
1270
1306
  "wrap"
1271
1307
  ])], 2)),
1272
1308
  createElementVNode("div", {