@dou-ui/code 0.1.0-alpha.23 → 0.1.0-alpha.24

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 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":""}
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/** Whether the box is narrow enough to use compact inline gutter columns. */\nconst compact = ref(false)\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/** Below this, inline mode tightens line-number columns and spacing to leave more room for code. */\nconst COMPACT_WIDTH = 480\n\nfunction syncWidth(width: number) {\n if (width <= 0) return\n roomy.value = width >= SPLIT_WIDTH\n compact.value = width < COMPACT_WIDTH\n}\n\nlet resize: ResizeObserver | undefined\nonMounted(() => {\n if (!root.value) return\n syncWidth(root.value.clientWidth)\n if (typeof ResizeObserver === 'undefined') return\n resize = new ResizeObserver(([entry]) => {\n if (entry) syncWidth(entry.contentRect.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 fullWidth: true,\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 fullWidth: true,\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\nfunction numberWidth(n: number, side: CodeDiffSide) {\n const count = digits(n)\n if (compact.value) return count * 7 + (side === 'original' ? 8 : 6)\n return Math.ceil(count * 7.5) + (side === 'original' ? 12 : 8)\n}\n\n/** The line numbers of one side, in the inline view's gutter. */\nconst numbersOf =\n (pick: 'aNums' | 'bNums', side: CodeDiffSide) =>\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({\n line: n,\n text: value ? String(value) : '',\n class: `${ns.e('number')} is-${side}${tone}`,\n })\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, 'original'),\n markers: numbersOf('aNums', 'original'),\n },\n {\n name: 'diff-modified',\n width: numberWidth(modifiedLines.value.length, 'modified'),\n markers: numbersOf('bNums', 'modified'),\n },\n {\n name: 'diff',\n width: compact.value ? 14 : 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 fullWidth: true,\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/** Whether a gutter column floats over the gutter edge instead of reserving width. */\nfunction isOverlay(gutter: CodeDiffGutter) {\n return gutter.overlay === true || (gutter.overlay === 'compact' && compact.value)\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 overlay: isOverlay(gutter),\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 overlay: isOverlay(gutter),\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\nconst sideScrollTop = new WeakMap<HTMLElement, number>()\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 for (const side of [sideA.value, sideB.value]) {\n const scroller = side?.querySelector<HTMLElement>('.dou-code-editor__scroller')\n if (scroller) sideScrollTop.set(scroller, scroller.scrollTop)\n }\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(event: Event) {\n const scroller = event.target as HTMLElement | null\n if (!scroller?.classList.contains('dou-code-editor__scroller')) return\n const top = scroller.scrollTop\n const prev = sideScrollTop.get(scroller)\n sideScrollTop.set(scroller, top)\n if (!spans.value.length) return\n // Horizontal scrolling does not change vertical span positions; keep spans visible.\n if (prev !== undefined ? prev === top : top === 0) 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=\"[\n ns.b(),\n ns.m(view),\n ns.is('compact', compact),\n ns.is('bordered', bordered),\n ns.is('scroll-y', scrollY),\n ]\"\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":""}
@@ -16,6 +16,8 @@ var _hoisted_2 = ["role", "aria-label"];
16
16
  * runs of unchanged lines hidden behind a bar that shows them.
17
17
  */
18
18
  var SPLIT_WIDTH = 560;
19
+ /** Below this, inline mode tightens line-number columns and spacing to leave more room for code. */
20
+ var COMPACT_WIDTH = 480;
19
21
  var BAR_HEIGHT = 28;
20
22
  /** What one side of the split view draws: tints, marks, fillers, hidden lines and bars. */
21
23
  var Kind = /* @__PURE__ */ function(Kind) {
@@ -89,6 +91,8 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
89
91
  const root = ref();
90
92
  /** Whether the box is wide enough for two columns. */
91
93
  const roomy = ref(true);
94
+ /** Whether the box is narrow enough to use compact inline gutter columns. */
95
+ const compact = ref(false);
92
96
  /** The view picked with the toggle, when `mode` isn't bound. */
93
97
  const picked = ref(null);
94
98
  watch(() => props.mode, () => picked.value = null);
@@ -103,11 +107,18 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
103
107
  emit("update:mode", other);
104
108
  }
105
109
  /** Below this, each side would show fewer than about 30 columns: one column reads better. */
110
+ function syncWidth(width) {
111
+ if (width <= 0) return;
112
+ roomy.value = width >= SPLIT_WIDTH;
113
+ compact.value = width < COMPACT_WIDTH;
114
+ }
106
115
  let resize;
107
116
  onMounted(() => {
108
- if (typeof ResizeObserver === "undefined" || !root.value) return;
117
+ if (!root.value) return;
118
+ syncWidth(root.value.clientWidth);
119
+ if (typeof ResizeObserver === "undefined") return;
109
120
  resize = new ResizeObserver(([entry]) => {
110
- if (entry) roomy.value = entry.contentRect.width >= SPLIT_WIDTH;
121
+ if (entry) syncWidth(entry.contentRect.width);
111
122
  });
112
123
  resize.observe(root.value);
113
124
  });
@@ -295,6 +306,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
295
306
  position: "above"
296
307
  },
297
308
  height: missing * LINE + blanks.reduce((sum, blank) => sum + blank.height, 0),
309
+ fullWidth: true,
298
310
  render: () => filler(missing, blanks)
299
311
  });
300
312
  });
@@ -310,6 +322,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
310
322
  position: "above"
311
323
  } : { line: first - 1 },
312
324
  height: BAR_HEIGHT,
325
+ fullWidth: true,
313
326
  render: () => bar(run, side === "a")
314
327
  });
315
328
  }
@@ -481,9 +494,13 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
481
494
  };
482
495
  });
483
496
  const digits = (n) => String(Math.max(1, n)).length;
484
- const numberWidth = (n) => digits(n) * 8 + 16;
497
+ function numberWidth(n, side) {
498
+ const count = digits(n);
499
+ if (compact.value) return count * 7 + (side === "original" ? 8 : 6);
500
+ return Math.ceil(count * 7.5) + (side === "original" ? 12 : 8);
501
+ }
485
502
  /** The line numbers of one side, in the inline view's gutter. */
486
- const numbersOf = (pick) => ({ visible }) => {
503
+ const numbersOf = (pick, side) => ({ visible }) => {
487
504
  const u = unified.value;
488
505
  if (!u) return [];
489
506
  const out = [];
@@ -495,7 +512,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
495
512
  out.push({
496
513
  line: n,
497
514
  text: value ? String(value) : "",
498
- class: `${ns.e("number")}${tone}`
515
+ class: `${ns.e("number")} is-${side}${tone}`
499
516
  });
500
517
  }
501
518
  return out;
@@ -531,17 +548,17 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
531
548
  return [
532
549
  {
533
550
  name: "diff-original",
534
- width: numberWidth(originalLines.value.length),
535
- markers: numbersOf("aNums")
551
+ width: numberWidth(originalLines.value.length, "original"),
552
+ markers: numbersOf("aNums", "original")
536
553
  },
537
554
  {
538
555
  name: "diff-modified",
539
- width: numberWidth(modifiedLines.value.length),
540
- markers: numbersOf("bNums")
556
+ width: numberWidth(modifiedLines.value.length, "modified"),
557
+ markers: numbersOf("bNums", "modified")
541
558
  },
542
559
  {
543
560
  name: "diff",
544
- width: 16,
561
+ width: compact.value ? 14 : 16,
545
562
  markers: ({ visible }) => {
546
563
  const u = unified.value;
547
564
  if (!u) return [];
@@ -582,6 +599,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
582
599
  position: "above"
583
600
  } : { line: first - 1 },
584
601
  height: BAR_HEIGHT,
602
+ fullWidth: true,
585
603
  render: () => bar(run)
586
604
  });
587
605
  }
@@ -779,12 +797,17 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
779
797
  title: typeof title === "function" ? (line) => title(line, side) : title
780
798
  };
781
799
  }
800
+ /** Whether a gutter column floats over the gutter edge instead of reserving width. */
801
+ function isOverlay(gutter) {
802
+ return gutter.overlay === true || gutter.overlay === "compact" && compact.value;
803
+ }
782
804
  /** A column of `gutters` as one side's editor draws it. */
783
805
  function sideGutter(gutter, side) {
784
806
  const name = sideName(side);
785
807
  return {
786
808
  name: gutter.name,
787
809
  width: gutter.width,
810
+ overlay: isOverlay(gutter),
788
811
  markers: ({ visible }) => (gutter.markers ?? []).filter((marker) => marker.side === name && marker.line >= visible.from && marker.line <= visible.to),
789
812
  hoverMarker: hoversOn(gutter, name) ? hoverMarkerOf(gutter.hoverMarker, name) : void 0,
790
813
  pressOn: gutter.hoverMarker?.side ? "markers" : gutter.pressOn,
@@ -821,6 +844,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
821
844
  return (props.gutters ?? []).map((gutter) => ({
822
845
  name: gutter.name,
823
846
  width: gutter.width,
847
+ overlay: isOverlay(gutter),
824
848
  pressOn: gutter.hoverMarker?.side ? "markers" : gutter.pressOn,
825
849
  markers: ({ visible }) => {
826
850
  const u = unified.value;
@@ -923,11 +947,16 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
923
947
  const keys = Object.keys(tops);
924
948
  if (keys.length !== Object.keys(had).length || keys.some((id) => had[id] !== tops[id])) spanTops.value = tops;
925
949
  }
950
+ const sideScrollTop = /* @__PURE__ */ new WeakMap();
926
951
  let stopPlacing;
927
952
  function startPlacing() {
928
953
  stopPlacing?.();
929
954
  stopPlacing = void 0;
930
955
  if (!spans.value.length || !sideA.value) return;
956
+ for (const side of [sideA.value, sideB.value]) {
957
+ const scroller = side?.querySelector(".dou-code-editor__scroller");
958
+ if (scroller) sideScrollTop.set(scroller, scroller.scrollTop);
959
+ }
931
960
  placeSpans();
932
961
  const moved = typeof MutationObserver === "undefined" ? null : new MutationObserver(schedulePlace);
933
962
  for (const side of [sideA.value, sideB.value]) if (side) moved?.observe(side, {
@@ -953,8 +982,14 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
953
982
  */
954
983
  const spansScrolling = ref(false);
955
984
  let restTimer;
956
- function onSideScroll() {
985
+ function onSideScroll(event) {
986
+ const scroller = event.target;
987
+ if (!scroller?.classList.contains("dou-code-editor__scroller")) return;
988
+ const top = scroller.scrollTop;
989
+ const prev = sideScrollTop.get(scroller);
990
+ sideScrollTop.set(scroller, top);
957
991
  if (!spans.value.length) return;
992
+ if (prev !== void 0 ? prev === top : top === 0) return;
958
993
  spansScrolling.value = true;
959
994
  clearTimeout(restTimer);
960
995
  restTimer = setTimeout(() => {
@@ -1096,6 +1131,7 @@ var code_diff_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
1096
1131
  class: normalizeClass([
1097
1132
  unref(ns).b(),
1098
1133
  unref(ns).m(view.value),
1134
+ unref(ns).is("compact", compact.value),
1099
1135
  unref(ns).is("bordered", __props.bordered),
1100
1136
  unref(ns).is("scroll-y", __props.scrollY)
1101
1137
  ]),