@dou-ui/code 0.1.0-alpha.2 → 0.1.0-alpha.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/code-diff.js.map +1 -1
- package/dist/code-diff.vue_vue_type_script_setup_true_lang.js +527 -37
- package/dist/code-diff.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/code-editor.js.map +1 -1
- package/dist/code-editor.vue_vue_type_script_setup_true_lang.js +176 -54
- package/dist/code-editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extension.js +6 -1
- package/dist/extension.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/types/code-diff.vue.d.ts +5 -2
- package/dist/types/code-editor.vue.d.ts +1 -0
- package/dist/types/extension.d.ts +44 -4
- package/dist/types/index.d.ts +7 -3
- package/dist/types/types.d.ts +89 -3
- package/package.json +3 -3
package/dist/code-editor.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"code-editor.js","names":["_sfc_main"],"sources":["../src/code-editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n AlertTriangleIcon,\n ChevronDownIcon,\n ChevronRightIcon,\n FunctionIcon,\n InfoIcon,\n LightbulbIcon,\n PackageIcon,\n SquareCodeIcon,\n SymbolClassIcon,\n SymbolConstantIcon,\n SymbolKeywordIcon,\n SymbolTypeAliasIcon,\n TypeIcon,\n VariableIcon,\n WrenchIcon,\n XCircleIcon,\n LetterCaseIcon,\n RegexIcon,\n WholeWordIcon,\n GripVerticalIcon,\n} from '@dou-ui/icons'\nimport {\n DouFindReplace,\n DouToggle,\n DouTooltip,\n holdPointer,\n isApplePlatform,\n isComposing,\n scrollPositionOf,\n useLocale,\n useNamespace,\n useTeleport,\n useZIndex,\n} from 'dou-ui'\nimport {\n computed,\n getCurrentInstance,\n markRaw,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n reactive,\n ref,\n shallowReactive,\n shallowRef,\n toRaw,\n type VNodeChild,\n watch,\n} from 'vue'\nimport { matchBracket } from './core/brackets'\nimport { ChangeSet } from './core/changes'\nimport { indentOf, moveCluster, snapCluster, wordAt } from './core/chars'\nimport type { CodeCommand, CodeCommandTarget } from './core/commands'\nimport {\n deleteCharBackward,\n deleteCharForward,\n insertNewline,\n insertTab,\n insertText,\n selectAll,\n} from './core/commands'\nimport { type CodeFold, foldEndAt, hiddenLines, mergeRanges } from './core/folding'\nimport { CodeHistory } from './core/history'\nimport {\n type CodeKeyBinding,\n buildKeymap,\n defaultKeymap,\n eventKey,\n keymapBindings,\n} from './core/keymap'\nimport {\n type CodeRange,\n type CodeSelection,\n isEmptyRange,\n mainRange,\n normalizeSelection,\n rangeFrom,\n rangeTo,\n sameSelection,\n selectionOf,\n} from './core/selection'\nimport { CodeText, splitLines } from './core/text'\nimport {\n CodeTransaction,\n type CodeState,\n type CodeTransactionMeta,\n type CodeTransactionResult,\n} from './core/transaction'\nimport {\n type CodeMatch,\n type CodeSearchQuery,\n matchAfter,\n replacementFor,\n searchText,\n} from './core/search'\nimport { CodeHighlighter } from './language/highlighter'\nimport { holdWorker, ownWorker, SyntaxWorkerClient } from './language/worker-client'\nimport { format, useCodeMessages } from './locale'\nimport CodeKeys from './code-keys.vue'\nimport {\n CODE_EDITOR_KEY,\n type CodeCompletion,\n type CodeCompletionKind,\n type CodeCompletionResult,\n type CodeHoverResult,\n type CodeSignatureResult,\n type CodeDecoration,\n type CodeDiagnostic,\n type CodeDiagnosticSeverity,\n type CodeExtension,\n type CodeExtensionContext,\n type CodeGutterMarker,\n type CodeHistoryHandler,\n type CodePanel,\n} from './extension'\nimport RenderPart from './render-part'\nimport { matchCompletion } from './completion/match'\nimport { parseSnippet } from './completion/snippet'\nimport { type CodeLineTokens, type CodeTokenType, lineParts, tokenTypes } from './language/language'\nimport type { CodeEditorEmits, CodeEditorExpose, CodeEditorProps } from './types'\nimport { diffText } from './view/input'\nimport {\n LineLayout,\n UNWRAPPED,\n type WrappedLine,\n rowOfCol,\n updateRows,\n wrapLine,\n} from './view/layout'\nimport { Measure } from './view/measure'\nimport { visibleViewport } from './view/viewport'\n\ndefineOptions({ name: 'DouCodeEditor' })\n\nconst props = withDefaults(defineProps<CodeEditorProps>(), {\n modelValue: undefined,\n doc: undefined,\n selection: undefined,\n lineNumbers: true,\n activeLine: true,\n tabSize: 2,\n language: undefined,\n worker: false,\n closeBrackets: true,\n matchBrackets: true,\n searchable: true,\n wrap: false,\n minimap: false,\n foldable: true,\n keys: true,\n messages: undefined,\n teleport: undefined,\n tabIndents: true,\n gutter: true,\n})\nconst emit = defineEmits<CodeEditorEmits>()\nconst ns = useNamespace('code-editor')\nconst instance = getCurrentInstance()!\n\n/** Space above the first line and below the last, and before and after each line; set from the styles once measured. */\nconst pad = reactive({ x: 12, y: 8 })\n/** Browsers stop growing an element somewhere past 16M px; taller texts scroll in scaled steps. */\nconst MAX_HEIGHT = 8_000_000\nconst OVERSCAN = 6\n/** The textarea mirrors at most this much text around the cursor. */\nconst WINDOW = 4000\n\nconst apple = isApplePlatform()\n\n// ---------------------------------------------------------------- state\n\n// A ref around the text makes a deep proxy of it; the editor reads the plain object.\nconst initialDoc = () =>\n (props.doc && toRaw(props.doc)) ??\n (props.modelValue !== undefined ? CodeText.of(props.modelValue) : CodeText.empty)\nconst startDoc = initialDoc()\nconst state = shallowRef<CodeState>(\n markRaw({\n doc: startDoc,\n selection: normalizeSelection(toRaw(props.selection) ?? selectionOf(0), startDoc.length),\n }),\n)\nconst doc = computed(() => state.value.doc)\nconst history = markRaw(new CodeHistory())\nconst historyTick = ref(0)\n\n/** The last string handed out, for the text it was made from, so it is joined at most once. */\nlet joined: { doc: CodeText; text: string } | null = null\nconst textOf = (text: CodeText) => {\n if (joined?.doc !== text) joined = { doc: text, text: text.toString() }\n return joined.text\n}\nconst listens = (event: string) => !!instance.vnode.props?.[event]\nlet lazyDirty = false\n/** Values this editor handed out; seeing one come back through a prop is only an echo. */\nconst handedOut = new WeakSet<object>()\nfunction emitDoc(value: CodeText) {\n handedOut.add(value)\n emit('update:doc', value)\n}\nfunction emitSelection(value: CodeSelection) {\n handedOut.add(value)\n emit('update:selection', value)\n}\n\nfunction emitChange(result: CodeTransactionResult) {\n const { state: next, before, changes } = result\n if (!changes.empty) {\n emitDoc(next.doc)\n if (props.modelModifiers?.lazy) lazyDirty = true\n else if (listens('onUpdate:modelValue')) emit('update:modelValue', textOf(next.doc))\n }\n if (!sameSelection(next.selection, before.selection)) emitSelection(next.selection)\n emit('transaction', result)\n}\n\n// ---------------------------------------------------------------- transactions\n\n/** Goal x of each cursor moved up or down, so it keeps its column across short lines. */\nlet goals = new Map<number, number>()\nlet pendingGoals = new Map<number, number>()\nconst blink = ref(0)\n\n/** The last press was a finger: the selection gets handles, and a toolbar over it. */\nconst touchUi = ref(false)\n/** A handle under a lone cursor, shown after a tap until the text changes. */\nconst caretHandle = ref(false)\n/** The toolbar over the selection (cut, copy, paste, select all). */\nconst menuOpen = ref(false)\n/** A finger drags a handle or a long-pressed selection: the magnifier shows. */\nconst touchDrag = ref(false)\n\n/** Steps whose changes aren't this user's typing: extensions' `transaction` hooks don't see them. */\nconst UNHOOKED = new Set(['undo', 'redo', 'external', 'remote'])\n\n/** Runs every extension's `update` hook for a step that was applied. */\nfunction notify(result: CodeTransactionResult) {\n for (const extension of extensions.value) extension.update?.(result, context)\n}\n\nfunction dispatch(tr: CodeTransaction): CodeTransactionResult {\n const { action } = tr.meta\n if (!UNHOOKED.has(action ?? ''))\n for (const extension of extensions.value) extension.transaction?.(tr, context)\n const result = tr.resolve()\n const before = state.value\n if (!result.changed) {\n pendingGoals = new Map()\n return result\n }\n // Someone else's change: what this user has open (menus, the problem box, the goal column) stays.\n const remote = action === 'remote'\n if (!result.changes.empty && !historyHandler.value) {\n history.record(result)\n historyTick.value++\n }\n if (!result.changes.empty) {\n if (composing.value) mapComposition(result.changes)\n syntaxChange(result.state.doc, result.changes)\n mapMatches(result.changes)\n updateWrap(before.doc, result.state.doc, result.changes)\n mapFolds(result.changes, result.state.doc)\n mapDiagnostics(result.changes, result.state.doc)\n scheduleLint()\n }\n state.value = markRaw(result.state)\n revealFolds()\n if (!remote) {\n problemBox.value = null\n // The toolbar is for the selection it opened on; typing also puts away the handle under a lone cursor.\n menuOpen.value = false\n if (!result.changes.empty) caretHandle.value = false\n goals = pendingGoals\n blink.value++\n }\n pendingGoals = new Map()\n if (!composing.value) syncInput()\n updateAssist(result)\n emitChange(result)\n notify(result)\n if (result.meta.scroll ?? !result.changes.empty)\n nextTick(() => {\n scrollIntoView()\n if (touchUi.value) followViewport()\n })\n return result\n}\n\nconst transaction = () => new CodeTransaction(state.value)\n\n// ---------------------------------------------------------------- extensions\n\n/** The extensions, highest priority first. */\nconst extensions = computed<CodeExtension[]>(() =>\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n (props.extensions ?? []).slice().sort((a, b) => (b.priority ?? 100) - (a.priority ?? 100)),\n)\n/** What extensions see; the same object as the instance, made once the instance is. */\nlet context: CodeExtensionContext\n\n/** Problems by who found them (`prop` for the prop, else the extension's name), moved with every edit. */\nconst diagnosticSets = shallowRef(new Map<string, CodeDiagnostic[]>())\nconst SEVERITY_RANK: Record<CodeDiagnosticSeverity, number> = {\n error: 0,\n warning: 1,\n info: 2,\n hint: 3,\n}\n\nconst diagnostics = computed<readonly CodeDiagnostic[]>(() => {\n const all: CodeDiagnostic[] = []\n for (const list of diagnosticSets.value.values()) all.push(...list)\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n return all.sort(\n (a, b) => a.from - b.from || SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity],\n )\n})\n\nfunction setDiagnostics(key: string, list: readonly CodeDiagnostic[] | null | undefined) {\n const length = doc.value.length\n const next = new Map(diagnosticSets.value)\n const clean = (list ?? []).map((d) => {\n const from = Math.max(0, Math.min(length, Math.min(d.from, d.to)))\n return { ...d, from, to: Math.max(from, Math.min(length, Math.max(d.from, d.to))) }\n })\n if (clean.length) next.set(key, clean)\n else if (!next.has(key)) return\n else next.delete(key)\n diagnosticSets.value = next\n}\n\n/** Moves the problems along with an edit; one whose text was all deleted shrinks to where it was. */\nfunction mapDiagnostics(changes: ChangeSet, after: CodeText) {\n if (!diagnosticSets.value.size) return\n const next = new Map<string, CodeDiagnostic[]>()\n for (const [key, list] of diagnosticSets.value)\n next.set(\n key,\n list.map((d) => {\n const from = Math.min(after.length, changes.mapPos(d.from, 1))\n return { ...d, from, to: Math.max(from, Math.min(after.length, changes.mapPos(d.to, -1))) }\n }),\n )\n diagnosticSets.value = next\n}\n\nwatch(\n () => props.diagnostics,\n (list) => setDiagnostics('prop', list),\n { immediate: true },\n)\n\n/** Runs the linters a moment after the text stops changing. */\nconst LINT_DELAY = 300\nlet lintTimer = 0\nconst linting = computed(() => extensions.value.some((extension) => extension.lint))\n\nfunction runLint(name?: string) {\n if (name === undefined) clearTimeout(lintTimer)\n const text = doc.value\n for (const extension of extensions.value) {\n if (!extension.lint || (name !== undefined && extension.name !== name)) continue\n let found: ReturnType<NonNullable<CodeExtension['lint']>>\n try {\n found = extension.lint(context)\n } catch (error) {\n console.error(`[@dou-ui/code] ${extension.name}: lint failed`, error)\n continue\n }\n // A linter that answers at once is shown at once, without a frame of old problems.\n if (!found || !('then' in found)) {\n setDiagnostics(extension.name, found)\n continue\n }\n Promise.resolve(found)\n .then((list) => {\n // Found in a text that has changed since: the next run follows.\n if (doc.value === text) setDiagnostics(extension.name, list)\n })\n .catch((error: unknown) =>\n console.error(`[@dou-ui/code] ${extension.name}: lint failed`, error),\n )\n }\n}\n\nfunction scheduleLint() {\n if (!linting.value || !mounted.value) return\n clearTimeout(lintTimer)\n lintTimer = window.setTimeout(runLint, LINT_DELAY)\n}\n\nwatch(extensions, (next, before) => {\n // The same extensions in a new array, as an inline `:extensions=\"[a]\"` gives on every render: nothing to do.\n if (\n before &&\n before.length === next.length &&\n next.every((extension, i) => extension === before[i])\n )\n return\n // A linter that went away takes its problems with it.\n for (const gone of before ?? []) if (!next.includes(gone)) setDiagnostics(gone.name, [])\n if (mounted.value) runLint()\n})\n\nfunction transact(build: (tr: CodeTransaction) => void, meta?: CodeTransactionMeta) {\n const tr = transaction()\n if (meta) tr.setMeta(meta)\n build(tr)\n return dispatch(tr)\n}\n\nfunction applySteps(step: { changes: ChangeSet; selection: CodeSelection } | null, action: string) {\n if (!step) return false\n const tr = transaction().setMeta({ action, history: false, scroll: true })\n for (const change of step.changes.changes) tr.replace(change.from, change.to, change.insert)\n tr.select(step.selection)\n dispatch(tr)\n return true\n}\n\n/** The undo history an extension brings in place of the editor's own; the first one wins. */\nconst historyHandler = computed<CodeHistoryHandler | null>(() => {\n for (const extension of extensions.value)\n if (extension.history) return markRaw(extension.history(context))\n return null\n})\nconst undo = () =>\n !props.readonly &&\n (historyHandler.value ? historyHandler.value.undo() : applySteps(history.undo(), 'undo'))\nconst redo = () =>\n !props.readonly &&\n (historyHandler.value ? historyHandler.value.redo() : applySteps(history.redo(), 'redo'))\nconst closeHistory = () => (historyHandler.value ? historyHandler.value.close?.() : history.close())\n\n/**\n * Takes in a new text from outside as the smallest change, so the cursor\n * and undo survive. `given` is the text as a `CodeText` when it came in as\n * one; it is kept as it is, so it compares equal when it comes back.\n */\nfunction receive(next: string, given?: CodeText) {\n if (joined && joined.text === next && joined.doc === doc.value) return\n const old = textOf(doc.value)\n const normalized = next.includes('\\r') ? next.replace(/\\r\\n?/g, '\\n') : next\n const diff = diffText(old, normalized, mainRange(state.value.selection).head)\n if (!diff) {\n if (given) {\n highlighter?.update(given, ChangeSet.of([], given.length))\n state.value = markRaw({ ...state.value, doc: given })\n if (wrapRows) rebuildWrap()\n }\n return\n }\n const tr = transaction().setMeta({ action: 'external', scroll: false })\n tr.replace(diff.from, diff.to, diff.insert)\n const resolved = tr.resolve()\n const result = given\n ? { ...resolved, state: markRaw({ ...resolved.state, doc: given }) }\n : resolved\n if (!historyHandler.value) {\n history.record(result)\n historyTick.value++\n }\n if (composing.value) mapComposition(result.changes)\n syntaxChange(result.state.doc, result.changes)\n updateWrap(result.before.doc, result.state.doc, result.changes)\n mapFolds(result.changes, result.state.doc)\n mapDiagnostics(result.changes, result.state.doc)\n problemBox.value = null\n scheduleLint()\n state.value = markRaw(result.state)\n mapMatches(result.changes)\n menuOpen.value = false\n caretHandle.value = false\n joined = { doc: result.state.doc, text: normalized }\n if (!composing.value) syncInput()\n if (!sameSelection(result.state.selection, result.before.selection))\n emitSelection(result.state.selection)\n // Hand the new text back in the other shape only; the one it came in is already up to date.\n if (!given) emitDoc(result.state.doc)\n else if (listens('onUpdate:modelValue')) emit('update:modelValue', normalized)\n emit('transaction', result)\n notify(result)\n}\n\nwatch(\n () => props.modelValue,\n (value) => value !== undefined && receive(value),\n)\nwatch(\n () => props.doc && toRaw(props.doc),\n (value) => {\n if (!value || value === doc.value || handedOut.has(value)) return\n receive(value.toString(), value)\n },\n)\nwatch(\n () => props.selection && toRaw(props.selection),\n (value) => {\n if (!value || handedOut.has(value)) return\n const next = normalizeSelection(value, doc.value.length)\n if (sameSelection(next, state.value.selection)) return\n dispatch(transaction().select(next).setMeta({ scroll: true }))\n },\n)\n\n// ---------------------------------------------------------------- layout\n\nconst root = ref<HTMLElement>()\nconst scroller = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\nconst probe = ref<HTMLElement>()\nconst input = ref<HTMLTextAreaElement>()\nconst measure = markRaw(new Measure(() => probe.value))\n/** Bumped when the font metrics change, so everything drawn from them is worked out again. */\nconst metrics = ref(0)\n\nconst mounted = ref(false)\nconst scrollTop = ref(0)\nconst scrollLeft = ref(0)\nconst viewHeight = ref(0)\nconst viewWidth = ref(0)\n/** The part of the scroller that is inside the window, for an editor taller than the page. */\nconst clip = ref<{ top: number; bottom: number } | null>(null)\n\nconst lineHeight = computed(() => {\n void metrics.value\n return measure.lineHeight\n})\n\n// ---------------------------------------------------------------- wrapping and folding\n\n/** The width a row of text may take when wrapping; 0 when lines don't wrap. */\nconst wrapWidth = computed(() => {\n // Cut nothing before the editor knows its width.\n if (!props.wrap || !mounted.value) return 0\n void metrics.value\n const width = viewWidth.value - gutterWidth.value - pad.x * 2 - measure.cell\n return Math.max(measure.cell * 8, width)\n})\n/** How each line text is cut at the current width; texts repeat (blank lines, braces), so this is by text. */\nlet wrapCache = new Map<string, WrappedLine>()\n/** Rows of each line while wrapping (index `n - 1`), kept in step with edits. */\nlet wrapRows: number[] | null = null\n/** Bumped when `wrapRows` changes without the text changing. */\nconst layoutTick = ref(0)\n\nfunction wrapOf(text: string): WrappedLine {\n const width = wrapWidth.value\n if (!width || text.length * measure.cell <= width / 2) return UNWRAPPED\n let wrapped = wrapCache.get(text)\n if (!wrapped) {\n if (wrapCache.size > 20_000) wrapCache = new Map()\n wrapped = wrapLine(text, width, measure)\n wrapCache.set(text, wrapped)\n }\n return wrapped\n}\n\nconst rowsOfText = (text: string) => wrapOf(text).breaks.length + 1\n\nfunction rebuildWrap() {\n wrapCache = new Map()\n wrapRows = wrapWidth.value ? doc.value.lineTexts(1, doc.value.lines).map(rowsOfText) : null\n layoutTick.value++\n}\n\n/** Moves the wrapped rows along with an edit, cutting again only the lines it touched. */\nfunction updateWrap(before: CodeText, after: CodeText, changes: ChangeSet) {\n if (!wrapRows) return\n if (!updateRows(wrapRows, before, after, changes, rowsOfText)) rebuildWrap()\n}\n\nconst folds = shallowRef<CodeFold[]>([])\nconst NOTHING_HIDDEN: Array<[number, number]> = []\nconst foldHidden = computed(() =>\n folds.value.length ? hiddenLines(doc.value, folds.value) : NOTHING_HIDDEN,\n)\n/** The lines extensions hide, as sorted ranges that don't overlap. */\nconst extensionHidden = computed(() => {\n const lines = doc.value.lines\n const ranges: Array<[number, number]> = []\n for (const extension of extensions.value) {\n if (!extension.hide) continue\n for (const { from, to } of extension.hide(context)) {\n const a = Math.max(1, Math.floor(from))\n const b = Math.min(lines, Math.floor(to))\n if (b >= a) ranges.push([a, b])\n }\n }\n return ranges.length ? mergeRanges(ranges) : NOTHING_HIDDEN\n})\n/** The lines not drawn: folded, or hidden by an extension. */\nconst hidden = computed(() => {\n const own = foldHidden.value\n const other = extensionHidden.value\n if (!other.length) return own\n if (!own.length) return other\n return mergeRanges([...own, ...other])\n})\nconst layout = computed<LineLayout>((previous) => {\n void layoutTick.value\n const lines = doc.value.lines\n const rows = wrapRows && wrapRows.length === lines ? wrapRows : null\n // One row per line and the same count: the same layout, so nothing drawn from it is worked out again.\n if (!rows && !hidden.value.length && previous?.uniform && previous.lines === lines)\n return previous\n return markRaw(new LineLayout(lines, rows, hidden.value))\n})\n\n// ---------------------------------------------------------------- widgets between lines\n\n/** The widgets' heights as last measured, by key. */\nconst widgetHeights = shallowReactive(new Map<string, number>())\n\ninterface PlacedWidget {\n key: string\n line: number\n above: boolean\n render: () => VNodeChild\n label?: string\n /** The row it sits just before: the line's first row above it, the next line's first row below it. */\n row: number\n height: number\n /** Heights of the widgets before it. */\n before: number\n}\n\n/** The extensions' widgets on lines that are drawn, in the order they sit, with their heights. */\nconst widgets = computed<PlacedWidget[]>(() => {\n const drawn = layout.value\n const lh = lineHeight.value\n const out: PlacedWidget[] = []\n for (const extension of extensions.value) {\n if (!extension.widgets) continue\n for (const widget of extension.widgets(context)) {\n const n =\n widget.pos !== undefined\n ? doc.value.lineAt(Math.max(0, Math.min(doc.value.length, widget.pos))).number\n : (widget.line ?? 0)\n if (n < 1 || n > drawn.lines || !drawn.shown(n)) continue\n const above = widget.position === 'above'\n const key = `${extension.name}/${widget.id}`\n out.push({\n key,\n line: n,\n above,\n render: widget.render,\n label: widget.label,\n row: drawn.rowOf(n) + (above ? 0 : drawn.rowsOf(n)),\n height: widgetHeights.get(key) ?? widget.height ?? lh,\n before: 0,\n })\n }\n }\n if (!out.length) return out\n // By row; on one row, the widget below a line before the one above the next.\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n out.sort((a, b) => a.row - b.row || Number(a.above) - Number(b.above) || a.line - b.line)\n let sum = 0\n for (const widget of out) {\n widget.before = sum\n sum += widget.height\n }\n return out\n})\n\n/** How much of the widgets' height comes before row `row`. */\nfunction widgetsBefore(row: number) {\n const list = widgets.value\n let lo = 0\n let hi = list.length\n // The first widget past `row`; all before it come first.\n while (lo < hi) {\n const mid = (lo + hi) >> 1\n if (list[mid]!.row <= row) lo = mid + 1\n else hi = mid\n }\n if (!lo) return 0\n const last = list[lo - 1]!\n return last.before + last.height\n}\n\n/** The y of row `row` from the text's top, below the widgets before it. */\nconst rowTop = (row: number) => row * lineHeight.value + widgetsBefore(row)\n\n/** The row at a y from the text's top; a y over a widget gives the row right after it. */\nfunction rowAtTextY(y: number) {\n const list = widgets.value\n const lh = lineHeight.value\n if (!list.length) return Math.floor(y / lh)\n // The last widget that starts at or before `y`.\n let lo = 0\n let hi = list.length\n while (lo < hi) {\n const mid = (lo + hi) >> 1\n if (list[mid]!.row * lh + list[mid]!.before <= y) lo = mid + 1\n else hi = mid\n }\n if (!lo) return Math.floor(y / lh)\n const widget = list[lo - 1]!\n const end = widget.row * lh + widget.before + widget.height\n if (y < end) return widget.row\n return widget.row + Math.floor((y - end) / lh)\n}\n\nconst widgetsHeight = computed(() => {\n const list = widgets.value\n const last = list[list.length - 1]\n return last ? last.before + last.height : 0\n})\n\nconst total = computed(() => layout.value.total * lineHeight.value + widgetsHeight.value)\nconst sizerHeight = computed(() => Math.min(total.value, MAX_HEIGHT) + pad.y * 2)\n/** How much faster than the scrollbar the text moves, above `MAX_HEIGHT`. */\nconst ratio = computed(() => {\n if (total.value <= MAX_HEIGHT) return 1\n const view = viewHeight.value || 1\n return Math.max(1, (total.value - view) / Math.max(1, MAX_HEIGHT - view))\n})\n/** Offset between the text's own y and where it is drawn in the scaled scroller. */\nconst shift = computed(() => scrollTop.value - scrollTop.value * ratio.value)\n/** The y line `n` is drawn at. */\nconst yOf = (line: number) => pad.y + rowTop(layout.value.rowOf(line)) + shift.value\n/** The row under a y in the content, from the text's top. */\nconst rowAtY = (y: number) => rowAtTextY(y - pad.y - shift.value)\n\nconst visibleFrom = computed(() => {\n const top = scrollTop.value * ratio.value + (clip.value?.top ?? 0)\n const row = rowAtTextY(Math.max(0, top - pad.y)) - OVERSCAN\n return layout.value.lineAtRow(Math.max(0, row)).n\n})\nconst visibleTo = computed(() => {\n const bottom = scrollTop.value * ratio.value + (clip.value?.bottom ?? viewHeight.value)\n const row = rowAtTextY(Math.max(0, bottom - pad.y)) + 1 + OVERSCAN\n return layout.value.lineAtRow(row).n\n})\n\n/** The widgets in view, where they are drawn. */\nconst shownWidgets = computed(() => {\n const list = widgets.value\n if (!list.length) return []\n const from = layout.value.rowOf(visibleFrom.value)\n const to = layout.value.rowOf(visibleTo.value) + layout.value.rowsOf(visibleTo.value)\n const lh = lineHeight.value\n return list\n .filter((widget) => widget.row >= from && widget.row <= to)\n .map((widget) => ({\n ...widget,\n top: pad.y + widget.row * lh + widget.before + shift.value,\n }))\n})\n\n/** Room left in the column of lines (and of numbers) before line `n` for the widgets there; none before the first line drawn, which is placed past them. */\nfunction gapBefore(n: number) {\n if (n === visibleFrom.value || !widgets.value.length) return 0\n const row = layout.value.rowOf(n)\n return widgetsBefore(row) - widgetsBefore(row - 1)\n}\n\nlet widgetObserver: ResizeObserver | undefined\nconst observedWidgets = new Map<Element, string>()\n/** Measures a widget as drawn, keeping its height so the lines after it are placed below it. */\nfunction observeWidget(el: Element | null, key: string) {\n if (!el || observedWidgets.get(el) === key) return\n observedWidgets.set(el, key)\n const measureNow = (target: Element) => {\n const id = observedWidgets.get(target)\n if (!id || !target.isConnected) return\n const height = (target as HTMLElement).offsetHeight\n // Nothing measured means no layout (a hidden editor): keep the guess.\n if (height && widgetHeights.get(id) !== height) widgetHeights.set(id, height)\n }\n measureNow(el)\n if (typeof ResizeObserver === 'undefined') return\n widgetObserver ??= new ResizeObserver((entries) => {\n for (const entry of entries) measureNow(entry.target)\n for (const [target] of observedWidgets)\n if (!target.isConnected) {\n widgetObserver!.unobserve(target)\n observedWidgets.delete(target)\n }\n })\n widgetObserver.observe(el)\n}\n\n/** The lines in view that are drawn (folded ones left out), with their text; read in runs, once per frame. */\nconst shownLines = computed(() => {\n const from = visibleFrom.value\n const to = visibleTo.value\n const text = doc.value\n const numbers: number[] = []\n const texts: string[] = []\n let n = from\n for (const [a, b] of hidden.value) {\n if (b < n) continue\n if (a > to) break\n if (a > n) {\n const chunk = text.lineTexts(n, a - 1)\n for (let i = 0; i < chunk.length; i++) numbers.push(n + i)\n texts.push(...chunk)\n }\n n = Math.max(n, b + 1)\n }\n if (n <= to) {\n const chunk = text.lineTexts(n, to)\n for (let i = 0; i < chunk.length; i++) numbers.push(n + i)\n texts.push(...chunk)\n }\n return { numbers, texts }\n})\nconst lines = computed(() => shownLines.value.texts)\n/** A line's text, from the lines in view when it is one of them. */\nfunction lineText(n: number) {\n const { numbers, texts } = shownLines.value\n let lo = 0\n let hi = numbers.length - 1\n while (lo <= hi) {\n const mid = (lo + hi) >> 1\n if (numbers[mid] === n) return texts[mid]!\n if (numbers[mid]! < n) lo = mid + 1\n else hi = mid - 1\n }\n return doc.value.line(n).text\n}\nconst isShown = (n: number) =>\n n >= visibleFrom.value && n <= visibleTo.value && layout.value.shown(n)\n\n/** Where column `col` of line `n` is drawn: the row's top, the x from the text's left edge, and which row of the line. */\nfunction place(n: number, text: string, col: number) {\n const wrapped = wrapOf(text)\n const sub = rowOfCol(wrapped, col)\n const top = yOf(n) + sub * lineHeight.value\n // The inline widgets before the column on its row, and one right at it: the cursor goes after them.\n if (!sub) return { top, x: measure.x(text, col) + inlineWidth(n, 0, col), sub }\n const start = wrapped.breaks[sub - 1]!\n return {\n top,\n x: wrapped.indent + measure.x(text, col) - measure.x(text, start) + inlineWidth(n, start, col),\n sub,\n }\n}\n\n/** The column nearest to `x` on row `sub` of line `n`. */\nfunction colAt(n: number, text: string, sub: number, x: number) {\n const wrapped = wrapOf(text)\n const { breaks } = wrapped\n if (!breaks.length) return colInRow(n, text, 0, text.length, x)\n const start = sub ? breaks[sub - 1]! : 0\n const end = sub < breaks.length ? breaks[sub]! : text.length\n const col = colInRow(n, text, start, end, Math.max(0, x - (sub ? wrapped.indent : 0)))\n // The end of a row that isn't the last is the start of the next one; stay on this row.\n if (sub < breaks.length && col >= end) return Math.max(start, moveCluster(text, end, -1))\n return Math.max(start, col)\n}\n\n/** Boxes over columns `from` to `to` of line `n`, one per row; `tail` adds width past the line's end. */\nfunction spans(n: number, text: string, from: number, to: number, tail = 0) {\n const wrapped = wrapOf(text)\n const out: Array<{ top: number; left: number; width: number }> = []\n const rows = wrapped.breaks.length + 1\n const top = yOf(n)\n for (let sub = 0; sub < rows; sub++) {\n const start = sub ? wrapped.breaks[sub - 1]! : 0\n const end = sub < rows - 1 ? wrapped.breaks[sub]! : text.length\n if (to < start || from > end || (from === end && sub < rows - 1)) continue\n const a = Math.max(from, start)\n const b = Math.min(to, end)\n const base = sub ? wrapped.indent - measure.x(text, start) : 0\n // From after the widgets at `a` to before those at `b`.\n const left = base + measure.x(text, a) + inlineWidth(n, start, a)\n const right =\n base + measure.x(text, b) + inlineWidth(n, start, b - 1) + (sub === rows - 1 ? tail : 0)\n if (right > left) out.push({ top: top + sub * lineHeight.value, left, width: right - left })\n }\n return out\n}\n\nconst SEVERITY_ICON = {\n error: XCircleIcon,\n warning: AlertTriangleIcon,\n info: InfoIcon,\n hint: LightbulbIcon,\n} as const\n\n/** Columns left of the line numbers: the problems' column, then the extensions' own. */\nconst gutterColumns = computed(() => {\n const columns: Array<{\n name: string\n width: number\n markers: () => CodeGutterMarker[]\n onPress?: (line: number, event: PointerEvent) => void\n }> = []\n if (!props.gutter) return columns\n // Kept while anything may report problems, so the text doesn't jump when the first one comes.\n if (props.diagnostics !== undefined || linting.value || diagnostics.value.length)\n columns.push({ name: 'problems', width: 16, markers: problemMarkers })\n for (const extension of extensions.value)\n for (const gutter of extension.gutters ?? [])\n columns.push({\n name: gutter.name,\n width: gutter.width ?? 16,\n markers: () => gutter.markers(context),\n onPress: gutter.onPress && ((line, event) => gutter.onPress!(line, event, context)),\n })\n return columns\n})\nconst gutterCells = computed(() =>\n gutterColumns.value.reduce((sum, column) => sum + column.width, 0),\n)\n\n/** The worst problem on each line in view, as a marker. */\nfunction problemMarkers(): CodeGutterMarker[] {\n const text = doc.value\n const first = visibleFrom.value\n const last = visibleTo.value\n const end = text.line(last).to\n const worst = new Map<number, CodeDiagnostic>()\n for (const problem of diagnostics.value) {\n if (problem.from > end) break\n const n = text.lineAt(problem.from).number\n if (n < first) continue\n const had = worst.get(n)\n if (!had || SEVERITY_RANK[problem.severity] < SEVERITY_RANK[had.severity]) worst.set(n, problem)\n }\n const m = messages.value\n return [...worst].map(([line, problem]) => ({\n line,\n icon: SEVERITY_ICON[problem.severity],\n class: `dou-code-editor__problem-icon is-${problem.severity}`,\n title: `${m[problem.severity]}:${problem.message}`,\n }))\n}\n\n/** The markers of each column, by line, for the lines in view. */\nconst gutterMarkers = computed(() =>\n gutterColumns.value.map((column) => {\n const byLine = new Map<number, CodeGutterMarker>()\n for (const marker of column.markers()) byLine.set(marker.line, marker)\n return byLine\n }),\n)\n\nconst gutterWidth = computed(() => {\n const cells = gutterCells.value\n if (!props.gutter || (!props.lineNumbers && !props.foldable && !cells)) return 0\n void metrics.value\n const digits = Math.max(2, String(doc.value.lines).length)\n const numbers = props.lineNumbers ? Math.ceil(digits * measure.cell) + 28 : 12\n return cells + numbers + (props.foldable ? 14 : 0)\n})\n\nconst contentWidth = computed(() => {\n if (props.wrap) return 0\n void metrics.value\n let widest = doc.value.widest * measure.cell\n for (const text of lines.value) {\n if (text.length * measure.cell * 2 < widest) continue\n widest = Math.max(widest, measure.x(text, text.length))\n }\n for (const [n, own] of lineDecorations.value.inlines) {\n const text = lineText(n)\n widest = Math.max(\n widest,\n measure.x(text, text.length) + own.reduce((w, i) => w + widthOf(i), 0),\n )\n }\n return Math.ceil(widest + pad.x * 2 + measure.cell)\n})\n\nwatch(wrapWidth, rebuildWrap, { immediate: true })\n\n// ---------------------------------------------------------------- folding\n\n/**\n * Where a fold starting at line `n` would end, or `null`; by brackets with a\n * language, else by indentation. Brackets in strings and comments count\n * only where the text has been read already, so folding a whole long text\n * doesn't read all of it first.\n */\nconst inStringOrComment = (pos: number) => {\n const kind = syntaxAt(pos)\n return kind === 'string' || kind === 'comment'\n}\n\nfunction foldEnd(n: number) {\n return foldEnds()(n)\n}\n\n/**\n * A function giving where folds end in the text as it is now, set up once\n * for asking about many lines; `lines` holds the lines' texts when the\n * caller has them.\n */\nfunction foldEnds(texts?: readonly string[]) {\n const text = doc.value\n const hl = highlighter\n const outer = props.language\n const tabSize = props.tabSize\n const lineOf = texts ? (k: number) => texts[k - 1]! : undefined\n return (n: number) => {\n const read = !!hl?.ready(n)\n const language = outer ? ((read ? hl!.languageAt(n) : null) ?? outer) : null\n return foldEndAt(text, n, {\n brackets: language?.brackets,\n tabSize,\n skip: read ? inStringOrComment : undefined,\n lineText: lineOf,\n })\n }\n}\n\n/** The lines that start a fold, from 1. */\nconst foldStarts = computed(() => folds.value.map((fold) => doc.value.lineAt(fold.from).number))\nwatch(foldStarts, (next, prev) => {\n if (next.length !== prev.length || next.some((n, i) => n !== prev[i])) emit('foldChange', next)\n})\n\nfunction setFolds(next: CodeFold[]) {\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n folds.value = next.slice().sort((a, b) => a.from - b.from)\n}\n\n/** Moves the folds along with an edit; a fold whose lines were joined goes away. */\nfunction mapFolds(changes: ChangeSet, after: CodeText) {\n if (!folds.value.length) return\n setFolds(\n folds.value\n .map((fold) => ({ from: changes.mapPos(fold.from, 1), to: changes.mapPos(fold.to, -1) }))\n .filter((fold) => after.lineAt(fold.to).number > after.lineAt(fold.from).number),\n )\n}\n\n/** Unfolds whatever hides a cursor, so the cursor is never out of sight. */\nfunction revealFolds() {\n if (!folds.value.length) return\n const heads = state.value.selection.ranges.map((range) => range.head)\n const keep = folds.value.filter((fold) => !heads.some((h) => h > fold.from && h <= fold.to))\n if (keep.length !== folds.value.length) folds.value = keep\n}\n\n/** Folds the block starting at line `n`; cursors inside move to its first line. */\nfunction foldLine(n: number) {\n const end = foldEnd(n)\n if (end === null) return false\n const text = doc.value\n const fold = { from: text.line(n).to, to: text.line(end).to }\n if (folds.value.some((f) => f.from === fold.from)) return false\n const { selection } = state.value\n if (selection.ranges.some((range) => range.head > fold.from && range.head <= fold.to)) {\n const ranges = selection.ranges.map((range) =>\n range.head > fold.from && range.head <= fold.to\n ? { anchor: fold.from, head: fold.from }\n : range,\n )\n dispatch(\n transaction().select(normalizeSelection({ ranges, main: selection.main }, text.length)),\n )\n }\n setFolds([...folds.value, fold])\n announce(format(messages.value.folded, { from: n + 1, to: end }))\n return true\n}\n\n/** Reads a fold out; the same words twice in a row are read again. */\nfunction announce(text: string) {\n announcement.value = announcement.value === text ? `${text}\\u200b` : text\n}\n\nconst folding = {\n fold(line?: number) {\n if (!props.foldable) return false\n const text = doc.value\n const n = line ?? text.lineAt(mainRange(state.value.selection).head).number\n if (line !== undefined) return foldLine(n)\n // The block that starts here, or else the nearest one above that reaches down to here.\n for (let k = n; k >= Math.max(1, n - 2000); k--) {\n const end = foldEnd(k)\n if (end !== null && (k === n || end >= n) && foldLine(k)) return true\n }\n return false\n },\n unfold(line?: number) {\n const text = doc.value\n const n = line ?? text.lineAt(mainRange(state.value.selection).head).number\n const keep = folds.value.filter((fold) => {\n const from = text.lineAt(fold.from).number\n return n < from || n > text.lineAt(fold.to).number\n })\n if (keep.length === folds.value.length) return false\n folds.value = keep\n announce(messages.value.unfolded)\n return true\n },\n foldAll() {\n if (!props.foldable) return false\n const text = doc.value\n const next: CodeFold[] = []\n const endOf = foldEnds(text.lineTexts(1, text.lines))\n for (let n = 1; n < text.lines; n++) {\n const end = endOf(n)\n if (end === null) continue\n next.push({ from: text.line(n).to, to: text.line(end).to })\n n = end\n }\n if (!next.length) return false\n setFolds(next)\n announce(messages.value.foldedAll)\n // Cursors that ended up hidden go to the top of their block.\n const { selection } = state.value\n const ranges = selection.ranges.map((range) => {\n const fold = next.find((f) => range.head > f.from && range.head <= f.to)\n return fold ? { anchor: fold.from, head: fold.from } : range\n })\n dispatch(\n transaction().select(normalizeSelection({ ranges, main: selection.main }, text.length)),\n )\n return true\n },\n unfoldAll() {\n if (!folds.value.length) return false\n folds.value = []\n announce(messages.value.unfoldedAll)\n return true\n },\n}\n\n/** Whether lines in view start a block, worked out only while the gutter is pointed at (or on touch screens). */\nconst gutterHover = ref(false)\n/**\n * A touch screen. Read once mounted, never while rendering on the server:\n * the first render must match the server's markup, then touch-only parts show.\n */\nconst coarse = ref(false)\nonMounted(() => {\n coarse.value = typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches\n})\nlet foldCache = { doc: null as CodeText | null, ends: new Map<number, number | null>() }\nconst foldableLines = computed(() => {\n const out = new Set<number>()\n if (!props.foldable || !(gutterHover.value || coarse.value)) return out\n void syntaxTick.value\n if (foldCache.doc !== doc.value) foldCache = { doc: doc.value, ends: new Map() }\n for (const n of shownLines.value.numbers) {\n let end = foldCache.ends.get(n)\n if (end === undefined) {\n end = foldEnd(n)\n foldCache.ends.set(n, end)\n }\n if (end !== null) out.add(n)\n }\n return out\n})\n\nfunction toggleFold(n: number, folded: boolean) {\n if (folded) folding.unfold(n)\n else folding.fold(n)\n}\n\n// ---------------------------------------------------------------- composition\n\nconst composing = ref(false)\n/** What the input method shows while composing: a replacement of the text, drawn but not applied yet. */\nconst preview = shallowRef<{ from: number; to: number; insert: string } | null>(null)\n/**\n * Changes that came in while composing (someone else's, or a new\n * `v-model`): the textarea still holds the text from before them, so what\n * it gives back is moved through these.\n */\nlet composeMap: ChangeSet | null = null\n\n/** A position in the text the textarea was filled from, in the text now. */\nconst composedPos = (pos: number, assoc: -1 | 1) =>\n composeMap ? composeMap.mapPos(pos, assoc) : pos\n\nfunction mapComposition(changes: ChangeSet) {\n composeMap = composeMap ? composeMap.compose(changes) : changes\n const shown = preview.value\n if (shown)\n preview.value = {\n ...shown,\n from: changes.mapPos(shown.from, -1),\n to: Math.max(changes.mapPos(shown.from, -1), changes.mapPos(shown.to, 1)),\n }\n}\n\n/** A class over part of a line, `from`–`to` in the line, with a title shown on hover. */\ntype Mark = [\n from: number,\n to: number,\n cls: string,\n title?: string,\n style?: Readonly<Record<string, string>>,\n]\n\n/** A widget inside a line, before column `col`. */\ninterface Inline {\n col: number\n key: string\n render: () => VNodeChild\n width?: number\n}\n\ninterface Row {\n n: number\n text: string\n /** How the line is cut into rows, when it wraps. */\n wrapped: WrappedLine\n /** The line starts a fold. */\n folded: boolean\n /** The line's tokens, when its language has read it; kept the same while the line doesn't change. */\n tokens: CodeLineTokens | null\n /** Set on the line being composed: the text drawn before, inside and after the composition. */\n compose?: [before: string, insert: string, after: string]\n /** Classes on parts of the line, from decorations and problems: `[from, to, class, title]` in the line. */\n marks?: Mark[]\n /** The same, as one string, to tell when they changed. */\n marksKey?: string\n /** Classes on the whole line, from decorations. */\n lineClass?: string\n /** Widgets inside the line, by column. */\n inlines?: Inline[]\n /** Their keys and columns, as one string, to tell when they changed. */\n inlinesKey?: string\n}\n\nconst rows = computed<Row[]>(() => {\n const { numbers, texts } = shownLines.value\n const p = preview.value\n const line = p ? doc.value.lineAt(p.from) : null\n const tokensOf = syntaxLines(visibleFrom.value, visibleTo.value)\n const starts = new Set(foldHidden.value.map(([from]) => from - 1))\n const { marks, lineClasses, inlines } = lineDecorations.value\n return texts.map((text, i) => {\n const n = numbers[i]!\n const tokens = tokensOf(n)\n const wrapped = wrapOf(text)\n const folded = starts.has(n)\n if (!p || n !== line!.number) {\n const own = marks.get(n)\n return {\n n,\n text,\n tokens,\n wrapped,\n folded,\n marks: own,\n marksKey: own?.map((m) => m.join(',')).join(';'),\n lineClass: lineClasses.get(n),\n inlines: inlines.get(n),\n inlinesKey: inlines\n .get(n)\n ?.map((item) => `${item.col}:${item.key}`)\n .join(';'),\n }\n }\n const col = p.from - line!.from\n const end = p.to <= line!.to ? p.to - line!.from : col\n return {\n n,\n text,\n tokens: null,\n wrapped,\n folded,\n compose: [text.slice(0, col), p.insert, text.slice(end)],\n }\n })\n})\n\n/** What extensions decorate, asked for while drawing. */\nconst decorations = computed<CodeDecoration[]>(() => {\n const out: CodeDecoration[] = []\n for (const extension of extensions.value)\n if (extension.decorations) out.push(...extension.decorations(context))\n return out\n})\n\n/** Decorations and problems on the lines in view, cut to each line. */\nconst lineDecorations = computed(() => {\n const marks = new Map<number, Mark[]>()\n const lineClasses = new Map<number, string>()\n const inlines = new Map<number, Inline[]>()\n const list = decorations.value\n const problems = diagnostics.value\n const session = snippet.value\n if (!list.length && !problems.length && !session) return { marks, lineClasses, inlines }\n const text = doc.value\n const first = visibleFrom.value\n const last = visibleTo.value\n const start = text.line(first).from\n const end = text.line(last).to\n const mark = (\n from: number,\n to: number,\n cls: string,\n title?: string,\n style?: Readonly<Record<string, string>>,\n ) => {\n if (to < start || from > end || to <= from) return\n const a = text.lineAt(Math.max(from, start))\n const b = text.lineAt(Math.min(to, end))\n for (let n = a.number; n <= b.number; n++) {\n const line = n === a.number ? a : n === b.number ? b : text.line(n)\n const x = Math.max(from, line.from) - line.from\n const y = Math.min(to, line.to) - line.from\n if (y <= x) continue\n const own = marks.get(n)\n const item: Mark = style\n ? [x, y, cls, title, style]\n : title\n ? [x, y, cls, title]\n : [x, y, cls]\n if (own) own.push(item)\n else marks.set(n, [item])\n }\n }\n for (const item of list) {\n if (item.type === 'line') {\n if (item.line < first || item.line > last) continue\n const had = lineClasses.get(item.line)\n lineClasses.set(item.line, had ? `${had} ${item.class}` : item.class)\n } else if (item.type === 'inline') {\n if (item.pos < start || item.pos > end) continue\n const line = text.lineAt(item.pos)\n const own = inlines.get(line.number) ?? []\n own.push({\n col: item.pos - line.from,\n key: item.id ?? `@${item.pos}`,\n render: item.render,\n width: item.width,\n })\n inlines.set(line.number, own)\n } else mark(item.from, item.to, item.class, item.title, item.style)\n }\n // In the order they are drawn: by column, then as given.\n for (const own of inlines.values())\n if (own.length > 1) {\n const order = new Map(own.map((item, i) => [item, i]))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n own.sort((a, b) => a.col - b.col || order.get(a)! - order.get(b)!)\n }\n for (const problem of problems) {\n if (problem.from > end) break\n let { from, to } = problem\n // An empty range marks the character after it, or the one before at the end of a line.\n if (from === to) {\n const line = text.lineAt(from)\n if (from < line.to) to = line.from + moveCluster(line.text, from - line.from, 1)\n else if (from > line.from) from = line.from + moveCluster(line.text, from - line.from, -1)\n else continue\n }\n mark(from, to, `dou-code-editor__problem is-${problem.severity}`)\n }\n // The snippet's places still to fill in, after the one being filled.\n if (session)\n for (let i = session.at + 1; i < session.groups.length; i++)\n for (const range of session.groups[i]!.ranges)\n if (range.to > range.from && range.from <= end)\n mark(range.from, range.to, 'dou-code-editor__field')\n return { marks, lineClasses, inlines }\n})\n\n// ---------------------------------------------------------------- widgets inside lines\n\n/** The widths of inline widgets as last measured, by key. */\nconst inlineWidths = shallowReactive(new Map<string, number>())\nconst widthOf = (item: Inline) => item.width ?? inlineWidths.get(item.key) ?? 0\n\n/** Width of the inline widgets on line `n` at columns `from` to `to`, both included. */\nfunction inlineWidth(n: number, from: number, to: number) {\n const own = lineDecorations.value.inlines.get(n)\n if (!own) return 0\n let sum = 0\n for (const item of own) if (item.col >= from && item.col <= to) sum += widthOf(item)\n return sum\n}\n\n/**\n * The column nearest to `x` (from the row's left, past its indent) on the\n * part `start`–`end` of line `n`, stepping over the inline widgets there.\n */\nfunction colInRow(n: number, text: string, start: number, end: number, x: number) {\n const own = lineDecorations.value.inlines.get(n)\n const x0 = measure.x(text, start)\n const clamp = (col: number, low: number) => Math.max(low, Math.min(end, col))\n if (!own) return clamp(measure.col(text, x0 + x), start)\n let offset = 0\n let low = start\n for (const item of own) {\n if (item.col < start || item.col > end) continue\n const at = measure.x(text, item.col) - x0 + offset\n if (x < at) return Math.min(item.col, clamp(measure.col(text, x0 + x - offset), low))\n const width = widthOf(item)\n // Over the widget: the cursor goes on its far side, before the character it stands at.\n if (x < at + width) return item.col\n offset += width\n low = item.col\n }\n return clamp(measure.col(text, x0 + x - offset), low)\n}\n\nlet inlineObserver: ResizeObserver | undefined\nconst observedInlines = new Map<Element, string>()\n/** Measures an inline widget as drawn, keeping its width so the text after it is placed past it. */\nfunction observeInline(el: Element | null, key: string, given: number | undefined) {\n if (!el || given !== undefined || observedInlines.get(el) === key) return\n observedInlines.set(el, key)\n const measureNow = (target: Element) => {\n const width = (target as HTMLElement).offsetWidth\n const id = observedInlines.get(target)\n if (id && target.isConnected && width && inlineWidths.get(id) !== width)\n inlineWidths.set(id, width)\n }\n measureNow(el)\n if (typeof ResizeObserver === 'undefined') return\n inlineObserver ??= new ResizeObserver((entries) => {\n for (const entry of entries) measureNow(entry.target)\n for (const [target] of observedInlines)\n if (!target.isConnected) {\n inlineObserver!.unobserve(target)\n observedInlines.delete(target)\n }\n })\n inlineObserver.observe(el)\n}\n\n// ---------------------------------------------------------------- syntax\n\n/** Lines read ahead of the last read one while drawing; further away, idle time catches up first. */\nconst SYNTAX_REACH = 2000\nlet highlighter: CodeHighlighter | null = null\n/** Bumped when lines in view got their tokens in idle time. */\nconst syntaxTick = ref(0)\n\nwatch(\n () => props.language,\n (language) => {\n highlighter = language ? markRaw(new CodeHighlighter(language, doc.value, props.tabSize)) : null\n syntaxTick.value++\n },\n { immediate: true },\n)\n\n/** The worker reading ahead, with `worker`, and how to let go of it. */\nlet syntaxWorker: SyntaxWorkerClient | null = null\nlet releaseWorker: (() => void) | null = null\nlet workerJob = 0\n\nfunction stopSyntaxWorker() {\n syntaxWorker?.dispose()\n syntaxWorker = null\n releaseWorker?.()\n releaseWorker = null\n}\n\n/** Reading goes back to the page, saying why while developing. */\nfunction workerFallback(message: string, error?: unknown) {\n stopSyntaxWorker()\n syntaxTick.value++\n if (process.env.NODE_ENV !== 'production')\n console.warn(\n `[@dou-ui/code] ${message}: colors are read on the page instead.`,\n ...(error ? [error] : []),\n )\n}\n\nfunction attachWorker(worker: Worker, release: () => void) {\n const language = props.language!\n releaseWorker = release\n syntaxWorker = new SyntaxWorkerClient(worker, language, () => doc.value, props.tabSize, {\n states(points) {\n const hl = highlighter\n if (!hl || hl.language !== language) return\n hl.adopt(points)\n syntaxTick.value++\n },\n unsupported(missing) {\n workerFallback(\n missing\n ? `the worker has no language named \"${missing}\" (for \"${language.name}\"); pass it to serveCodeHighlighting in the worker`\n : `the states of \"${language.name}\" can't be sent from the worker; keep them to plain data`,\n )\n },\n failed(error) {\n workerFallback('the highlighting worker failed', error)\n },\n })\n syntaxTick.value++\n}\n\n// The worker starts in the browser only, once the editor is there; the editor ends it.\nwatch(\n [() => props.language, () => props.worker, mounted],\n ([language, option, isMounted]) => {\n stopSyntaxWorker()\n const job = ++workerJob\n if (!language || !option || !isMounted || typeof Worker === 'undefined') return\n if (option === true) {\n ownWorker().then(\n ({ worker, release }) => {\n if (job === workerJob) attachWorker(worker, release)\n else release()\n },\n (error) =>\n job === workerJob && workerFallback('the built-in worker could not start', error),\n )\n return\n }\n let worker: Worker\n try {\n worker = option()\n } catch (error) {\n workerFallback('the worker could not start', error)\n return\n }\n attachWorker(worker, holdWorker(worker))\n },\n { immediate: true },\n)\nonBeforeUnmount(() => {\n workerJob++\n stopSyntaxWorker()\n})\n\n/** Brings the colors along with a change of the text. */\nfunction syntaxChange(next: CodeText, changes: ChangeSet) {\n highlighter?.update(next, changes)\n syntaxWorker?.change(changes)\n}\n\n/** Gets the tokens of the lines in view, asking idle time for the ones too far ahead. */\nfunction syntaxLines(from: number, to: number): (n: number) => CodeLineTokens | null {\n void syntaxTick.value\n const hl = highlighter\n if (!hl) return () => null\n if (!hl.ready(to) && to - hl.frontier > SYNTAX_REACH) {\n if (syntaxWorker) syntaxWorker.want(hl.frontier, to)\n else scheduleSyntax(to)\n return (n) => (hl.ready(n) ? hl.line(n) : null)\n }\n return (n) => hl.line(n)\n}\n\nlet syntaxJob = 0\nlet syntaxUntil = 0\n/** Runs `task` when the page is idle, with how long it may take (ms). */\nconst idle =\n typeof requestIdleCallback === 'function'\n ? (task: (budget: number) => void) =>\n requestIdleCallback((deadline) => task(deadline.timeRemaining()), { timeout: 100 })\n : (task: (budget: number) => void) => window.setTimeout(() => task(8), 16)\nconst cancelIdle = (id: number) =>\n typeof cancelIdleCallback === 'function' ? cancelIdleCallback(id) : clearTimeout(id)\n\nfunction scheduleSyntax(until: number) {\n syntaxUntil = Math.max(syntaxUntil, until)\n if (syntaxJob) return\n syntaxJob = idle((budget) => {\n syntaxJob = 0\n const hl = highlighter\n if (!hl) return\n // the idle time there is, up to 20ms so a key pressed meanwhile waits little; some when it timed out\n hl.work(performance.now() + Math.min(20, Math.max(4, budget - 1)), syntaxUntil)\n if (hl.ready(syntaxUntil)) {\n syntaxUntil = 0\n syntaxTick.value++\n } else scheduleSyntax(syntaxUntil)\n })\n}\n\n/** The kind of token the character at `pos` is part of, when its line has been read. */\nfunction syntaxAt(pos: number): CodeTokenType | null {\n const hl = highlighter\n if (!hl || pos < 0 || pos >= doc.value.length) return null\n const line = doc.value.lineAt(pos)\n const tokens = hl.line(line.number, SYNTAX_REACH)\n if (!tokens) return null\n const col = pos - line.from\n for (let i = 0; i < tokens.length; i += 2) {\n if (col < tokens[i]!) {\n const type = tokens[i + 1]!\n return type < 0 ? null : tokenTypes[type]!\n }\n }\n return null\n}\n\nfunction languageAt(pos: number) {\n const hl = highlighter\n if (!hl) return null\n const line = doc.value.lineAt(Math.min(Math.max(pos, 0), doc.value.length))\n // Within reach only: far down an unread file, the outer language will do.\n if (line.number - hl.frontier > SYNTAX_REACH) return hl.language\n return hl.languageAt(line.number)\n}\n\n/**\n * A piece of a line, with the classes it is drawn with and the title of a\n * mark over it; or, with `inline`, the line's inline widget of that index\n * (its text empty).\n */\ntype Part = [\n text: string,\n cls: string | null,\n title?: string,\n inline?: number,\n style?: Readonly<Record<string, string>>,\n]\n\n/** A line cut where its tokens and marks start and end, each piece with its classes, and its inline widgets between. */\nfunction partsOf(row: Row): Part[] {\n const parts = textParts(row)\n const own = row.inlines\n if (!own?.length) return parts\n const out: Part[] = []\n let at = 0\n let next = 0\n for (const part of parts) {\n while (next < own.length && own[next]!.col <= at) out.push(['', null, undefined, next++])\n // A widget inside the piece cuts it.\n let piece = part\n while (next < own.length && own[next]!.col < at + piece[0].length) {\n const cut = own[next]!.col - at\n out.push([piece[0].slice(0, cut), piece[1], piece[2], undefined, piece[4]])\n piece = [piece[0].slice(cut), piece[1], piece[2], undefined, piece[4]]\n at += cut\n while (next < own.length && own[next]!.col <= at) out.push(['', null, undefined, next++])\n }\n out.push(piece)\n at += piece[0].length\n }\n while (next < own.length) out.push(['', null, undefined, next++])\n return out\n}\n\nfunction textParts(row: Row): Part[] {\n const base = lineParts(row.text, row.tokens)\n const marks = row.marks\n if (!marks?.length) return base.map(([text, type]) => [text, type && `dou-syntax-${type}`])\n const cuts = new Set<number>([0, row.text.length])\n for (const [from, to] of marks) {\n cuts.add(from)\n cuts.add(to)\n }\n let at = 0\n for (const [text] of base) {\n cuts.add(at)\n at += text.length\n }\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n const points = [...cuts].sort((a, b) => a - b)\n const out: Part[] = []\n let index = 0\n let partStart = 0\n for (let i = 0; i + 1 < points.length; i++) {\n const from = points[i]!\n const to = points[i + 1]!\n if (to <= from || from >= row.text.length) continue\n while (partStart + base[index]![0].length <= from) partStart += base[index++]![0].length\n const type = base[index]![1]\n let cls = type ? `dou-syntax-${type}` : ''\n let title: string | undefined\n let style: Readonly<Record<string, string>> | undefined\n for (const [a, b, name, label, css] of marks)\n if (a <= from && b >= to) {\n cls = cls ? `${cls} ${name}` : name\n title = label ?? title\n if (css) style = style ? { ...style, ...css } : css\n }\n const piece = row.text.slice(from, to)\n out.push(\n style\n ? [piece, cls || null, title, undefined, style]\n : title\n ? [piece, cls || null, title]\n : [piece, cls || null],\n )\n }\n return out\n}\n\n/** The parts of one row of a wrapped line. */\nfunction rowParts(row: Row, sub: number) {\n const { breaks } = row.wrapped\n const start = sub ? breaks[sub - 1]! : 0\n const end = sub < breaks.length ? breaks[sub]! : row.text.length\n const out: Part[] = []\n let at = 0\n const last = sub === breaks.length\n for (const part of partsOf(row)) {\n const [text, type, title, inline, style] = part\n // A widget goes on the row its column starts; at the very end, on the last row.\n if (inline !== undefined) {\n if (at >= start && (at < end || (last && at === end))) out.push(part)\n continue\n }\n const from = Math.max(at, start)\n const to = Math.min(at + text.length, end)\n if (to > from) out.push([text.slice(from - at, to - at), type, title, undefined, style])\n at += text.length\n }\n return out\n}\n\n// ---------------------------------------------------------------- overlays\n\nconst focused = ref(false)\n\ninterface Box {\n key: string\n left: number\n top: number\n width: number\n}\n\nconst cursors = computed(() => {\n void metrics.value\n const out: Box[] = []\n const { doc: text, selection } = state.value\n const p = preview.value\n selection.ranges.forEach((range, i) => {\n const pos = range.head\n const line = text.lineAt(pos)\n if (!isShown(line.number)) return\n let lineStr = lineText(line.number)\n if (p && i === selection.main) {\n const at = text.lineAt(p.from)\n lineStr =\n rows.value\n .find((row) => row.n === at.number)\n ?.compose?.slice(0, 2)\n .join('') ?? lineStr\n out.push({\n key: `c${i}`,\n left: pad.x + measure.x(lineStr, lineStr.length),\n top: yOf(at.number),\n width: 2,\n })\n return\n }\n const at = place(line.number, lineStr, pos - line.from)\n out.push({ key: `c${i}`, left: pad.x + at.x, top: at.top, width: 2 })\n })\n return out\n})\n\nconst selectionBoxes = computed(() => {\n void metrics.value\n if (preview.value) return []\n const out: Box[] = []\n const { doc: text, selection } = state.value\n const first = visibleFrom.value\n const last = visibleTo.value\n selection.ranges.forEach((range, i) => {\n if (isEmptyRange(range)) return\n const from = text.lineAt(rangeFrom(range))\n const to = text.lineAt(rangeTo(range))\n for (let n = Math.max(from.number, first); n <= Math.min(to.number, last); n++) {\n if (!layout.value.shown(n)) continue\n const str = lineText(n)\n const a = n === from.number ? rangeFrom(range) - from.from : 0\n const b = n === to.number ? rangeTo(range) - to.from : str.length\n // A selected line break shows as half a cell past the end.\n const boxes = spans(n, str, a, b, n === to.number ? 0 : measure.cell / 2)\n boxes.forEach((box, k) =>\n out.push({ key: `s${i}-${n}-${k}`, ...box, left: pad.x + box.left }),\n )\n }\n })\n return out\n})\n\nconst activeLineTop = computed(() => {\n const n = doc.value.lineAt(mainRange(state.value.selection).head).number\n return isShown(n) ? yOf(n) : null\n})\nconst activeLineRows = computed(() => layout.value.rowsOf(activeLineNumber.value) || 1)\nconst activeLineNumber = computed(\n () => doc.value.lineAt(mainRange(state.value.selection).head).number,\n)\n\n// Moving onto a line with widgets reads out what they are, the way problems are read out.\nwatch(activeLineNumber, (n) => {\n if (!focused.value || !widgets.value.length) return\n const labels = widgets.value\n .filter((widget) => widget.line === n && widget.label)\n .map((widget) => widget.label!)\n if (labels.length) announce(labels.join(' · '))\n})\n\n/** The bracket at the main cursor and its partner, outlined; a bracket without one is marked. */\nconst bracketBoxes = computed(() => {\n void metrics.value\n void syntaxTick.value\n if (!props.matchBrackets || !props.language || !focused.value || preview.value) return []\n const main = mainRange(state.value.selection)\n if (!isEmptyRange(main)) return []\n const text = doc.value\n const brackets = languageAt(main.head)?.brackets ?? props.language.brackets\n const found = matchBracket(text, main.head, brackets, (pos) => {\n const kind = syntaxAt(pos)\n return kind === 'string' || kind === 'comment'\n })\n if (!found) return []\n const out: Array<Box & { matched: boolean }> = []\n for (const pos of found.match === null ? [found.from] : [found.from, found.match]) {\n const line = text.lineAt(pos)\n if (!isShown(line.number)) continue\n const str = lineText(line.number)\n const [box] = spans(line.number, str, pos - line.from, pos - line.from + 1)\n if (box)\n out.push({ key: `b${pos}`, ...box, left: pad.x + box.left, matched: found.match !== null })\n }\n return out\n})\n\n// ---------------------------------------------------------------- search\n\nconst messages = useCodeMessages(() => props.messages)\nconst searchOpen = ref(false)\nconst showReplace = ref(false)\nconst query = ref<CodeSearchQuery>({ search: '' })\nconst panel = ref<InstanceType<typeof DouFindReplace>>()\nconst { t: common } = useLocale()\n/** The toggles in the find box. */\nconst searchOptions = [\n { key: 'caseSensitive', icon: LetterCaseIcon },\n { key: 'wholeWord', icon: WholeWordIcon },\n { key: 'regexp', icon: RegexIcon },\n] as const\n/** The matches, kept in step with edits between searches. */\nconst matches = shallowRef<CodeMatch[]>([])\nconst capped = ref(false)\nconst searchError = ref<string>()\n/** Read out after a replacement. */\nconst announcement = ref('')\nlet searchTimer = 0\n\nfunction runSearch() {\n clearTimeout(searchTimer)\n searchTimer = 0\n if (!searchOpen.value || !query.value.search) {\n matches.value = []\n capped.value = false\n searchError.value = undefined\n return\n }\n const result = searchText(doc.value, query.value)\n matches.value = result.matches\n capped.value = result.capped\n searchError.value = result.error\n}\n\n/** Searches again a little later, so typing in a long text doesn't search on every key. */\nfunction scheduleSearch(delay = 120) {\n clearTimeout(searchTimer)\n searchTimer = window.setTimeout(runSearch, delay)\n}\n\nwatch(query, () => {\n runSearch()\n // While typing the search, the first match from the selection on is selected, as a preview.\n revealMatch(matchAfter(matches.value, rangeFrom(mainRange(state.value.selection))))\n})\n\n/** Moves the matches along with an edit, and searches again soon. */\nfunction mapMatches(changes: ChangeSet) {\n if (!searchOpen.value || !matches.value.length) return\n matches.value = matches.value\n .map((m) => ({ from: changes.mapPos(m.from, 1), to: changes.mapPos(m.to, -1) }))\n .filter((m) => m.to > m.from)\n scheduleSearch(doc.value.length > 200_000 ? 300 : 120)\n}\n\n/** Which match the main selection is exactly on, or `-1`. */\nconst currentMatch = computed(() => {\n const main = mainRange(state.value.selection)\n const i = matchAfter(matches.value, rangeFrom(main))\n const m = matches.value[i]\n return m && m.from === rangeFrom(main) && m.to === rangeTo(main) ? i : -1\n})\n\nfunction revealMatch(index: number) {\n const m = matches.value[index]\n if (!m) return false\n dispatch(transaction().select(m.from, m.to).setMeta({ scroll: true }))\n return true\n}\n\nfunction nextMatch() {\n if (!matches.value.length) return false\n const main = mainRange(state.value.selection)\n const at = currentMatch.value >= 0 ? rangeTo(main) : rangeFrom(main)\n let i = matchAfter(matches.value, at)\n if (currentMatch.value >= 0 && i === currentMatch.value) i = (i + 1) % matches.value.length\n return revealMatch(i)\n}\n\nfunction previousMatch() {\n if (!matches.value.length) return false\n const list = matches.value\n const from = rangeFrom(mainRange(state.value.selection))\n const after = matchAfter(list, from)\n // `matchAfter` wraps to the first past the end; the one before the cursor is then the last.\n return revealMatch(\n list[after]!.from < from ? list.length - 1 : (after - 1 + list.length) % list.length,\n )\n}\n\nfunction openSearch(replace = false, given?: Partial<CodeSearchQuery>) {\n if (!props.searchable) return false\n menuOpen.value = false\n closeProblems()\n const main = mainRange(state.value.selection)\n const patch: Partial<CodeSearchQuery> = { ...given }\n // A selection on one line, or else the word at the cursor, becomes the search.\n if (given?.search === undefined) {\n const selected = doc.value.slice(rangeFrom(main), rangeTo(main))\n if (selected && !selected.includes('\\n')) patch.search = selected\n else if (!selected) {\n const line = doc.value.lineAt(main.head)\n const col = main.head - line.from\n const text = lineText(line.number)\n for (const at of [col, col - 1]) {\n if (at < 0 || at >= text.length || !/[\\p{L}\\p{N}_$]/u.test(text[at]!)) continue\n const word = wordAt(text, at)\n patch.search = text.slice(word.from, word.to)\n // Select it, so the search starts from this word rather than the next one.\n dispatch(transaction().select(line.from + word.from, line.from + word.to))\n break\n }\n }\n }\n if (Object.keys(patch).length) query.value = { ...query.value, ...patch }\n // Given a replacement, the replace box opens with it.\n if ((replace || given?.replace !== undefined) && !target.readonly) showReplace.value = true\n searchOpen.value = true\n runSearch()\n panel.value?.focus(replace ? 'replace' : 'find')\n nextTick(() => panel.value?.focus(replace ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n if (!searchOpen.value) return false\n searchOpen.value = false\n matches.value = []\n focusInput()\n return true\n}\n\nfunction replaceOne() {\n if (target.readonly) return\n if (currentMatch.value < 0) {\n nextMatch()\n return\n }\n const m = matches.value[currentMatch.value]!\n const insert = replacementFor(doc.value, m, query.value)\n const tr = transaction().setMeta({ action: 'replace', scroll: true })\n tr.replace(m.from, m.to, insert)\n dispatch(tr)\n runSearch()\n // On to the next match after the replaced text.\n const i = matchAfter(matches.value, m.from + insert.length)\n if (i >= 0 && (matches.value[i]!.from >= m.from + insert.length || i === 0)) revealMatch(i)\n}\n\nfunction replaceAll() {\n if (target.readonly) return\n // Every match, also past the number shown.\n const all = capped.value ? searchText(doc.value, query.value, Infinity).matches : matches.value\n if (!all.length) return\n const text = doc.value\n const tr = transaction().setMeta({ action: 'replace', scroll: true })\n for (const m of all) tr.replace(m.from, m.to, replacementFor(text, m, query.value))\n dispatch(tr)\n // Leave a cursor rather than a selection on the last replacement, which would look like a match left over.\n const head = mainRange(state.value.selection).head\n dispatch(transaction().select(head))\n announcement.value = common('findReplace.replaced', { count: all.length })\n runSearch()\n}\n\n/** The matches on the lines in view, as boxes; the one selected stands out. */\nconst matchBoxes = computed(() => {\n void metrics.value\n if (!searchOpen.value || !matches.value.length) return []\n const text = doc.value\n const first = text.line(visibleFrom.value).from\n const last = text.line(visibleTo.value).to\n const out: Array<Box & { current: boolean }> = []\n for (let i = matchAfter(matches.value, first); i >= 0 && i < matches.value.length; i++) {\n const m = matches.value[i]!\n // Past the view, or wrapped around to the first match above it.\n if (m.from > last || m.to < first) break\n const from = text.lineAt(m.from)\n const to = text.lineAt(m.to)\n for (\n let n = Math.max(from.number, visibleFrom.value);\n n <= Math.min(to.number, visibleTo.value);\n n++\n ) {\n if (!layout.value.shown(n)) continue\n const str = lineText(n)\n const a = n === from.number ? m.from - from.from : 0\n const b = n === to.number ? m.to - to.from : str.length\n spans(n, str, a, b).forEach((box, k) =>\n out.push({\n key: `m${m.from}-${n}-${k}`,\n ...box,\n left: pad.x + box.left,\n current: i === currentMatch.value,\n }),\n )\n }\n if (out.length > 2000) break\n }\n return out\n})\n\n/** Marks beside the scrollbar for where the matches are in the whole text, one per pixel row. */\nconst searchMarks = computed(() => {\n if (!searchOpen.value || !matches.value.length) return []\n const text = doc.value\n const drawn = layout.value\n /** Where a line sits in the whole text, from 0 to 1, as drawn (wrapped rows and folds counted). */\n const lh = lineHeight.value\n const all = total.value\n const share = (pos: number) => (rowTop(drawn.rowOf(text.lineAt(pos).number)) + lh / 2) / all\n const taken = new Set<number>()\n const out: Array<{ top: number; current: boolean }> = []\n const current = matches.value[currentMatch.value]\n // A thousand evenly spread matches show the picture; more only cost time.\n const step = Math.max(1, Math.floor(matches.value.length / 1000))\n for (let i = 0; i < matches.value.length; i += step) {\n const top = Math.round(share(matches.value[i]!.from) * 1000) / 10\n if (taken.has(top)) continue\n taken.add(top)\n out.push({ top, current: false })\n }\n if (current) out.push({ top: share(current.from) * 100, current: true })\n return out\n})\n\n// ---------------------------------------------------------------- problems\n\n/** The box over a place in the text with the problems there and their fixes; `keyboard` when opened by a key, so arrows pick a fix. */\nconst problemBox = shallowRef<{\n pos: number\n problems: CodeDiagnostic[]\n /** Text from the extensions' `hover`, shown above the problems. */\n info: Array<string | (() => VNodeChild)>\n /** The part of the text the box is about; the mouse may move inside it without the box changing. */\n from: number\n to: number\n index: number\n keyboard: boolean\n} | null>(null)\nconst problemEl = ref<HTMLElement>()\nconst problemSize = ref({ width: 0, height: 0 })\nlet problemTimer = 0\n\n/** The problems that cover a position; an empty one covers the character it marks. */\nfunction problemsAt(pos: number) {\n const out: CodeDiagnostic[] = []\n for (const problem of diagnostics.value) {\n if (problem.from > pos) break\n if (pos <= Math.max(problem.to, problem.from + 1)) out.push(problem)\n }\n return out\n}\n\nconst fixes = computed(() =>\n (problemBox.value?.problems ?? []).flatMap((problem) =>\n (problem.actions ?? []).map((action) => ({ problem, action })),\n ),\n)\n\nfunction showProblems(pos: number, keyboard: boolean) {\n clearTimeout(problemTimer)\n const problems = problemsAt(pos)\n if (!problems.length) {\n problemBox.value = null\n return false\n }\n const hasFixes = problems.some((problem) => problem.actions?.length)\n problemBox.value = {\n pos,\n problems,\n info: [],\n ...problemsSpan(problems, pos),\n index: keyboard && hasFixes ? 0 : -1,\n keyboard,\n }\n return true\n}\n\nfunction problemsSpan(problems: CodeDiagnostic[], pos: number) {\n let from = pos\n let to = pos\n for (const problem of problems) {\n from = Math.min(from, problem.from)\n to = Math.max(to, problem.to)\n }\n return { from, to }\n}\n\n/** Counts requests for hover text, so an answer to an older one is dropped. */\nlet hoverRequest = 0\nlet hoverAbort: AbortController | null = null\n\n/**\n * Shows what is known about a place: the extensions' hover text and the\n * problems there. Slow sources fill in when they answer. `false` when\n * there is nothing and nothing is coming.\n */\nfunction showInfo(pos: number, keyboard: boolean) {\n clearTimeout(problemTimer)\n const id = ++hoverRequest\n hoverAbort?.abort()\n const abort = new AbortController()\n hoverAbort = abort\n const text = doc.value\n const problems = problemsAt(pos)\n const info: Array<string | (() => VNodeChild)> = []\n let { from, to } = problemsSpan(problems, pos)\n const line = text.lineAt(pos)\n const word = wordAt(line.text, pos - line.from)\n const add = (result: CodeHoverResult | null | undefined) => {\n if (!result) return\n info.push(result.content)\n from = Math.min(from, result.from ?? line.from + word.from)\n to = Math.max(to, result.to ?? line.from + word.to)\n }\n const apply = () => {\n if (id !== hoverRequest || doc.value !== text) return\n if (!problems.length && !info.length) {\n problemBox.value = null\n return\n }\n const hasFixes = problems.some((problem) => problem.actions?.length)\n problemBox.value = {\n pos,\n problems,\n info: info.slice(),\n from,\n to,\n index: keyboard && hasFixes ? 0 : -1,\n keyboard,\n }\n if (keyboard) {\n const said = info.filter((item) => typeof item === 'string') as string[]\n if (said.length) announce(said.join('\\n'))\n }\n }\n let waiting = 0\n for (const extension of extensions.value) {\n if (!extension.hover) continue\n let answer: ReturnType<NonNullable<CodeExtension['hover']>>\n try {\n answer = extension.hover({ pos, signal: abort.signal }, context)\n } catch (error) {\n console.error(`[@dou-ui/code] ${extension.name}: hover failed`, error)\n continue\n }\n if (answer && 'then' in answer) {\n waiting++\n Promise.resolve(answer)\n .then((result) => {\n add(result)\n apply()\n })\n .catch((error: unknown) => {\n if (!abort.signal.aborted)\n console.error(`[@dou-ui/code] ${extension.name}: hover failed`, error)\n })\n } else add(answer)\n }\n apply()\n return problems.length > 0 || info.length > 0 || waiting > 0\n}\n\n/** Reads out the fix picked from the keyboard, and where it is in the list. */\nfunction announceFix() {\n const index = problemBox.value?.index ?? -1\n const fix = fixes.value[index]\n if (!fix) return\n announce(\n format(messages.value.itemAt, {\n label: fix.action.label,\n index: index + 1,\n count: fixes.value.length,\n }),\n )\n}\n\nfunction closeProblems() {\n clearTimeout(problemTimer)\n hoverRequest++\n hoverAbort?.abort()\n hoverAbort = null\n problemBox.value = null\n}\n// The touch toolbar and the hover box would cover each other: the toolbar, asked for last, wins.\nwatch(menuOpen, (open) => open && closeProblems())\n\n// A press anywhere else on the page puts the box away; inside the editor, the press decides.\nfunction onPressAway(event: PointerEvent) {\n const at = event.target as Node | null\n if (at && (root.value?.contains(at) || problemEl.value?.contains(at))) return\n closeProblems()\n}\nwatch(\n () => !!problemBox.value,\n (open, _old, onCleanup) => {\n if (!open || typeof window === 'undefined') return\n window.addEventListener('pointerdown', onPressAway, true)\n onCleanup(() => window.removeEventListener('pointerdown', onPressAway, true))\n },\n)\n\n/** The line whose problem icon in the gutter is under a pointer. */\nfunction problemIconLine(event: Event) {\n const cell = (event.target as Element | null)?.closest?.(`.${ns.e('problem-icon')}`)\n const line = cell?.getAttribute('data-line')\n return line ? Number(line) : null\n}\n\n/** Shows the problems on a line, as a press on its icon in the gutter asks. */\nfunction showLineProblems(n: number) {\n const line = doc.value.line(n)\n const first = diagnostics.value.find((problem) => problem.from >= line.from)\n if (!first || first.from > line.to) return\n menuOpen.value = false\n showInfo(first.from, false)\n}\n\nfunction runFix(index: number) {\n const fix = fixes.value[index]\n if (!fix) return\n closeProblems()\n fix.action.run(context, fix.problem)\n focusInput()\n}\n\n/** Moves the cursor to the next problem after it (`1`) or before it (`-1`), going round, and shows it. */\nfunction goToProblem(direction: 1 | -1) {\n const list = diagnostics.value\n if (!list.length) return false\n const head = mainRange(state.value.selection).head\n let found: CodeDiagnostic | undefined\n if (direction > 0) found = list.find((problem) => problem.from > head) ?? list[0]\n else {\n for (let i = list.length - 1; i >= 0 && !found; i--) if (list[i]!.from < head) found = list[i]\n found ??= list[list.length - 1]\n }\n const problem = found!\n dispatch(transaction().select(problem.from).setMeta({ scroll: true }))\n showProblems(problem.from, true)\n const m = messages.value\n announce(\n format(m.problemAt, {\n line: doc.value.lineAt(problem.from).number,\n severity: m[problem.severity],\n message: problem.message,\n }),\n )\n return true\n}\n\nconst diagnosticControl = {\n next: () => goToProblem(1),\n previous: () => goToProblem(-1),\n showFixes: () => {\n if (!showProblems(mainRange(state.value.selection).head, true)) return false\n announceFix()\n return true\n },\n}\n\n/** Keys while the box is open from the keyboard: arrows pick a fix, Enter makes it, Escape closes the box. */\nfunction problemKey(name: string) {\n const box = problemBox.value\n if (!box) return false\n if (name === 'escape') {\n closeProblems()\n return true\n }\n const count = fixes.value.length\n if (!box.keyboard || !count) return false\n if (name === 'arrowdown' || name === 'arrowup') {\n const step = name === 'arrowdown' ? 1 : -1\n problemBox.value = { ...box, index: (box.index + step + count) % count }\n announceFix()\n return true\n }\n if (name === 'enter' || name === 'tab') {\n runFix(Math.max(0, box.index))\n return true\n }\n return false\n}\n\n/**\n * Shows the problems under the mouse after a moment; leaving them hides the\n * box a moment later. Fingers are left out: a tap shows the box itself, and\n * the mouse events a browser makes up after it would only close it again.\n */\nfunction onContentHover(event: PointerEvent) {\n if (event.pointerType !== 'mouse' || drag || problemBox.value?.keyboard) return\n const rect = content.value?.getBoundingClientRect()\n if (!rect) return\n const point = { x: event.clientX, y: event.clientY }\n const pos = posAtCoords(point)\n const at = coordsAtPos(pos)\n // Only over the text itself, not the empty space after a line.\n const over = !!at && Math.abs(point.x - at.left) <= measure.cell * 2\n const box = problemBox.value\n if (box && over && pos >= box.from && pos <= box.to) {\n clearTimeout(problemTimer)\n return\n }\n clearTimeout(problemTimer)\n // Only worth asking where there is something: a problem, or a word for the extensions to explain.\n const asks = over && (problemsAt(pos).length > 0 || extensions.value.some((e) => e.hover))\n problemTimer = window.setTimeout(\n () => (asks ? showInfo(pos, false) || closeProblems() : closeProblems()),\n asks ? 350 : 250,\n )\n}\n\n/** The mouse came onto the box: it stays. */\nfunction keepProblems() {\n clearTimeout(problemTimer)\n}\n\nfunction onContentLeave(event: PointerEvent) {\n if (event.pointerType !== 'mouse' || problemBox.value?.keyboard) return\n clearTimeout(problemTimer)\n problemTimer = window.setTimeout(closeProblems, 250)\n}\n\n// Below the line, above it when there is no room, always in view.\nconst problemStyle = computed(() => {\n const box = problemBox.value\n return box ? floatingStyle(box.pos, problemSize.value) : null\n})\n\n/**\n * Where a box about position `pos` goes: below its line, or above it when\n * there is no room (first, with `above`), always in view; too tall for\n * either side, it scrolls inside on the roomier one.\n */\nfunction floatingStyle(pos: number, size: { width: number; height: number }, above = false) {\n const inside = pointOf(pos)\n if (!inside) return null\n let at: { x: number; top: number } = inside\n let view = visibleBox()\n if (floatingTarget.value) {\n // Above the page: in the window's coordinates, wherever the window is scrolled.\n const page = toPage(inside)\n if (!page) return null\n at = page\n view = pageBox()\n }\n const { width, height } = size\n const lh = lineHeight.value\n // Never wider than the text area in view, on a phone too.\n const maxWidth = `${Math.max(0, Math.floor(Math.min(440, view.right - view.left - 8)))}px`\n if (above && at.top - 4 - height >= view.top) {\n const left = Math.max(view.left + 4, Math.min(at.x - 12, view.right - width - 4))\n return {\n transform: `translate(${Math.round(left)}px, ${Math.round(at.top - 4 - height)}px)`,\n maxHeight: undefined,\n maxWidth,\n }\n }\n // A finger's cursor has its handle below the line: the box goes above when there is room, or under the handle.\n const below = at.top + lh + 4\n const roomBelow = view.bottom - 4 - below\n const roomAbove = at.top - 4 - view.top\n // A finger's cursor has its handle below the line, which the box keeps clear of where it can.\n const handle = touchUi.value && caretHandle.value ? HANDLE : 0\n let top: number\n let room: number\n if (roomBelow - handle >= height) [top, room] = [below + handle, roomBelow - handle]\n else if (roomAbove >= height) [top, room] = [at.top - 4 - height, roomAbove]\n else if (roomBelow >= height || roomBelow >= roomAbove) [top, room] = [below, roomBelow]\n // Too tall for either side: on the roomier one, scrolling inside.\n else [top, room] = [view.top + 4, roomAbove]\n const left = Math.max(view.left + 4, Math.min(at.x - 12, view.right - width - 4))\n return {\n transform: `translate(${Math.round(left)}px, ${Math.round(top)}px)`,\n maxHeight: height > room ? `${Math.max(0, Math.floor(room))}px` : undefined,\n maxWidth,\n }\n}\n\n/** Keeps a floating box's whole size, even while it is cut short and scrolls. */\nfunction measureFloating(\n el: HTMLElement | undefined,\n size: { value: { width: number; height: number } },\n) {\n if (el)\n size.value = {\n width: el.offsetWidth,\n height: el.scrollHeight + el.offsetHeight - el.clientHeight,\n }\n}\n\nwatch([problemEl, problemBox], () => measureFloating(problemEl.value, problemSize), {\n flush: 'post',\n})\n\n// ---------------------------------------------------------------- completion\n\nconst KIND_ICON: Record<CodeCompletionKind, unknown> = {\n keyword: SymbolKeywordIcon,\n function: FunctionIcon,\n method: FunctionIcon,\n variable: VariableIcon,\n property: WrenchIcon,\n constant: SymbolConstantIcon,\n class: SymbolClassIcon,\n type: SymbolTypeAliasIcon,\n module: PackageIcon,\n snippet: SquareCodeIcon,\n text: TypeIcon,\n}\n\ninterface CompletionItem {\n option: CodeCompletion\n /** Where its text goes, from here to the cursor. */\n from: number\n /** The parts of the label that were typed. */\n ranges: Array<[number, number]>\n score: number\n}\n\n/** The open completion list: the answers it came from, and the entries that match what is typed. */\nconst completion = shallowRef<{\n pos: number\n results: CodeCompletionResult[]\n items: CompletionItem[]\n index: number\n explicit: boolean\n /** Picked from with the keys, not just opened by typing. */\n moved: boolean\n} | null>(null)\nconst completionEl = ref<HTMLElement>()\nconst completionList = ref<HTMLElement>()\nconst completionSize = ref({ width: 0, height: 0 })\nconst completionId = `dou-code-completion-${instance.uid}`\nconst hasCompletion = computed(() => extensions.value.some((extension) => extension.completion))\nlet completionRequest = 0\nlet completionAbort: AbortController | null = null\n\nconst WORD_BEFORE = /[\\p{L}\\p{N}_$]+$/u\nconst WORD_CHAR = /[\\p{L}\\p{N}_$]/u\n\n/** The word right before `pos`. */\nfunction wordBefore(pos: number) {\n const line = doc.value.lineAt(pos)\n const found = WORD_BEFORE.exec(line.text.slice(0, pos - line.from))\n const text = found ? found[0] : ''\n return { from: pos - text.length, to: pos, text }\n}\n\n/** The answers' entries that match what is typed since each answer's `from`, best first. */\nfunction rankCompletions(results: readonly CodeCompletionResult[], pos: number) {\n const out: CompletionItem[] = []\n const text = doc.value\n for (const result of results) {\n if (result.from > pos || result.from < 0) continue\n const typed = text.slice(result.from, pos)\n for (const option of result.options) {\n const match = matchCompletion(option.label, typed)\n if (match)\n out.push({\n option,\n from: result.from,\n ranges: match.ranges,\n score: match.score + (option.boost ?? 0),\n })\n }\n }\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n out.sort((a, b) => b.score - a.score || a.option.label.localeCompare(b.option.label))\n return out.length > 200 ? out.slice(0, 200) : out\n}\n\n/** Asks the extensions for completions at the cursor and opens the list with what matches. */\nfunction startCompletion(explicit: boolean) {\n const main = mainRange(state.value.selection)\n const sources = extensions.value.filter((extension) => extension.completion)\n if (!sources.length || !isEmptyRange(main) || props.readonly || props.disabled) {\n closeCompletion()\n return false\n }\n const pos = main.head\n const id = ++completionRequest\n completionAbort?.abort()\n const abort = new AbortController()\n completionAbort = abort\n const text = doc.value\n const request = { pos, word: wordBefore(pos), explicit, signal: abort.signal }\n // Until the new answers come, the last ones go on matching what is typed.\n const previous = completion.value?.results ?? []\n const results: CodeCompletionResult[] = []\n let waiting = 0\n const apply = () => {\n if (id !== completionRequest || doc.value !== text) return\n if (mainRange(state.value.selection).head !== pos) return\n const source = results.length || !waiting ? results : previous\n const items = rankCompletions(source, pos)\n // The word is already all there: nothing to complete, unless asked.\n const done =\n !explicit && items.length === 1 && text.slice(items[0]!.from, pos) === items[0]!.option.label\n if (!items.length || done) {\n if (!waiting) completion.value = null\n return\n }\n const before = completion.value\n const picked = before?.items[before.index]?.option\n const kept = picked ? items.findIndex((item) => item.option === picked) : -1\n completion.value = {\n pos,\n results: source,\n items,\n index: Math.max(0, kept),\n explicit,\n moved: kept > 0 && !!before?.moved,\n }\n // A list that opens is read out with its first entry; the textarea is not a combobox to some readers.\n if (!before) announceCompletion()\n }\n for (const extension of sources) {\n let answer: ReturnType<NonNullable<CodeExtension['completion']>>\n try {\n answer = extension.completion!(request, context)\n } catch (error) {\n console.error(`[@dou-ui/code] ${extension.name}: completion failed`, error)\n continue\n }\n if (answer && 'then' in answer) {\n waiting++\n Promise.resolve(answer)\n .then((result) => {\n waiting--\n if (result) results.push(result)\n apply()\n })\n .catch((error: unknown) => {\n waiting--\n if (!abort.signal.aborted)\n console.error(`[@dou-ui/code] ${extension.name}: completion failed`, error)\n apply()\n })\n } else if (answer) results.push(answer)\n }\n apply()\n return true\n}\n\nfunction closeCompletion() {\n completionRequest++\n completionAbort?.abort()\n completionAbort = null\n completion.value = null\n}\n\nfunction moveCompletion(step: number) {\n const list = completion.value\n if (!list) return\n const count = list.items.length\n // Arrows go round; pages stop at the ends.\n const index =\n Math.abs(step) === 1\n ? (list.index + step + count) % count\n : Math.max(0, Math.min(count - 1, list.index + step))\n completion.value = { ...list, index, moved: true }\n announceCompletion()\n nextTick(() =>\n completionList.value\n ?.querySelector(`#${completionId}-${index}`)\n ?.scrollIntoView?.({ block: 'nearest' }),\n )\n}\n\n/** Reads out the picked entry, and where it is in the list. */\nfunction announceCompletion() {\n const list = completion.value\n const item = list?.items[list.index]\n if (!item) return\n announce(\n format(messages.value.itemAt, {\n label: item.option.detail ? `${item.option.label} ${item.option.detail}` : item.option.label,\n index: list.index + 1,\n count: list.items.length,\n }),\n )\n}\n\n/** Puts the entry's text in place of what was typed for it. */\nfunction acceptCompletion(index: number) {\n const list = completion.value\n const item = list?.items[index]\n if (!item) return\n closeCompletion()\n const pos = mainRange(state.value.selection).head\n const { option } = item\n if (option.snippet !== undefined) insertSnippet(item.from, pos, option.snippet)\n else {\n const insert = option.insert ?? option.label\n dispatch(\n transaction()\n .replace(item.from, pos, insert)\n .select(item.from + insert.length)\n .setMeta({ action: 'complete', scroll: true }),\n )\n }\n focusInput()\n}\n\n/** Keys while the list is open: arrows and pages pick, Enter or Tab puts the entry in, Escape closes it. */\nfunction completionKey(name: string) {\n if (!completion.value) return false\n if (name === 'arrowdown' || name === 'arrowup') moveCompletion(name === 'arrowdown' ? 1 : -1)\n else if (name === 'pagedown' || name === 'pageup') moveCompletion(name === 'pagedown' ? 8 : -8)\n else if (\n name === 'tab' &&\n snippet.value &&\n !completion.value.moved &&\n !completion.value.explicit\n ) {\n // Inside a snippet, Tab goes on to the next place unless an entry was picked with the keys.\n closeCompletion()\n return false\n } else if (name === 'enter' || name === 'tab') acceptCompletion(completion.value.index)\n else if (name === 'escape') closeCompletion()\n else return false\n return true\n}\n\n/** A label cut where the typed characters start and end. */\nfunction labelParts(item: CompletionItem) {\n const { label } = item.option\n const out: Array<[string, boolean]> = []\n let at = 0\n for (const [from, to] of item.ranges) {\n if (from > at) out.push([label.slice(at, from), false])\n out.push([label.slice(from, to), true])\n at = to\n }\n if (at < label.length) out.push([label.slice(at), false])\n return out\n}\n\nconst completionStyle = computed(() => {\n const list = completion.value\n if (!list) return null\n const first = list.items[list.index]?.from ?? list.pos\n return floatingStyle(first, completionSize.value)\n})\nwatch(\n [completionEl, completion],\n () => {\n const el = completionEl.value\n const list = completionList.value\n // Its whole height: the list scrolls when the box is cut short.\n if (el && list)\n completionSize.value = {\n width: el.offsetWidth,\n height: el.offsetHeight + list.scrollHeight - list.clientHeight,\n }\n },\n { flush: 'post' },\n)\n\n// ---------------------------------------------------------------- snippets\n\n/** The snippet being filled in: its places, grouped by number in Tab order, and which one is selected. */\nconst snippet = shallowRef<{\n groups: Array<{ index: number; ranges: Array<{ from: number; to: number }> }>\n at: number\n /** Where the snippet ends, for the cursor once all its places are filled in. */\n end: number\n} | null>(null)\n\n/** Inserts a snippet in place of `from`–`to`, its later lines indented like the first, and selects its first place. */\nfunction insertSnippet(from: number, to: number, source: string) {\n const line = doc.value.lineAt(from)\n const indent = indentOf(line.text)\n // A tab in a snippet is one step of indent, as the editor indents.\n const unit = props.indentWithTabs ? '\\t' : ' '.repeat(props.tabSize)\n const own = source.replace(/\\t/g, unit)\n const { text, fields } = parseSnippet(indent ? own.replace(/\\n/g, `\\n${indent}`) : own)\n const groups: Array<{ index: number; ranges: Array<{ from: number; to: number }> }> = []\n for (const field of fields) {\n const range = { from: from + field.from, to: from + field.to }\n const group = groups.find((g) => g.index === field.index)\n if (group) group.ranges.push(range)\n else groups.push({ index: field.index, ranges: [range] })\n }\n const tr = transaction().replace(from, to, text).setMeta({ action: 'complete', scroll: true })\n if (!groups.length) {\n snippet.value = null\n dispatch(tr.select(from + text.length))\n return\n }\n const first = groups[0]!\n tr.select({ ranges: first.ranges.map((r) => ({ anchor: r.from, head: r.to })), main: 0 })\n dispatch(tr)\n // Its places are in the new text already, so set after the change. Nothing more to fill in once there: no session to keep.\n snippet.value =\n groups.length > 1 || first.index !== 0 ? { groups, at: 0, end: from + text.length } : null\n}\n\n/** Selects the next or previous place of the snippet; past the last, the snippet is done. */\nfunction snippetField(dir: 1 | -1) {\n const session = snippet.value\n if (!session) return false\n const next = Math.max(0, session.at + dir)\n const group = session.groups[next]\n if (!group) {\n // Past the last place, with no $0: done, the cursor after the snippet.\n snippet.value = null\n dispatch(transaction().select(session.end).setMeta({ action: 'snippet', scroll: true }))\n return true\n }\n // $0 is where it ends: reaching it is done.\n snippet.value = group.index === 0 ? null : { ...session, at: next }\n dispatch(\n transaction()\n .select({ ranges: group.ranges.map((r) => ({ anchor: r.from, head: r.to })), main: 0 })\n .setMeta({ action: 'snippet', scroll: true }),\n )\n return true\n}\n\n// ---------------------------------------------------------------- parameter hints\n\nconst signature = shallowRef<{ pos: number; result: CodeSignatureResult } | null>(null)\nconst signatureEl = ref<HTMLElement>()\nconst signatureSize = ref({ width: 0, height: 0 })\n\nlet signatureRequest = 0\nlet signatureAbort: AbortController | null = null\n\n/** Asks the extensions about the call around the cursor; the first answer, by priority, is shown. */\nfunction updateSignature() {\n const id = ++signatureRequest\n signatureAbort?.abort()\n const abort = new AbortController()\n signatureAbort = abort\n // At the head, also with a snippet's place selected.\n const pos = mainRange(state.value.selection).head\n const text = doc.value\n type Answer = ReturnType<NonNullable<CodeExtension['signature']>>\n const answers: Answer[] = []\n for (const extension of extensions.value) {\n if (!extension.signature) continue\n try {\n const answer = extension.signature({ pos, signal: abort.signal }, context)\n if (answer && 'then' in answer)\n answers.push(\n Promise.resolve(answer).catch((error: unknown) => {\n if (!abort.signal.aborted)\n console.error(`[@dou-ui/code] ${extension.name}: signature failed`, error)\n return null\n }),\n )\n else answers.push(answer)\n } catch (error) {\n console.error(`[@dou-ui/code] ${extension.name}: signature failed`, error)\n }\n }\n const show = (result: CodeSignatureResult | null | undefined) => {\n if (id !== signatureRequest || doc.value !== text) return\n if (mainRange(state.value.selection).head !== pos) return\n if (!result) {\n signature.value = null\n return\n }\n const before = signature.value?.result\n signature.value = { pos, result }\n // Read out when the parameter changes, not on every key.\n if (!before || before.label !== result.label || before.active !== result.active) {\n const param = result.params[result.active]\n announce(param ? result.label.slice(param[0], param[1]) : result.label)\n }\n }\n // The first answer in priority order; a slow one is waited for, the box staying as it was meanwhile.\n let i = 0\n const next = (): void => {\n for (; i < answers.length; i++) {\n const answer = answers[i]\n if (answer && 'then' in answer) {\n const at = i\n void answer.then((result) => {\n answers[at] = result\n next()\n })\n return\n }\n if (answer) return show(answer)\n }\n show(null)\n }\n next()\n}\n\nfunction closeSignature() {\n signatureRequest++\n signatureAbort?.abort()\n signatureAbort = null\n signature.value = null\n}\n\nconst signatureParts = computed(() => {\n const result = signature.value?.result\n if (!result) return []\n const param = result.params[result.active]\n if (!param) return [[result.label, false]] as Array<[string, boolean]>\n return [\n [result.label.slice(0, param[0]), false],\n [result.label.slice(param[0], param[1]), true],\n [result.label.slice(param[1]), false],\n ] as Array<[string, boolean]>\n})\n\nconst signatureStyle = computed(() => {\n const box = signature.value\n return box ? floatingStyle(box.pos, signatureSize.value, true) : null\n})\nwatch([signatureEl, signature], () => measureFloating(signatureEl.value, signatureSize), {\n flush: 'post',\n})\n\nconst teleport = useTeleport(() => props.teleport)\n/**\n * Where the boxes about the text and the touch handles render: above the\n * page by default, so a short editor never cuts them off; inside the frame\n * (`null`) when `teleport` is `false`, and until the editor is mounted.\n */\nconst floatingTarget = computed(() =>\n // Only once mounted: the server's markup keeps them in place, so hydrating never looks for them in the body.\n teleport.value.disabled || !mounted.value ? null : teleport.value.to,\n)\nconst floatingZ = ref(0)\nconst floatingEl = ref<HTMLElement>()\n/**\n * The layer above the page sits in the page, not fixed to the window, so it\n * scrolls with the page on its own and never lags behind a finger's scroll.\n * Its boxes are placed in the window's coordinates; this moves the layer so\n * those land where the window has them, as of the last scroll.\n */\nconst layerShift = ref({ x: 0, y: 0 })\nfunction readLayerShift() {\n const el = floatingEl.value\n if (!el || !floatingTarget.value) return\n const rect = el.getBoundingClientRect()\n const { x, y } = layerShift.value\n layerShift.value = { x: x - rect.left, y: y - rect.top }\n}\n/** Bumped when the page scrolls or resizes, for boxes placed in the window's coordinates. */\nconst viewportTick = ref(0)\nconst bumpViewport = () => {\n readLayerShift()\n viewportTick.value++\n}\n/**\n * A box the editor sits in scrolling (a drawer, a side panel, an app's main\n * area): the layer above the page scrolls with the page only, so it hides\n * until that box stops, rather than trail behind the text.\n */\nconst boxScrolling = ref(false)\nlet boxScrollTimer = 0\n/**\n * How the editor moves when the page scrolls, read as the layer opens: with\n * the page; not at all, inside a `fixed` box (a bar pinned to the bottom, a\n * panel), where the layer stays fixed too; or partly, inside a `sticky` box,\n * where the layer hides while the page scrolls.\n */\nconst anchorMode = ref<'page' | 'fixed' | 'sticky'>('page')\nfunction readAnchorMode() {\n let mode: 'page' | 'fixed' | 'sticky' = 'page'\n for (let el = root.value?.parentElement; el && el !== document.body; el = el.parentElement) {\n const { position } = getComputedStyle(el)\n if (position === 'fixed') {\n mode = 'fixed'\n break\n }\n if (position === 'sticky') mode = 'sticky'\n }\n anchorMode.value = mode\n}\nfunction onAnyScroll(event: Event) {\n const box = event.target\n const page = !(box instanceof Element)\n if (\n page\n ? anchorMode.value === 'sticky'\n : box !== scroller.value && !!root.value && box.contains(root.value)\n ) {\n boxScrolling.value = true\n clearTimeout(boxScrollTimer)\n boxScrollTimer = window.setTimeout(() => (boxScrolling.value = false), 160)\n }\n bumpViewport()\n}\n/** Whether the focus is on the bar of keys itself, reached by Escape then Tab: the bar stays while it is. */\nconst keysFocused = ref(false)\n/** The bar of keys, on a touch screen while the editor takes input, or while the focus is on it. */\nconst showKeys = computed(\n () =>\n !!props.keys &&\n coarse.value &&\n (focused.value || keysFocused.value) &&\n !props.readonly &&\n !props.disabled,\n)\nconst floatingOpen = computed(\n () =>\n !!(problemBox.value || completion.value || signature.value) ||\n (touchUi.value && focused.value) ||\n showKeys.value,\n)\nwatch(floatingOpen, (open, _old, onCleanup) => {\n if (!open || typeof window === 'undefined') return\n floatingZ.value = nextZIndex()\n // The boxes above the page take the editor's own variables with them, as they are now.\n readFrameFont()\n readAnchorMode()\n readLayerShift()\n // Once fixed or not as read, from where the layer now is.\n void nextTick(bumpViewport)\n const vv = window.visualViewport\n window.addEventListener('scroll', onAnyScroll, { capture: true, passive: true })\n window.addEventListener('resize', bumpViewport, { passive: true })\n vv?.addEventListener('resize', bumpViewport, { passive: true })\n vv?.addEventListener('scroll', bumpViewport, { passive: true })\n onCleanup(() => {\n window.removeEventListener('scroll', onAnyScroll, { capture: true })\n clearTimeout(boxScrollTimer)\n boxScrolling.value = false\n window.removeEventListener('resize', bumpViewport)\n vv?.removeEventListener('resize', bumpViewport)\n vv?.removeEventListener('scroll', bumpViewport)\n })\n})\n\n/** Where a point of the content is in the window; `null` while it is out of the editor's view. */\nfunction toPage(inside: { x: number; top: number }) {\n void viewportTick.value\n const view = visibleBox()\n if (inside.top + lineHeight.value <= view.top || inside.top >= view.bottom) return null\n if (inside.x < view.left - 1 || inside.x > view.right + 1) return null\n const rect = content.value?.getBoundingClientRect()\n if (!rect) return null\n return { x: rect.left + inside.x, top: rect.top + inside.top }\n}\n\n/** The editor's text in view, in the window's coordinates. */\nfunction frameInPage() {\n void viewportTick.value\n const view = visibleBox()\n const rect = content.value?.getBoundingClientRect()\n const x = rect?.left ?? 0\n const y = rect?.top ?? 0\n return { left: x + view.left, top: y + view.top, right: x + view.right, bottom: y + view.bottom }\n}\n\n/**\n * The part of the page in view, in the window's coordinates: on a phone,\n * above the keyboard and the bar of keys over it.\n */\nfunction pageBox() {\n void viewportTick.value\n const { left, top, width, height } = visibleViewport()\n return {\n left,\n top,\n right: left + width,\n bottom: top + height,\n }\n}\n\n/** After each change: opens, updates or closes the completion list and the parameter hints, and moves the snippet's places. */\nfunction updateAssist(result: CodeTransactionResult) {\n const { action } = result.meta\n const { changes } = result\n const main = mainRange(result.state.selection)\n const session = snippet.value\n if (session) {\n const groups = changes.empty\n ? session.groups\n : session.groups.map((group) => ({\n index: group.index,\n ranges: group.ranges.map((range) => ({\n from: changes.mapPos(range.from, -1),\n to: changes.mapPos(range.to, 1),\n })),\n }))\n // Leaving the place being filled in ends the snippet.\n const current = groups[session.at]\n const inside = current?.ranges.some((range) => main.head >= range.from && main.head <= range.to)\n const end = changes.empty ? session.end : changes.mapPos(session.end, 1)\n snippet.value =\n action === 'snippet' || action === 'complete' || inside ? { ...session, groups, end } : null\n }\n if (action === 'remote') {\n // Someone else's change: the list and the hints stay, unless it reached what they are about.\n if (changes.empty) return\n const head = mainRange(result.before.selection).head\n const map = (pos: number) => changes.mapPos(pos, -1)\n const list = completion.value\n if (list) {\n const start = Math.min(list.pos, ...list.results.map((answer) => answer.from))\n if (changes.touches(Math.min(start, head), Math.max(list.pos, head))) closeCompletion()\n else\n completion.value = {\n ...list,\n pos: map(list.pos),\n results: list.results.map((answer) => ({ ...answer, from: map(answer.from) })),\n items: list.items.map((item) => ({ ...item, from: map(item.from) })),\n }\n }\n const hints = signature.value\n if (hints)\n if (changes.touches(Math.min(hints.pos, head), Math.max(hints.pos, head))) updateSignature()\n else signature.value = { ...hints, pos: map(hints.pos) }\n return\n }\n if (action === 'complete' || action === 'snippet') {\n // A completed call puts the cursor inside its brackets: the hints show right away.\n updateSignature()\n return\n }\n if (action === 'input' && !changes.empty && result.state.selection.ranges.length === 1) {\n // What was typed, also when a closing bracket came in after it.\n const ch = changes.changes[changes.changes.length - 1]!.insert\n ? result.state.doc.slice(main.head - 1, main.head)\n : ''\n const trigger = extensions.value.some((extension) => extension.completionTriggers?.includes(ch))\n if (ch && (WORD_CHAR.test(ch) || trigger)) startCompletion(false)\n else closeCompletion()\n if (signature.value || ch === '(' || ch === ',') updateSignature()\n return\n }\n if (action === 'delete' && completion.value && wordBefore(main.head).text)\n startCompletion(completion.value.explicit)\n else closeCompletion()\n if (signature.value) updateSignature()\n}\n\n/** Where the problems sit along the scrollbar, by severity. */\nconst problemMarks = computed(() => {\n const list = diagnostics.value\n if (!list.length) return []\n const text = doc.value\n const drawn = layout.value\n const lh = lineHeight.value\n const all = total.value\n const taken = new Set<string>()\n const out: Array<{ top: number; severity: CodeDiagnosticSeverity }> = []\n for (const problem of list) {\n const y = rowTop(drawn.rowOf(text.lineAt(problem.from).number)) + lh / 2\n const top = Math.round((y / all) * 1000) / 10\n const key = `${top}${problem.severity}`\n if (taken.has(key)) continue\n taken.add(key)\n out.push({ top, severity: problem.severity })\n if (out.length >= 1000) break\n }\n return out\n})\n\n// ---------------------------------------------------------------- panels\n\nconst panels = computed(() => {\n const top: Array<{ key: string; render: CodePanel['render'] }> = []\n const bottom: typeof top = []\n for (const extension of extensions.value)\n for (const bar of extension.panels?.(context) ?? [])\n (bar.position === 'top' ? top : bottom).push({\n key: `${extension.name}/${bar.name}`,\n render: bar.render,\n })\n return { top, bottom }\n})\n\nconst searchControl = {\n open: (replace?: boolean) => openSearch(replace),\n close: closeSearch,\n next: () => nextMatch(),\n previous: () => previousMatch(),\n}\n\n// ---------------------------------------------------------------- the hidden textarea\n\n/**\n * What the textarea holds: the text from `from` to `to`, and the caret\n * inside it. `selected` is the selection its caret stands for, on a touch\n * screen: whatever the textarea is given there replaces it.\n */\nlet mirror: {\n from: number\n to: number\n value: string\n start: number\n end: number\n selected: { from: number; to: number } | null\n} = { from: 0, to: 0, value: '', start: 0, end: 0, selected: null }\nconst inputBox = ref({ top: pad.y, left: pad.x, height: 20 })\n\nfunction syncInput() {\n const { doc: text, selection } = state.value\n const main = mainRange(selection)\n const first = text.lineAt(rangeFrom(main))\n const last = text.lineAt(rangeTo(main))\n let from = first.from\n let to = last.to\n // Mirror whole lines of the selection while they are short; else only around the cursor.\n if (to - from > WINDOW || last.number - first.number > 50) {\n const line = text.lineAt(main.head)\n from = Math.max(line.from, main.head - WINDOW / 2)\n to = Math.min(line.to, main.head + WINDOW / 2)\n from = line.from + snapCluster(line.text, from - line.from)\n }\n const value = text.slice(from, to)\n let start = Math.max(0, Math.min(rangeFrom(main), to) - from)\n const end = Math.max(0, Math.min(rangeTo(main), to) - from)\n // On a touch screen the textarea keeps only a caret, at the selection's end: a selection\n // there would bring the system's own handles and menu up over the editor's.\n const selected =\n coarse.value && !isEmptyRange(main) ? { from: rangeFrom(main), to: rangeTo(main) } : null\n if (selected) start = end\n mirror = { from, to, value, start, end, selected }\n composeMap = null\n // Put the textarea where its caret lines up with the drawn main cursor, so input methods open there.\n const startLine = text.lineAt(from)\n const headLine = text.lineAt(main.head)\n const headText = headLine.number === startLine.number ? startLine.text : headLine.text\n const caret = place(headLine.number, headText, main.head - headLine.from)\n const lineStart = headLine.number === startLine.number ? from - startLine.from : 0\n inputBox.value = {\n top: caret.top - (headLine.number - startLine.number) * lineHeight.value,\n left:\n pad.x +\n caret.x -\n (measure.x(headText, main.head - headLine.from) - measure.x(headText, lineStart)),\n height: (text.lineAt(to).number - startLine.number + 1) * lineHeight.value,\n }\n const el = input.value\n if (!el) return\n if (el.value !== value) el.value = value\n if (document.activeElement === el && (el.selectionStart !== start || el.selectionEnd !== end))\n el.setSelectionRange(start, end, main.head < main.anchor ? 'backward' : 'forward')\n}\n\n/** The text a change in the textarea replaces: the part it changed, or the selection its caret stands for. */\nfunction inputRange(diff: { from: number; to: number }) {\n const { selected } = mirror\n const from = composedPos(selected ? selected.from : mirror.from + diff.from, -1)\n const to = Math.max(from, composedPos(selected ? selected.to : mirror.from + diff.to, 1))\n return { from, to }\n}\n\n/** Turns what the textarea now holds into a change of the text. */\nfunction readInput() {\n const el = input.value\n if (!el || props.readonly) return\n const diff = diffText(mirror.value, el.value, mirror.start)\n if (!diff) return\n const { from, to } = inputRange(diff)\n let { insert } = diff\n // The Enter that confirmed a composition only confirms it.\n if (insert.endsWith('\\n') && performance.now() - confirmEnter < 200) {\n insert = insert.slice(0, -1)\n confirmEnter = -Infinity\n }\n if (!insert && from === to) return syncInput()\n const { doc: text, selection } = state.value\n const main = mainRange(selection)\n // Typing over the selection or at the cursor: the same goes to every cursor.\n if (from === rangeFrom(main) && to === rangeTo(main) && insert) {\n if (insert === '\\n') return run(insertNewline)\n if (insertText(target, insert)) return\n dispatch(transaction().replaceSelection(insert).setMeta({ action: 'input' }))\n return\n }\n // The caret standing for the selection deleted something: the selection goes.\n if (mirror.selected && !insert && from === rangeFrom(main) && to === rangeTo(main))\n return run(deleteCharBackward)\n if (!insert && isEmptyRange(main)) {\n const line = text.lineAt(main.head)\n const col = main.head - line.from\n const back = col ? line.from + moveCluster(line.text, col, -1) : main.head - 1\n const forward =\n col < line.text.length ? line.from + moveCluster(line.text, col, 1) : main.head + 1\n if (from === back && to === main.head) return run(deleteCharBackward)\n if (from === main.head && to === forward) return run(deleteCharForward)\n }\n // Anything else (autocorrect, a word recomposed): apply it as it is, and take the caret the textarea has.\n const tr = transaction().setMeta({ action: insert ? 'input' : 'delete' })\n tr.replace(from, to, insert)\n if (mirror.selected) {\n dispatch(tr.select(from + insert.length))\n return\n }\n const result = tr.resolve()\n const base = composedPos(mirror.from, 1)\n const caret = (offset: number) => base + offset\n const ranges = result.state.selection.ranges.slice()\n const backward = el.selectionDirection === 'backward'\n const head = caret(backward ? el.selectionStart : el.selectionEnd)\n const anchor = caret(backward ? el.selectionEnd : el.selectionStart)\n ranges[result.state.selection.main] = { anchor, head }\n tr.select({ ranges, main: result.state.selection.main })\n dispatch(tr)\n}\n\nfunction onInput() {\n if (composing.value) {\n const el = input.value!\n const diff = diffText(mirror.value, el.value, mirror.start)\n if (!diff) {\n preview.value = null\n return\n }\n preview.value = { ...inputRange(diff), insert: diff.insert }\n return\n }\n readInput()\n}\n\nfunction onCompositionStart() {\n composing.value = true\n}\n\nfunction onCompositionEnd() {\n composing.value = false\n preview.value = null\n readInput()\n syncInput()\n}\n\nfunction onSelectionChange() {\n const el = input.value\n if (!el || document.activeElement !== el || composing.value) return\n if (el.selectionStart === mirror.start && el.selectionEnd === mirror.end) return\n if (el.value !== mirror.value) return\n // The caret moved by itself (the space bar on a phone keyboard, say): follow it.\n const backward = el.selectionDirection === 'backward'\n const start = mirror.from + el.selectionStart\n const end = mirror.from + el.selectionEnd\n const selection = state.value.selection\n const ranges = selection.ranges.slice()\n ranges[selection.main] = backward ? { anchor: end, head: start } : { anchor: start, head: end }\n mirror.start = el.selectionStart\n mirror.end = el.selectionEnd\n dispatch(transaction().select({ ranges, main: selection.main }).setMeta({ scroll: true }))\n}\n\n// ---------------------------------------------------------------- commands and keys\n\nconst target: CodeCommandTarget = {\n get state() {\n return state.value\n },\n get readonly() {\n return !!props.readonly || !!props.disabled\n },\n get tabSize() {\n return props.tabSize\n },\n get indentWithTabs() {\n return !!props.indentWithTabs\n },\n get pageLines() {\n return Math.max(1, Math.floor((viewHeight.value || 400) / lineHeight.value) - 1)\n },\n get language() {\n return props.language ?? null\n },\n get closeBrackets() {\n return props.closeBrackets\n },\n transaction,\n dispatch,\n moveVertically,\n undo,\n redo,\n languageAt,\n syntaxAt,\n get search() {\n return props.searchable ? searchControl : undefined\n },\n get folding() {\n return props.foldable ? folding : undefined\n },\n get diagnostics() {\n return diagnosticControl\n },\n assist: {\n complete: () => startCompletion(true),\n hover: () => showInfo(mainRange(state.value.selection).head, true),\n field: (dir) => snippetField(dir),\n },\n}\n\nfunction run(command: CodeCommand) {\n return command(target)\n}\n\n/** Moves by rows as drawn: a wrapped line's rows one by one, over folded lines. */\nfunction moveVertically(range: CodeRange, count: number) {\n const { doc: text } = state.value\n const line = text.lineAt(range.head)\n const at = place(line.number, line.text, range.head - line.from)\n const goal = goals.get(range.head) ?? at.x\n const row = layout.value.rowOf(line.number) + at.sub + count\n let head: number\n if (row < 0) head = 0\n else if (row >= layout.value.total) head = text.length\n else {\n const { n, sub } = layout.value.lineAtRow(row)\n const next = text.line(n)\n head = next.from + colAt(next.number, next.text, sub, goal)\n }\n pendingGoals.set(head, goal)\n return head\n}\n\n/** The extensions' keys, lowest priority first, since later bindings are tried first. */\nfunction extensionKeys() {\n const list = extensions.value\n const out: CodeKeyBinding[] = []\n for (let i = list.length - 1; i >= 0; i--) out.push(...keymapBindings(list[i]!.keymap?.(context)))\n return out\n}\n\nconst keymap = computed(() =>\n buildKeymap(\n [\n // Without indenting, Tab is left to the browser, but still fills in snippets.\n ...(props.tabIndents ? defaultKeymap : defaultKeymap.filter((b) => b.run !== insertTab)),\n ...extensionKeys(),\n ...keymapBindings(props.keymap),\n ],\n apple,\n ),\n)\n/** After Escape, Tab leaves the editor instead of indenting, so keyboard users are never stuck. */\nlet tabLeaves = false\n\n/** When Enter last confirmed a composition; some browsers also put a line break into the textarea for it, right after. */\nlet confirmEnter = -Infinity\n\nfunction onKeydown(event: KeyboardEvent) {\n if (isComposing(event) || composing.value) {\n if (event.key === 'Enter') confirmEnter = performance.now()\n return\n }\n confirmEnter = -Infinity\n const name = eventKey(event, apple)\n if (completionKey(name) || problemKey(name)) {\n event.preventDefault()\n event.stopPropagation()\n return\n }\n // Escape first puts away the toolbar over the selection.\n if (name === 'escape' && menuOpen.value) {\n menuOpen.value = false\n event.preventDefault()\n event.stopPropagation()\n return\n }\n // Escape also ends filling in a snippet.\n if (name === 'escape' && snippet.value) {\n snippet.value = null\n event.preventDefault()\n event.stopPropagation()\n return\n }\n const leaving = tabLeaves && (name === 'tab' || name === 'shift+tab')\n tabLeaves = name === 'escape'\n if (leaving) {\n // Tab goes on to the bar of keys first, which sits elsewhere in the page.\n const first =\n name === 'tab' && !shownWidgets.value.length ? keysEl.value?.querySelector('button') : null\n if (first) {\n event.preventDefault()\n first.focus()\n }\n return\n }\n for (const command of keymap.value.get(name) ?? []) {\n if (command(target)) {\n event.preventDefault()\n event.stopPropagation()\n return\n }\n }\n}\n\nfunction onBeforeInput(event: InputEvent) {\n // The browser's own undo would only undo the textarea's mirror.\n if (event.inputType === 'historyUndo' || event.inputType === 'historyRedo') {\n event.preventDefault()\n if (event.inputType === 'historyUndo') undo()\n else redo()\n }\n}\n\n// ---------------------------------------------------------------- clipboard\n\nfunction selectedText() {\n const { doc: text, selection } = state.value\n return selection.ranges\n .filter((range) => !isEmptyRange(range))\n .map((range) => text.slice(rangeFrom(range), rangeTo(range)))\n .join('\\n')\n}\n\nfunction onCopy(event: ClipboardEvent) {\n const text = selectedText()\n if (!text) return\n event.preventDefault()\n event.clipboardData?.setData('text/plain', text)\n}\n\nfunction onCut(event: ClipboardEvent) {\n onCopy(event)\n if (!event.defaultPrevented || target.readonly) return\n dispatch(transaction().replaceSelection('').setMeta({ action: 'cut' }))\n}\n\nfunction onPaste(event: ClipboardEvent) {\n event.preventDefault()\n pasteText(event.clipboardData?.getData('text/plain'))\n}\n\nfunction pasteText(text: string | undefined) {\n if (!text || target.readonly) return\n const { ranges } = state.value.selection\n const parts = splitLines(text)\n // One line per cursor when the counts match.\n const spread = ranges.length > 1 && parts.length === ranges.length\n dispatch(\n transaction()\n .replaceSelection(spread ? (_, i) => parts[i]! : text)\n .setMeta({ action: 'paste' }),\n )\n}\n\n// ---------------------------------------------------------------- pointer\n\n/** The text position under a point in the page, clamped to the text. */\nfunction posAtCoords(point: { x: number; y: number }) {\n const rect = content.value?.getBoundingClientRect()\n if (!rect) return 0\n const { n, sub } = layout.value.lineAtRow(rowAtY(point.y - rect.top))\n const line = state.value.doc.line(n)\n return line.from + colAt(n, line.text, sub, point.x - rect.left - pad.x)\n}\n\nfunction coordsAtPos(pos: number) {\n const rect = content.value?.getBoundingClientRect()\n if (!rect) return null\n const line = doc.value.lineAt(pos)\n if (!isShown(line.number)) return null\n const at = place(line.number, line.text, pos - line.from)\n const top = rect.top + at.top\n return { left: rect.left + pad.x + at.x, top, bottom: top + lineHeight.value }\n}\n\ntype Unit = 'char' | 'word' | 'line'\n\n/** The span of one unit around a position: itself, its word or its whole line. */\nfunction unitAt(pos: number, unit: Unit) {\n if (unit === 'char') return { from: pos, to: pos }\n const line = doc.value.lineAt(pos)\n if (unit === 'line') return { from: line.from, to: Math.min(doc.value.length, line.to + 1) }\n const word = wordAt(line.text, pos - line.from)\n return { from: line.from + word.from, to: line.from + word.to }\n}\n\nlet drag: {\n unit: Unit\n start: { from: number; to: number }\n x: number\n y: number\n frame: number\n hold: ReturnType<typeof holdPointer>\n /** Where a column selection (Alt + Shift drag) started. */\n column?: { n: number; x: number }\n /** A finger drags: from a handle, or after a long press. */\n touch?: boolean\n /** A handle under a lone cursor moves the cursor, selecting nothing. */\n caret?: boolean\n /** From the finger to the text point it moves, so the handle doesn't jump under the finger. */\n offset?: { x: number; y: number }\n} | null = null\n\n/** The line and the x inside the text (from the line's start) under a point in the page. */\nfunction lineAtCoords(point: { x: number; y: number }) {\n const rect = content.value!.getBoundingClientRect()\n const { n } = layout.value.lineAtRow(rowAtY(point.y - rect.top))\n return { n, x: Math.max(0, point.x - rect.left - pad.x) }\n}\n\n/** A rectangle of text from the drag's start to `point`: one range per line, cut at the same x. */\nfunction extendColumns(point: { x: number; y: number }) {\n const start = drag!.column!\n const end = lineAtCoords(point)\n const ranges: CodeRange[] = []\n const step = end.n >= start.n ? 1 : -1\n for (let n = start.n; ; n += step) {\n if (!layout.value.shown(n) && n !== end.n) continue\n const line = doc.value.line(n)\n const anchor = line.from + measure.col(line.text, start.x)\n const head = line.from + measure.col(line.text, end.x)\n // Lines too short to reach the rectangle are left out, unless the rectangle is only a line of cursors.\n if (anchor !== head || start.x === end.x || measure.x(line.text, line.text.length) >= start.x)\n ranges.push({ anchor, head })\n if (n === end.n) break\n }\n if (!ranges.length) return\n dispatch(\n transaction()\n .select(normalizeSelection({ ranges, main: ranges.length - 1 }, doc.value.length))\n .setMeta({ scroll: false }),\n )\n}\n\nfunction extendTo(point: { x: number; y: number }) {\n if (!drag) return\n if (drag.column) return extendColumns(point)\n const { offset } = drag\n const pos = posAtCoords(offset ? { x: point.x - offset.x, y: point.y - offset.y } : point)\n if (drag.caret) {\n dispatch(transaction().select(pos).setMeta({ scroll: false }))\n caretHandle.value = true\n return\n }\n // A handle keeps at least one character selected.\n if (offset && pos === drag.start.from) return\n const at = unitAt(pos, drag.unit)\n const { start } = drag\n const range =\n at.from < start.from\n ? { anchor: start.to, head: at.from }\n : { anchor: start.from, head: Math.max(at.to, start.to) }\n if (drag.unit === 'char') {\n range.anchor = start.from\n range.head = pos\n }\n const selection = state.value.selection\n const ranges = selection.ranges.slice()\n ranges[selection.main] = range\n dispatch(transaction().select({ ranges, main: selection.main }).setMeta({ scroll: false }))\n}\n\n/** Scrolls while a drag is held past the top or bottom edge. */\nfunction autoScroll() {\n if (!drag || !scroller.value) return\n const rect = scroller.value.getBoundingClientRect()\n const dy = drag.y < rect.top ? drag.y - rect.top : drag.y > rect.bottom ? drag.y - rect.bottom : 0\n const dx =\n drag.x < rect.left + gutterWidth.value\n ? drag.x - rect.left - gutterWidth.value\n : drag.x > rect.right\n ? drag.x - rect.right\n : 0\n if (dy || dx) {\n scroller.value.scrollTop += dy / 2\n scroller.value.scrollLeft += dx / 2\n onScroll()\n extendTo(drag)\n }\n drag.frame = requestAnimationFrame(autoScroll)\n}\n\nfunction startDrag(\n event: PointerEvent | { clientX: number; clientY: number },\n unit: Unit,\n start: { from: number; to: number },\n hold = holdPointer(event as PointerEvent, root.value),\n touch?: { caret?: boolean; offset?: { x: number; y: number } },\n) {\n drag = {\n unit,\n start,\n x: event.clientX,\n y: event.clientY,\n frame: 0,\n hold,\n touch: !!touch,\n ...touch,\n }\n touchDrag.value = !!touch\n drag.hold.grab()\n drag.frame = requestAnimationFrame(autoScroll)\n window.addEventListener('pointermove', onDragMove)\n window.addEventListener('pointerup', endDrag)\n window.addEventListener('pointercancel', endDrag)\n}\n\nfunction onDragMove(event: PointerEvent) {\n if (!drag) return\n drag.x = event.clientX\n drag.y = event.clientY\n extendTo(drag)\n}\n\nfunction endDrag() {\n if (!drag) return\n cancelAnimationFrame(drag.frame)\n drag.hold.release()\n const { touch, caret } = drag\n drag = null\n touchDrag.value = false\n // A selection made by finger offers what can be done with it.\n if (touch && !caret && !isEmptyRange(mainRange(state.value.selection))) menuOpen.value = true\n window.removeEventListener('pointermove', onDragMove)\n window.removeEventListener('pointerup', endDrag)\n window.removeEventListener('pointercancel', endDrag)\n}\n\nfunction focusInput() {\n if (props.disabled) return\n input.value?.focus({ preventScroll: true })\n}\n\n/** Selects the unit at `pos`: alone, extending the main range (`extend`), or as one more range (`add`). */\nfunction select(unit: Unit, pos: number, extend: boolean, add = false) {\n const at = unitAt(pos, unit)\n const { selection } = state.value\n const main = mainRange(selection)\n const range = extend\n ? { anchor: main.anchor, head: pos < main.anchor ? at.from : at.to }\n : { anchor: at.from, head: at.to }\n const next = add\n ? { ranges: [...selection.ranges, range], main: selection.ranges.length }\n : { ranges: [range], main: 0 }\n dispatch(\n transaction().select(normalizeSelection(next, doc.value.length)).setMeta({ scroll: false }),\n )\n // A drag goes on from the anchor kept by Shift, or from the unit pressed.\n return extend ? { from: main.anchor, to: main.anchor } : at\n}\n\n/** A tap that may turn into a scroll or a long press; touches only act once they end in place. */\nlet touch: {\n x: number\n y: number\n timer: number\n pointer: number\n /** Taken at the press, so a long press can keep the page from scrolling. */\n hold: ReturnType<typeof holdPointer>\n} | null = null\n\n/** The fold toggle or folded marker under a pointer, as the line it belongs to. */\nfunction foldTarget(event: Event) {\n const el = (event.target as Element | null)?.closest?.('[data-fold], [data-unfold]')\n if (!el) return null\n const unfold = el.getAttribute('data-unfold')\n return unfold\n ? { n: Number(unfold), folded: true }\n : { n: Number(el.getAttribute('data-fold')), folded: el.classList.contains('is-folded') }\n}\n\nfunction onPointerDown(event: PointerEvent, area: 'text' | 'gutter') {\n if (event.button !== 0 || props.disabled) return\n const cell = (event.target as Element | null)?.closest?.('[data-gutter-cell]')\n const column = cell && gutterColumns.value[Number(cell.getAttribute('data-gutter-cell'))]\n if (column?.onPress) {\n event.preventDefault()\n event.stopPropagation()\n column.onPress(Number(cell!.getAttribute('data-line')), event)\n return\n }\n const fold = foldTarget(event)\n if (fold) {\n event.preventDefault()\n event.stopPropagation()\n toggleFold(fold.n, fold.folded)\n return\n }\n const pos = posAtCoords({ x: event.clientX, y: event.clientY })\n // A click on a problem's icon shows it; a finger's tap does, once it ends in place.\n const iconLine = area === 'gutter' ? problemIconLine(event) : null\n if (iconLine !== null && event.pointerType === 'mouse') {\n event.preventDefault()\n showLineProblems(iconLine)\n return\n }\n if (event.pointerType !== 'mouse') {\n onPointerCancel()\n const x = event.clientX\n const y = event.clientY\n touch = {\n x,\n y,\n pointer: event.pointerId,\n // Lets go when the finger lifts unheard (Safari can send its `pointerup` to a removed line).\n hold: holdPointer(event, root.value, () => {\n onPointerCancel()\n endDrag()\n }),\n // A long press selects the word under the finger; sliding on from there selects word by word.\n timer: window.setTimeout(() => {\n if (!touch) return\n const { hold } = touch\n touch = null\n touchUi.value = true\n const unit: Unit = area === 'gutter' ? 'line' : 'word'\n const at = select(unit, pos, false)\n focusInput()\n startDrag({ clientX: x, clientY: y }, unit, at, hold, {})\n }, 450),\n }\n return\n }\n touchUi.value = false\n menuOpen.value = false\n closeProblems()\n event.preventDefault()\n focusInput()\n // Alt + Shift drag selects a rectangle, one range per line.\n if (event.altKey && event.shiftKey && area === 'text') {\n startDrag(event, 'char', { from: pos, to: pos })\n drag!.column = lineAtCoords({ x: event.clientX, y: event.clientY })\n extendColumns({ x: event.clientX, y: event.clientY })\n return\n }\n const count = countClick(event)\n const unit: Unit = area === 'gutter' || count === 3 ? 'line' : count === 2 ? 'word' : 'char'\n // Alt + click adds a cursor; dragging from there selects with it.\n startDrag(event, unit, select(unit, pos, event.shiftKey, event.altKey && !event.shiftKey))\n}\n\n/**\n * Counts quick clicks in one spot ourselves: a `pointerdown`'s `detail` is\n * 0 in some browsers, and the `mousedown` that has it is held back here.\n */\nlet lastClick = { time: 0, x: 0, y: 0, count: 0 }\nfunction countClick(event: PointerEvent) {\n const near =\n Math.abs(event.clientX - lastClick.x) < 4 && Math.abs(event.clientY - lastClick.y) < 4\n const count = near && event.timeStamp - lastClick.time < 500 ? (lastClick.count % 3) + 1 : 1\n lastClick = { time: event.timeStamp, x: event.clientX, y: event.clientY, count }\n return count\n}\n\nfunction onPointerMove(event: PointerEvent) {\n if (!touch || event.pointerId !== touch.pointer) return\n // Moving before the long press is a scroll, which the page goes on with.\n if (Math.hypot(event.clientX - touch.x, event.clientY - touch.y) > 8) onPointerCancel()\n}\n\nfunction onPointerUp(event: PointerEvent, area: 'text' | 'gutter') {\n if (!touch || event.pointerId !== touch.pointer) return\n onPointerCancel()\n const iconLine = area === 'gutter' ? problemIconLine(event) : null\n if (iconLine !== null) return showLineProblems(iconLine)\n const pos = posAtCoords({ x: event.clientX, y: event.clientY })\n const main = mainRange(state.value.selection)\n // A tap on the cursor itself opens the toolbar, or puts it away.\n const onCursor =\n area === 'text' && focused.value && isEmptyRange(main) && main.head === pos && caretHandle.value\n const wasOpen = menuOpen.value\n // A problem under the cursor is shown first; a tap with it already shown brings the toolbar.\n const showsProblem = area === 'text' && problemsAt(pos).length > 0 && !problemBox.value\n touchUi.value = true\n select(area === 'gutter' ? 'line' : 'char', pos, false)\n caretHandle.value = area === 'text'\n menuOpen.value = area === 'gutter' || (onCursor && !wasOpen && !showsProblem)\n // A tap on a problem shows it, the way hovering does with a mouse.\n if (area === 'text' && !menuOpen.value) showInfo(pos, false)\n focusInput()\n}\n\nfunction onPointerCancel() {\n if (touch) {\n clearTimeout(touch.timer)\n touch.hold.release()\n }\n touch = null\n}\n\n// ---------------------------------------------------------------- touch: handles, toolbar, magnifier\n\n/** The part of the content in view, in its own px. */\nfunction visibleBox() {\n const top = scrollTop.value + (clip.value?.top ?? 0)\n const bottom = scrollTop.value + (clip.value?.bottom ?? viewHeight.value)\n const left = scrollLeft.value\n return { top, bottom, left, right: left + Math.max(0, viewWidth.value - gutterWidth.value) }\n}\n\n/** Where a position is drawn in the content, when its line is in view. */\nfunction pointOf(pos: number) {\n const line = doc.value.lineAt(pos)\n if (!isShown(line.number)) return null\n const at = place(line.number, lineText(line.number), pos - line.from)\n return { x: pad.x + at.x, top: at.top, sub: at.sub, n: line.number }\n}\n\ntype HandleKind = 'start' | 'end' | 'caret'\n\n/** Handles under the ends of the selection, or under a lone cursor right after a tap. */\nconst handles = computed(() => {\n void metrics.value\n if (!touchUi.value || !focused.value || preview.value || props.disabled) return []\n const main = mainRange(state.value.selection)\n const ends: Array<[HandleKind, number]> = isEmptyRange(main)\n ? caretHandle.value && !props.readonly\n ? [['caret', main.head]]\n : []\n : [\n ['start', rangeFrom(main)],\n ['end', rangeTo(main)],\n ]\n const out: Array<{ kind: HandleKind; left: number; top: number }> = []\n for (const [kind, pos] of ends) {\n const inside = pointOf(pos)\n // Above the page, a handle shows only while its end is in the editor's view.\n const at = inside && floatingTarget.value ? toPage(inside) : inside\n if (at) out.push({ kind, left: Math.round(at.x), top: Math.round(at.top + lineHeight.value) })\n }\n return out\n})\n\n/** A handle pressed but not moved yet: a press that stays put is a tap or a long press on the text below. */\nlet handlePress: {\n kind: HandleKind\n x: number\n y: number\n pointer: number\n hold: ReturnType<typeof holdPointer>\n timer: number\n} | null = null\n\nfunction onHandleDown(event: PointerEvent, kind: HandleKind) {\n if (event.button !== 0) return\n event.preventDefault()\n event.stopPropagation()\n onPointerCancel()\n endHandlePress()\n const hold = holdPointer(event, root.value, () => {\n clearHandlePress()\n endDrag()\n })\n hold.grab()\n handlePress = {\n kind,\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n hold,\n // The handle under a lone cursor reaches over the next line; held there, the press is for that line's text.\n timer:\n kind === 'caret'\n ? window.setTimeout(() => {\n if (!handlePress) return\n const { x, y } = handlePress\n const taken = handlePress.hold\n clearHandlePress()\n const at = select('word', posAtCoords({ x, y }), false)\n startDrag({ clientX: x, clientY: y }, 'word', at, taken, {})\n }, 450)\n : 0,\n }\n window.addEventListener('pointermove', onHandleMove)\n window.addEventListener('pointerup', onHandleUp)\n window.addEventListener('pointercancel', endHandlePress)\n}\n\nfunction clearHandlePress() {\n if (handlePress) clearTimeout(handlePress.timer)\n handlePress = null\n window.removeEventListener('pointermove', onHandleMove)\n window.removeEventListener('pointerup', onHandleUp)\n window.removeEventListener('pointercancel', endHandlePress)\n}\n\nfunction endHandlePress() {\n handlePress?.hold.release()\n clearHandlePress()\n}\n\nfunction onHandleMove(event: PointerEvent) {\n const press = handlePress\n if (!press || event.pointerId !== press.pointer) return\n if (Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) return\n const { kind, hold, x, y } = press\n clearHandlePress()\n const main = mainRange(state.value.selection)\n const pos = kind === 'start' ? rangeFrom(main) : kind === 'end' ? rangeTo(main) : main.head\n const fixed = kind === 'start' ? rangeTo(main) : kind === 'end' ? rangeFrom(main) : pos\n const at = coordsAtPos(pos)\n if (!at) return hold.release()\n // The end being dragged becomes the head, so the drag moves it.\n if (kind !== 'caret') dispatch(transaction().select(fixed, pos).setMeta({ scroll: false }))\n menuOpen.value = false\n // From where the finger went down, so the handle keeps its place under it.\n const offset = { x: x - at.left, y: y - (at.top + lineHeight.value / 2) }\n startDrag(event, 'char', { from: fixed, to: fixed }, hold, { caret: kind === 'caret', offset })\n onDragMove(event)\n}\n\nfunction onHandleUp(event: PointerEvent) {\n const press = handlePress\n if (!press || event.pointerId !== press.pointer) return\n endHandlePress()\n if (press.kind !== 'caret') return\n // The handle reaches over the next line: a tap there is for that line's text, as if the handle were not there.\n const pos = posAtCoords({ x: event.clientX, y: event.clientY })\n const line = doc.value.lineAt(pos).number\n if (line !== doc.value.lineAt(mainRange(state.value.selection).head).number) {\n select('char', pos, false)\n menuOpen.value = false\n showInfo(pos, false)\n return focusInput()\n }\n // A tap on the handle under the cursor opens the toolbar, or puts it away.\n menuOpen.value = !menuOpen.value\n}\n\n/** Room between the toolbar or magnifier and what they point at. */\nconst GAP = 8\n/** How high a handle reaches below its line, which the toolbar keeps clear of. */\nconst HANDLE = 24\n\nconst menuEl = ref<HTMLElement>()\nconst menuSize = ref({ width: 0, height: 0 })\nconst canPaste = typeof navigator !== 'undefined' && !!navigator.clipboard?.readText\n\n/** The toolbar's buttons for the selection now. */\nconst menuItems = computed(() => {\n if (!menuOpen.value || !focused.value || props.disabled) return []\n const m = messages.value\n const main = mainRange(state.value.selection)\n const empty = isEmptyRange(main)\n const editable = !target.readonly\n const items: Array<{ key: string; label: string; run: () => void }> = []\n if (!empty && editable) items.push({ key: 'cut', label: m.cut, run: () => copySelection(true) })\n if (!empty) items.push({ key: 'copy', label: m.copy, run: () => copySelection(false) })\n if (editable && canPaste) items.push({ key: 'paste', label: m.paste, run: pasteFromClipboard })\n if (rangeFrom(main) > 0 || rangeTo(main) < doc.value.length)\n items.push({\n key: 'all',\n label: m.selectAll,\n run: () => {\n run(selectAll)\n menuOpen.value = true\n },\n })\n for (const extension of extensions.value) {\n if (!extension.menu) continue\n extension.menu(context).forEach((item, i) =>\n items.push({\n key: `${extension.name}/${i}`,\n label: item.label,\n run: () => {\n menuOpen.value = false\n item.run(context)\n },\n }),\n )\n }\n return items\n})\n\n// Above the selection; below it (past its handle) when there is no room; always in view.\nconst menuStyle = computed(() => {\n if (!menuItems.value.length) return null\n const main = mainRange(state.value.selection)\n let start = pointOf(rangeFrom(main))\n let end = pointOf(rangeTo(main))\n let view = visibleBox()\n let frame = view\n if (floatingTarget.value) {\n start = start && toPage(start) && { ...start, ...toPage(start)! }\n end = end && toPage(end) && { ...end, ...toPage(end)! }\n view = pageBox()\n frame = frameInPage()\n }\n if (!start && !end) return null\n const { width, height } = menuSize.value\n const lh = lineHeight.value\n const sameRow = start && end && start.top === end.top\n const x = sameRow ? (start!.x + end!.x) / 2 : (frame.left + frame.right) / 2\n const above = start ? start.top - GAP - height : -Infinity\n const below = (end ?? start)!.top + lh + HANDLE + GAP\n let top = above >= view.top + GAP ? above : below\n top = Math.max(view.top + GAP, Math.min(top, view.bottom - height - GAP))\n const left = Math.max(view.left + GAP, Math.min(x - width / 2, view.right - width - GAP))\n return { transform: `translate(${Math.round(left)}px, ${Math.round(top)}px)` }\n})\n\nwatch(\n [menuEl, menuItems],\n () => {\n const el = menuEl.value\n if (el) menuSize.value = { width: el.offsetWidth, height: el.offsetHeight }\n },\n { flush: 'post' },\n)\n\n/** Copies through the textarea, which hands the selection to the copy event. */\nfunction copyFromInput() {\n focusInput()\n document.execCommand('copy')\n}\n\nfunction writeClipboard(text: string) {\n const fallback = copyFromInput\n if (navigator.clipboard?.writeText) navigator.clipboard.writeText(text).catch(fallback)\n else fallback()\n}\n\nfunction copySelection(cut: boolean) {\n const text = selectedText()\n if (!text) return\n writeClipboard(text)\n if (cut && !target.readonly)\n dispatch(transaction().replaceSelection('').setMeta({ action: 'cut' }))\n menuOpen.value = false\n}\n\nfunction pasteFromClipboard() {\n menuOpen.value = false\n navigator.clipboard\n .readText()\n .then((text) => pasteText(text))\n .catch(() => {})\n}\n\n/** The editor's variables the boxes use, carried to them when they are drawn above the page. */\nconst FRAME_VARS = [\n '--dou-code-editor-font-size',\n '--dou-code-editor-line-height',\n '--dou-code-editor-bg',\n '--dou-code-editor-error',\n '--dou-code-editor-warning',\n '--dou-code-editor-info',\n '--dou-code-editor-selection',\n] as const\nconst frameVars = shallowRef<Record<string, string>>({})\n/** The editor's font, for the magnifier when it is drawn above the page. */\nconst frameFont = shallowRef<Record<string, string>>({})\nfunction readFrameFont() {\n const el = root.value\n if (!el) return\n const style = getComputedStyle(el)\n const vars: Record<string, string> = {}\n for (const name of FRAME_VARS) {\n const value = style.getPropertyValue(name).trim()\n if (value) vars[name] = value\n }\n frameVars.value = vars\n frameFont.value = {\n fontFamily: style.fontFamily,\n fontSize: style.fontSize,\n '--dou-code-editor-line-height': `${lineHeight.value}px`,\n '--dou-code-editor-tab-size': String(props.tabSize),\n }\n}\n\n/** The magnifier over a finger dragging the selection: the row at the moving end, larger. */\nconst MAGNIFIER = { width: 128, scale: 1.5 }\nconst magnifier = computed(() => {\n if (!touchDrag.value) return null\n void metrics.value\n const head = mainRange(state.value.selection).head\n const inside = pointOf(head)\n if (!inside) return null\n const row = rows.value.find((r) => r.n === inside.n)\n if (!row) return null\n const outside = !!floatingTarget.value\n const page = outside ? toPage(inside) : inside\n if (!page) return null\n const at = { ...inside, x: page.x, top: page.top }\n const lh = lineHeight.value\n const height = Math.round(lh * MAGNIFIER.scale) + 8\n const view = outside ? pageBox() : visibleBox()\n const { width } = MAGNIFIER\n const above = at.top - GAP - height\n const top = above >= view.top + 4 ? above : at.top + lh + HANDLE + GAP\n const left = Math.max(view.left + 4, Math.min(at.x - width / 2, view.right - width - 4))\n const parts = row.wrapped.breaks.length\n ? rowParts(row, at.sub)\n : row.tokens || row.marks || row.inlines\n ? partsOf(row)\n : ([[row.text, null]] as Part[])\n // The text, scaled from the row's left edge, slid so the moving end sits under the caret.\n const x = inside.x - pad.x\n const caret = Math.max(4, Math.min(width - 4, at.x - left))\n return {\n parts,\n inlines: row.inlines ?? [],\n indent: at.sub ? row.wrapped.indent : 0,\n style: {\n transform: `translate(${Math.round(left)}px, ${Math.round(top)}px)`,\n height: `${height}px`,\n // Above the page, it takes the editor's font with it.\n ...(outside ? frameFont.value : null),\n },\n textStyle: {\n transform: `translateX(${caret - x * MAGNIFIER.scale}px) scale(${MAGNIFIER.scale})`,\n },\n caret,\n }\n})\n\n// ---------------------------------------------------------------- touch: keyboard\n\nconst keysList = computed(() => (Array.isArray(props.keys) ? props.keys : undefined))\nconst keysEditor = { run }\nconst { next: nextZIndex } = useZIndex()\nconst keysZIndex = ref<number>()\nwatch(showKeys, (shown) => {\n if (shown) keysZIndex.value = nextZIndex()\n})\n/**\n * The bar of keys sits in the page below the editor, and scrolls with it:\n * it never follows the keyboard, whose bars and panels each browser draws\n * its own way. A finger moves it anywhere by its grip, and it keeps that\n * place by the editor while the editor is in use.\n */\nconst KEYS_HEIGHT = 44\nconst KEYS_GAP = 8\nconst keysEl = ref<HTMLElement>()\n/** Where the bar is, from the editor's top left corner; `null` until it first shows. */\nconst keysAt = ref<{ x: number; y: number } | null>(null)\n/** Whether a finger or a key moved the bar: then it stays put, even as the keyboard comes up. */\nlet keysMoved = false\nconst keysShift = ref({ x: 0, y: 0 })\nfunction readKeysShift() {\n const el = keysEl.value\n if (!el) return\n const rect = el.getBoundingClientRect()\n const at = keysClient.value\n if (!at) return\n // Moves the bar so that it lands where it is placed in the window, wherever its box starts.\n keysShift.value = {\n x: keysShift.value.x + at.x - rect.left,\n y: keysShift.value.y + at.y - rect.top,\n }\n}\n\n/** The editor's box in the window, as of the last scroll. */\nfunction rootInPage() {\n void viewportTick.value\n return root.value?.getBoundingClientRect() ?? null\n}\n\n/** The bar's width: the editor's, within the window. */\nconst keysWidth = computed(() => {\n const rect = rootInPage()\n if (!rect) return 0\n return Math.max(0, Math.min(rect.width, visibleViewport().width - KEYS_GAP * 2))\n})\n\n/** Keeps the bar within the part of the page in view. */\nfunction clampKeys(at: { x: number; y: number }) {\n const rect = rootInPage()\n if (!rect) return at\n const view = visibleViewport()\n const x = rect.left + at.x\n const y = rect.top + at.y\n const left = Math.max(\n view.left + KEYS_GAP,\n Math.min(x, view.left + view.width - keysWidth.value - KEYS_GAP),\n )\n const top = Math.max(\n view.top + KEYS_GAP,\n Math.min(y, view.top + view.height - KEYS_HEIGHT - KEYS_GAP),\n )\n return { x: left - rect.left, y: top - rect.top }\n}\n\n/** Below the editor, a gap apart, or as low as the page in view goes. */\nfunction placeKeys() {\n const rect = rootInPage()\n if (!rect) return\n keysAt.value = clampKeys({ x: 0, y: rect.height + KEYS_GAP })\n}\n\nconst keysClient = computed(() => {\n const rect = rootInPage()\n const at = keysAt.value\n return rect && at ? { x: rect.left + at.x, y: rect.top + at.y } : null\n})\n\nconst keysStyle = computed(() => {\n const at = keysClient.value\n if (!at) return { visibility: 'hidden' as const, zIndex: keysZIndex.value }\n return {\n // Not rounded: the shift is read from the box as drawn, and rounding twice would be a pixel off.\n transform: `translate(${at.x + keysShift.value.x}px, ${at.y + keysShift.value.y}px)`,\n width: `${keysWidth.value}px`,\n zIndex: keysZIndex.value,\n }\n})\n\nwatch(showKeys, (shown) => {\n if (!shown) keysFocused.value = false\n else if (typeof window !== 'undefined') settleKeys()\n})\n\n/**\n * Brings the bar into the page in view: not moved yet, to its place below\n * the editor; moved, only as far as it takes to be seen again.\n */\nfunction settleKeys() {\n if (!showKeys.value) return\n if (keysMoved && keysAt.value) keysAt.value = clampKeys(keysAt.value)\n else placeKeys()\n}\n\n/** How much of the bottom of the page in view the bar takes, when it sits there. */\nfunction keysRoom() {\n const rect = showKeys.value && keysAt.value ? root.value?.getBoundingClientRect() : null\n if (!rect || !keysAt.value) return 0\n const view = visibleViewport()\n const bottom = view.top + view.height\n const top = rect.top + keysAt.value.y\n return top + KEYS_HEIGHT >= bottom - KEYS_GAP - 1 ? bottom - top + KEYS_GAP : 0\n}\n\nconst TABBABLE =\n 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]'\n\n/** Tab out of the bar goes on to what follows the editor; Shift+Tab, or Escape, back into it. */\nfunction onKeysKeydown(event: KeyboardEvent) {\n const bar = keysEl.value\n if (!bar) return\n if (event.key === 'Escape') {\n event.preventDefault()\n input.value?.focus()\n return\n }\n if (event.key !== 'Tab') return\n const inside = [...bar.querySelectorAll<HTMLElement>(TABBABLE)].filter((el) => el.tabIndex >= 0)\n const here = inside.indexOf(document.activeElement as HTMLElement)\n if (event.shiftKey && here <= 0) {\n event.preventDefault()\n input.value?.focus()\n } else if (!event.shiftKey && here === inside.length - 1) {\n event.preventDefault()\n const from = document.activeElement as HTMLElement | null\n for (const el of document.querySelectorAll<HTMLElement>(TABBABLE)) {\n if (\n el.tabIndex < 0 ||\n bar.contains(el) ||\n !root.value ||\n root.value.contains(el) ||\n !(root.value.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING)\n ) {\n continue\n }\n // Hidden ones take no focus: on to the next.\n el.focus()\n if (document.activeElement === el) return\n }\n from?.blur()\n }\n}\n\nfunction onKeysFocusOut(event: FocusEvent) {\n // On to another key of the bar, it stays.\n if (!keysEl.value?.contains(event.relatedTarget as Node | null)) keysFocused.value = false\n}\n// After drawing, from the box as drawn: wherever the page scrolled, the bar's own box starts.\nwatch([showKeys, viewportTick], () => readKeysShift(), { flush: 'post' })\n\n/** A finger on the bar's grip: where it went down, and where the bar was then. */\nlet keysDrag: {\n pointer: number\n x: number\n y: number\n from: { x: number; y: number }\n hold: ReturnType<typeof holdPointer>\n} | null = null\n\nfunction onKeysGripDown(event: PointerEvent) {\n if (event.button !== 0 || !keysAt.value) return\n event.preventDefault()\n const hold = holdPointer(event, keysEl.value, endKeysDrag)\n hold.grab()\n keysDrag = {\n pointer: event.pointerId,\n x: event.clientX,\n y: event.clientY,\n from: keysAt.value,\n hold,\n }\n window.addEventListener('pointermove', onKeysGripMove)\n window.addEventListener('pointerup', endKeysDrag)\n window.addEventListener('pointercancel', endKeysDrag)\n}\n\nfunction onKeysGripMove(event: PointerEvent) {\n const press = keysDrag\n if (!press || event.pointerId !== press.pointer) return\n keysMoved = true\n keysAt.value = clampKeys({\n x: press.from.x + event.clientX - press.x,\n y: press.from.y + event.clientY - press.y,\n })\n}\n\nfunction endKeysDrag() {\n keysDrag?.hold.release()\n keysDrag = null\n window.removeEventListener('pointermove', onKeysGripMove)\n window.removeEventListener('pointerup', endKeysDrag)\n window.removeEventListener('pointercancel', endKeysDrag)\n}\n\n/** The grip moves by the arrow keys too, a step at a time. */\nfunction onKeysGripKey(event: KeyboardEvent) {\n const step = { ArrowUp: [0, -1], ArrowDown: [0, 1], ArrowLeft: [-1, 0], ArrowRight: [1, 0] }[\n event.key\n ]\n if (!step || !keysAt.value) return\n event.preventDefault()\n keysMoved = true\n const by = event.shiftKey ? 40 : 8\n keysAt.value = clampKeys({ x: keysAt.value.x + step[0]! * by, y: keysAt.value.y + step[1]! * by })\n}\n\n/**\n * Keeps the main cursor clear of the phone's keyboard:\n * scrolls the editor when the cursor can move inside it, else the page.\n */\nfunction followViewport() {\n const vv = window.visualViewport\n const el = scroller.value\n if (!vv || !el || !focused.value) return\n const at = coordsAtPos(mainRange(state.value.selection).head)\n if (!at) return\n const lh = lineHeight.value\n // Room below the cursor for its handle too.\n const room = lh / 2 + (handles.value.length ? HANDLE : 0)\n const rect = el.getBoundingClientRect()\n const view = visibleViewport()\n // The bar of keys at the bottom of the view covers what is behind it.\n const covered = keysRoom()\n const bottom = view.top + view.height - covered\n const visibleTop = Math.max(rect.top, view.top)\n const visibleBottom = Math.min(rect.bottom, bottom)\n if (at.bottom + room > visibleBottom && visibleBottom - visibleTop >= lh * 3) {\n el.scrollTop += (at.bottom + room - visibleBottom) / ratio.value\n onScroll()\n } else if (at.top - lh / 2 < visibleTop && visibleBottom - visibleTop >= lh * 3) {\n el.scrollTop -= (visibleTop - at.top + lh / 2) / ratio.value\n onScroll()\n }\n // Whatever the editor couldn't scroll, the page does.\n const after = coordsAtPos(mainRange(state.value.selection).head)\n if (!after || after.bottom + room <= bottom) return\n const before = window.scrollY\n window.scrollBy(0, after.bottom + room - bottom)\n // The bar at the bottom of the view stays there as the page goes up under it.\n if (covered && keysAt.value) {\n keysAt.value = { x: keysAt.value.x, y: keysAt.value.y + window.scrollY - before }\n }\n}\n\n/** How much of the window the keyboard took when last seen. */\nlet keyboardHeight = 0\nfunction readKeyboard() {\n const vv = window.visualViewport\n // Zoomed in, the view is smaller by the zoom, not by a keyboard.\n return vv ? Math.max(0, window.innerHeight - vv.height * vv.scale) : 0\n}\n\n/**\n * Follows the keyboard as it comes up or grows (a row of candidates, another\n * layout), and only then: the view also resizes while the page scrolls, as\n * the browser's own bars shrink and grow, and scrolling the page back to the\n * cursor then would fight the finger.\n */\nfunction onViewportChange() {\n const now = readKeyboard()\n const grew = now > keyboardHeight + 1\n keyboardHeight = now\n if (!grew || fingerScrolling) return\n // The bar first finds its place in view above the keyboard, so the cursor can keep clear of it.\n settleKeys()\n followViewport()\n}\n\n/**\n * A finger scrolls the page, by dragging or by the glide after it: the view\n * resizing meanwhile is the browser's bars, never a reason to scroll back.\n * The browser scrolling to the cursor on its own, as a tap brings the\n * keyboard up, has no finger moving and leaves the editor free to follow.\n */\nlet fingerScrolling = false\nlet pageScrollTimer = 0\nfunction settleLater() {\n clearTimeout(pageScrollTimer)\n pageScrollTimer = window.setTimeout(() => (fingerScrolling = false), 160)\n}\nfunction onPageScroll() {\n if (fingerScrolling) settleLater()\n}\nfunction onFingerMove() {\n fingerScrolling = true\n settleLater()\n}\n\n/** On a touch screen the keyboard comes and goes with focus; the view follows it meanwhile. */\nconst following = computed(() => coarse.value && focused.value)\nfunction unfollow() {\n if (typeof window === 'undefined') return\n const vv = window.visualViewport\n vv?.removeEventListener('resize', onViewportChange)\n window.removeEventListener('scroll', onPageScroll)\n window.removeEventListener('touchmove', onFingerMove)\n clearTimeout(pageScrollTimer)\n fingerScrolling = false\n}\nwatch(following, (on) => {\n const vv = window.visualViewport\n if (on) {\n keyboardHeight = readKeyboard()\n vv?.addEventListener('resize', onViewportChange)\n window.addEventListener('scroll', onPageScroll, { passive: true })\n window.addEventListener('touchmove', onFingerMove, { passive: true })\n } else unfollow()\n})\n\n// ---------------------------------------------------------------- minimap\n\n/** Height of a row in the minimap, and width of a character, in px. */\nconst MINI_ROW = 2\nconst MINI_CELL = 1\n/** The minimap's width, padding included. */\nconst MINI_WIDTH = 96\nconst MINI_PAD = 6\nconst minimapCanvas = ref<HTMLCanvasElement>()\n/** The editor's own width, minimap included. */\nconst rootWidth = ref(0)\nconst minimapOn = computed(() => !!props.minimap && mounted.value && rootWidth.value >= 480)\n\n/** Where the minimap is: the row at its top (fractional), and the part in view as a box. */\nconst minimap = computed(() => {\n if (!minimapOn.value) return null\n const track = viewHeight.value\n const lh = lineHeight.value || 1\n const height = layout.value.total * MINI_ROW\n const textTop = scrollTop.value * ratio.value\n const first = rowAtTextY(Math.max(0, textTop - pad.y))\n const last = rowAtTextY(Math.max(0, textTop + track - pad.y))\n const range = Math.max(1, total.value + pad.y * 2 - track)\n const progress = Math.min(1, Math.max(0, textTop / range))\n const top = height > track ? progress * (height - track) : 0\n const firstFraction = first + ((textTop - pad.y - rowTop(first)) / lh || 0)\n return {\n top,\n track,\n height,\n slider: {\n top: Math.max(0, firstFraction) * MINI_ROW - top,\n height: Math.max(MINI_ROW * 4, (last - first + 1) * MINI_ROW),\n },\n }\n})\n\n/** Whether a character is drawn two cells wide: CJK, Hangul, full-width forms. */\nconst isWideCode = (code: number) =>\n (code >= 0x1100 && code <= 0x115f) ||\n (code >= 0x2e80 && code <= 0xa4cf) ||\n (code >= 0xac00 && code <= 0xd7a3) ||\n (code >= 0xf900 && code <= 0xfaff) ||\n (code >= 0xfe30 && code <= 0xfe4f) ||\n (code >= 0xff00 && code <= 0xff60) ||\n (code >= 0xffe0 && code <= 0xffe6)\n\n/** The token colors, read from the theme when it changes. */\nlet miniColors: { key: string; text: string; types: string[] } | null = null\nfunction minimapColors(canvas: HTMLCanvasElement) {\n const style = getComputedStyle(canvas)\n const key = `${style.color}|${style.getPropertyValue('--dou-color-syntax-keyword')}`\n if (miniColors?.key === key) return miniColors\n const swatch = document.createElement('span')\n swatch.style.display = 'none'\n canvas.parentElement!.append(swatch)\n const types = tokenTypes.map((type) => {\n swatch.style.color = `var(--dou-color-syntax-${type}, currentColor)`\n return getComputedStyle(swatch).color\n })\n swatch.remove()\n miniColors = { key, text: style.color, types }\n return miniColors\n}\n\nlet miniFrame = 0\nfunction drawMinimap() {\n miniFrame = 0\n const canvas = minimapCanvas.value\n const map = minimap.value\n if (!canvas || !map) return\n const dpr = window.devicePixelRatio || 1\n const width = MINI_WIDTH\n const height = map.track\n if (canvas.width !== Math.round(width * dpr) || canvas.height !== Math.round(height * dpr)) {\n canvas.width = Math.round(width * dpr)\n canvas.height = Math.round(height * dpr)\n }\n const ctx = canvas.getContext('2d')\n if (!ctx) return\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n ctx.clearRect(0, 0, width, height)\n const colors = minimapColors(canvas)\n const text = doc.value\n const lay = layout.value\n const hl = highlighter\n const cols = Math.floor((width - MINI_PAD * 2) / MINI_CELL)\n const tab = props.tabSize\n const firstRow = Math.max(0, Math.floor(map.top / MINI_ROW))\n const lastRow = Math.min(lay.total - 1, Math.ceil((map.top + height) / MINI_ROW))\n const mark = MINI_ROW * 0.75\n ctx.globalAlpha = 0.7\n let row = firstRow\n while (row <= lastRow) {\n const { n, sub } = lay.lineAtRow(row)\n const rowText = text.lineText(n)\n const breaks = wrapRows ? wrapOf(rowText).breaks : []\n const tokens = hl && (hl.ready(n) || n - hl.frontier <= SYNTAX_REACH) ? hl.line(n) : null\n const rowsHere = lay.rowsOf(n)\n for (let k = sub; k < rowsHere && row <= lastRow; k++, row++) {\n const start = k ? breaks[k - 1]! : 0\n const end = k < breaks.length ? breaks[k]! : rowText.length\n const y = row * MINI_ROW - map.top\n let col = 0\n let runFrom = -1\n let runColor = ''\n let t = 0\n const flush = () => {\n if (runFrom < 0) return\n ctx.fillStyle = runColor\n ctx.fillRect(MINI_PAD + runFrom * MINI_CELL, y, (col - runFrom) * MINI_CELL, mark)\n runFrom = -1\n }\n for (let i = start; i < end && col < cols; i++) {\n const code = rowText.charCodeAt(i)\n if (code === 32 || code === 9) {\n flush()\n col += code === 9 ? tab - (col % tab) : 1\n continue\n }\n let color = colors.text\n if (tokens) {\n while (t < tokens.length && tokens[t]! <= i) t += 2\n const type = t < tokens.length ? tokens[t + 1]! : -1\n if (type >= 0) color = colors.types[type]!\n }\n if (runFrom >= 0 && color !== runColor) flush()\n if (runFrom < 0) {\n runFrom = col\n runColor = color\n }\n // CJK and other wide characters take two cells, as they do in the text\n col += code >= 0x1100 && isWideCode(code) ? 2 : 1\n }\n flush()\n }\n }\n}\nfunction scheduleMinimap() {\n if (!miniFrame && minimapOn.value) miniFrame = requestAnimationFrame(drawMinimap)\n}\nwatch([minimap, doc, layout, syntaxTick, () => props.tabSize], () => scheduleMinimap(), {\n flush: 'post',\n})\n// The colors come from the theme: switching it (a class on the page, or the system's) draws again.\nlet themeWatch: (() => void) | null = null\nwatch(minimapOn, (on) => {\n themeWatch?.()\n themeWatch = null\n if (!on || typeof MutationObserver === 'undefined') return\n const observer = new MutationObserver(scheduleMinimap)\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['class', 'style', 'data-dou-theme'],\n })\n const dark = matchMedia?.('(prefers-color-scheme: dark)')\n dark?.addEventListener?.('change', scheduleMinimap)\n themeWatch = () => {\n observer.disconnect()\n dark?.removeEventListener?.('change', scheduleMinimap)\n }\n})\nonBeforeUnmount(() => {\n if (miniFrame) cancelAnimationFrame(miniFrame)\n themeWatch?.()\n})\n\n/** Scrolls so that minimap row `row` is in the middle of the view. */\nfunction scrollToMiniRow(row: number) {\n const el = scroller.value\n if (!el) return\n const lay = layout.value\n const at = Math.max(0, Math.min(lay.total - 1, Math.floor(row)))\n const y = pad.y + rowTop(at) - el.clientHeight / 2\n el.scrollTop = Math.max(0, y / ratio.value)\n onScroll()\n}\n\nlet miniDrag: { y: number; scroll: number; pointer: number } | null = null\nfunction onMinimapDown(event: PointerEvent) {\n const map = minimap.value\n const canvas = event.currentTarget as HTMLElement\n if (!map || event.button !== 0) return\n event.preventDefault()\n const box = canvas.getBoundingClientRect()\n const y = event.clientY - box.top\n // A press beside the mark goes there first; dragging then moves the mark.\n if (y < map.slider.top || y > map.slider.top + map.slider.height)\n scrollToMiniRow((map.top + y) / MINI_ROW)\n miniDrag = { y: event.clientY, scroll: scroller.value?.scrollTop ?? 0, pointer: event.pointerId }\n canvas.setPointerCapture?.(event.pointerId)\n}\nfunction onMinimapMove(event: PointerEvent) {\n const map = minimap.value\n const el = scroller.value\n if (!miniDrag || !map || !el || event.pointerId !== miniDrag.pointer) return\n const dy = event.clientY - miniDrag.y\n const max = el.scrollHeight - el.clientHeight\n // The mark follows the pointer: over a short text it moves with the rows, over a long one along the track.\n const room =\n map.height > map.track ? map.track - map.slider.height : map.height - map.slider.height\n el.scrollTop = Math.max(0, Math.min(max, miniDrag.scroll + (dy * max) / Math.max(1, room)))\n onScroll()\n}\nfunction onMinimapUp(event: PointerEvent) {\n if (miniDrag?.pointer === event.pointerId) miniDrag = null\n}\n\n// ---------------------------------------------------------------- scrolling\n\nfunction onScroll() {\n const el = scroller.value\n if (!el) return\n // iOS reports positions past either end while the content bounces back\n const { top, left } = scrollPositionOf(el)\n scrollTop.value = top\n scrollLeft.value = left\n updateClip()\n}\n\n/** Keeps a position in view, with a line of room around it. */\nfunction scrollIntoView(pos = mainRange(state.value.selection).head) {\n const el = scroller.value\n if (!el) return\n const line = doc.value.lineAt(pos)\n const lh = lineHeight.value\n const view = el.clientHeight\n if (view < lh * 3) return\n const at = place(line.number, line.text, pos - line.from)\n const y = at.top - shift.value\n const top = el.scrollTop * ratio.value\n const margin = Math.min(lh, view / 4)\n if (y - margin < top) el.scrollTop = Math.max(0, (y - margin) / ratio.value)\n else if (y + lh + margin > top + view) el.scrollTop = (y + lh + margin - view) / ratio.value\n const x = pad.x + at.x\n const width = el.clientWidth - gutterWidth.value\n if (x - measure.cell * 2 < el.scrollLeft) el.scrollLeft = Math.max(0, x - measure.cell * 4)\n else if (x + measure.cell * 2 > el.scrollLeft + width)\n el.scrollLeft = x + measure.cell * 4 - width\n onScroll()\n}\n\nlet clipFrame = 0\n/** For an editor taller than the window, draws only the lines inside the window. */\nfunction updateClip() {\n const el = scroller.value\n if (!el) return\n if (el.clientHeight <= window.innerHeight) {\n if (clip.value) clip.value = null\n return\n }\n const rect = el.getBoundingClientRect()\n const top = Math.max(0, -rect.top)\n const bottom = Math.max(top, Math.min(el.clientHeight, window.innerHeight - rect.top))\n if (clip.value?.top !== top || clip.value?.bottom !== bottom) clip.value = { top, bottom }\n}\nfunction onWindowScroll(event: Event) {\n if (event.target === scroller.value || clipFrame) return\n clipFrame = requestAnimationFrame(() => {\n clipFrame = 0\n updateClip()\n })\n}\n\nlet resize: ResizeObserver | undefined\nfunction refreshMetrics() {\n measure.refresh(props.tabSize)\n pad.y = measure.padY\n pad.x = measure.padX\n readFrameFont()\n metrics.value++\n syncInput()\n}\n\nwatch(\n () => props.tabSize,\n () => refreshMetrics(),\n)\n\nonMounted(() => {\n refreshMetrics()\n const el = scroller.value!\n viewHeight.value = el.clientHeight\n viewWidth.value = el.clientWidth\n rootWidth.value = root.value?.clientWidth ?? 0\n if (typeof ResizeObserver !== 'undefined') {\n resize = new ResizeObserver(() => {\n viewHeight.value = el.clientHeight\n viewWidth.value = el.clientWidth\n rootWidth.value = root.value?.clientWidth ?? 0\n updateClip()\n })\n resize.observe(el)\n if (root.value) resize.observe(root.value)\n }\n updateClip()\n mounted.value = true\n window.addEventListener('scroll', onWindowScroll, { capture: true, passive: true })\n window.addEventListener('resize', onWindowScroll, { passive: true })\n document.addEventListener('selectionchange', onSelectionChange)\n // Web fonts change the cell width once they arrive.\n document.fonts?.ready.then(() => root.value && refreshMetrics())\n document.fonts?.addEventListener?.('loadingdone', refreshMetrics)\n if (props.autofocus) focusInput()\n for (const extension of extensions.value) startExtension(extension)\n runLint()\n})\n\n/** What each extension's `setup` returned, to run when it goes. */\nconst cleanups = new Map<CodeExtension, () => void>()\nfunction startExtension(extension: CodeExtension) {\n if (cleanups.has(extension)) return\n const cleanup = extension.setup?.(context)\n cleanups.set(extension, typeof cleanup === 'function' ? cleanup : () => {})\n}\nlet restarts: number[] = []\nlet restartWarned = false\n/** An extension made in the template is new on every render, and set up again each time. */\nfunction warnRestarts() {\n if (process.env.NODE_ENV === 'production' || restartWarned) return\n const now = Date.now()\n restarts = [...restarts.filter((time) => now - time < 1000), now]\n if (restarts.length < 4) return\n restartWarned = true\n console.warn(\n '[@dou-ui/code] the extensions keep being set up again, which also starts their state over (such as a shared undo history). Create them once in <script setup> instead of in the template.',\n )\n}\nwatch(extensions, (next) => {\n if (!mounted.value) return\n let restarted = false\n for (const [extension, cleanup] of cleanups)\n if (!next.includes(extension)) {\n cleanup()\n cleanups.delete(extension)\n restarted = true\n }\n for (const extension of next) startExtension(extension)\n if (restarted) warnRestarts()\n})\n\nonBeforeUnmount(() => {\n if (syntaxJob) cancelIdle(syntaxJob)\n clearTimeout(searchTimer)\n resize?.disconnect()\n widgetObserver?.disconnect()\n inlineObserver?.disconnect()\n endDrag()\n onPointerCancel()\n endHandlePress()\n unfollow()\n clearTimeout(lintTimer)\n clearTimeout(problemTimer)\n for (const cleanup of cleanups.values()) cleanup()\n cleanups.clear()\n cancelAnimationFrame(clipFrame)\n window.removeEventListener('scroll', onWindowScroll, { capture: true })\n window.removeEventListener('resize', onWindowScroll)\n document.removeEventListener('selectionchange', onSelectionChange)\n document.fonts?.removeEventListener?.('loadingdone', refreshMetrics)\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n syncInput()\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n // A press or drag never outlives the focus: the page must scroll again once the keyboard is away.\n onPointerCancel()\n endHandlePress()\n endDrag()\n focused.value = false\n menuOpen.value = false\n // A finger's box goes with the keyboard; a mouse's stays while the mouse is over it.\n if (problemBox.value?.keyboard || touchUi.value) closeProblems()\n closeCompletion()\n closeSignature()\n closeHistory()\n if (lazyDirty) {\n lazyDirty = false\n emit('update:modelValue', textOf(doc.value))\n }\n emit('blur', event)\n}\n\nconst api: CodeExtensionContext = {\n get state() {\n return state.value\n },\n get doc() {\n return state.value.doc\n },\n get selection() {\n return state.value.selection\n },\n transact,\n run,\n undo,\n redo,\n get canUndo() {\n if (historyHandler.value) return historyHandler.value.canUndo()\n void historyTick.value\n return history.canUndo\n },\n get canRedo() {\n if (historyHandler.value) return historyHandler.value.canRedo()\n void historyTick.value\n return history.canRedo\n },\n select(anchor, head) {\n const selection = typeof anchor === 'number' ? selectionOf(anchor, head) : anchor\n dispatch(\n transaction()\n .select(normalizeSelection(selection, doc.value.length))\n .setMeta({ scroll: true }),\n )\n },\n scrollIntoView,\n coordsAtPos,\n posAtCoords,\n focus: focusInput,\n blur: () => input.value?.blur(),\n openSearch: (given) => openSearch(false, given),\n closeSearch,\n fold: (line) => folding.fold(line),\n unfold: (line) => folding.unfold(line),\n foldAll: () => folding.foldAll(),\n unfoldAll: () => folding.unfoldAll(),\n get folds() {\n return foldStarts.value\n },\n get diagnostics() {\n return diagnostics.value\n },\n get visible() {\n return { from: visibleFrom.value, to: visibleTo.value }\n },\n get focused() {\n return focused.value\n },\n get messages() {\n return messages.value\n },\n announce,\n relint: (name) => {\n if (mounted.value) runLint(name)\n },\n}\ncontext = api\nprovide(CODE_EDITOR_KEY, api)\ndefineExpose<CodeEditorExpose>(api)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n ns.is('focused', focused),\n ns.is('readonly', !!readonly),\n ns.is('disabled', !!disabled),\n ns.is('foldable', foldable),\n ns.is('wrap', wrap),\n ]\"\n :style=\"{\n '--dou-code-editor-gutter': `${gutterWidth}px`,\n '--dou-code-editor-gutter-cells': `${gutterCells}px`,\n '--dou-code-editor-tab-size': tabSize,\n }\"\n >\n <div v-if=\"searchOpen\" :class=\"ns.e('search')\">\n <DouFindReplace\n ref=\"panel\"\n :search=\"query.search\"\n :replace=\"query.replace ?? ''\"\n v-model:replacing=\"showReplace\"\n :count=\"matches.length\"\n :current=\"currentMatch\"\n :capped=\"capped\"\n :error=\"searchError && common('findReplace.invalidRegexp')\"\n :readonly=\"readonly || disabled\"\n @update:search=\"query = { ...query, search: $event }\"\n @update:replace=\"query = { ...query, replace: $event }\"\n @next=\"nextMatch()\"\n @previous=\"previousMatch()\"\n @replace-one=\"replaceOne\"\n @replace-all=\"replaceAll\"\n @close=\"closeSearch\"\n >\n <template #options>\n <DouTooltip\n v-for=\"option in searchOptions\"\n :key=\"option.key\"\n :content=\"common(`findReplace.${option.key}`)\"\n >\n <DouToggle\n :pressed=\"!!query[option.key]\"\n size=\"sm\"\n :aria-label=\"common(`findReplace.${option.key}`)\"\n @update:pressed=\"query = { ...query, [option.key]: $event }\"\n >\n <component :is=\"option.icon\" />\n </DouToggle>\n </DouTooltip>\n </template>\n </DouFindReplace>\n </div>\n <div v-if=\"problemMarks.length\" :class=\"ns.e('marks')\" aria-hidden=\"true\">\n <div\n v-for=\"mark in problemMarks\"\n :key=\"`${mark.top}${mark.severity}`\"\n :class=\"[ns.e('mark'), ns.e('problem-mark'), ns.is(mark.severity, true)]\"\n :style=\"{ top: `${mark.top}%` }\"\n />\n </div>\n <div v-if=\"searchMarks.length\" :class=\"ns.e('marks')\" aria-hidden=\"true\">\n <div\n v-for=\"mark in searchMarks\"\n :key=\"`${mark.top}${mark.current ? 'c' : ''}`\"\n :class=\"[ns.e('mark'), ns.is('current', mark.current)]\"\n :style=\"{ top: `${mark.top}%` }\"\n />\n </div>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ announcement }}</div>\n <div v-if=\"panels.top.length\" :class=\"[ns.e('panels'), ns.is('top', true)]\">\n <RenderPart v-for=\"panel in panels.top\" :key=\"panel.key\" :render=\"panel.render\" />\n </div>\n <div :class=\"ns.e('body')\">\n <div ref=\"scroller\" :class=\"ns.e('scroller')\" @scroll.passive=\"onScroll\">\n <div\n :class=\"ns.e('sizer')\"\n :style=\"{\n height: `${sizerHeight}px`,\n minWidth: `max(100%, ${contentWidth + gutterWidth}px)`,\n }\"\n >\n <div\n v-if=\"gutter && (lineNumbers || foldable || gutterCells)\"\n :class=\"ns.e('gutter')\"\n aria-hidden=\"true\"\n @pointerdown=\"onPointerDown($event, 'gutter')\"\n @pointermove=\"onPointerMove\"\n @pointerup=\"onPointerUp($event, 'gutter')\"\n @pointercancel=\"onPointerCancel\"\n @pointerenter=\"gutterHover = true\"\n @pointerleave=\"gutterHover = false\"\n @mousedown.prevent\n >\n <div\n :class=\"ns.e('numbers')\"\n :style=\"{ transform: `translateY(${yOf(visibleFrom)}px)` }\"\n >\n <div\n v-for=\"row in rows\"\n :key=\"row.n\"\n :class=\"[ns.e('number'), ns.is('active', row.n === activeLineNumber)]\"\n :style=\"{\n height: row.wrapped.breaks.length\n ? `${(row.wrapped.breaks.length + 1) * lineHeight}px`\n : undefined,\n marginTop: gapBefore(row.n) ? `${gapBefore(row.n)}px` : undefined,\n }\"\n >\n <span v-if=\"gutterCells\" :class=\"ns.e('cells')\">\n <span\n v-for=\"(column, c) in gutterColumns\"\n :key=\"column.name\"\n :class=\"[ns.e('cell'), gutterMarkers[c]?.get(row.n)?.class]\"\n :style=\"{ width: `${column.width}px` }\"\n :title=\"gutterMarkers[c]?.get(row.n)?.title\"\n :data-gutter-cell=\"column.onPress ? c : undefined\"\n :data-line=\"row.n\"\n >\n <template v-if=\"gutterMarkers[c]?.get(row.n)\">\n <component\n :is=\"gutterMarkers[c]!.get(row.n)!.icon\"\n v-if=\"gutterMarkers[c]!.get(row.n)!.icon\"\n />\n <template v-else>{{ gutterMarkers[c]!.get(row.n)!.text }}</template>\n </template>\n </span>\n </span>\n <template v-if=\"lineNumbers\">{{ row.n }}</template>\n <span\n v-if=\"foldable && (row.folded || foldableLines.has(row.n))\"\n :class=\"[ns.e('fold-toggle'), ns.is('folded', row.folded)]\"\n :data-fold=\"row.n\"\n >\n <ChevronRightIcon v-if=\"row.folded\" />\n <ChevronDownIcon v-else />\n </span>\n </div>\n </div>\n </div>\n <div\n ref=\"content\"\n :class=\"ns.e('content')\"\n @pointerdown=\"onPointerDown($event, 'text')\"\n @pointermove=\"(onPointerMove($event), onContentHover($event))\"\n @pointerup=\"onPointerUp($event, 'text')\"\n @pointercancel=\"onPointerCancel\"\n @pointerleave=\"onContentLeave\"\n @mousedown.prevent\n >\n <div ref=\"probe\" :class=\"ns.e('probe')\" aria-hidden=\"true\" />\n <div\n v-if=\"activeLine && activeLineTop !== null && !disabled\"\n :class=\"ns.e('active-line')\"\n :style=\"{\n transform: `translateY(${activeLineTop}px)`,\n height: activeLineRows > 1 ? `${activeLineRows * lineHeight}px` : undefined,\n }\"\n />\n <div :class=\"ns.e('matches')\" aria-hidden=\"true\">\n <div\n v-for=\"box in matchBoxes\"\n :key=\"box.key\"\n :class=\"[ns.e('match'), ns.is('current', box.current)]\"\n :style=\"{\n transform: `translate(${box.left}px, ${box.top}px)`,\n width: `${box.width}px`,\n }\"\n />\n </div>\n <div :class=\"ns.e('brackets')\" aria-hidden=\"true\">\n <div\n v-for=\"box in bracketBoxes\"\n :key=\"box.key\"\n :class=\"[ns.e('bracket'), ns.is('unmatched', !box.matched)]\"\n :style=\"{\n transform: `translate(${box.left}px, ${box.top}px)`,\n width: `${box.width}px`,\n }\"\n />\n </div>\n <div :class=\"ns.e('selections')\" aria-hidden=\"true\">\n <div\n v-for=\"box in selectionBoxes\"\n :key=\"box.key\"\n :class=\"ns.e('selection')\"\n :style=\"{\n transform: `translate(${box.left}px, ${box.top}px)`,\n width: `${box.width}px`,\n }\"\n />\n </div>\n <div\n :class=\"ns.e('lines')\"\n aria-hidden=\"true\"\n :style=\"{ transform: `translateY(${yOf(visibleFrom)}px)` }\"\n >\n <div\n v-for=\"row in rows\"\n :key=\"row.n\"\n v-memo=\"[\n row.text,\n row.tokens,\n row.compose?.join('\\u0000'),\n row.wrapped,\n row.folded,\n row.marksKey,\n row.inlinesKey,\n row.lineClass,\n gapBefore(row.n),\n ]\"\n :class=\"[\n ns.e('line'),\n ns.is('wrapped', !!row.wrapped.breaks.length),\n row.lineClass,\n ]\"\n :style=\"gapBefore(row.n) ? { marginTop: `${gapBefore(row.n)}px` } : undefined\"\n >\n <template v-if=\"row.compose\"\n >{{ row.compose[0] }}<span :class=\"ns.e('compose')\">{{ row.compose[1] }}</span\n >{{ row.compose[2] }}</template\n >\n <template v-else-if=\"row.wrapped.breaks.length\"\n ><div\n v-for=\"(_, sub) in row.wrapped.breaks.length + 1\"\n :key=\"sub\"\n :class=\"ns.e('row')\"\n :style=\"sub ? { paddingLeft: `${row.wrapped.indent}px` } : undefined\"\n >\n <template v-for=\"(part, i) in rowParts(row, sub)\" :key=\"i\"\n ><span\n v-if=\"part[3] !== undefined\"\n :ref=\"\n (el) =>\n observeInline(\n el as Element | null,\n row.inlines![part[3]!]!.key,\n row.inlines![part[3]!]!.width,\n )\n \"\n :class=\"ns.e('inline')\"\n :style=\"\n row.inlines![part[3]!]!.width !== undefined\n ? { width: `${row.inlines![part[3]!]!.width}px` }\n : undefined\n \"\n ><RenderPart :render=\"row.inlines![part[3]!]!.render\" /></span\n ><span\n v-else-if=\"part[1]\"\n :class=\"part[1]\"\n :title=\"part[2]\"\n :style=\"part[4]\"\n >{{ part[0] }}</span\n ><template v-else>{{ part[0] }}</template></template\n ><span\n v-if=\"row.folded && sub === row.wrapped.breaks.length\"\n :class=\"ns.e('fold-marker')\"\n :data-unfold=\"row.n\"\n :title=\"messages.unfold\"\n >⋯</span\n >\n </div></template\n >\n <template v-else-if=\"row.tokens || row.marks || row.inlines\"\n ><template v-for=\"(part, i) in partsOf(row)\" :key=\"i\"\n ><span\n v-if=\"part[3] !== undefined\"\n :ref=\"\n (el) =>\n observeInline(\n el as Element | null,\n row.inlines![part[3]!]!.key,\n row.inlines![part[3]!]!.width,\n )\n \"\n :class=\"ns.e('inline')\"\n :style=\"\n row.inlines![part[3]!]!.width !== undefined\n ? { width: `${row.inlines![part[3]!]!.width}px` }\n : undefined\n \"\n ><RenderPart :render=\"row.inlines![part[3]!]!.render\" /></span\n ><span v-else-if=\"part[1]\" :class=\"part[1]\" :title=\"part[2]\" :style=\"part[4]\">{{\n part[0]\n }}</span\n ><template v-else>{{ part[0] }}</template></template\n ></template\n >\n <template v-else>{{ row.text }}</template>\n <span\n v-if=\"row.folded && !row.wrapped.breaks.length\"\n :class=\"ns.e('fold-marker')\"\n :data-unfold=\"row.n\"\n :title=\"messages.unfold\"\n >⋯</span\n >\n </div>\n </div>\n <div\n v-if=\"placeholder && !doc.length && !composing\"\n :class=\"ns.e('placeholder')\"\n aria-hidden=\"true\"\n >\n {{ placeholder }}\n </div>\n <div v-if=\"focused\" :key=\"blink\" :class=\"ns.e('cursors')\" aria-hidden=\"true\">\n <div\n v-for=\"cursor in cursors\"\n :key=\"cursor.key\"\n :class=\"ns.e('cursor')\"\n :style=\"{ transform: `translate(${cursor.left - 1}px, ${cursor.top}px)` }\"\n />\n </div>\n <!-- The boxes about the text and the touch handles: above the page, or inside the frame. -->\n <Teleport :to=\"floatingTarget || 'body'\" :disabled=\"!floatingTarget\">\n <div\n ref=\"floatingEl\"\n :class=\"[\n ns.e('floating'),\n ns.is('outside', !!floatingTarget),\n ns.is('fixed', !!floatingTarget && anchorMode === 'fixed'),\n ns.is('scrolling', !!floatingTarget && boxScrolling),\n ]\"\n :style=\"\n floatingTarget\n ? {\n ...frameVars,\n zIndex: floatingZ,\n transform: `translate(${layerShift.x}px, ${layerShift.y}px)`,\n }\n : undefined\n \"\n >\n <div\n v-if=\"problemStyle\"\n ref=\"problemEl\"\n :class=\"ns.e('problems')\"\n role=\"group\"\n :aria-label=\"problemBox!.problems.length ? messages.problems : messages.details\"\n :style=\"problemStyle\"\n @pointerdown.stop.prevent\n @pointermove.stop\n @pointerenter=\"keepProblems\"\n @pointerleave=\"onContentLeave\"\n >\n <div\n v-for=\"(item, i) in problemBox!.info\"\n :key=\"`info-${i}`\"\n :class=\"ns.e('hover')\"\n >\n <template v-if=\"typeof item === 'string'\">{{ item }}</template>\n <RenderPart v-else :render=\"item\" />\n </div>\n <div\n v-for=\"(problem, i) in problemBox!.problems\"\n :key=\"i\"\n :class=\"[ns.e('problem-item'), ns.is(problem.severity, true)]\"\n >\n <component\n :is=\"SEVERITY_ICON[problem.severity]\"\n :class=\"ns.e('problem-severity')\"\n />\n <span :class=\"ns.e('problem-message')\"\n >{{ problem.message\n }}<span v-if=\"problem.source\" :class=\"ns.e('problem-source')\">\n {{ problem.source }}</span\n ></span\n >\n </div>\n <div v-if=\"fixes.length\" :class=\"ns.e('fixes')\">\n <button\n v-for=\"(fix, i) in fixes\"\n :key=\"i\"\n type=\"button\"\n tabindex=\"-1\"\n :class=\"[ns.e('fix'), ns.is('active', i === problemBox!.index)]\"\n :aria-current=\"i === problemBox!.index || undefined\"\n @click=\"runFix(i)\"\n >\n {{ fix.action.label }}\n </button>\n </div>\n </div>\n <div\n v-if=\"completionStyle\"\n ref=\"completionEl\"\n :class=\"ns.e('completions')\"\n :style=\"completionStyle\"\n @pointerdown.stop.prevent\n @pointermove.stop\n >\n <div\n :id=\"completionId\"\n ref=\"completionList\"\n :class=\"ns.e('completion-list')\"\n role=\"listbox\"\n :aria-label=\"messages.completions\"\n >\n <div\n v-for=\"(item, i) in completion!.items\"\n :id=\"`${completionId}-${i}`\"\n :key=\"i\"\n role=\"option\"\n :aria-selected=\"i === completion!.index\"\n :class=\"[ns.e('completion'), ns.is('active', i === completion!.index)]\"\n @click=\"acceptCompletion(i)\"\n >\n <component\n :is=\"KIND_ICON[item.option.kind ?? 'text']\"\n :class=\"[ns.e('completion-kind'), ns.is(item.option.kind ?? 'text', true)]\"\n aria-hidden=\"true\"\n />\n <span :class=\"ns.e('completion-label')\"\n ><template v-for=\"(part, j) in labelParts(item)\" :key=\"j\"\n ><mark v-if=\"part[1]\" :class=\"ns.e('completion-match')\">{{\n part[0]\n }}</mark\n ><template v-else>{{ part[0] }}</template></template\n ></span\n >\n <span v-if=\"item.option.detail\" :class=\"ns.e('completion-detail')\">{{\n item.option.detail\n }}</span>\n </div>\n </div>\n <div\n v-if=\"completion!.items[completion!.index]?.option.info\"\n :class=\"ns.e('completion-info')\"\n >\n <template\n v-if=\"typeof completion!.items[completion!.index]!.option.info === 'string'\"\n >{{ completion!.items[completion!.index]!.option.info }}</template\n >\n <RenderPart\n v-else\n :render=\"\n completion!.items[completion!.index]!.option.info as () => VNodeChild\n \"\n />\n </div>\n </div>\n <div\n v-if=\"signatureStyle\"\n ref=\"signatureEl\"\n :class=\"ns.e('signature')\"\n role=\"note\"\n :aria-label=\"messages.signature\"\n :style=\"signatureStyle\"\n @pointerdown.stop.prevent\n >\n <div :class=\"ns.e('signature-label')\">\n <template v-for=\"(part, i) in signatureParts\" :key=\"i\"\n ><span v-if=\"part[1]\" :class=\"ns.e('signature-active')\">{{ part[0] }}</span\n ><template v-else>{{ part[0] }}</template></template\n >\n </div>\n <div v-if=\"signature!.result.info\" :class=\"ns.e('signature-info')\">\n <template v-if=\"typeof signature!.result.info === 'string'\">{{\n signature!.result.info\n }}</template>\n <RenderPart v-else :render=\"signature!.result.info\" />\n </div>\n </div>\n <div\n v-for=\"handle in handles\"\n :key=\"handle.kind\"\n :class=\"[ns.e('handle'), ns.is(handle.kind, true)]\"\n :style=\"{ transform: `translate(${handle.left}px, ${handle.top}px)` }\"\n aria-hidden=\"true\"\n @pointerdown=\"onHandleDown($event, handle.kind)\"\n />\n <div\n v-if=\"magnifier\"\n :class=\"ns.e('magnifier')\"\n :style=\"magnifier.style\"\n aria-hidden=\"true\"\n >\n <div\n :class=\"ns.e('magnifier-text')\"\n :style=\"[magnifier.textStyle, { paddingLeft: `${magnifier.indent}px` }]\"\n >\n <template v-for=\"(part, i) in magnifier.parts\" :key=\"i\"\n ><span\n v-if=\"part[3] !== undefined\"\n :class=\"ns.e('inline')\"\n :style=\"{ width: `${widthOf(magnifier.inlines[part[3]!]!)}px` }\"\n ><RenderPart :render=\"magnifier.inlines[part[3]!]!.render\" /></span\n ><span\n v-else-if=\"part[1]\"\n :class=\"part[1]\"\n :title=\"part[2]\"\n :style=\"part[4]\"\n >{{ part[0] }}</span\n ><template v-else>{{ part[0] }}</template></template\n >\n </div>\n <div\n :class=\"ns.e('magnifier-caret')\"\n :style=\"{ left: `${magnifier.caret - 1}px` }\"\n />\n </div>\n <div\n v-if=\"menuStyle\"\n ref=\"menuEl\"\n :class=\"ns.e('menu')\"\n role=\"toolbar\"\n :aria-label=\"messages.editMenu\"\n :style=\"menuStyle\"\n @pointerdown.stop.prevent\n >\n <button\n v-for=\"item in menuItems\"\n :key=\"item.key\"\n type=\"button\"\n tabindex=\"-1\"\n :class=\"ns.e('menu-button')\"\n @click=\"item.run()\"\n >\n {{ item.label }}\n </button>\n </div>\n </div>\n </Teleport>\n <textarea\n ref=\"input\"\n :class=\"ns.e('input')\"\n :style=\"{\n top: `${inputBox.top}px`,\n left: `${inputBox.left}px`,\n height: `${inputBox.height}px`,\n }\"\n :aria-label=\"ariaLabel\"\n :aria-placeholder=\"placeholder || undefined\"\n :aria-autocomplete=\"hasCompletion ? 'list' : undefined\"\n :aria-controls=\"completion ? completionId : undefined\"\n :readonly=\"readonly\"\n :disabled=\"disabled\"\n wrap=\"off\"\n autocomplete=\"off\"\n autocorrect=\"off\"\n autocapitalize=\"off\"\n spellcheck=\"false\"\n enterkeyhint=\"enter\"\n @keydown=\"onKeydown\"\n @beforeinput=\"onBeforeInput\"\n @input=\"onInput\"\n @compositionstart=\"onCompositionStart\"\n @compositionend=\"onCompositionEnd\"\n @copy=\"onCopy\"\n @cut=\"onCut\"\n @paste=\"onPaste\"\n @focus=\"onFocus\"\n @blur=\"onBlur\"\n />\n <!-- After the textarea, so Escape then Tab reaches what is inside the widgets. -->\n <div\n v-if=\"shownWidgets.length\"\n :class=\"ns.e('widgets')\"\n @pointerdown.stop\n @pointermove.stop\n @mousedown.stop\n >\n <div\n v-for=\"widget in shownWidgets\"\n :key=\"widget.key\"\n :ref=\"(el) => observeWidget(el as Element | null, widget.key)\"\n :class=\"ns.e('widget')\"\n :role=\"widget.label ? 'group' : undefined\"\n :aria-label=\"widget.label\"\n :style=\"{\n transform: `translate(${scrollLeft}px, ${widget.top}px)`,\n width: `${Math.max(0, viewWidth - gutterWidth)}px`,\n }\"\n >\n <RenderPart :render=\"widget.render\" />\n </div>\n </div>\n </div>\n </div>\n </div>\n <div\n v-if=\"minimapOn && minimap\"\n :class=\"ns.e('minimap')\"\n aria-hidden=\"true\"\n @pointerdown=\"onMinimapDown\"\n @pointermove=\"onMinimapMove\"\n @pointerup=\"onMinimapUp\"\n @pointercancel=\"onMinimapUp\"\n >\n <canvas ref=\"minimapCanvas\" :class=\"ns.e('minimap-canvas')\" />\n <div\n :class=\"ns.e('minimap-view')\"\n :style=\"{\n transform: `translateY(${minimap.slider.top}px)`,\n height: `${minimap.slider.height}px`,\n }\"\n />\n </div>\n </div>\n <div v-if=\"panels.bottom.length\" :class=\"[ns.e('panels'), ns.is('bottom', true)]\">\n <RenderPart v-for=\"panel in panels.bottom\" :key=\"panel.key\" :render=\"panel.render\" />\n </div>\n <Teleport to=\"body\">\n <div\n v-if=\"showKeys\"\n ref=\"keysEl\"\n :class=\"[\n ns.e('keys'),\n ns.is('fixed', anchorMode === 'fixed'),\n ns.is('scrolling', boxScrolling),\n ]\"\n :style=\"keysStyle\"\n @focusin=\"keysFocused = true\"\n @focusout=\"onKeysFocusOut\"\n @keydown=\"onKeysKeydown\"\n >\n <button\n type=\"button\"\n :class=\"ns.e('keys-grip')\"\n :aria-label=\"messages.moveKeys\"\n :title=\"messages.moveKeys\"\n aria-keyshortcuts=\"ArrowUp ArrowDown ArrowLeft ArrowRight\"\n @pointerdown=\"onKeysGripDown\"\n @keydown=\"onKeysGripKey\"\n @mousedown.prevent\n >\n <GripVerticalIcon />\n </button>\n <CodeKeys :editor=\"keysEditor\" :keys=\"keysList\" :messages=\"messages\" />\n </div>\n </Teleport>\n </div>\n</template>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"code-editor.js","names":["_sfc_main"],"sources":["../src/code-editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n AlertTriangleIcon,\n ChevronDownIcon,\n ChevronRightIcon,\n FunctionIcon,\n InfoIcon,\n LightbulbIcon,\n PackageIcon,\n SquareCodeIcon,\n SymbolClassIcon,\n SymbolConstantIcon,\n SymbolKeywordIcon,\n SymbolTypeAliasIcon,\n TypeIcon,\n VariableIcon,\n WrenchIcon,\n XCircleIcon,\n LetterCaseIcon,\n RegexIcon,\n WholeWordIcon,\n GripVerticalIcon,\n} from '@dou-ui/icons'\nimport {\n DouFindReplace,\n DouToggle,\n DouTooltip,\n holdPointer,\n isApplePlatform,\n isComposing,\n scrollPositionOf,\n useLocale,\n useNamespace,\n useTeleport,\n useZIndex,\n} from 'dou-ui'\nimport {\n computed,\n getCurrentInstance,\n inject,\n markRaw,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n reactive,\n ref,\n shallowReactive,\n shallowRef,\n toRaw,\n type VNodeChild,\n watch,\n} from 'vue'\nimport { matchBracket } from './core/brackets'\nimport { ChangeSet } from './core/changes'\nimport { indentOf, moveCluster, snapCluster, wordAt } from './core/chars'\nimport type { CodeCommand, CodeCommandTarget } from './core/commands'\nimport {\n deleteCharBackward,\n deleteCharForward,\n insertNewline,\n insertTab,\n insertText,\n selectAll,\n} from './core/commands'\nimport { type CodeFold, foldEndAt, hiddenLines, mergeRanges } from './core/folding'\nimport { CodeHistory } from './core/history'\nimport {\n type CodeKeyBinding,\n buildKeymap,\n defaultKeymap,\n eventKey,\n keymapBindings,\n} from './core/keymap'\nimport {\n type CodeRange,\n type CodeSelection,\n isEmptyRange,\n mainRange,\n normalizeSelection,\n rangeFrom,\n rangeTo,\n sameSelection,\n selectionOf,\n} from './core/selection'\nimport { CodeText, splitLines } from './core/text'\nimport {\n CodeTransaction,\n type CodeState,\n type CodeTransactionMeta,\n type CodeTransactionResult,\n} from './core/transaction'\nimport {\n type CodeMatch,\n type CodeSearchQuery,\n matchAfter,\n replacementFor,\n searchText,\n} from './core/search'\nimport { CodeHighlighter } from './language/highlighter'\nimport { holdWorker, ownWorker, SyntaxWorkerClient } from './language/worker-client'\nimport { format, useCodeMessages } from './locale'\nimport CodeKeys from './code-keys.vue'\nimport {\n CODE_EDITOR_KEY,\n WIDGET_HEIGHT_KEY,\n type CodeCompletion,\n type CodeCompletionKind,\n type CodeCompletionResult,\n type CodeHoverResult,\n type CodeSignatureResult,\n type CodeDecoration,\n type CodeDiagnostic,\n type CodeDiagnosticSeverity,\n type CodeExtension,\n type CodeExtensionContext,\n type CodeGutterHoverMarker,\n type CodeGutterMarker,\n type CodeHistoryHandler,\n type CodePanel,\n} from './extension'\nimport RenderPart from './render-part'\nimport { matchCompletion } from './completion/match'\nimport { parseSnippet } from './completion/snippet'\nimport { type CodeLineTokens, type CodeTokenType, lineParts, tokenTypes } from './language/language'\nimport type { CodeEditorEmits, CodeEditorExpose, CodeEditorProps } from './types'\nimport { diffText } from './view/input'\nimport {\n LineLayout,\n UNWRAPPED,\n type WrappedLine,\n rowOfCol,\n updateRows,\n wrapLine,\n} from './view/layout'\nimport { Measure } from './view/measure'\nimport { visibleViewport } from './view/viewport'\n\ndefineOptions({ name: 'DouCodeEditor' })\n\nconst props = withDefaults(defineProps<CodeEditorProps>(), {\n modelValue: undefined,\n doc: undefined,\n selection: undefined,\n lineNumbers: true,\n activeLine: true,\n tabSize: 2,\n language: undefined,\n worker: false,\n closeBrackets: true,\n matchBrackets: true,\n searchable: true,\n wrap: false,\n minimap: false,\n foldable: true,\n keys: true,\n messages: undefined,\n teleport: undefined,\n tabIndents: true,\n gutter: true,\n bordered: true,\n})\nconst emit = defineEmits<CodeEditorEmits>()\nconst ns = useNamespace('code-editor')\nconst instance = getCurrentInstance()!\n\n/** Space above the first line and below the last, and before and after each line; set from the styles once measured. */\nconst pad = reactive({ x: 12, y: 8 })\n/** Browsers stop growing an element somewhere past 16M px; taller texts scroll in scaled steps. */\nconst MAX_HEIGHT = 8_000_000\nconst OVERSCAN = 6\n/** The textarea mirrors at most this much text around the cursor. */\nconst WINDOW = 4000\n\nconst apple = isApplePlatform()\n\n// ---------------------------------------------------------------- state\n\n// A ref around the text makes a deep proxy of it; the editor reads the plain object.\nconst initialDoc = () =>\n (props.doc && toRaw(props.doc)) ??\n (props.modelValue !== undefined ? CodeText.of(props.modelValue) : CodeText.empty)\nconst startDoc = initialDoc()\nconst state = shallowRef<CodeState>(\n markRaw({\n doc: startDoc,\n selection: normalizeSelection(toRaw(props.selection) ?? selectionOf(0), startDoc.length),\n }),\n)\nconst doc = computed(() => state.value.doc)\nconst history = markRaw(new CodeHistory())\nconst historyTick = ref(0)\n\n/** The last string handed out, for the text it was made from, so it is joined at most once. */\nlet joined: { doc: CodeText; text: string } | null = null\nconst textOf = (text: CodeText) => {\n if (joined?.doc !== text) joined = { doc: text, text: text.toString() }\n return joined.text\n}\nconst listens = (event: string) => !!instance.vnode.props?.[event]\nlet lazyDirty = false\n/** Values this editor handed out; seeing one come back through a prop is only an echo. */\nconst handedOut = new WeakSet<object>()\nfunction emitDoc(value: CodeText) {\n handedOut.add(value)\n emit('update:doc', value)\n}\nfunction emitSelection(value: CodeSelection) {\n handedOut.add(value)\n emit('update:selection', value)\n}\n\nfunction emitChange(result: CodeTransactionResult) {\n const { state: next, before, changes } = result\n if (!changes.empty) {\n emitDoc(next.doc)\n if (props.modelModifiers?.lazy) lazyDirty = true\n else if (listens('onUpdate:modelValue')) emit('update:modelValue', textOf(next.doc))\n }\n if (!sameSelection(next.selection, before.selection)) emitSelection(next.selection)\n emit('transaction', result)\n}\n\n// ---------------------------------------------------------------- transactions\n\n/** Goal x of each cursor moved up or down, so it keeps its column across short lines. */\nlet goals = new Map<number, number>()\nlet pendingGoals = new Map<number, number>()\nconst blink = ref(0)\n\n/** The last press was a finger: the selection gets handles, and a toolbar over it. */\nconst touchUi = ref(false)\n/** A handle under a lone cursor, shown after a tap until the text changes. */\nconst caretHandle = ref(false)\n/** The toolbar over the selection (cut, copy, paste, select all). */\nconst menuOpen = ref(false)\n/** A finger drags a handle or a long-pressed selection: the magnifier shows. */\nconst touchDrag = ref(false)\n\n/** Steps whose changes aren't this user's typing: extensions' `transaction` hooks don't see them. */\nconst UNHOOKED = new Set(['undo', 'redo', 'external', 'remote'])\n\n/** Runs every extension's `update` hook for a step that was applied. */\nfunction notify(result: CodeTransactionResult) {\n for (const extension of extensions.value) extension.update?.(result, context)\n}\n\nfunction dispatch(tr: CodeTransaction): CodeTransactionResult {\n const { action } = tr.meta\n if (!UNHOOKED.has(action ?? ''))\n for (const extension of extensions.value) extension.transaction?.(tr, context)\n const result = tr.resolve()\n const before = state.value\n if (!result.changed) {\n pendingGoals = new Map()\n return result\n }\n // Someone else's change: what this user has open (menus, the problem box, the goal column) stays.\n const remote = action === 'remote'\n if (!result.changes.empty && !historyHandler.value) {\n history.record(result)\n historyTick.value++\n }\n if (!result.changes.empty) {\n if (composing.value) mapComposition(result.changes)\n syntaxChange(result.state.doc, result.changes)\n mapMatches(result.changes)\n updateWrap(before.doc, result.state.doc, result.changes)\n mapFolds(result.changes, result.state.doc)\n mapDiagnostics(result.changes, result.state.doc)\n scheduleLint()\n }\n state.value = markRaw(result.state)\n revealFolds()\n if (!remote) {\n problemBox.value = null\n // The toolbar is for the selection it opened on; typing also puts away the handle under a lone cursor.\n menuOpen.value = false\n if (!result.changes.empty) caretHandle.value = false\n goals = pendingGoals\n blink.value++\n }\n pendingGoals = new Map()\n if (!composing.value) syncInput()\n updateAssist(result)\n emitChange(result)\n notify(result)\n if (result.meta.scroll ?? !result.changes.empty)\n nextTick(() => {\n scrollIntoView()\n if (touchUi.value) followViewport()\n })\n return result\n}\n\nconst transaction = () => new CodeTransaction(state.value)\n\n// ---------------------------------------------------------------- extensions\n\n/** The extensions, highest priority first. */\nconst extensions = computed<CodeExtension[]>(() =>\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n (props.extensions ?? []).slice().sort((a, b) => (b.priority ?? 100) - (a.priority ?? 100)),\n)\n/** What extensions see; the same object as the instance, made once the instance is. */\nlet context: CodeExtensionContext\n\n/** Problems by who found them (`prop` for the prop, else the extension's name), moved with every edit. */\nconst diagnosticSets = shallowRef(new Map<string, CodeDiagnostic[]>())\nconst SEVERITY_RANK: Record<CodeDiagnosticSeverity, number> = {\n error: 0,\n warning: 1,\n info: 2,\n hint: 3,\n}\n\nconst diagnostics = computed<readonly CodeDiagnostic[]>(() => {\n const all: CodeDiagnostic[] = []\n for (const list of diagnosticSets.value.values()) all.push(...list)\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n return all.sort(\n (a, b) => a.from - b.from || SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity],\n )\n})\n\nfunction setDiagnostics(key: string, list: readonly CodeDiagnostic[] | null | undefined) {\n const length = doc.value.length\n const next = new Map(diagnosticSets.value)\n const clean = (list ?? []).map((d) => {\n const from = Math.max(0, Math.min(length, Math.min(d.from, d.to)))\n return { ...d, from, to: Math.max(from, Math.min(length, Math.max(d.from, d.to))) }\n })\n if (clean.length) next.set(key, clean)\n else if (!next.has(key)) return\n else next.delete(key)\n diagnosticSets.value = next\n}\n\n/** Moves the problems along with an edit; one whose text was all deleted shrinks to where it was. */\nfunction mapDiagnostics(changes: ChangeSet, after: CodeText) {\n if (!diagnosticSets.value.size) return\n const next = new Map<string, CodeDiagnostic[]>()\n for (const [key, list] of diagnosticSets.value)\n next.set(\n key,\n list.map((d) => {\n const from = Math.min(after.length, changes.mapPos(d.from, 1))\n return { ...d, from, to: Math.max(from, Math.min(after.length, changes.mapPos(d.to, -1))) }\n }),\n )\n diagnosticSets.value = next\n}\n\nwatch(\n () => props.diagnostics,\n (list) => setDiagnostics('prop', list),\n { immediate: true },\n)\n\n/** Runs the linters a moment after the text stops changing. */\nconst LINT_DELAY = 300\nlet lintTimer = 0\nconst linting = computed(() => extensions.value.some((extension) => extension.lint))\n\nfunction runLint(name?: string) {\n if (name === undefined) clearTimeout(lintTimer)\n const text = doc.value\n for (const extension of extensions.value) {\n if (!extension.lint || (name !== undefined && extension.name !== name)) continue\n let found: ReturnType<NonNullable<CodeExtension['lint']>>\n try {\n found = extension.lint(context)\n } catch (error) {\n console.error(`[@dou-ui/code] ${extension.name}: lint failed`, error)\n continue\n }\n // A linter that answers at once is shown at once, without a frame of old problems.\n if (!found || !('then' in found)) {\n setDiagnostics(extension.name, found)\n continue\n }\n Promise.resolve(found)\n .then((list) => {\n // Found in a text that has changed since: the next run follows.\n if (doc.value === text) setDiagnostics(extension.name, list)\n })\n .catch((error: unknown) =>\n console.error(`[@dou-ui/code] ${extension.name}: lint failed`, error),\n )\n }\n}\n\nfunction scheduleLint() {\n if (!linting.value || !mounted.value) return\n clearTimeout(lintTimer)\n lintTimer = window.setTimeout(runLint, LINT_DELAY)\n}\n\nwatch(extensions, (next, before) => {\n // The same extensions in a new array, as an inline `:extensions=\"[a]\"` gives on every render: nothing to do.\n if (\n before &&\n before.length === next.length &&\n next.every((extension, i) => extension === before[i])\n )\n return\n // A linter that went away takes its problems with it.\n for (const gone of before ?? []) if (!next.includes(gone)) setDiagnostics(gone.name, [])\n if (mounted.value) runLint()\n})\n\nfunction transact(build: (tr: CodeTransaction) => void, meta?: CodeTransactionMeta) {\n const tr = transaction()\n if (meta) tr.setMeta(meta)\n build(tr)\n return dispatch(tr)\n}\n\nfunction applySteps(step: { changes: ChangeSet; selection: CodeSelection } | null, action: string) {\n if (!step) return false\n const tr = transaction().setMeta({ action, history: false, scroll: true })\n for (const change of step.changes.changes) tr.replace(change.from, change.to, change.insert)\n tr.select(step.selection)\n dispatch(tr)\n return true\n}\n\n/** The undo history an extension brings in place of the editor's own; the first one wins. */\nconst historyHandler = computed<CodeHistoryHandler | null>(() => {\n for (const extension of extensions.value)\n if (extension.history) return markRaw(extension.history(context))\n return null\n})\nconst undo = () =>\n !props.readonly &&\n (historyHandler.value ? historyHandler.value.undo() : applySteps(history.undo(), 'undo'))\nconst redo = () =>\n !props.readonly &&\n (historyHandler.value ? historyHandler.value.redo() : applySteps(history.redo(), 'redo'))\nconst closeHistory = () => (historyHandler.value ? historyHandler.value.close?.() : history.close())\n\n/**\n * Takes in a new text from outside as the smallest change, so the cursor\n * and undo survive. `given` is the text as a `CodeText` when it came in as\n * one; it is kept as it is, so it compares equal when it comes back.\n */\nfunction receive(next: string, given?: CodeText) {\n if (joined && joined.text === next && joined.doc === doc.value) return\n const old = textOf(doc.value)\n const normalized = next.includes('\\r') ? next.replace(/\\r\\n?/g, '\\n') : next\n const diff = diffText(old, normalized, mainRange(state.value.selection).head)\n if (!diff) {\n if (given) {\n highlighter?.update(given, ChangeSet.of([], given.length))\n state.value = markRaw({ ...state.value, doc: given })\n if (wrapRows) rebuildWrap()\n }\n return\n }\n const tr = transaction().setMeta({ action: 'external', scroll: false })\n tr.replace(diff.from, diff.to, diff.insert)\n const resolved = tr.resolve()\n const result = given\n ? { ...resolved, state: markRaw({ ...resolved.state, doc: given }) }\n : resolved\n if (!historyHandler.value) {\n history.record(result)\n historyTick.value++\n }\n if (composing.value) mapComposition(result.changes)\n syntaxChange(result.state.doc, result.changes)\n updateWrap(result.before.doc, result.state.doc, result.changes)\n mapFolds(result.changes, result.state.doc)\n mapDiagnostics(result.changes, result.state.doc)\n problemBox.value = null\n scheduleLint()\n state.value = markRaw(result.state)\n mapMatches(result.changes)\n menuOpen.value = false\n caretHandle.value = false\n joined = { doc: result.state.doc, text: normalized }\n if (!composing.value) syncInput()\n if (!sameSelection(result.state.selection, result.before.selection))\n emitSelection(result.state.selection)\n // Hand the new text back in the other shape only; the one it came in is already up to date.\n if (!given) emitDoc(result.state.doc)\n else if (listens('onUpdate:modelValue')) emit('update:modelValue', normalized)\n emit('transaction', result)\n notify(result)\n}\n\nwatch(\n () => props.modelValue,\n (value) => value !== undefined && receive(value),\n)\nwatch(\n () => props.doc && toRaw(props.doc),\n (value) => {\n if (!value || value === doc.value || handedOut.has(value)) return\n receive(value.toString(), value)\n },\n)\nwatch(\n () => props.selection && toRaw(props.selection),\n (value) => {\n if (!value || handedOut.has(value)) return\n const next = normalizeSelection(value, doc.value.length)\n if (sameSelection(next, state.value.selection)) return\n dispatch(transaction().select(next).setMeta({ scroll: true }))\n },\n)\n\n// ---------------------------------------------------------------- layout\n\nconst root = ref<HTMLElement>()\nconst scroller = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\nconst probe = ref<HTMLElement>()\nconst input = ref<HTMLTextAreaElement>()\nconst measure = markRaw(new Measure(() => probe.value))\n/** Bumped when the font metrics change, so everything drawn from them is worked out again. */\nconst metrics = ref(0)\n\nconst mounted = ref(false)\nconst scrollTop = ref(0)\nconst scrollLeft = ref(0)\nconst viewHeight = ref(0)\nconst viewWidth = ref(0)\n/** The part of the scroller that is inside the window, for an editor taller than the page. */\nconst clip = ref<{ top: number; bottom: number } | null>(null)\n\nconst lineHeight = computed(() => {\n void metrics.value\n return measure.lineHeight\n})\n\n// ---------------------------------------------------------------- wrapping and folding\n\n/** The width a row of text may take when wrapping; 0 when lines don't wrap. */\nconst wrapWidth = computed(() => {\n // Cut nothing before the editor knows its width.\n if (!props.wrap || !mounted.value) return 0\n void metrics.value\n const width = viewWidth.value - gutterWidth.value - pad.x * 2 - measure.cell\n return Math.max(measure.cell * 8, width)\n})\n/** How each line text is cut at the current width; texts repeat (blank lines, braces), so this is by text. */\nlet wrapCache = new Map<string, WrappedLine>()\n/** Rows of each line while wrapping (index `n - 1`), kept in step with edits. */\nlet wrapRows: number[] | null = null\n/** Bumped when `wrapRows` changes without the text changing. */\nconst layoutTick = ref(0)\n\nfunction wrapOf(text: string): WrappedLine {\n const width = wrapWidth.value\n if (!width || text.length * measure.cell <= width / 2) return UNWRAPPED\n let wrapped = wrapCache.get(text)\n if (!wrapped) {\n if (wrapCache.size > 20_000) wrapCache = new Map()\n wrapped = wrapLine(text, width, measure)\n wrapCache.set(text, wrapped)\n }\n return wrapped\n}\n\nconst rowsOfText = (text: string) => wrapOf(text).breaks.length + 1\n\nfunction rebuildWrap() {\n wrapCache = new Map()\n wrapRows = wrapWidth.value ? doc.value.lineTexts(1, doc.value.lines).map(rowsOfText) : null\n layoutTick.value++\n}\n\n/** Moves the wrapped rows along with an edit, cutting again only the lines it touched. */\nfunction updateWrap(before: CodeText, after: CodeText, changes: ChangeSet) {\n if (!wrapRows) return\n if (!updateRows(wrapRows, before, after, changes, rowsOfText)) rebuildWrap()\n}\n\nconst folds = shallowRef<CodeFold[]>([])\nconst NOTHING_HIDDEN: Array<[number, number]> = []\nconst foldHidden = computed(() =>\n folds.value.length ? hiddenLines(doc.value, folds.value) : NOTHING_HIDDEN,\n)\n/** The lines extensions hide, as sorted ranges that don't overlap. */\nconst extensionHidden = computed(() => {\n const lines = doc.value.lines\n const ranges: Array<[number, number]> = []\n for (const extension of extensions.value) {\n if (!extension.hide) continue\n for (const { from, to } of extension.hide(context)) {\n const a = Math.max(1, Math.floor(from))\n const b = Math.min(lines, Math.floor(to))\n if (b >= a) ranges.push([a, b])\n }\n }\n return ranges.length ? mergeRanges(ranges) : NOTHING_HIDDEN\n})\n/** The lines not drawn: folded, or hidden by an extension. */\nconst hidden = computed(() => {\n const own = foldHidden.value\n const other = extensionHidden.value\n if (!other.length) return own\n if (!own.length) return other\n return mergeRanges([...own, ...other])\n})\nconst layout = computed<LineLayout>((previous) => {\n void layoutTick.value\n const lines = doc.value.lines\n const rows = wrapRows && wrapRows.length === lines ? wrapRows : null\n // One row per line and the same count: the same layout, so nothing drawn from it is worked out again.\n if (!rows && !hidden.value.length && previous?.uniform && previous.lines === lines)\n return previous\n return markRaw(new LineLayout(lines, rows, hidden.value))\n})\n\n// ---------------------------------------------------------------- widgets between lines\n\n/** The widgets' heights as last measured, by key. */\nconst widgetHeights = shallowReactive(new Map<string, number>())\nconst onWidgetHeight = inject(WIDGET_HEIGHT_KEY, null)\n\ninterface PlacedWidget {\n key: string\n line: number\n above: boolean\n render: () => VNodeChild\n label?: string\n /** The row it sits just before: the line's first row above it, the next line's first row below it. */\n row: number\n height: number\n /** Heights of the widgets before it. */\n before: number\n}\n\n/** The extensions' widgets on lines that are drawn, in the order they sit, with their heights. */\nconst widgets = computed<PlacedWidget[]>(() => {\n const drawn = layout.value\n const lh = lineHeight.value\n const out: PlacedWidget[] = []\n for (const extension of extensions.value) {\n if (!extension.widgets) continue\n for (const widget of extension.widgets(context)) {\n const n =\n widget.pos !== undefined\n ? doc.value.lineAt(Math.max(0, Math.min(doc.value.length, widget.pos))).number\n : (widget.line ?? 0)\n if (n < 1 || n > drawn.lines || !drawn.shown(n)) continue\n const above = widget.position === 'above'\n const key = `${extension.name}/${widget.id}`\n out.push({\n key,\n line: n,\n above,\n render: widget.render,\n label: widget.label,\n row: drawn.rowOf(n) + (above ? 0 : drawn.rowsOf(n)),\n height: widgetHeights.get(key) ?? widget.height ?? lh,\n before: 0,\n })\n }\n }\n if (!out.length) return out\n // By row; on one row, the widget below a line before the one above the next.\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n out.sort((a, b) => a.row - b.row || Number(a.above) - Number(b.above) || a.line - b.line)\n let sum = 0\n for (const widget of out) {\n widget.before = sum\n sum += widget.height\n }\n return out\n})\n\n/** How much of the widgets' height comes before row `row`. */\nfunction widgetsBefore(row: number) {\n const list = widgets.value\n let lo = 0\n let hi = list.length\n // The first widget past `row`; all before it come first.\n while (lo < hi) {\n const mid = (lo + hi) >> 1\n if (list[mid]!.row <= row) lo = mid + 1\n else hi = mid\n }\n if (!lo) return 0\n const last = list[lo - 1]!\n return last.before + last.height\n}\n\n/** The y of row `row` from the text's top, below the widgets before it. */\nconst rowTop = (row: number) => row * lineHeight.value + widgetsBefore(row)\n\n/** The row at a y from the text's top; a y over a widget gives the row right after it. */\nfunction rowAtTextY(y: number) {\n const list = widgets.value\n const lh = lineHeight.value\n if (!list.length) return Math.floor(y / lh)\n // The last widget that starts at or before `y`.\n let lo = 0\n let hi = list.length\n while (lo < hi) {\n const mid = (lo + hi) >> 1\n if (list[mid]!.row * lh + list[mid]!.before <= y) lo = mid + 1\n else hi = mid\n }\n if (!lo) return Math.floor(y / lh)\n const widget = list[lo - 1]!\n const end = widget.row * lh + widget.before + widget.height\n if (y < end) return widget.row\n return widget.row + Math.floor((y - end) / lh)\n}\n\nconst widgetsHeight = computed(() => {\n const list = widgets.value\n const last = list[list.length - 1]\n return last ? last.before + last.height : 0\n})\n\nconst total = computed(() => layout.value.total * lineHeight.value + widgetsHeight.value)\nconst sizerHeight = computed(() => Math.min(total.value, MAX_HEIGHT) + pad.y * 2)\n/** How much faster than the scrollbar the text moves, above `MAX_HEIGHT`. */\nconst ratio = computed(() => {\n if (total.value <= MAX_HEIGHT) return 1\n const view = viewHeight.value || 1\n return Math.max(1, (total.value - view) / Math.max(1, MAX_HEIGHT - view))\n})\n/** Offset between the text's own y and where it is drawn in the scaled scroller. */\nconst shift = computed(() => scrollTop.value - scrollTop.value * ratio.value)\n/** The y line `n` is drawn at. */\nconst yOf = (line: number) => pad.y + rowTop(layout.value.rowOf(line)) + shift.value\n/** The row under a y in the content, from the text's top. */\nconst rowAtY = (y: number) => rowAtTextY(y - pad.y - shift.value)\n\nconst visibleFrom = computed(() => {\n const top = scrollTop.value * ratio.value + (clip.value?.top ?? 0)\n const row = rowAtTextY(Math.max(0, top - pad.y)) - OVERSCAN\n return layout.value.lineAtRow(Math.max(0, row)).n\n})\nconst visibleTo = computed(() => {\n const bottom = scrollTop.value * ratio.value + (clip.value?.bottom ?? viewHeight.value)\n const row = rowAtTextY(Math.max(0, bottom - pad.y)) + 1 + OVERSCAN\n return layout.value.lineAtRow(row).n\n})\n\n/** The widgets in view, where they are drawn. */\nconst shownWidgets = computed(() => {\n const list = widgets.value\n if (!list.length) return []\n const from = layout.value.rowOf(visibleFrom.value)\n const to = layout.value.rowOf(visibleTo.value) + layout.value.rowsOf(visibleTo.value)\n const lh = lineHeight.value\n return list\n .filter((widget) => widget.row >= from && widget.row <= to)\n .map((widget) => ({\n ...widget,\n top: pad.y + widget.row * lh + widget.before + shift.value,\n }))\n})\n\n/** Room left in the column of lines (and of numbers) before line `n` for the widgets there; none before the first line drawn, which is placed past them. */\nfunction gapBefore(n: number) {\n if (n === visibleFrom.value || !widgets.value.length) return 0\n const row = layout.value.rowOf(n)\n return widgetsBefore(row) - widgetsBefore(row - 1)\n}\n\nlet widgetObserver: ResizeObserver | undefined\nconst observedWidgets = new Map<Element, string>()\n/** Measures a widget as drawn, keeping its height so the lines after it are placed below it. */\nfunction observeWidget(el: Element | null, key: string) {\n if (!el || observedWidgets.get(el) === key) return\n observedWidgets.set(el, key)\n const measureNow = (target: Element) => {\n const id = observedWidgets.get(target)\n if (!id || !target.isConnected) return\n const height = (target as HTMLElement).offsetHeight\n // Nothing measured means no layout (a hidden editor): keep the guess.\n if (height && widgetHeights.get(id) !== height) {\n // first, so whoever listens has it before the new layout takes the widget away\n onWidgetHeight?.(id, height)\n widgetHeights.set(id, height)\n }\n }\n measureNow(el)\n if (typeof ResizeObserver === 'undefined') return\n widgetObserver ??= new ResizeObserver((entries) => {\n for (const entry of entries) measureNow(entry.target)\n for (const [target] of observedWidgets)\n if (!target.isConnected) {\n widgetObserver!.unobserve(target)\n observedWidgets.delete(target)\n }\n })\n widgetObserver.observe(el)\n}\n\n/** The lines in view that are drawn (folded ones left out), with their text; read in runs, once per frame. */\nconst shownLines = computed(() => {\n const from = visibleFrom.value\n const to = visibleTo.value\n const text = doc.value\n const numbers: number[] = []\n const texts: string[] = []\n let n = from\n for (const [a, b] of hidden.value) {\n if (b < n) continue\n if (a > to) break\n if (a > n) {\n const chunk = text.lineTexts(n, a - 1)\n for (let i = 0; i < chunk.length; i++) numbers.push(n + i)\n texts.push(...chunk)\n }\n n = Math.max(n, b + 1)\n }\n if (n <= to) {\n const chunk = text.lineTexts(n, to)\n for (let i = 0; i < chunk.length; i++) numbers.push(n + i)\n texts.push(...chunk)\n }\n return { numbers, texts }\n})\nconst lines = computed(() => shownLines.value.texts)\n/** A line's text, from the lines in view when it is one of them. */\nfunction lineText(n: number) {\n const { numbers, texts } = shownLines.value\n let lo = 0\n let hi = numbers.length - 1\n while (lo <= hi) {\n const mid = (lo + hi) >> 1\n if (numbers[mid] === n) return texts[mid]!\n if (numbers[mid]! < n) lo = mid + 1\n else hi = mid - 1\n }\n return doc.value.line(n).text\n}\nconst isShown = (n: number) =>\n n >= visibleFrom.value && n <= visibleTo.value && layout.value.shown(n)\n\n/** Where column `col` of line `n` is drawn: the row's top, the x from the text's left edge, and which row of the line. */\nfunction place(n: number, text: string, col: number) {\n const wrapped = wrapOf(text)\n const sub = rowOfCol(wrapped, col)\n const top = yOf(n) + sub * lineHeight.value\n // The inline widgets before the column on its row, and one right at it: the cursor goes after them.\n if (!sub) return { top, x: measure.x(text, col) + inlineWidth(n, 0, col), sub }\n const start = wrapped.breaks[sub - 1]!\n return {\n top,\n x: wrapped.indent + measure.x(text, col) - measure.x(text, start) + inlineWidth(n, start, col),\n sub,\n }\n}\n\n/** The column nearest to `x` on row `sub` of line `n`. */\nfunction colAt(n: number, text: string, sub: number, x: number) {\n const wrapped = wrapOf(text)\n const { breaks } = wrapped\n if (!breaks.length) return colInRow(n, text, 0, text.length, x)\n const start = sub ? breaks[sub - 1]! : 0\n const end = sub < breaks.length ? breaks[sub]! : text.length\n const col = colInRow(n, text, start, end, Math.max(0, x - (sub ? wrapped.indent : 0)))\n // The end of a row that isn't the last is the start of the next one; stay on this row.\n if (sub < breaks.length && col >= end) return Math.max(start, moveCluster(text, end, -1))\n return Math.max(start, col)\n}\n\n/** Boxes over columns `from` to `to` of line `n`, one per row; `tail` adds width past the line's end. */\nfunction spans(n: number, text: string, from: number, to: number, tail = 0) {\n const wrapped = wrapOf(text)\n const out: Array<{ top: number; left: number; width: number }> = []\n const rows = wrapped.breaks.length + 1\n const top = yOf(n)\n for (let sub = 0; sub < rows; sub++) {\n const start = sub ? wrapped.breaks[sub - 1]! : 0\n const end = sub < rows - 1 ? wrapped.breaks[sub]! : text.length\n if (to < start || from > end || (from === end && sub < rows - 1)) continue\n const a = Math.max(from, start)\n const b = Math.min(to, end)\n const base = sub ? wrapped.indent - measure.x(text, start) : 0\n // From after the widgets at `a` to before those at `b`.\n const left = base + measure.x(text, a) + inlineWidth(n, start, a)\n const right =\n base + measure.x(text, b) + inlineWidth(n, start, b - 1) + (sub === rows - 1 ? tail : 0)\n if (right > left) out.push({ top: top + sub * lineHeight.value, left, width: right - left })\n }\n return out\n}\n\nconst SEVERITY_ICON = {\n error: XCircleIcon,\n warning: AlertTriangleIcon,\n info: InfoIcon,\n hint: LightbulbIcon,\n} as const\n\n/** Columns left of the line numbers: the problems' column, then the extensions' own. */\nconst gutterColumns = computed(() => {\n const columns: Array<{\n name: string\n width: number\n markers: () => CodeGutterMarker[]\n onPress?: (line: number, event: PointerEvent | KeyboardEvent) => void\n pressOn?: 'any' | 'markers'\n }> = []\n if (!props.gutter) return columns\n // Kept while anything may report problems, so the text doesn't jump when the first one comes.\n if (props.diagnostics !== undefined || linting.value || diagnostics.value.length)\n columns.push({ name: 'problems', width: 16, markers: problemMarkers })\n for (const extension of extensions.value)\n for (const gutter of extension.gutters ?? [])\n columns.push({\n name: gutter.name,\n width: gutter.width ?? 16,\n markers: () => withHoverMarker(gutter.markers?.(context) ?? [], gutter.hoverMarker),\n onPress: gutter.onPress && ((line, event) => gutter.onPress!(line, event, context)),\n pressOn: gutter.pressOn,\n })\n return columns\n})\nconst gutterCells = computed(() =>\n gutterColumns.value.reduce((sum, column) => sum + column.width, 0),\n)\n\n/** A column's markers, and its `hoverMarker` on the other lines in view. */\nfunction withHoverMarker(own: CodeGutterMarker[], hover: CodeGutterHoverMarker | undefined) {\n if (!hover) return own\n const taken = new Set(own.map((marker) => marker.line))\n const out = [...own]\n for (let line = visibleFrom.value; line <= visibleTo.value; line++)\n if (!taken.has(line))\n out.push({\n icon: hover.icon,\n text: hover.text,\n class: hover.class,\n title: typeof hover.title === 'function' ? hover.title(line) : hover.title,\n line,\n visible: 'hover',\n })\n return out\n}\n\n/** The worst problem on each line in view, as a marker. */\nfunction problemMarkers(): CodeGutterMarker[] {\n const text = doc.value\n const first = visibleFrom.value\n const last = visibleTo.value\n const end = text.line(last).to\n const worst = new Map<number, CodeDiagnostic>()\n for (const problem of diagnostics.value) {\n if (problem.from > end) break\n const n = text.lineAt(problem.from).number\n if (n < first) continue\n const had = worst.get(n)\n if (!had || SEVERITY_RANK[problem.severity] < SEVERITY_RANK[had.severity]) worst.set(n, problem)\n }\n const m = messages.value\n return [...worst].map(([line, problem]) => ({\n line,\n icon: SEVERITY_ICON[problem.severity],\n class: `dou-code-editor__problem-icon is-${problem.severity}`,\n title: `${m[problem.severity]}:${problem.message}`,\n }))\n}\n\n/** The markers of each column, by line, for the lines in view. */\n/** The line the mouse is over in the text, so the gutter can show markers waiting for it. */\nconst hoveredLine = ref<number | null>(null)\nfunction lineAtY(y: number) {\n const rect = content.value?.getBoundingClientRect()\n if (!rect) return null\n return doc.value.lineAt(posAtCoords({ x: rect.left + 1, y })).number\n}\n\n/** A marker in a pressable column is a button: Enter or Space presses it. */\nfunction onCellKeydown(event: KeyboardEvent, column: number, line: number) {\n if (event.key !== 'Enter' && event.key !== ' ') return\n const press = gutterColumns.value[column]?.onPress\n if (!press || props.disabled) return\n event.preventDefault()\n const cell = event.currentTarget as HTMLElement\n press(line, event)\n // A press that takes its marker away (removing a breakpoint) would drop the focus on the page: back to the text.\n void nextTick(() => {\n const where = document.activeElement\n const gone = !cell.isConnected || cell.getAttribute('role') !== 'button'\n if (gone && (!where || where === document.body || where === cell)) focusInput()\n })\n}\n\n/** Columns already warned about markers without a name, while developing. */\nconst unnamed = new Set<string>()\nconst gutterMarkers = computed(() =>\n gutterColumns.value.map((column) => {\n const byLine = new Map<number, CodeGutterMarker>()\n for (const marker of column.markers()) {\n byLine.set(marker.line, marker)\n if (process.env.NODE_ENV !== 'production' && column.onPress && !marker.title) {\n if (!unnamed.has(column.name))\n console.warn(\n `[@dou-ui/code] gutter \"${column.name}\": a marker in a column with \\`onPress\\` is a button and needs a \\`title\\` to name it.`,\n )\n unnamed.add(column.name)\n }\n }\n return byLine\n }),\n)\n\nconst gutterWidth = computed(() => {\n const cells = gutterCells.value\n if (!props.gutter || (!props.lineNumbers && !props.foldable && !cells)) return 0\n void metrics.value\n const digits = Math.max(2, String(doc.value.lines).length)\n const numbers = props.lineNumbers ? Math.ceil(digits * measure.cell) + 28 : 12\n return cells + numbers + (props.foldable ? 14 : 0)\n})\n\nconst contentWidth = computed(() => {\n if (props.wrap) return 0\n void metrics.value\n let widest = doc.value.widest * measure.cell\n for (const text of lines.value) {\n if (text.length * measure.cell * 2 < widest) continue\n widest = Math.max(widest, measure.x(text, text.length))\n }\n for (const [n, own] of lineDecorations.value.inlines) {\n const text = lineText(n)\n widest = Math.max(\n widest,\n measure.x(text, text.length) + own.reduce((w, i) => w + widthOf(i), 0),\n )\n }\n return Math.ceil(widest + pad.x * 2 + measure.cell)\n})\n\nwatch(wrapWidth, rebuildWrap, { immediate: true })\n\n// ---------------------------------------------------------------- folding\n\n/**\n * Where a fold starting at line `n` would end, or `null`; by brackets with a\n * language, else by indentation. Brackets in strings and comments count\n * only where the text has been read already, so folding a whole long text\n * doesn't read all of it first.\n */\nconst inStringOrComment = (pos: number) => {\n const kind = syntaxAt(pos)\n return kind === 'string' || kind === 'comment'\n}\n\nfunction foldEnd(n: number) {\n return foldEnds()(n)\n}\n\n/**\n * A function giving where folds end in the text as it is now, set up once\n * for asking about many lines; `lines` holds the lines' texts when the\n * caller has them.\n */\nfunction foldEnds(texts?: readonly string[]) {\n const text = doc.value\n const hl = highlighter\n const outer = props.language\n const tabSize = props.tabSize\n const lineOf = texts ? (k: number) => texts[k - 1]! : undefined\n return (n: number) => {\n const read = !!hl?.ready(n)\n const language = outer ? ((read ? hl!.languageAt(n) : null) ?? outer) : null\n return foldEndAt(text, n, {\n brackets: language?.brackets,\n tabSize,\n skip: read ? inStringOrComment : undefined,\n lineText: lineOf,\n })\n }\n}\n\n/** The lines that start a fold, from 1. */\nconst foldStarts = computed(() => folds.value.map((fold) => doc.value.lineAt(fold.from).number))\nwatch(foldStarts, (next, prev) => {\n if (next.length !== prev.length || next.some((n, i) => n !== prev[i])) emit('foldChange', next)\n})\n\nfunction setFolds(next: CodeFold[]) {\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n folds.value = next.slice().sort((a, b) => a.from - b.from)\n}\n\n/** Moves the folds along with an edit; a fold whose lines were joined goes away. */\nfunction mapFolds(changes: ChangeSet, after: CodeText) {\n if (!folds.value.length) return\n setFolds(\n folds.value\n .map((fold) => ({ from: changes.mapPos(fold.from, 1), to: changes.mapPos(fold.to, -1) }))\n .filter((fold) => after.lineAt(fold.to).number > after.lineAt(fold.from).number),\n )\n}\n\n/** Unfolds whatever hides a cursor, so the cursor is never out of sight. */\nfunction revealFolds() {\n if (!folds.value.length) return\n const heads = state.value.selection.ranges.map((range) => range.head)\n const keep = folds.value.filter((fold) => !heads.some((h) => h > fold.from && h <= fold.to))\n if (keep.length !== folds.value.length) folds.value = keep\n}\n\n/** Folds the block starting at line `n`; cursors inside move to its first line. */\nfunction foldLine(n: number) {\n const end = foldEnd(n)\n if (end === null) return false\n const text = doc.value\n const fold = { from: text.line(n).to, to: text.line(end).to }\n if (folds.value.some((f) => f.from === fold.from)) return false\n const { selection } = state.value\n if (selection.ranges.some((range) => range.head > fold.from && range.head <= fold.to)) {\n const ranges = selection.ranges.map((range) =>\n range.head > fold.from && range.head <= fold.to\n ? { anchor: fold.from, head: fold.from }\n : range,\n )\n dispatch(\n transaction().select(normalizeSelection({ ranges, main: selection.main }, text.length)),\n )\n }\n setFolds([...folds.value, fold])\n announce(format(messages.value.folded, { from: n + 1, to: end }))\n return true\n}\n\n/** Reads a fold out; the same words twice in a row are read again. */\nfunction announce(text: string) {\n announcement.value = announcement.value === text ? `${text}\\u200b` : text\n}\n\nconst folding = {\n fold(line?: number) {\n if (!props.foldable) return false\n const text = doc.value\n const n = line ?? text.lineAt(mainRange(state.value.selection).head).number\n if (line !== undefined) return foldLine(n)\n // The block that starts here, or else the nearest one above that reaches down to here.\n for (let k = n; k >= Math.max(1, n - 2000); k--) {\n const end = foldEnd(k)\n if (end !== null && (k === n || end >= n) && foldLine(k)) return true\n }\n return false\n },\n unfold(line?: number) {\n const text = doc.value\n const n = line ?? text.lineAt(mainRange(state.value.selection).head).number\n const keep = folds.value.filter((fold) => {\n const from = text.lineAt(fold.from).number\n return n < from || n > text.lineAt(fold.to).number\n })\n if (keep.length === folds.value.length) return false\n folds.value = keep\n announce(messages.value.unfolded)\n return true\n },\n foldAll() {\n if (!props.foldable) return false\n const text = doc.value\n const next: CodeFold[] = []\n const endOf = foldEnds(text.lineTexts(1, text.lines))\n for (let n = 1; n < text.lines; n++) {\n const end = endOf(n)\n if (end === null) continue\n next.push({ from: text.line(n).to, to: text.line(end).to })\n n = end\n }\n if (!next.length) return false\n setFolds(next)\n announce(messages.value.foldedAll)\n // Cursors that ended up hidden go to the top of their block.\n const { selection } = state.value\n const ranges = selection.ranges.map((range) => {\n const fold = next.find((f) => range.head > f.from && range.head <= f.to)\n return fold ? { anchor: fold.from, head: fold.from } : range\n })\n dispatch(\n transaction().select(normalizeSelection({ ranges, main: selection.main }, text.length)),\n )\n return true\n },\n unfoldAll() {\n if (!folds.value.length) return false\n folds.value = []\n announce(messages.value.unfoldedAll)\n return true\n },\n}\n\n/** Whether lines in view start a block, worked out only while the gutter is pointed at (or on touch screens). */\nconst gutterHover = ref(false)\n/**\n * A touch screen. Read once mounted, never while rendering on the server:\n * the first render must match the server's markup, then touch-only parts show.\n */\nconst coarse = ref(false)\nonMounted(() => {\n coarse.value = typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches\n})\nlet foldCache = { doc: null as CodeText | null, ends: new Map<number, number | null>() }\nconst foldableLines = computed(() => {\n const out = new Set<number>()\n if (!props.foldable || !(gutterHover.value || coarse.value)) return out\n void syntaxTick.value\n if (foldCache.doc !== doc.value) foldCache = { doc: doc.value, ends: new Map() }\n for (const n of shownLines.value.numbers) {\n let end = foldCache.ends.get(n)\n if (end === undefined) {\n end = foldEnd(n)\n foldCache.ends.set(n, end)\n }\n if (end !== null) out.add(n)\n }\n return out\n})\n\nfunction toggleFold(n: number, folded: boolean) {\n if (folded) folding.unfold(n)\n else folding.fold(n)\n}\n\n// ---------------------------------------------------------------- composition\n\nconst composing = ref(false)\n/** What the input method shows while composing: a replacement of the text, drawn but not applied yet. */\nconst preview = shallowRef<{ from: number; to: number; insert: string } | null>(null)\n/**\n * Changes that came in while composing (someone else's, or a new\n * `v-model`): the textarea still holds the text from before them, so what\n * it gives back is moved through these.\n */\nlet composeMap: ChangeSet | null = null\n\n/** A position in the text the textarea was filled from, in the text now. */\nconst composedPos = (pos: number, assoc: -1 | 1) =>\n composeMap ? composeMap.mapPos(pos, assoc) : pos\n\nfunction mapComposition(changes: ChangeSet) {\n composeMap = composeMap ? composeMap.compose(changes) : changes\n const shown = preview.value\n if (shown)\n preview.value = {\n ...shown,\n from: changes.mapPos(shown.from, -1),\n to: Math.max(changes.mapPos(shown.from, -1), changes.mapPos(shown.to, 1)),\n }\n}\n\n/** A class over part of a line, `from`–`to` in the line, with a title shown on hover. */\ntype Mark = [\n from: number,\n to: number,\n cls: string,\n title?: string,\n style?: Readonly<Record<string, string>>,\n]\n\n/** A widget inside a line, before column `col`. */\ninterface Inline {\n col: number\n key: string\n render: () => VNodeChild\n width?: number\n}\n\ninterface Row {\n n: number\n text: string\n /** How the line is cut into rows, when it wraps. */\n wrapped: WrappedLine\n /** The line starts a fold. */\n folded: boolean\n /** The line's tokens, when its language has read it; kept the same while the line doesn't change. */\n tokens: CodeLineTokens | null\n /** Set on the line being composed: the text drawn before, inside and after the composition. */\n compose?: [before: string, insert: string, after: string]\n /** Classes on parts of the line, from decorations and problems: `[from, to, class, title]` in the line. */\n marks?: Mark[]\n /** The same, as one string, to tell when they changed. */\n marksKey?: string\n /** Classes on the whole line, from decorations. */\n lineClass?: string\n /** Widgets inside the line, by column. */\n inlines?: Inline[]\n /** Their keys and columns, as one string, to tell when they changed. */\n inlinesKey?: string\n}\n\nconst rows = computed<Row[]>(() => {\n const { numbers, texts } = shownLines.value\n const p = preview.value\n const line = p ? doc.value.lineAt(p.from) : null\n const tokensOf = syntaxLines(visibleFrom.value, visibleTo.value)\n const starts = new Set(foldHidden.value.map(([from]) => from - 1))\n const { marks, lineClasses, inlines } = lineDecorations.value\n return texts.map((text, i) => {\n const n = numbers[i]!\n const tokens = tokensOf(n)\n const wrapped = wrapOf(text)\n const folded = starts.has(n)\n if (!p || n !== line!.number) {\n const own = marks.get(n)\n return {\n n,\n text,\n tokens,\n wrapped,\n folded,\n marks: own,\n marksKey: own?.map((m) => m.join(',')).join(';'),\n lineClass: lineClasses.get(n),\n inlines: inlines.get(n),\n inlinesKey: inlines\n .get(n)\n ?.map((item) => `${item.col}:${item.key}`)\n .join(';'),\n }\n }\n const col = p.from - line!.from\n const end = p.to <= line!.to ? p.to - line!.from : col\n return {\n n,\n text,\n tokens: null,\n wrapped,\n folded,\n compose: [text.slice(0, col), p.insert, text.slice(end)],\n }\n })\n})\n\n/** What extensions decorate, asked for while drawing. */\nconst decorations = computed<CodeDecoration[]>(() => {\n const out: CodeDecoration[] = []\n for (const extension of extensions.value)\n if (extension.decorations) out.push(...extension.decorations(context))\n return out\n})\n\n/** Decorations and problems on the lines in view, cut to each line. */\nconst lineDecorations = computed(() => {\n const marks = new Map<number, Mark[]>()\n const lineClasses = new Map<number, string>()\n const inlines = new Map<number, Inline[]>()\n const list = decorations.value\n const problems = diagnostics.value\n const session = snippet.value\n if (!list.length && !problems.length && !session) return { marks, lineClasses, inlines }\n const text = doc.value\n const first = visibleFrom.value\n const last = visibleTo.value\n const start = text.line(first).from\n const end = text.line(last).to\n const mark = (\n from: number,\n to: number,\n cls: string,\n title?: string,\n style?: Readonly<Record<string, string>>,\n ) => {\n if (to < start || from > end || to <= from) return\n const a = text.lineAt(Math.max(from, start))\n const b = text.lineAt(Math.min(to, end))\n for (let n = a.number; n <= b.number; n++) {\n const line = n === a.number ? a : n === b.number ? b : text.line(n)\n const x = Math.max(from, line.from) - line.from\n const y = Math.min(to, line.to) - line.from\n if (y <= x) continue\n const own = marks.get(n)\n const item: Mark = style\n ? [x, y, cls, title, style]\n : title\n ? [x, y, cls, title]\n : [x, y, cls]\n if (own) own.push(item)\n else marks.set(n, [item])\n }\n }\n for (const item of list) {\n if (item.type === 'line') {\n if (item.line < first || item.line > last) continue\n const had = lineClasses.get(item.line)\n lineClasses.set(item.line, had ? `${had} ${item.class}` : item.class)\n } else if (item.type === 'inline') {\n if (item.pos < start || item.pos > end) continue\n const line = text.lineAt(item.pos)\n const own = inlines.get(line.number) ?? []\n own.push({\n col: item.pos - line.from,\n key: item.id ?? `@${item.pos}`,\n render: item.render,\n width: item.width,\n })\n inlines.set(line.number, own)\n } else mark(item.from, item.to, item.class, item.title, item.style)\n }\n // In the order they are drawn: by column, then as given.\n for (const own of inlines.values())\n if (own.length > 1) {\n const order = new Map(own.map((item, i) => [item, i]))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n own.sort((a, b) => a.col - b.col || order.get(a)! - order.get(b)!)\n }\n for (const problem of problems) {\n if (problem.from > end) break\n let { from, to } = problem\n // An empty range marks the character after it, or the one before at the end of a line.\n if (from === to) {\n const line = text.lineAt(from)\n if (from < line.to) to = line.from + moveCluster(line.text, from - line.from, 1)\n else if (from > line.from) from = line.from + moveCluster(line.text, from - line.from, -1)\n else continue\n }\n mark(from, to, `dou-code-editor__problem is-${problem.severity}`)\n }\n // The snippet's places still to fill in, after the one being filled.\n if (session)\n for (let i = session.at + 1; i < session.groups.length; i++)\n for (const range of session.groups[i]!.ranges)\n if (range.to > range.from && range.from <= end)\n mark(range.from, range.to, 'dou-code-editor__field')\n return { marks, lineClasses, inlines }\n})\n\n// ---------------------------------------------------------------- widgets inside lines\n\n/** The widths of inline widgets as last measured, by key. */\nconst inlineWidths = shallowReactive(new Map<string, number>())\nconst widthOf = (item: Inline) => item.width ?? inlineWidths.get(item.key) ?? 0\n\n/** Width of the inline widgets on line `n` at columns `from` to `to`, both included. */\nfunction inlineWidth(n: number, from: number, to: number) {\n const own = lineDecorations.value.inlines.get(n)\n if (!own) return 0\n let sum = 0\n for (const item of own) if (item.col >= from && item.col <= to) sum += widthOf(item)\n return sum\n}\n\n/**\n * The column nearest to `x` (from the row's left, past its indent) on the\n * part `start`–`end` of line `n`, stepping over the inline widgets there.\n */\nfunction colInRow(n: number, text: string, start: number, end: number, x: number) {\n const own = lineDecorations.value.inlines.get(n)\n const x0 = measure.x(text, start)\n const clamp = (col: number, low: number) => Math.max(low, Math.min(end, col))\n if (!own) return clamp(measure.col(text, x0 + x), start)\n let offset = 0\n let low = start\n for (const item of own) {\n if (item.col < start || item.col > end) continue\n const at = measure.x(text, item.col) - x0 + offset\n if (x < at) return Math.min(item.col, clamp(measure.col(text, x0 + x - offset), low))\n const width = widthOf(item)\n // Over the widget: the cursor goes on its far side, before the character it stands at.\n if (x < at + width) return item.col\n offset += width\n low = item.col\n }\n return clamp(measure.col(text, x0 + x - offset), low)\n}\n\nlet inlineObserver: ResizeObserver | undefined\nconst observedInlines = new Map<Element, string>()\n/** Measures an inline widget as drawn, keeping its width so the text after it is placed past it. */\nfunction observeInline(el: Element | null, key: string, given: number | undefined) {\n if (!el || given !== undefined || observedInlines.get(el) === key) return\n observedInlines.set(el, key)\n const measureNow = (target: Element) => {\n const width = (target as HTMLElement).offsetWidth\n const id = observedInlines.get(target)\n if (id && target.isConnected && width && inlineWidths.get(id) !== width)\n inlineWidths.set(id, width)\n }\n measureNow(el)\n if (typeof ResizeObserver === 'undefined') return\n inlineObserver ??= new ResizeObserver((entries) => {\n for (const entry of entries) measureNow(entry.target)\n for (const [target] of observedInlines)\n if (!target.isConnected) {\n inlineObserver!.unobserve(target)\n observedInlines.delete(target)\n }\n })\n inlineObserver.observe(el)\n}\n\n// ---------------------------------------------------------------- syntax\n\n/** Lines read ahead of the last read one while drawing; further away, idle time catches up first. */\nconst SYNTAX_REACH = 2000\nlet highlighter: CodeHighlighter | null = null\n/** Bumped when lines in view got their tokens in idle time. */\nconst syntaxTick = ref(0)\n\nwatch(\n () => props.language,\n (language) => {\n highlighter = language ? markRaw(new CodeHighlighter(language, doc.value, props.tabSize)) : null\n syntaxTick.value++\n },\n { immediate: true },\n)\n\n/** The worker reading ahead, with `worker`, and how to let go of it. */\nlet syntaxWorker: SyntaxWorkerClient | null = null\nlet releaseWorker: (() => void) | null = null\nlet workerJob = 0\n\nfunction stopSyntaxWorker() {\n syntaxWorker?.dispose()\n syntaxWorker = null\n releaseWorker?.()\n releaseWorker = null\n}\n\n/** Reading goes back to the page, saying why while developing. */\nfunction workerFallback(message: string, error?: unknown) {\n stopSyntaxWorker()\n syntaxTick.value++\n if (process.env.NODE_ENV !== 'production')\n console.warn(\n `[@dou-ui/code] ${message}: colors are read on the page instead.`,\n ...(error ? [error] : []),\n )\n}\n\nfunction attachWorker(worker: Worker, release: () => void) {\n const language = props.language!\n releaseWorker = release\n syntaxWorker = new SyntaxWorkerClient(worker, language, () => doc.value, props.tabSize, {\n states(points) {\n const hl = highlighter\n if (!hl || hl.language !== language) return\n hl.adopt(points)\n syntaxTick.value++\n },\n unsupported(missing) {\n workerFallback(\n missing\n ? `the worker has no language named \"${missing}\" (for \"${language.name}\"); pass it to serveCodeHighlighting in the worker`\n : `the states of \"${language.name}\" can't be sent from the worker; keep them to plain data`,\n )\n },\n failed(error) {\n workerFallback('the highlighting worker failed', error)\n },\n })\n syntaxTick.value++\n}\n\n// The worker starts in the browser only, once the editor is there; the editor ends it.\nwatch(\n [() => props.language, () => props.worker, mounted],\n ([language, option, isMounted]) => {\n stopSyntaxWorker()\n const job = ++workerJob\n if (!language || !option || !isMounted || typeof Worker === 'undefined') return\n if (option === true) {\n ownWorker().then(\n ({ worker, release }) => {\n if (job === workerJob) attachWorker(worker, release)\n else release()\n },\n (error) =>\n job === workerJob && workerFallback('the built-in worker could not start', error),\n )\n return\n }\n let worker: Worker\n try {\n worker = option()\n } catch (error) {\n workerFallback('the worker could not start', error)\n return\n }\n attachWorker(worker, holdWorker(worker))\n },\n { immediate: true },\n)\nonBeforeUnmount(() => {\n workerJob++\n stopSyntaxWorker()\n})\n\n/** Brings the colors along with a change of the text. */\nfunction syntaxChange(next: CodeText, changes: ChangeSet) {\n highlighter?.update(next, changes)\n syntaxWorker?.change(changes)\n}\n\n/** Gets the tokens of the lines in view, asking idle time for the ones too far ahead. */\nfunction syntaxLines(from: number, to: number): (n: number) => CodeLineTokens | null {\n void syntaxTick.value\n const hl = highlighter\n if (!hl) return () => null\n if (!hl.ready(to) && to - hl.frontier > SYNTAX_REACH) {\n if (syntaxWorker) syntaxWorker.want(hl.frontier, to)\n else scheduleSyntax(to)\n return (n) => (hl.ready(n) ? hl.line(n) : null)\n }\n return (n) => hl.line(n)\n}\n\nlet syntaxJob = 0\nlet syntaxUntil = 0\n/** Runs `task` when the page is idle, with how long it may take (ms). */\nconst idle =\n typeof requestIdleCallback === 'function'\n ? (task: (budget: number) => void) =>\n requestIdleCallback((deadline) => task(deadline.timeRemaining()), { timeout: 100 })\n : (task: (budget: number) => void) => window.setTimeout(() => task(8), 16)\nconst cancelIdle = (id: number) =>\n typeof cancelIdleCallback === 'function' ? cancelIdleCallback(id) : clearTimeout(id)\n\nfunction scheduleSyntax(until: number) {\n syntaxUntil = Math.max(syntaxUntil, until)\n if (syntaxJob) return\n syntaxJob = idle((budget) => {\n syntaxJob = 0\n const hl = highlighter\n if (!hl) return\n // the idle time there is, up to 20ms so a key pressed meanwhile waits little; some when it timed out\n hl.work(performance.now() + Math.min(20, Math.max(4, budget - 1)), syntaxUntil)\n if (hl.ready(syntaxUntil)) {\n syntaxUntil = 0\n syntaxTick.value++\n } else scheduleSyntax(syntaxUntil)\n })\n}\n\n/** The kind of token the character at `pos` is part of, when its line has been read. */\nfunction syntaxAt(pos: number): CodeTokenType | null {\n const hl = highlighter\n if (!hl || pos < 0 || pos >= doc.value.length) return null\n const line = doc.value.lineAt(pos)\n const tokens = hl.line(line.number, SYNTAX_REACH)\n if (!tokens) return null\n const col = pos - line.from\n for (let i = 0; i < tokens.length; i += 2) {\n if (col < tokens[i]!) {\n const type = tokens[i + 1]!\n return type < 0 ? null : tokenTypes[type]!\n }\n }\n return null\n}\n\nfunction languageAt(pos: number) {\n const hl = highlighter\n if (!hl) return null\n const line = doc.value.lineAt(Math.min(Math.max(pos, 0), doc.value.length))\n // Within reach only: far down an unread file, the outer language will do.\n if (line.number - hl.frontier > SYNTAX_REACH) return hl.language\n return hl.languageAt(line.number)\n}\n\n/**\n * A piece of a line, with the classes it is drawn with and the title of a\n * mark over it; or, with `inline`, the line's inline widget of that index\n * (its text empty).\n */\ntype Part = [\n text: string,\n cls: string | null,\n title?: string,\n inline?: number,\n style?: Readonly<Record<string, string>>,\n]\n\n/** A line cut where its tokens and marks start and end, each piece with its classes, and its inline widgets between. */\nfunction partsOf(row: Row): Part[] {\n const parts = textParts(row)\n const own = row.inlines\n if (!own?.length) return parts\n const out: Part[] = []\n let at = 0\n let next = 0\n for (const part of parts) {\n while (next < own.length && own[next]!.col <= at) out.push(['', null, undefined, next++])\n // A widget inside the piece cuts it.\n let piece = part\n while (next < own.length && own[next]!.col < at + piece[0].length) {\n const cut = own[next]!.col - at\n out.push([piece[0].slice(0, cut), piece[1], piece[2], undefined, piece[4]])\n piece = [piece[0].slice(cut), piece[1], piece[2], undefined, piece[4]]\n at += cut\n while (next < own.length && own[next]!.col <= at) out.push(['', null, undefined, next++])\n }\n out.push(piece)\n at += piece[0].length\n }\n while (next < own.length) out.push(['', null, undefined, next++])\n return out\n}\n\nfunction textParts(row: Row): Part[] {\n const base = lineParts(row.text, row.tokens)\n const marks = row.marks\n if (!marks?.length) return base.map(([text, type]) => [text, type && `dou-syntax-${type}`])\n const cuts = new Set<number>([0, row.text.length])\n for (const [from, to] of marks) {\n cuts.add(from)\n cuts.add(to)\n }\n let at = 0\n for (const [text] of base) {\n cuts.add(at)\n at += text.length\n }\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n const points = [...cuts].sort((a, b) => a - b)\n const out: Part[] = []\n let index = 0\n let partStart = 0\n for (let i = 0; i + 1 < points.length; i++) {\n const from = points[i]!\n const to = points[i + 1]!\n if (to <= from || from >= row.text.length) continue\n while (partStart + base[index]![0].length <= from) partStart += base[index++]![0].length\n const type = base[index]![1]\n let cls = type ? `dou-syntax-${type}` : ''\n let title: string | undefined\n let style: Readonly<Record<string, string>> | undefined\n for (const [a, b, name, label, css] of marks)\n if (a <= from && b >= to) {\n cls = cls ? `${cls} ${name}` : name\n title = label ?? title\n if (css) style = style ? { ...style, ...css } : css\n }\n const piece = row.text.slice(from, to)\n out.push(\n style\n ? [piece, cls || null, title, undefined, style]\n : title\n ? [piece, cls || null, title]\n : [piece, cls || null],\n )\n }\n return out\n}\n\n/** The parts of one row of a wrapped line. */\nfunction rowParts(row: Row, sub: number) {\n const { breaks } = row.wrapped\n const start = sub ? breaks[sub - 1]! : 0\n const end = sub < breaks.length ? breaks[sub]! : row.text.length\n const out: Part[] = []\n let at = 0\n const last = sub === breaks.length\n for (const part of partsOf(row)) {\n const [text, type, title, inline, style] = part\n // A widget goes on the row its column starts; at the very end, on the last row.\n if (inline !== undefined) {\n if (at >= start && (at < end || (last && at === end))) out.push(part)\n continue\n }\n const from = Math.max(at, start)\n const to = Math.min(at + text.length, end)\n if (to > from) out.push([text.slice(from - at, to - at), type, title, undefined, style])\n at += text.length\n }\n return out\n}\n\n// ---------------------------------------------------------------- overlays\n\nconst focused = ref(false)\n\ninterface Box {\n key: string\n left: number\n top: number\n width: number\n}\n\nconst cursors = computed(() => {\n void metrics.value\n const out: Box[] = []\n const { doc: text, selection } = state.value\n const p = preview.value\n selection.ranges.forEach((range, i) => {\n const pos = range.head\n const line = text.lineAt(pos)\n if (!isShown(line.number)) return\n let lineStr = lineText(line.number)\n if (p && i === selection.main) {\n const at = text.lineAt(p.from)\n lineStr =\n rows.value\n .find((row) => row.n === at.number)\n ?.compose?.slice(0, 2)\n .join('') ?? lineStr\n out.push({\n key: `c${i}`,\n left: pad.x + measure.x(lineStr, lineStr.length),\n top: yOf(at.number),\n width: 2,\n })\n return\n }\n const at = place(line.number, lineStr, pos - line.from)\n out.push({ key: `c${i}`, left: pad.x + at.x, top: at.top, width: 2 })\n })\n return out\n})\n\nconst selectionBoxes = computed(() => {\n void metrics.value\n if (preview.value) return []\n const out: Box[] = []\n const { doc: text, selection } = state.value\n const first = visibleFrom.value\n const last = visibleTo.value\n selection.ranges.forEach((range, i) => {\n if (isEmptyRange(range)) return\n const from = text.lineAt(rangeFrom(range))\n const to = text.lineAt(rangeTo(range))\n for (let n = Math.max(from.number, first); n <= Math.min(to.number, last); n++) {\n if (!layout.value.shown(n)) continue\n const str = lineText(n)\n const a = n === from.number ? rangeFrom(range) - from.from : 0\n const b = n === to.number ? rangeTo(range) - to.from : str.length\n // A selected line break shows as half a cell past the end.\n const boxes = spans(n, str, a, b, n === to.number ? 0 : measure.cell / 2)\n boxes.forEach((box, k) =>\n out.push({ key: `s${i}-${n}-${k}`, ...box, left: pad.x + box.left }),\n )\n }\n })\n return out\n})\n\nconst activeLineTop = computed(() => {\n const n = doc.value.lineAt(mainRange(state.value.selection).head).number\n return isShown(n) ? yOf(n) : null\n})\nconst activeLineRows = computed(() => layout.value.rowsOf(activeLineNumber.value) || 1)\nconst activeLineNumber = computed(\n () => doc.value.lineAt(mainRange(state.value.selection).head).number,\n)\n\n// Moving onto a line with widgets reads out what they are, the way problems are read out.\nwatch(activeLineNumber, (n) => {\n if (!focused.value || !widgets.value.length) return\n const labels = widgets.value\n .filter((widget) => widget.line === n && widget.label)\n .map((widget) => widget.label!)\n if (labels.length) announce(labels.join(' · '))\n})\n\n/** The bracket at the main cursor and its partner, outlined; a bracket without one is marked. */\nconst bracketBoxes = computed(() => {\n void metrics.value\n void syntaxTick.value\n if (!props.matchBrackets || !props.language || !focused.value || preview.value) return []\n const main = mainRange(state.value.selection)\n if (!isEmptyRange(main)) return []\n const text = doc.value\n const brackets = languageAt(main.head)?.brackets ?? props.language.brackets\n const found = matchBracket(text, main.head, brackets, (pos) => {\n const kind = syntaxAt(pos)\n return kind === 'string' || kind === 'comment'\n })\n if (!found) return []\n const out: Array<Box & { matched: boolean }> = []\n for (const pos of found.match === null ? [found.from] : [found.from, found.match]) {\n const line = text.lineAt(pos)\n if (!isShown(line.number)) continue\n const str = lineText(line.number)\n const [box] = spans(line.number, str, pos - line.from, pos - line.from + 1)\n if (box)\n out.push({ key: `b${pos}`, ...box, left: pad.x + box.left, matched: found.match !== null })\n }\n return out\n})\n\n// ---------------------------------------------------------------- search\n\nconst messages = useCodeMessages(() => props.messages)\nconst searchOpen = ref(false)\nconst showReplace = ref(false)\nconst query = ref<CodeSearchQuery>({ search: '' })\nconst panel = ref<InstanceType<typeof DouFindReplace>>()\nconst { t: common } = useLocale()\n/** The toggles in the find box. */\nconst searchOptions = [\n { key: 'caseSensitive', icon: LetterCaseIcon },\n { key: 'wholeWord', icon: WholeWordIcon },\n { key: 'regexp', icon: RegexIcon },\n] as const\n/** The matches, kept in step with edits between searches. */\nconst matches = shallowRef<CodeMatch[]>([])\nconst capped = ref(false)\nconst searchError = ref<string>()\n/** Read out after a replacement. */\nconst announcement = ref('')\nlet searchTimer = 0\n\nfunction runSearch() {\n clearTimeout(searchTimer)\n searchTimer = 0\n if (!searchOpen.value || !query.value.search) {\n matches.value = []\n capped.value = false\n searchError.value = undefined\n return\n }\n const result = searchText(doc.value, query.value)\n matches.value = result.matches\n capped.value = result.capped\n searchError.value = result.error\n}\n\n/** Searches again a little later, so typing in a long text doesn't search on every key. */\nfunction scheduleSearch(delay = 120) {\n clearTimeout(searchTimer)\n searchTimer = window.setTimeout(runSearch, delay)\n}\n\nwatch(query, () => {\n runSearch()\n // While typing the search, the first match from the selection on is selected, as a preview.\n revealMatch(matchAfter(matches.value, rangeFrom(mainRange(state.value.selection))))\n})\n\n/** Moves the matches along with an edit, and searches again soon. */\nfunction mapMatches(changes: ChangeSet) {\n if (!searchOpen.value || !matches.value.length) return\n matches.value = matches.value\n .map((m) => ({ from: changes.mapPos(m.from, 1), to: changes.mapPos(m.to, -1) }))\n .filter((m) => m.to > m.from)\n scheduleSearch(doc.value.length > 200_000 ? 300 : 120)\n}\n\n/** Which match the main selection is exactly on, or `-1`. */\nconst currentMatch = computed(() => {\n const main = mainRange(state.value.selection)\n const i = matchAfter(matches.value, rangeFrom(main))\n const m = matches.value[i]\n return m && m.from === rangeFrom(main) && m.to === rangeTo(main) ? i : -1\n})\n\nfunction revealMatch(index: number) {\n const m = matches.value[index]\n if (!m) return false\n dispatch(transaction().select(m.from, m.to).setMeta({ scroll: true }))\n return true\n}\n\nfunction nextMatch() {\n if (!matches.value.length) return false\n const main = mainRange(state.value.selection)\n const at = currentMatch.value >= 0 ? rangeTo(main) : rangeFrom(main)\n let i = matchAfter(matches.value, at)\n if (currentMatch.value >= 0 && i === currentMatch.value) i = (i + 1) % matches.value.length\n return revealMatch(i)\n}\n\nfunction previousMatch() {\n if (!matches.value.length) return false\n const list = matches.value\n const from = rangeFrom(mainRange(state.value.selection))\n const after = matchAfter(list, from)\n // `matchAfter` wraps to the first past the end; the one before the cursor is then the last.\n return revealMatch(\n list[after]!.from < from ? list.length - 1 : (after - 1 + list.length) % list.length,\n )\n}\n\nfunction openSearch(replace = false, given?: Partial<CodeSearchQuery>) {\n if (!props.searchable) return false\n menuOpen.value = false\n closeProblems()\n const main = mainRange(state.value.selection)\n const patch: Partial<CodeSearchQuery> = { ...given }\n // A selection on one line, or else the word at the cursor, becomes the search.\n if (given?.search === undefined) {\n const selected = doc.value.slice(rangeFrom(main), rangeTo(main))\n if (selected && !selected.includes('\\n')) patch.search = selected\n else if (!selected) {\n const line = doc.value.lineAt(main.head)\n const col = main.head - line.from\n const text = lineText(line.number)\n for (const at of [col, col - 1]) {\n if (at < 0 || at >= text.length || !/[\\p{L}\\p{N}_$]/u.test(text[at]!)) continue\n const word = wordAt(text, at)\n patch.search = text.slice(word.from, word.to)\n // Select it, so the search starts from this word rather than the next one.\n dispatch(transaction().select(line.from + word.from, line.from + word.to))\n break\n }\n }\n }\n if (Object.keys(patch).length) query.value = { ...query.value, ...patch }\n // Given a replacement, the replace box opens with it.\n if ((replace || given?.replace !== undefined) && !target.readonly) showReplace.value = true\n searchOpen.value = true\n runSearch()\n panel.value?.focus(replace ? 'replace' : 'find')\n nextTick(() => panel.value?.focus(replace ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n if (!searchOpen.value) return false\n searchOpen.value = false\n matches.value = []\n focusInput()\n return true\n}\n\nfunction replaceOne() {\n if (target.readonly) return\n if (currentMatch.value < 0) {\n nextMatch()\n return\n }\n const m = matches.value[currentMatch.value]!\n const insert = replacementFor(doc.value, m, query.value)\n const tr = transaction().setMeta({ action: 'replace', scroll: true })\n tr.replace(m.from, m.to, insert)\n dispatch(tr)\n runSearch()\n // On to the next match after the replaced text.\n const i = matchAfter(matches.value, m.from + insert.length)\n if (i >= 0 && (matches.value[i]!.from >= m.from + insert.length || i === 0)) revealMatch(i)\n}\n\nfunction replaceAll() {\n if (target.readonly) return\n // Every match, also past the number shown.\n const all = capped.value ? searchText(doc.value, query.value, Infinity).matches : matches.value\n if (!all.length) return\n const text = doc.value\n const tr = transaction().setMeta({ action: 'replace', scroll: true })\n for (const m of all) tr.replace(m.from, m.to, replacementFor(text, m, query.value))\n dispatch(tr)\n // Leave a cursor rather than a selection on the last replacement, which would look like a match left over.\n const head = mainRange(state.value.selection).head\n dispatch(transaction().select(head))\n announcement.value = common('findReplace.replaced', { count: all.length })\n runSearch()\n}\n\n/** The matches on the lines in view, as boxes; the one selected stands out. */\nconst matchBoxes = computed(() => {\n void metrics.value\n if (!searchOpen.value || !matches.value.length) return []\n const text = doc.value\n const first = text.line(visibleFrom.value).from\n const last = text.line(visibleTo.value).to\n const out: Array<Box & { current: boolean }> = []\n for (let i = matchAfter(matches.value, first); i >= 0 && i < matches.value.length; i++) {\n const m = matches.value[i]!\n // Past the view, or wrapped around to the first match above it.\n if (m.from > last || m.to < first) break\n const from = text.lineAt(m.from)\n const to = text.lineAt(m.to)\n for (\n let n = Math.max(from.number, visibleFrom.value);\n n <= Math.min(to.number, visibleTo.value);\n n++\n ) {\n if (!layout.value.shown(n)) continue\n const str = lineText(n)\n const a = n === from.number ? m.from - from.from : 0\n const b = n === to.number ? m.to - to.from : str.length\n spans(n, str, a, b).forEach((box, k) =>\n out.push({\n key: `m${m.from}-${n}-${k}`,\n ...box,\n left: pad.x + box.left,\n current: i === currentMatch.value,\n }),\n )\n }\n if (out.length > 2000) break\n }\n return out\n})\n\n/** Marks beside the scrollbar for where the matches are in the whole text, one per pixel row. */\nconst searchMarks = computed(() => {\n if (!searchOpen.value || !matches.value.length) return []\n const text = doc.value\n const drawn = layout.value\n /** Where a line sits in the whole text, from 0 to 1, as drawn (wrapped rows and folds counted). */\n const lh = lineHeight.value\n const all = total.value\n const share = (pos: number) => (rowTop(drawn.rowOf(text.lineAt(pos).number)) + lh / 2) / all\n const taken = new Set<number>()\n const out: Array<{ top: number; current: boolean }> = []\n const current = matches.value[currentMatch.value]\n // A thousand evenly spread matches show the picture; more only cost time.\n const step = Math.max(1, Math.floor(matches.value.length / 1000))\n for (let i = 0; i < matches.value.length; i += step) {\n const top = Math.round(share(matches.value[i]!.from) * 1000) / 10\n if (taken.has(top)) continue\n taken.add(top)\n out.push({ top, current: false })\n }\n if (current) out.push({ top: share(current.from) * 100, current: true })\n return out\n})\n\n// ---------------------------------------------------------------- problems\n\n/** The box over a place in the text with the problems there and their fixes; `keyboard` when opened by a key, so arrows pick a fix. */\nconst problemBox = shallowRef<{\n pos: number\n problems: CodeDiagnostic[]\n /** Text from the extensions' `hover`, shown above the problems. */\n info: Array<string | (() => VNodeChild)>\n /** The part of the text the box is about; the mouse may move inside it without the box changing. */\n from: number\n to: number\n index: number\n keyboard: boolean\n} | null>(null)\nconst problemEl = ref<HTMLElement>()\nconst problemSize = ref({ width: 0, height: 0 })\nlet problemTimer = 0\n\n/** The problems that cover a position; an empty one covers the character it marks. */\nfunction problemsAt(pos: number) {\n const out: CodeDiagnostic[] = []\n for (const problem of diagnostics.value) {\n if (problem.from > pos) break\n if (pos <= Math.max(problem.to, problem.from + 1)) out.push(problem)\n }\n return out\n}\n\nconst fixes = computed(() =>\n (problemBox.value?.problems ?? []).flatMap((problem) =>\n (problem.actions ?? []).map((action) => ({ problem, action })),\n ),\n)\n\nfunction showProblems(pos: number, keyboard: boolean) {\n clearTimeout(problemTimer)\n const problems = problemsAt(pos)\n if (!problems.length) {\n problemBox.value = null\n return false\n }\n const hasFixes = problems.some((problem) => problem.actions?.length)\n problemBox.value = {\n pos,\n problems,\n info: [],\n ...problemsSpan(problems, pos),\n index: keyboard && hasFixes ? 0 : -1,\n keyboard,\n }\n return true\n}\n\nfunction problemsSpan(problems: CodeDiagnostic[], pos: number) {\n let from = pos\n let to = pos\n for (const problem of problems) {\n from = Math.min(from, problem.from)\n to = Math.max(to, problem.to)\n }\n return { from, to }\n}\n\n/** Counts requests for hover text, so an answer to an older one is dropped. */\nlet hoverRequest = 0\nlet hoverAbort: AbortController | null = null\n\n/**\n * Shows what is known about a place: the extensions' hover text and the\n * problems there. Slow sources fill in when they answer. `false` when\n * there is nothing and nothing is coming.\n */\nfunction showInfo(pos: number, keyboard: boolean) {\n clearTimeout(problemTimer)\n const id = ++hoverRequest\n hoverAbort?.abort()\n const abort = new AbortController()\n hoverAbort = abort\n const text = doc.value\n const problems = problemsAt(pos)\n const info: Array<string | (() => VNodeChild)> = []\n let { from, to } = problemsSpan(problems, pos)\n const line = text.lineAt(pos)\n const word = wordAt(line.text, pos - line.from)\n const add = (result: CodeHoverResult | null | undefined) => {\n if (!result) return\n info.push(result.content)\n from = Math.min(from, result.from ?? line.from + word.from)\n to = Math.max(to, result.to ?? line.from + word.to)\n }\n const apply = () => {\n if (id !== hoverRequest || doc.value !== text) return\n if (!problems.length && !info.length) {\n problemBox.value = null\n return\n }\n const hasFixes = problems.some((problem) => problem.actions?.length)\n problemBox.value = {\n pos,\n problems,\n info: info.slice(),\n from,\n to,\n index: keyboard && hasFixes ? 0 : -1,\n keyboard,\n }\n if (keyboard) {\n const said = info.filter((item) => typeof item === 'string') as string[]\n if (said.length) announce(said.join('\\n'))\n }\n }\n let waiting = 0\n for (const extension of extensions.value) {\n if (!extension.hover) continue\n let answer: ReturnType<NonNullable<CodeExtension['hover']>>\n try {\n answer = extension.hover({ pos, signal: abort.signal }, context)\n } catch (error) {\n console.error(`[@dou-ui/code] ${extension.name}: hover failed`, error)\n continue\n }\n if (answer && 'then' in answer) {\n waiting++\n Promise.resolve(answer)\n .then((result) => {\n add(result)\n apply()\n })\n .catch((error: unknown) => {\n if (!abort.signal.aborted)\n console.error(`[@dou-ui/code] ${extension.name}: hover failed`, error)\n })\n } else add(answer)\n }\n apply()\n return problems.length > 0 || info.length > 0 || waiting > 0\n}\n\n/** Reads out the fix picked from the keyboard, and where it is in the list. */\nfunction announceFix() {\n const index = problemBox.value?.index ?? -1\n const fix = fixes.value[index]\n if (!fix) return\n announce(\n format(messages.value.itemAt, {\n label: fix.action.label,\n index: index + 1,\n count: fixes.value.length,\n }),\n )\n}\n\nfunction closeProblems() {\n clearTimeout(problemTimer)\n hoverRequest++\n hoverAbort?.abort()\n hoverAbort = null\n problemBox.value = null\n}\n// The touch toolbar and the hover box would cover each other: the toolbar, asked for last, wins.\nwatch(menuOpen, (open) => open && closeProblems())\n\n// A press anywhere else on the page puts the box away; inside the editor, the press decides.\nfunction onPressAway(event: PointerEvent) {\n const at = event.target as Node | null\n if (at && (root.value?.contains(at) || problemEl.value?.contains(at))) return\n closeProblems()\n}\nwatch(\n () => !!problemBox.value,\n (open, _old, onCleanup) => {\n if (!open || typeof window === 'undefined') return\n window.addEventListener('pointerdown', onPressAway, true)\n onCleanup(() => window.removeEventListener('pointerdown', onPressAway, true))\n },\n)\n\n/** The line whose problem icon in the gutter is under a pointer. */\nfunction problemIconLine(event: Event) {\n const cell = (event.target as Element | null)?.closest?.(`.${ns.e('problem-icon')}`)\n const line = cell?.getAttribute('data-line')\n return line ? Number(line) : null\n}\n\n/** Shows the problems on a line, as a press on its icon in the gutter asks. */\nfunction showLineProblems(n: number) {\n const line = doc.value.line(n)\n const first = diagnostics.value.find((problem) => problem.from >= line.from)\n if (!first || first.from > line.to) return\n menuOpen.value = false\n showInfo(first.from, false)\n}\n\nfunction runFix(index: number) {\n const fix = fixes.value[index]\n if (!fix) return\n closeProblems()\n fix.action.run(context, fix.problem)\n focusInput()\n}\n\n/** Moves the cursor to the next problem after it (`1`) or before it (`-1`), going round, and shows it. */\nfunction goToProblem(direction: 1 | -1) {\n const list = diagnostics.value\n if (!list.length) return false\n const head = mainRange(state.value.selection).head\n let found: CodeDiagnostic | undefined\n if (direction > 0) found = list.find((problem) => problem.from > head) ?? list[0]\n else {\n for (let i = list.length - 1; i >= 0 && !found; i--) if (list[i]!.from < head) found = list[i]\n found ??= list[list.length - 1]\n }\n const problem = found!\n dispatch(transaction().select(problem.from).setMeta({ scroll: true }))\n showProblems(problem.from, true)\n const m = messages.value\n announce(\n format(m.problemAt, {\n line: doc.value.lineAt(problem.from).number,\n severity: m[problem.severity],\n message: problem.message,\n }),\n )\n return true\n}\n\nconst diagnosticControl = {\n next: () => goToProblem(1),\n previous: () => goToProblem(-1),\n showFixes: () => {\n if (!showProblems(mainRange(state.value.selection).head, true)) return false\n announceFix()\n return true\n },\n}\n\n/** Keys while the box is open from the keyboard: arrows pick a fix, Enter makes it, Escape closes the box. */\nfunction problemKey(name: string) {\n const box = problemBox.value\n if (!box) return false\n if (name === 'escape') {\n closeProblems()\n return true\n }\n const count = fixes.value.length\n if (!box.keyboard || !count) return false\n if (name === 'arrowdown' || name === 'arrowup') {\n const step = name === 'arrowdown' ? 1 : -1\n problemBox.value = { ...box, index: (box.index + step + count) % count }\n announceFix()\n return true\n }\n if (name === 'enter' || name === 'tab') {\n runFix(Math.max(0, box.index))\n return true\n }\n return false\n}\n\n/**\n * Shows the problems under the mouse after a moment; leaving them hides the\n * box a moment later. Fingers are left out: a tap shows the box itself, and\n * the mouse events a browser makes up after it would only close it again.\n */\nfunction onContentHover(event: PointerEvent) {\n if (event.pointerType === 'mouse') hoveredLine.value = lineAtY(event.clientY)\n if (event.pointerType !== 'mouse' || drag || problemBox.value?.keyboard) return\n const rect = content.value?.getBoundingClientRect()\n if (!rect) return\n const point = { x: event.clientX, y: event.clientY }\n const pos = posAtCoords(point)\n const at = coordsAtPos(pos)\n // Only over the text itself, not the empty space after a line.\n const over = !!at && Math.abs(point.x - at.left) <= measure.cell * 2\n const box = problemBox.value\n if (box && over && pos >= box.from && pos <= box.to) {\n clearTimeout(problemTimer)\n return\n }\n clearTimeout(problemTimer)\n // Only worth asking where there is something: a problem, or a word for the extensions to explain.\n const asks = over && (problemsAt(pos).length > 0 || extensions.value.some((e) => e.hover))\n problemTimer = window.setTimeout(\n () => (asks ? showInfo(pos, false) || closeProblems() : closeProblems()),\n asks ? 350 : 250,\n )\n}\n\n/** The mouse came onto the box: it stays. */\nfunction keepProblems() {\n clearTimeout(problemTimer)\n}\n\nfunction onContentLeave(event: PointerEvent) {\n hoveredLine.value = null\n if (event.pointerType !== 'mouse' || problemBox.value?.keyboard) return\n clearTimeout(problemTimer)\n problemTimer = window.setTimeout(closeProblems, 250)\n}\n\n// Below the line, above it when there is no room, always in view.\nconst problemStyle = computed(() => {\n const box = problemBox.value\n return box ? floatingStyle(box.pos, problemSize.value) : null\n})\n\n/**\n * Where a box about position `pos` goes: below its line, or above it when\n * there is no room (first, with `above`), always in view; too tall for\n * either side, it scrolls inside on the roomier one.\n */\nfunction floatingStyle(pos: number, size: { width: number; height: number }, above = false) {\n const inside = pointOf(pos)\n if (!inside) return null\n let at: { x: number; top: number } = inside\n let view = visibleBox()\n if (floatingTarget.value) {\n // Above the page: in the window's coordinates, wherever the window is scrolled.\n const page = toPage(inside)\n if (!page) return null\n at = page\n view = pageBox()\n }\n const { width, height } = size\n const lh = lineHeight.value\n // Never wider than the text area in view, on a phone too.\n const maxWidth = `${Math.max(0, Math.floor(Math.min(440, view.right - view.left - 8)))}px`\n if (above && at.top - 4 - height >= view.top) {\n const left = Math.max(view.left + 4, Math.min(at.x - 12, view.right - width - 4))\n return {\n transform: `translate(${Math.round(left)}px, ${Math.round(at.top - 4 - height)}px)`,\n maxHeight: undefined,\n maxWidth,\n }\n }\n // A finger's cursor has its handle below the line: the box goes above when there is room, or under the handle.\n const below = at.top + lh + 4\n const roomBelow = view.bottom - 4 - below\n const roomAbove = at.top - 4 - view.top\n // A finger's cursor has its handle below the line, which the box keeps clear of where it can.\n const handle = touchUi.value && caretHandle.value ? HANDLE : 0\n let top: number\n let room: number\n if (roomBelow - handle >= height) [top, room] = [below + handle, roomBelow - handle]\n else if (roomAbove >= height) [top, room] = [at.top - 4 - height, roomAbove]\n else if (roomBelow >= height || roomBelow >= roomAbove) [top, room] = [below, roomBelow]\n // Too tall for either side: on the roomier one, scrolling inside.\n else [top, room] = [view.top + 4, roomAbove]\n const left = Math.max(view.left + 4, Math.min(at.x - 12, view.right - width - 4))\n return {\n transform: `translate(${Math.round(left)}px, ${Math.round(top)}px)`,\n maxHeight: height > room ? `${Math.max(0, Math.floor(room))}px` : undefined,\n maxWidth,\n }\n}\n\n/** Keeps a floating box's whole size, even while it is cut short and scrolls. */\nfunction measureFloating(\n el: HTMLElement | undefined,\n size: { value: { width: number; height: number } },\n) {\n if (el)\n size.value = {\n width: el.offsetWidth,\n height: el.scrollHeight + el.offsetHeight - el.clientHeight,\n }\n}\n\nwatch([problemEl, problemBox], () => measureFloating(problemEl.value, problemSize), {\n flush: 'post',\n})\n\n// ---------------------------------------------------------------- completion\n\nconst KIND_ICON: Record<CodeCompletionKind, unknown> = {\n keyword: SymbolKeywordIcon,\n function: FunctionIcon,\n method: FunctionIcon,\n variable: VariableIcon,\n property: WrenchIcon,\n constant: SymbolConstantIcon,\n class: SymbolClassIcon,\n type: SymbolTypeAliasIcon,\n module: PackageIcon,\n snippet: SquareCodeIcon,\n text: TypeIcon,\n}\n\ninterface CompletionItem {\n option: CodeCompletion\n /** Where its text goes, from here to the cursor. */\n from: number\n /** The parts of the label that were typed. */\n ranges: Array<[number, number]>\n score: number\n}\n\n/** The open completion list: the answers it came from, and the entries that match what is typed. */\nconst completion = shallowRef<{\n pos: number\n results: CodeCompletionResult[]\n items: CompletionItem[]\n index: number\n explicit: boolean\n /** Picked from with the keys, not just opened by typing. */\n moved: boolean\n} | null>(null)\nconst completionEl = ref<HTMLElement>()\nconst completionList = ref<HTMLElement>()\nconst completionSize = ref({ width: 0, height: 0 })\nconst completionId = `dou-code-completion-${instance.uid}`\nconst hasCompletion = computed(() => extensions.value.some((extension) => extension.completion))\nlet completionRequest = 0\nlet completionAbort: AbortController | null = null\n\nconst WORD_BEFORE = /[\\p{L}\\p{N}_$]+$/u\nconst WORD_CHAR = /[\\p{L}\\p{N}_$]/u\n\n/** The word right before `pos`. */\nfunction wordBefore(pos: number) {\n const line = doc.value.lineAt(pos)\n const found = WORD_BEFORE.exec(line.text.slice(0, pos - line.from))\n const text = found ? found[0] : ''\n return { from: pos - text.length, to: pos, text }\n}\n\n/** The answers' entries that match what is typed since each answer's `from`, best first. */\nfunction rankCompletions(results: readonly CodeCompletionResult[], pos: number) {\n const out: CompletionItem[] = []\n const text = doc.value\n for (const result of results) {\n if (result.from > pos || result.from < 0) continue\n const typed = text.slice(result.from, pos)\n for (const option of result.options) {\n const match = matchCompletion(option.label, typed)\n if (match)\n out.push({\n option,\n from: result.from,\n ranges: match.ranges,\n score: match.score + (option.boost ?? 0),\n })\n }\n }\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n out.sort((a, b) => b.score - a.score || a.option.label.localeCompare(b.option.label))\n return out.length > 200 ? out.slice(0, 200) : out\n}\n\n/** Asks the extensions for completions at the cursor and opens the list with what matches. */\nfunction startCompletion(explicit: boolean) {\n const main = mainRange(state.value.selection)\n const sources = extensions.value.filter((extension) => extension.completion)\n if (!sources.length || !isEmptyRange(main) || props.readonly || props.disabled) {\n closeCompletion()\n return false\n }\n const pos = main.head\n const id = ++completionRequest\n completionAbort?.abort()\n const abort = new AbortController()\n completionAbort = abort\n const text = doc.value\n const request = { pos, word: wordBefore(pos), explicit, signal: abort.signal }\n // Until the new answers come, the last ones go on matching what is typed.\n const previous = completion.value?.results ?? []\n const results: CodeCompletionResult[] = []\n let waiting = 0\n const apply = () => {\n if (id !== completionRequest || doc.value !== text) return\n if (mainRange(state.value.selection).head !== pos) return\n const source = results.length || !waiting ? results : previous\n const items = rankCompletions(source, pos)\n // The word is already all there: nothing to complete, unless asked.\n const done =\n !explicit && items.length === 1 && text.slice(items[0]!.from, pos) === items[0]!.option.label\n if (!items.length || done) {\n if (!waiting) completion.value = null\n return\n }\n const before = completion.value\n const picked = before?.items[before.index]?.option\n const kept = picked ? items.findIndex((item) => item.option === picked) : -1\n completion.value = {\n pos,\n results: source,\n items,\n index: Math.max(0, kept),\n explicit,\n moved: kept > 0 && !!before?.moved,\n }\n // A list that opens is read out with its first entry; the textarea is not a combobox to some readers.\n if (!before) announceCompletion()\n }\n for (const extension of sources) {\n let answer: ReturnType<NonNullable<CodeExtension['completion']>>\n try {\n answer = extension.completion!(request, context)\n } catch (error) {\n console.error(`[@dou-ui/code] ${extension.name}: completion failed`, error)\n continue\n }\n if (answer && 'then' in answer) {\n waiting++\n Promise.resolve(answer)\n .then((result) => {\n waiting--\n if (result) results.push(result)\n apply()\n })\n .catch((error: unknown) => {\n waiting--\n if (!abort.signal.aborted)\n console.error(`[@dou-ui/code] ${extension.name}: completion failed`, error)\n apply()\n })\n } else if (answer) results.push(answer)\n }\n apply()\n return true\n}\n\nfunction closeCompletion() {\n completionRequest++\n completionAbort?.abort()\n completionAbort = null\n completion.value = null\n}\n\nfunction moveCompletion(step: number) {\n const list = completion.value\n if (!list) return\n const count = list.items.length\n // Arrows go round; pages stop at the ends.\n const index =\n Math.abs(step) === 1\n ? (list.index + step + count) % count\n : Math.max(0, Math.min(count - 1, list.index + step))\n completion.value = { ...list, index, moved: true }\n announceCompletion()\n nextTick(() =>\n completionList.value\n ?.querySelector(`#${completionId}-${index}`)\n ?.scrollIntoView?.({ block: 'nearest' }),\n )\n}\n\n/** Reads out the picked entry, and where it is in the list. */\nfunction announceCompletion() {\n const list = completion.value\n const item = list?.items[list.index]\n if (!item) return\n announce(\n format(messages.value.itemAt, {\n label: item.option.detail ? `${item.option.label} ${item.option.detail}` : item.option.label,\n index: list.index + 1,\n count: list.items.length,\n }),\n )\n}\n\n/** Puts the entry's text in place of what was typed for it. */\nfunction acceptCompletion(index: number) {\n const list = completion.value\n const item = list?.items[index]\n if (!item) return\n closeCompletion()\n const pos = mainRange(state.value.selection).head\n const { option } = item\n if (option.snippet !== undefined) insertSnippet(item.from, pos, option.snippet)\n else {\n const insert = option.insert ?? option.label\n dispatch(\n transaction()\n .replace(item.from, pos, insert)\n .select(item.from + insert.length)\n .setMeta({ action: 'complete', scroll: true }),\n )\n }\n focusInput()\n}\n\n/** Keys while the list is open: arrows and pages pick, Enter or Tab puts the entry in, Escape closes it. */\nfunction completionKey(name: string) {\n if (!completion.value) return false\n if (name === 'arrowdown' || name === 'arrowup') moveCompletion(name === 'arrowdown' ? 1 : -1)\n else if (name === 'pagedown' || name === 'pageup') moveCompletion(name === 'pagedown' ? 8 : -8)\n else if (\n name === 'tab' &&\n snippet.value &&\n !completion.value.moved &&\n !completion.value.explicit\n ) {\n // Inside a snippet, Tab goes on to the next place unless an entry was picked with the keys.\n closeCompletion()\n return false\n } else if (name === 'enter' || name === 'tab') acceptCompletion(completion.value.index)\n else if (name === 'escape') closeCompletion()\n else return false\n return true\n}\n\n/** A label cut where the typed characters start and end. */\nfunction labelParts(item: CompletionItem) {\n const { label } = item.option\n const out: Array<[string, boolean]> = []\n let at = 0\n for (const [from, to] of item.ranges) {\n if (from > at) out.push([label.slice(at, from), false])\n out.push([label.slice(from, to), true])\n at = to\n }\n if (at < label.length) out.push([label.slice(at), false])\n return out\n}\n\nconst completionStyle = computed(() => {\n const list = completion.value\n if (!list) return null\n const first = list.items[list.index]?.from ?? list.pos\n return floatingStyle(first, completionSize.value)\n})\nwatch(\n [completionEl, completion],\n () => {\n const el = completionEl.value\n const list = completionList.value\n // Its whole height: the list scrolls when the box is cut short.\n if (el && list)\n completionSize.value = {\n width: el.offsetWidth,\n height: el.offsetHeight + list.scrollHeight - list.clientHeight,\n }\n },\n { flush: 'post' },\n)\n\n// ---------------------------------------------------------------- snippets\n\n/** The snippet being filled in: its places, grouped by number in Tab order, and which one is selected. */\nconst snippet = shallowRef<{\n groups: Array<{ index: number; ranges: Array<{ from: number; to: number }> }>\n at: number\n /** Where the snippet ends, for the cursor once all its places are filled in. */\n end: number\n} | null>(null)\n\n/** Inserts a snippet in place of `from`–`to`, its later lines indented like the first, and selects its first place. */\nfunction insertSnippet(from: number, to: number, source: string) {\n const line = doc.value.lineAt(from)\n const indent = indentOf(line.text)\n // A tab in a snippet is one step of indent, as the editor indents.\n const unit = props.indentWithTabs ? '\\t' : ' '.repeat(props.tabSize)\n const own = source.replace(/\\t/g, unit)\n const { text, fields } = parseSnippet(indent ? own.replace(/\\n/g, `\\n${indent}`) : own)\n const groups: Array<{ index: number; ranges: Array<{ from: number; to: number }> }> = []\n for (const field of fields) {\n const range = { from: from + field.from, to: from + field.to }\n const group = groups.find((g) => g.index === field.index)\n if (group) group.ranges.push(range)\n else groups.push({ index: field.index, ranges: [range] })\n }\n const tr = transaction().replace(from, to, text).setMeta({ action: 'complete', scroll: true })\n if (!groups.length) {\n snippet.value = null\n dispatch(tr.select(from + text.length))\n return\n }\n const first = groups[0]!\n tr.select({ ranges: first.ranges.map((r) => ({ anchor: r.from, head: r.to })), main: 0 })\n dispatch(tr)\n // Its places are in the new text already, so set after the change. Nothing more to fill in once there: no session to keep.\n snippet.value =\n groups.length > 1 || first.index !== 0 ? { groups, at: 0, end: from + text.length } : null\n}\n\n/** Selects the next or previous place of the snippet; past the last, the snippet is done. */\nfunction snippetField(dir: 1 | -1) {\n const session = snippet.value\n if (!session) return false\n const next = Math.max(0, session.at + dir)\n const group = session.groups[next]\n if (!group) {\n // Past the last place, with no $0: done, the cursor after the snippet.\n snippet.value = null\n dispatch(transaction().select(session.end).setMeta({ action: 'snippet', scroll: true }))\n return true\n }\n // $0 is where it ends: reaching it is done.\n snippet.value = group.index === 0 ? null : { ...session, at: next }\n dispatch(\n transaction()\n .select({ ranges: group.ranges.map((r) => ({ anchor: r.from, head: r.to })), main: 0 })\n .setMeta({ action: 'snippet', scroll: true }),\n )\n return true\n}\n\n// ---------------------------------------------------------------- parameter hints\n\nconst signature = shallowRef<{ pos: number; result: CodeSignatureResult } | null>(null)\nconst signatureEl = ref<HTMLElement>()\nconst signatureSize = ref({ width: 0, height: 0 })\n\nlet signatureRequest = 0\nlet signatureAbort: AbortController | null = null\n\n/** Asks the extensions about the call around the cursor; the first answer, by priority, is shown. */\nfunction updateSignature() {\n const id = ++signatureRequest\n signatureAbort?.abort()\n const abort = new AbortController()\n signatureAbort = abort\n // At the head, also with a snippet's place selected.\n const pos = mainRange(state.value.selection).head\n const text = doc.value\n type Answer = ReturnType<NonNullable<CodeExtension['signature']>>\n const answers: Answer[] = []\n for (const extension of extensions.value) {\n if (!extension.signature) continue\n try {\n const answer = extension.signature({ pos, signal: abort.signal }, context)\n if (answer && 'then' in answer)\n answers.push(\n Promise.resolve(answer).catch((error: unknown) => {\n if (!abort.signal.aborted)\n console.error(`[@dou-ui/code] ${extension.name}: signature failed`, error)\n return null\n }),\n )\n else answers.push(answer)\n } catch (error) {\n console.error(`[@dou-ui/code] ${extension.name}: signature failed`, error)\n }\n }\n const show = (result: CodeSignatureResult | null | undefined) => {\n if (id !== signatureRequest || doc.value !== text) return\n if (mainRange(state.value.selection).head !== pos) return\n if (!result) {\n signature.value = null\n return\n }\n const before = signature.value?.result\n signature.value = { pos, result }\n // Read out when the parameter changes, not on every key.\n if (!before || before.label !== result.label || before.active !== result.active) {\n const param = result.params[result.active]\n announce(param ? result.label.slice(param[0], param[1]) : result.label)\n }\n }\n // The first answer in priority order; a slow one is waited for, the box staying as it was meanwhile.\n let i = 0\n const next = (): void => {\n for (; i < answers.length; i++) {\n const answer = answers[i]\n if (answer && 'then' in answer) {\n const at = i\n void answer.then((result) => {\n answers[at] = result\n next()\n })\n return\n }\n if (answer) return show(answer)\n }\n show(null)\n }\n next()\n}\n\nfunction closeSignature() {\n signatureRequest++\n signatureAbort?.abort()\n signatureAbort = null\n signature.value = null\n}\n\nconst signatureParts = computed(() => {\n const result = signature.value?.result\n if (!result) return []\n const param = result.params[result.active]\n if (!param) return [[result.label, false]] as Array<[string, boolean]>\n return [\n [result.label.slice(0, param[0]), false],\n [result.label.slice(param[0], param[1]), true],\n [result.label.slice(param[1]), false],\n ] as Array<[string, boolean]>\n})\n\nconst signatureStyle = computed(() => {\n const box = signature.value\n return box ? floatingStyle(box.pos, signatureSize.value, true) : null\n})\nwatch([signatureEl, signature], () => measureFloating(signatureEl.value, signatureSize), {\n flush: 'post',\n})\n\nconst teleport = useTeleport(() => props.teleport)\n/**\n * Where the boxes about the text and the touch handles render: above the\n * page by default, so a short editor never cuts them off; inside the frame\n * (`null`) when `teleport` is `false`, and until the editor is mounted.\n */\nconst floatingTarget = computed(() =>\n // Only once mounted: the server's markup keeps them in place, so hydrating never looks for them in the body.\n teleport.value.disabled || !mounted.value ? null : teleport.value.to,\n)\nconst floatingZ = ref(0)\nconst floatingEl = ref<HTMLElement>()\n/**\n * The layer above the page sits in the page, not fixed to the window, so it\n * scrolls with the page on its own and never lags behind a finger's scroll.\n * Its boxes are placed in the window's coordinates; this moves the layer so\n * those land where the window has them, as of the last scroll.\n */\nconst layerShift = ref({ x: 0, y: 0 })\nfunction readLayerShift() {\n const el = floatingEl.value\n if (!el || !floatingTarget.value) return\n const rect = el.getBoundingClientRect()\n const { x, y } = layerShift.value\n layerShift.value = { x: x - rect.left, y: y - rect.top }\n}\n/** Bumped when the page scrolls or resizes, for boxes placed in the window's coordinates. */\nconst viewportTick = ref(0)\nconst bumpViewport = () => {\n readLayerShift()\n viewportTick.value++\n}\n/**\n * A box the editor sits in scrolling (a drawer, a side panel, an app's main\n * area): the layer above the page scrolls with the page only, so it hides\n * until that box stops, rather than trail behind the text.\n */\nconst boxScrolling = ref(false)\nlet boxScrollTimer = 0\n/**\n * How the editor moves when the page scrolls, read as the layer opens: with\n * the page; not at all, inside a `fixed` box (a bar pinned to the bottom, a\n * panel), where the layer stays fixed too; or partly, inside a `sticky` box,\n * where the layer hides while the page scrolls.\n */\nconst anchorMode = ref<'page' | 'fixed' | 'sticky'>('page')\nfunction readAnchorMode() {\n let mode: 'page' | 'fixed' | 'sticky' = 'page'\n for (let el = root.value?.parentElement; el && el !== document.body; el = el.parentElement) {\n const { position } = getComputedStyle(el)\n if (position === 'fixed') {\n mode = 'fixed'\n break\n }\n if (position === 'sticky') mode = 'sticky'\n }\n anchorMode.value = mode\n}\nfunction onAnyScroll(event: Event) {\n const box = event.target\n const page = !(box instanceof Element)\n if (\n page\n ? anchorMode.value === 'sticky'\n : box !== scroller.value && !!root.value && box.contains(root.value)\n ) {\n boxScrolling.value = true\n clearTimeout(boxScrollTimer)\n boxScrollTimer = window.setTimeout(() => (boxScrolling.value = false), 160)\n }\n bumpViewport()\n}\n/** Whether the focus is on the bar of keys itself, reached by Escape then Tab: the bar stays while it is. */\nconst keysFocused = ref(false)\n/** The bar of keys, on a touch screen while the editor takes input, or while the focus is on it. */\nconst showKeys = computed(\n () =>\n !!props.keys &&\n coarse.value &&\n (focused.value || keysFocused.value) &&\n !props.readonly &&\n !props.disabled,\n)\nconst floatingOpen = computed(\n () =>\n !!(problemBox.value || completion.value || signature.value) ||\n (touchUi.value && focused.value) ||\n showKeys.value,\n)\nwatch(floatingOpen, (open, _old, onCleanup) => {\n if (!open || typeof window === 'undefined') return\n floatingZ.value = nextZIndex()\n // The boxes above the page take the editor's own variables with them, as they are now.\n readFrameFont()\n readAnchorMode()\n readLayerShift()\n // Once fixed or not as read, from where the layer now is.\n void nextTick(bumpViewport)\n const vv = window.visualViewport\n window.addEventListener('scroll', onAnyScroll, { capture: true, passive: true })\n window.addEventListener('resize', bumpViewport, { passive: true })\n vv?.addEventListener('resize', bumpViewport, { passive: true })\n vv?.addEventListener('scroll', bumpViewport, { passive: true })\n onCleanup(() => {\n window.removeEventListener('scroll', onAnyScroll, { capture: true })\n clearTimeout(boxScrollTimer)\n boxScrolling.value = false\n window.removeEventListener('resize', bumpViewport)\n vv?.removeEventListener('resize', bumpViewport)\n vv?.removeEventListener('scroll', bumpViewport)\n })\n})\n\n/** Where a point of the content is in the window; `null` while it is out of the editor's view. */\nfunction toPage(inside: { x: number; top: number }) {\n void viewportTick.value\n const view = visibleBox()\n if (inside.top + lineHeight.value <= view.top || inside.top >= view.bottom) return null\n if (inside.x < view.left - 1 || inside.x > view.right + 1) return null\n const rect = content.value?.getBoundingClientRect()\n if (!rect) return null\n return { x: rect.left + inside.x, top: rect.top + inside.top }\n}\n\n/** The editor's text in view, in the window's coordinates. */\nfunction frameInPage() {\n void viewportTick.value\n const view = visibleBox()\n const rect = content.value?.getBoundingClientRect()\n const x = rect?.left ?? 0\n const y = rect?.top ?? 0\n return { left: x + view.left, top: y + view.top, right: x + view.right, bottom: y + view.bottom }\n}\n\n/**\n * The part of the page in view, in the window's coordinates: on a phone,\n * above the keyboard and the bar of keys over it.\n */\nfunction pageBox() {\n void viewportTick.value\n const { left, top, width, height } = visibleViewport()\n return {\n left,\n top,\n right: left + width,\n bottom: top + height,\n }\n}\n\n/** After each change: opens, updates or closes the completion list and the parameter hints, and moves the snippet's places. */\nfunction updateAssist(result: CodeTransactionResult) {\n const { action } = result.meta\n const { changes } = result\n const main = mainRange(result.state.selection)\n const session = snippet.value\n if (session) {\n const groups = changes.empty\n ? session.groups\n : session.groups.map((group) => ({\n index: group.index,\n ranges: group.ranges.map((range) => ({\n from: changes.mapPos(range.from, -1),\n to: changes.mapPos(range.to, 1),\n })),\n }))\n // Leaving the place being filled in ends the snippet.\n const current = groups[session.at]\n const inside = current?.ranges.some((range) => main.head >= range.from && main.head <= range.to)\n const end = changes.empty ? session.end : changes.mapPos(session.end, 1)\n snippet.value =\n action === 'snippet' || action === 'complete' || inside ? { ...session, groups, end } : null\n }\n if (action === 'remote') {\n // Someone else's change: the list and the hints stay, unless it reached what they are about.\n if (changes.empty) return\n const head = mainRange(result.before.selection).head\n const map = (pos: number) => changes.mapPos(pos, -1)\n const list = completion.value\n if (list) {\n const start = Math.min(list.pos, ...list.results.map((answer) => answer.from))\n if (changes.touches(Math.min(start, head), Math.max(list.pos, head))) closeCompletion()\n else\n completion.value = {\n ...list,\n pos: map(list.pos),\n results: list.results.map((answer) => ({ ...answer, from: map(answer.from) })),\n items: list.items.map((item) => ({ ...item, from: map(item.from) })),\n }\n }\n const hints = signature.value\n if (hints)\n if (changes.touches(Math.min(hints.pos, head), Math.max(hints.pos, head))) updateSignature()\n else signature.value = { ...hints, pos: map(hints.pos) }\n return\n }\n if (action === 'complete' || action === 'snippet') {\n // A completed call puts the cursor inside its brackets: the hints show right away.\n updateSignature()\n return\n }\n if (action === 'input' && !changes.empty && result.state.selection.ranges.length === 1) {\n // What was typed, also when a closing bracket came in after it.\n const ch = changes.changes[changes.changes.length - 1]!.insert\n ? result.state.doc.slice(main.head - 1, main.head)\n : ''\n const trigger = extensions.value.some((extension) => extension.completionTriggers?.includes(ch))\n if (ch && (WORD_CHAR.test(ch) || trigger)) startCompletion(false)\n else closeCompletion()\n if (signature.value || ch === '(' || ch === ',') updateSignature()\n return\n }\n if (action === 'delete' && completion.value && wordBefore(main.head).text)\n startCompletion(completion.value.explicit)\n else closeCompletion()\n if (signature.value) updateSignature()\n}\n\n/** Where the problems sit along the scrollbar, by severity. */\nconst problemMarks = computed(() => {\n const list = diagnostics.value\n if (!list.length) return []\n const text = doc.value\n const drawn = layout.value\n const lh = lineHeight.value\n const all = total.value\n const taken = new Set<string>()\n const out: Array<{ top: number; severity: CodeDiagnosticSeverity }> = []\n for (const problem of list) {\n const y = rowTop(drawn.rowOf(text.lineAt(problem.from).number)) + lh / 2\n const top = Math.round((y / all) * 1000) / 10\n const key = `${top}${problem.severity}`\n if (taken.has(key)) continue\n taken.add(key)\n out.push({ top, severity: problem.severity })\n if (out.length >= 1000) break\n }\n return out\n})\n\n// ---------------------------------------------------------------- panels\n\nconst panels = computed(() => {\n const top: Array<{ key: string; render: CodePanel['render'] }> = []\n const bottom: typeof top = []\n for (const extension of extensions.value)\n for (const bar of extension.panels?.(context) ?? [])\n (bar.position === 'top' ? top : bottom).push({\n key: `${extension.name}/${bar.name}`,\n render: bar.render,\n })\n return { top, bottom }\n})\n\nconst searchControl = {\n open: (replace?: boolean) => openSearch(replace),\n close: closeSearch,\n next: () => nextMatch(),\n previous: () => previousMatch(),\n}\n\n// ---------------------------------------------------------------- the hidden textarea\n\n/**\n * What the textarea holds: the text from `from` to `to`, and the caret\n * inside it. `selected` is the selection its caret stands for, on a touch\n * screen: whatever the textarea is given there replaces it.\n */\nlet mirror: {\n from: number\n to: number\n value: string\n start: number\n end: number\n selected: { from: number; to: number } | null\n} = { from: 0, to: 0, value: '', start: 0, end: 0, selected: null }\nconst inputBox = ref({ top: pad.y, left: pad.x, height: 20 })\n\nfunction syncInput() {\n const { doc: text, selection } = state.value\n const main = mainRange(selection)\n const first = text.lineAt(rangeFrom(main))\n const last = text.lineAt(rangeTo(main))\n let from = first.from\n let to = last.to\n // Mirror whole lines of the selection while they are short; else only around the cursor.\n if (to - from > WINDOW || last.number - first.number > 50) {\n const line = text.lineAt(main.head)\n from = Math.max(line.from, main.head - WINDOW / 2)\n to = Math.min(line.to, main.head + WINDOW / 2)\n from = line.from + snapCluster(line.text, from - line.from)\n }\n const value = text.slice(from, to)\n let start = Math.max(0, Math.min(rangeFrom(main), to) - from)\n const end = Math.max(0, Math.min(rangeTo(main), to) - from)\n // On a touch screen the textarea keeps only a caret, at the selection's end: a selection\n // there would bring the system's own handles and menu up over the editor's.\n const selected =\n coarse.value && !isEmptyRange(main) ? { from: rangeFrom(main), to: rangeTo(main) } : null\n if (selected) start = end\n mirror = { from, to, value, start, end, selected }\n composeMap = null\n // Put the textarea where its caret lines up with the drawn main cursor, so input methods open there.\n const startLine = text.lineAt(from)\n const headLine = text.lineAt(main.head)\n const headText = headLine.number === startLine.number ? startLine.text : headLine.text\n const caret = place(headLine.number, headText, main.head - headLine.from)\n const lineStart = headLine.number === startLine.number ? from - startLine.from : 0\n inputBox.value = {\n top: caret.top - (headLine.number - startLine.number) * lineHeight.value,\n left:\n pad.x +\n caret.x -\n (measure.x(headText, main.head - headLine.from) - measure.x(headText, lineStart)),\n height: (text.lineAt(to).number - startLine.number + 1) * lineHeight.value,\n }\n const el = input.value\n if (!el) return\n if (el.value !== value) el.value = value\n if (document.activeElement === el && (el.selectionStart !== start || el.selectionEnd !== end))\n el.setSelectionRange(start, end, main.head < main.anchor ? 'backward' : 'forward')\n}\n\n/** The text a change in the textarea replaces: the part it changed, or the selection its caret stands for. */\nfunction inputRange(diff: { from: number; to: number }) {\n const { selected } = mirror\n const from = composedPos(selected ? selected.from : mirror.from + diff.from, -1)\n const to = Math.max(from, composedPos(selected ? selected.to : mirror.from + diff.to, 1))\n return { from, to }\n}\n\n/** Turns what the textarea now holds into a change of the text. */\nfunction readInput() {\n const el = input.value\n if (!el || props.readonly) return\n const diff = diffText(mirror.value, el.value, mirror.start)\n if (!diff) return\n const { from, to } = inputRange(diff)\n let { insert } = diff\n // The Enter that confirmed a composition only confirms it.\n if (insert.endsWith('\\n') && performance.now() - confirmEnter < 200) {\n insert = insert.slice(0, -1)\n confirmEnter = -Infinity\n }\n if (!insert && from === to) return syncInput()\n const { doc: text, selection } = state.value\n const main = mainRange(selection)\n // Typing over the selection or at the cursor: the same goes to every cursor.\n if (from === rangeFrom(main) && to === rangeTo(main) && insert) {\n if (insert === '\\n') return run(insertNewline)\n if (insertText(target, insert)) return\n dispatch(transaction().replaceSelection(insert).setMeta({ action: 'input' }))\n return\n }\n // The caret standing for the selection deleted something: the selection goes.\n if (mirror.selected && !insert && from === rangeFrom(main) && to === rangeTo(main))\n return run(deleteCharBackward)\n if (!insert && isEmptyRange(main)) {\n const line = text.lineAt(main.head)\n const col = main.head - line.from\n const back = col ? line.from + moveCluster(line.text, col, -1) : main.head - 1\n const forward =\n col < line.text.length ? line.from + moveCluster(line.text, col, 1) : main.head + 1\n if (from === back && to === main.head) return run(deleteCharBackward)\n if (from === main.head && to === forward) return run(deleteCharForward)\n }\n // Anything else (autocorrect, a word recomposed): apply it as it is, and take the caret the textarea has.\n const tr = transaction().setMeta({ action: insert ? 'input' : 'delete' })\n tr.replace(from, to, insert)\n if (mirror.selected) {\n dispatch(tr.select(from + insert.length))\n return\n }\n const result = tr.resolve()\n const base = composedPos(mirror.from, 1)\n const caret = (offset: number) => base + offset\n const ranges = result.state.selection.ranges.slice()\n const backward = el.selectionDirection === 'backward'\n const head = caret(backward ? el.selectionStart : el.selectionEnd)\n const anchor = caret(backward ? el.selectionEnd : el.selectionStart)\n ranges[result.state.selection.main] = { anchor, head }\n tr.select({ ranges, main: result.state.selection.main })\n dispatch(tr)\n}\n\nfunction onInput() {\n if (composing.value) {\n const el = input.value!\n const diff = diffText(mirror.value, el.value, mirror.start)\n if (!diff) {\n preview.value = null\n return\n }\n preview.value = { ...inputRange(diff), insert: diff.insert }\n return\n }\n readInput()\n}\n\nfunction onCompositionStart() {\n composing.value = true\n}\n\nfunction onCompositionEnd() {\n composing.value = false\n preview.value = null\n readInput()\n syncInput()\n}\n\nfunction onSelectionChange() {\n const el = input.value\n if (!el || document.activeElement !== el || composing.value) return\n if (el.selectionStart === mirror.start && el.selectionEnd === mirror.end) return\n if (el.value !== mirror.value) return\n // The caret moved by itself (the space bar on a phone keyboard, say): follow it.\n const backward = el.selectionDirection === 'backward'\n const start = mirror.from + el.selectionStart\n const end = mirror.from + el.selectionEnd\n const selection = state.value.selection\n const ranges = selection.ranges.slice()\n ranges[selection.main] = backward ? { anchor: end, head: start } : { anchor: start, head: end }\n mirror.start = el.selectionStart\n mirror.end = el.selectionEnd\n dispatch(transaction().select({ ranges, main: selection.main }).setMeta({ scroll: true }))\n}\n\n// ---------------------------------------------------------------- commands and keys\n\nconst target: CodeCommandTarget = {\n get state() {\n return state.value\n },\n get readonly() {\n return !!props.readonly || !!props.disabled\n },\n get tabSize() {\n return props.tabSize\n },\n get indentWithTabs() {\n return !!props.indentWithTabs\n },\n get pageLines() {\n return Math.max(1, Math.floor((viewHeight.value || 400) / lineHeight.value) - 1)\n },\n get language() {\n return props.language ?? null\n },\n get closeBrackets() {\n return props.closeBrackets\n },\n transaction,\n dispatch,\n moveVertically,\n undo,\n redo,\n languageAt,\n syntaxAt,\n get search() {\n return props.searchable ? searchControl : undefined\n },\n get folding() {\n return props.foldable ? folding : undefined\n },\n get diagnostics() {\n return diagnosticControl\n },\n assist: {\n complete: () => startCompletion(true),\n hover: () => showInfo(mainRange(state.value.selection).head, true),\n field: (dir) => snippetField(dir),\n },\n}\n\nfunction run(command: CodeCommand) {\n return command(target)\n}\n\n/** Moves by rows as drawn: a wrapped line's rows one by one, over folded lines. */\nfunction moveVertically(range: CodeRange, count: number) {\n const { doc: text } = state.value\n const line = text.lineAt(range.head)\n const at = place(line.number, line.text, range.head - line.from)\n const goal = goals.get(range.head) ?? at.x\n const row = layout.value.rowOf(line.number) + at.sub + count\n let head: number\n if (row < 0) head = 0\n else if (row >= layout.value.total) head = text.length\n else {\n const { n, sub } = layout.value.lineAtRow(row)\n const next = text.line(n)\n head = next.from + colAt(next.number, next.text, sub, goal)\n }\n pendingGoals.set(head, goal)\n return head\n}\n\n/** The extensions' keys, lowest priority first, since later bindings are tried first. */\nfunction extensionKeys() {\n const list = extensions.value\n const out: CodeKeyBinding[] = []\n for (let i = list.length - 1; i >= 0; i--) out.push(...keymapBindings(list[i]!.keymap?.(context)))\n return out\n}\n\nconst keymap = computed(() =>\n buildKeymap(\n [\n // Without indenting, Tab is left to the browser, but still fills in snippets.\n ...(props.tabIndents ? defaultKeymap : defaultKeymap.filter((b) => b.run !== insertTab)),\n ...extensionKeys(),\n ...keymapBindings(props.keymap),\n ],\n apple,\n ),\n)\n/** After Escape, Tab leaves the editor instead of indenting, so keyboard users are never stuck. */\nlet tabLeaves = false\nconst MODIFIERS = new Set(['Shift', 'Control', 'Alt', 'Meta'])\n\n/** When Enter last confirmed a composition; some browsers also put a line break into the textarea for it, right after. */\nlet confirmEnter = -Infinity\n\nfunction onKeydown(event: KeyboardEvent) {\n if (isComposing(event) || composing.value) {\n if (event.key === 'Enter') confirmEnter = performance.now()\n return\n }\n confirmEnter = -Infinity\n const name = eventKey(event, apple)\n if (completionKey(name) || problemKey(name)) {\n event.preventDefault()\n event.stopPropagation()\n return\n }\n // Escape first puts away the toolbar over the selection.\n if (name === 'escape' && menuOpen.value) {\n menuOpen.value = false\n event.preventDefault()\n event.stopPropagation()\n return\n }\n // Escape also ends filling in a snippet.\n if (name === 'escape' && snippet.value) {\n snippet.value = null\n event.preventDefault()\n event.stopPropagation()\n return\n }\n const leaving = tabLeaves && (name === 'tab' || name === 'shift+tab')\n // Shift pressed on its way to Shift+Tab comes down on its own first\n if (!MODIFIERS.has(event.key)) tabLeaves = name === 'escape'\n if (leaving) {\n // Tab goes on to the bar of keys first, which sits elsewhere in the page.\n const first =\n name === 'tab' && !shownWidgets.value.length ? keysEl.value?.querySelector('button') : null\n if (first) {\n event.preventDefault()\n first.focus()\n }\n return\n }\n for (const command of keymap.value.get(name) ?? []) {\n if (command(target)) {\n event.preventDefault()\n event.stopPropagation()\n return\n }\n }\n}\n\nfunction onBeforeInput(event: InputEvent) {\n // The browser's own undo would only undo the textarea's mirror.\n if (event.inputType === 'historyUndo' || event.inputType === 'historyRedo') {\n event.preventDefault()\n if (event.inputType === 'historyUndo') undo()\n else redo()\n }\n}\n\n// ---------------------------------------------------------------- clipboard\n\nfunction selectedText() {\n const { doc: text, selection } = state.value\n return selection.ranges\n .filter((range) => !isEmptyRange(range))\n .map((range) => text.slice(rangeFrom(range), rangeTo(range)))\n .join('\\n')\n}\n\nfunction onCopy(event: ClipboardEvent) {\n const text = selectedText()\n if (!text) return\n event.preventDefault()\n event.clipboardData?.setData('text/plain', text)\n}\n\nfunction onCut(event: ClipboardEvent) {\n onCopy(event)\n if (!event.defaultPrevented || target.readonly) return\n dispatch(transaction().replaceSelection('').setMeta({ action: 'cut' }))\n}\n\nfunction onPaste(event: ClipboardEvent) {\n event.preventDefault()\n pasteText(event.clipboardData?.getData('text/plain'))\n}\n\nfunction pasteText(text: string | undefined) {\n if (!text || target.readonly) return\n const { ranges } = state.value.selection\n const parts = splitLines(text)\n // One line per cursor when the counts match.\n const spread = ranges.length > 1 && parts.length === ranges.length\n dispatch(\n transaction()\n .replaceSelection(spread ? (_, i) => parts[i]! : text)\n .setMeta({ action: 'paste' }),\n )\n}\n\n// ---------------------------------------------------------------- pointer\n\n/** The text position under a point in the page, clamped to the text. */\nfunction posAtCoords(point: { x: number; y: number }) {\n const rect = content.value?.getBoundingClientRect()\n if (!rect) return 0\n const { n, sub } = layout.value.lineAtRow(rowAtY(point.y - rect.top))\n const line = state.value.doc.line(n)\n return line.from + colAt(n, line.text, sub, point.x - rect.left - pad.x)\n}\n\nfunction coordsAtPos(pos: number) {\n const rect = content.value?.getBoundingClientRect()\n if (!rect) return null\n const line = doc.value.lineAt(pos)\n if (!isShown(line.number)) return null\n const at = place(line.number, line.text, pos - line.from)\n const top = rect.top + at.top\n return { left: rect.left + pad.x + at.x, top, bottom: top + lineHeight.value }\n}\n\ntype Unit = 'char' | 'word' | 'line'\n\n/** The span of one unit around a position: itself, its word or its whole line. */\nfunction unitAt(pos: number, unit: Unit) {\n if (unit === 'char') return { from: pos, to: pos }\n const line = doc.value.lineAt(pos)\n if (unit === 'line') return { from: line.from, to: Math.min(doc.value.length, line.to + 1) }\n const word = wordAt(line.text, pos - line.from)\n return { from: line.from + word.from, to: line.from + word.to }\n}\n\nlet drag: {\n unit: Unit\n start: { from: number; to: number }\n x: number\n y: number\n frame: number\n hold: ReturnType<typeof holdPointer>\n /** Where a column selection (Alt + Shift drag) started. */\n column?: { n: number; x: number }\n /** A finger drags: from a handle, or after a long press. */\n touch?: boolean\n /** A handle under a lone cursor moves the cursor, selecting nothing. */\n caret?: boolean\n /** From the finger to the text point it moves, so the handle doesn't jump under the finger. */\n offset?: { x: number; y: number }\n} | null = null\n\n/** The line and the x inside the text (from the line's start) under a point in the page. */\nfunction lineAtCoords(point: { x: number; y: number }) {\n const rect = content.value!.getBoundingClientRect()\n const { n } = layout.value.lineAtRow(rowAtY(point.y - rect.top))\n return { n, x: Math.max(0, point.x - rect.left - pad.x) }\n}\n\n/** A rectangle of text from the drag's start to `point`: one range per line, cut at the same x. */\nfunction extendColumns(point: { x: number; y: number }) {\n const start = drag!.column!\n const end = lineAtCoords(point)\n const ranges: CodeRange[] = []\n const step = end.n >= start.n ? 1 : -1\n for (let n = start.n; ; n += step) {\n if (!layout.value.shown(n) && n !== end.n) continue\n const line = doc.value.line(n)\n const anchor = line.from + measure.col(line.text, start.x)\n const head = line.from + measure.col(line.text, end.x)\n // Lines too short to reach the rectangle are left out, unless the rectangle is only a line of cursors.\n if (anchor !== head || start.x === end.x || measure.x(line.text, line.text.length) >= start.x)\n ranges.push({ anchor, head })\n if (n === end.n) break\n }\n if (!ranges.length) return\n dispatch(\n transaction()\n .select(normalizeSelection({ ranges, main: ranges.length - 1 }, doc.value.length))\n .setMeta({ scroll: false }),\n )\n}\n\nfunction extendTo(point: { x: number; y: number }) {\n if (!drag) return\n if (drag.column) return extendColumns(point)\n const { offset } = drag\n const pos = posAtCoords(offset ? { x: point.x - offset.x, y: point.y - offset.y } : point)\n if (drag.caret) {\n dispatch(transaction().select(pos).setMeta({ scroll: false }))\n caretHandle.value = true\n return\n }\n // A handle keeps at least one character selected.\n if (offset && pos === drag.start.from) return\n const at = unitAt(pos, drag.unit)\n const { start } = drag\n const range =\n at.from < start.from\n ? { anchor: start.to, head: at.from }\n : { anchor: start.from, head: Math.max(at.to, start.to) }\n if (drag.unit === 'char') {\n range.anchor = start.from\n range.head = pos\n }\n const selection = state.value.selection\n const ranges = selection.ranges.slice()\n ranges[selection.main] = range\n dispatch(transaction().select({ ranges, main: selection.main }).setMeta({ scroll: false }))\n}\n\n/** Scrolls while a drag is held past the top or bottom edge. */\nfunction autoScroll() {\n if (!drag || !scroller.value) return\n const rect = scroller.value.getBoundingClientRect()\n const dy = drag.y < rect.top ? drag.y - rect.top : drag.y > rect.bottom ? drag.y - rect.bottom : 0\n const dx =\n drag.x < rect.left + gutterWidth.value\n ? drag.x - rect.left - gutterWidth.value\n : drag.x > rect.right\n ? drag.x - rect.right\n : 0\n if (dy || dx) {\n scroller.value.scrollTop += dy / 2\n scroller.value.scrollLeft += dx / 2\n onScroll()\n extendTo(drag)\n }\n drag.frame = requestAnimationFrame(autoScroll)\n}\n\nfunction startDrag(\n event: PointerEvent | { clientX: number; clientY: number },\n unit: Unit,\n start: { from: number; to: number },\n hold = holdPointer(event as PointerEvent, root.value),\n touch?: { caret?: boolean; offset?: { x: number; y: number } },\n) {\n drag = {\n unit,\n start,\n x: event.clientX,\n y: event.clientY,\n frame: 0,\n hold,\n touch: !!touch,\n ...touch,\n }\n touchDrag.value = !!touch\n drag.hold.grab()\n drag.frame = requestAnimationFrame(autoScroll)\n window.addEventListener('pointermove', onDragMove)\n window.addEventListener('pointerup', endDrag)\n window.addEventListener('pointercancel', endDrag)\n}\n\nfunction onDragMove(event: PointerEvent) {\n if (!drag) return\n drag.x = event.clientX\n drag.y = event.clientY\n extendTo(drag)\n}\n\nfunction endDrag() {\n if (!drag) return\n cancelAnimationFrame(drag.frame)\n drag.hold.release()\n const { touch, caret } = drag\n drag = null\n touchDrag.value = false\n // A selection made by finger offers what can be done with it.\n if (touch && !caret && !isEmptyRange(mainRange(state.value.selection))) menuOpen.value = true\n window.removeEventListener('pointermove', onDragMove)\n window.removeEventListener('pointerup', endDrag)\n window.removeEventListener('pointercancel', endDrag)\n}\n\nfunction focusInput() {\n if (props.disabled) return\n input.value?.focus({ preventScroll: true })\n}\n\n/** Selects the unit at `pos`: alone, extending the main range (`extend`), or as one more range (`add`). */\nfunction select(unit: Unit, pos: number, extend: boolean, add = false) {\n const at = unitAt(pos, unit)\n const { selection } = state.value\n const main = mainRange(selection)\n const range = extend\n ? { anchor: main.anchor, head: pos < main.anchor ? at.from : at.to }\n : { anchor: at.from, head: at.to }\n const next = add\n ? { ranges: [...selection.ranges, range], main: selection.ranges.length }\n : { ranges: [range], main: 0 }\n dispatch(\n transaction().select(normalizeSelection(next, doc.value.length)).setMeta({ scroll: false }),\n )\n // A drag goes on from the anchor kept by Shift, or from the unit pressed.\n return extend ? { from: main.anchor, to: main.anchor } : at\n}\n\n/** A tap that may turn into a scroll or a long press; touches only act once they end in place. */\nlet touch: {\n x: number\n y: number\n timer: number\n pointer: number\n /** Taken at the press, so a long press can keep the page from scrolling. */\n hold: ReturnType<typeof holdPointer>\n} | null = null\n\n/** A finger or pen on a pressable gutter cell, which presses if it lifts in place. */\nlet cellTap: { x: number; y: number; pointer: number; column: number; line: number } | null = null\n\n/**\n * A tap on a gutter cell lifted in place. A marker still out of sight (shown\n * on hover, which a finger can't do) isn't pressed yet: the cursor moves to\n * its line, which shows it, and the next tap presses it.\n */\nfunction endCellTap(event: PointerEvent) {\n const tap = cellTap\n cellTap = null\n if (!tap) return\n const column = gutterColumns.value[tap.column]\n if (!column?.onPress || props.disabled) return\n const marker = gutterMarkers.value[tap.column]?.get(tap.line)\n if (marker?.visible === 'hover' && !(focused.value && activeLineNumber.value === tap.line)) {\n touchUi.value = true\n select('char', doc.value.line(tap.line).from, false)\n focusInput()\n return\n }\n column.onPress(tap.line, event)\n}\n\n/** The fold toggle or folded marker under a pointer, as the line it belongs to. */\nfunction foldTarget(event: Event) {\n const el = (event.target as Element | null)?.closest?.('[data-fold], [data-unfold]')\n if (!el) return null\n const unfold = el.getAttribute('data-unfold')\n return unfold\n ? { n: Number(unfold), folded: true }\n : { n: Number(el.getAttribute('data-fold')), folded: el.classList.contains('is-folded') }\n}\n\nfunction onPointerDown(event: PointerEvent, area: 'text' | 'gutter') {\n if (event.button !== 0 || props.disabled) return\n const cell = (event.target as Element | null)?.closest?.('[data-gutter-cell]')\n const c = Number(cell?.getAttribute('data-gutter-cell'))\n const column = cell && gutterColumns.value[c]\n if (column?.onPress) {\n event.preventDefault()\n event.stopPropagation()\n const line = Number(cell!.getAttribute('data-line'))\n // A finger or pen presses once it lifts in place: dragging from here scrolls.\n if (event.pointerType === 'touch' || event.pointerType === 'pen') {\n onPointerCancel()\n cellTap = { x: event.clientX, y: event.clientY, pointer: event.pointerId, column: c, line }\n return\n }\n column.onPress(line, event)\n return\n }\n const fold = foldTarget(event)\n if (fold) {\n event.preventDefault()\n event.stopPropagation()\n toggleFold(fold.n, fold.folded)\n return\n }\n const pos = posAtCoords({ x: event.clientX, y: event.clientY })\n // A click on a problem's icon shows it; a finger's tap does, once it ends in place.\n const iconLine = area === 'gutter' ? problemIconLine(event) : null\n if (iconLine !== null && event.pointerType === 'mouse') {\n event.preventDefault()\n showLineProblems(iconLine)\n return\n }\n if (event.pointerType !== 'mouse') {\n onPointerCancel()\n const x = event.clientX\n const y = event.clientY\n touch = {\n x,\n y,\n pointer: event.pointerId,\n // Lets go when the finger lifts unheard (Safari can send its `pointerup` to a removed line).\n hold: holdPointer(event, root.value, () => {\n onPointerCancel()\n endDrag()\n }),\n // A long press selects the word under the finger; sliding on from there selects word by word.\n timer: window.setTimeout(() => {\n if (!touch) return\n const { hold } = touch\n touch = null\n touchUi.value = true\n const unit: Unit = area === 'gutter' ? 'line' : 'word'\n const at = select(unit, pos, false)\n focusInput()\n startDrag({ clientX: x, clientY: y }, unit, at, hold, {})\n }, 450),\n }\n return\n }\n touchUi.value = false\n menuOpen.value = false\n closeProblems()\n event.preventDefault()\n focusInput()\n // Alt + Shift drag selects a rectangle, one range per line.\n if (event.altKey && event.shiftKey && area === 'text') {\n startDrag(event, 'char', { from: pos, to: pos })\n drag!.column = lineAtCoords({ x: event.clientX, y: event.clientY })\n extendColumns({ x: event.clientX, y: event.clientY })\n return\n }\n const count = countClick(event)\n const unit: Unit = area === 'gutter' || count === 3 ? 'line' : count === 2 ? 'word' : 'char'\n // Alt + click adds a cursor; dragging from there selects with it.\n startDrag(event, unit, select(unit, pos, event.shiftKey, event.altKey && !event.shiftKey))\n}\n\n/**\n * Counts quick clicks in one spot ourselves: a `pointerdown`'s `detail` is\n * 0 in some browsers, and the `mousedown` that has it is held back here.\n */\nlet lastClick = { time: 0, x: 0, y: 0, count: 0 }\nfunction countClick(event: PointerEvent) {\n const near =\n Math.abs(event.clientX - lastClick.x) < 4 && Math.abs(event.clientY - lastClick.y) < 4\n const count = near && event.timeStamp - lastClick.time < 500 ? (lastClick.count % 3) + 1 : 1\n lastClick = { time: event.timeStamp, x: event.clientX, y: event.clientY, count }\n return count\n}\n\nfunction onPointerMove(event: PointerEvent) {\n if (cellTap && event.pointerId === cellTap.pointer) {\n if (Math.hypot(event.clientX - cellTap.x, event.clientY - cellTap.y) > 8) cellTap = null\n return\n }\n if (!touch || event.pointerId !== touch.pointer) return\n // Moving before the long press is a scroll, which the page goes on with.\n if (Math.hypot(event.clientX - touch.x, event.clientY - touch.y) > 8) onPointerCancel()\n}\n\nfunction onPointerUp(event: PointerEvent, area: 'text' | 'gutter') {\n if (cellTap && event.pointerId === cellTap.pointer) return endCellTap(event)\n if (!touch || event.pointerId !== touch.pointer) return\n onPointerCancel()\n const iconLine = area === 'gutter' ? problemIconLine(event) : null\n if (iconLine !== null) return showLineProblems(iconLine)\n const pos = posAtCoords({ x: event.clientX, y: event.clientY })\n const main = mainRange(state.value.selection)\n // A tap on the cursor itself opens the toolbar, or puts it away.\n const onCursor =\n area === 'text' && focused.value && isEmptyRange(main) && main.head === pos && caretHandle.value\n const wasOpen = menuOpen.value\n // A problem under the cursor is shown first; a tap with it already shown brings the toolbar.\n const showsProblem = area === 'text' && problemsAt(pos).length > 0 && !problemBox.value\n touchUi.value = true\n select(area === 'gutter' ? 'line' : 'char', pos, false)\n caretHandle.value = area === 'text'\n menuOpen.value = area === 'gutter' || (onCursor && !wasOpen && !showsProblem)\n // A tap on a problem shows it, the way hovering does with a mouse.\n if (area === 'text' && !menuOpen.value) showInfo(pos, false)\n focusInput()\n}\n\nfunction onPointerCancel() {\n cellTap = null\n if (touch) {\n clearTimeout(touch.timer)\n touch.hold.release()\n }\n touch = null\n}\n\n// ---------------------------------------------------------------- touch: handles, toolbar, magnifier\n\n/** The part of the content in view, in its own px. */\nfunction visibleBox() {\n const top = scrollTop.value + (clip.value?.top ?? 0)\n const bottom = scrollTop.value + (clip.value?.bottom ?? viewHeight.value)\n const left = scrollLeft.value\n return { top, bottom, left, right: left + Math.max(0, viewWidth.value - gutterWidth.value) }\n}\n\n/** Where a position is drawn in the content, when its line is in view. */\nfunction pointOf(pos: number) {\n const line = doc.value.lineAt(pos)\n if (!isShown(line.number)) return null\n const at = place(line.number, lineText(line.number), pos - line.from)\n return { x: pad.x + at.x, top: at.top, sub: at.sub, n: line.number }\n}\n\ntype HandleKind = 'start' | 'end' | 'caret'\n\n/** Handles under the ends of the selection, or under a lone cursor right after a tap. */\nconst handles = computed(() => {\n void metrics.value\n if (!touchUi.value || !focused.value || preview.value || props.disabled) return []\n const main = mainRange(state.value.selection)\n const ends: Array<[HandleKind, number]> = isEmptyRange(main)\n ? caretHandle.value && !props.readonly\n ? [['caret', main.head]]\n : []\n : [\n ['start', rangeFrom(main)],\n ['end', rangeTo(main)],\n ]\n const out: Array<{ kind: HandleKind; left: number; top: number }> = []\n for (const [kind, pos] of ends) {\n const inside = pointOf(pos)\n // Above the page, a handle shows only while its end is in the editor's view.\n const at = inside && floatingTarget.value ? toPage(inside) : inside\n if (at) out.push({ kind, left: Math.round(at.x), top: Math.round(at.top + lineHeight.value) })\n }\n return out\n})\n\n/** A handle pressed but not moved yet: a press that stays put is a tap or a long press on the text below. */\nlet handlePress: {\n kind: HandleKind\n x: number\n y: number\n pointer: number\n hold: ReturnType<typeof holdPointer>\n timer: number\n} | null = null\n\nfunction onHandleDown(event: PointerEvent, kind: HandleKind) {\n if (event.button !== 0) return\n event.preventDefault()\n event.stopPropagation()\n onPointerCancel()\n endHandlePress()\n const hold = holdPointer(event, root.value, () => {\n clearHandlePress()\n endDrag()\n })\n hold.grab()\n handlePress = {\n kind,\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n hold,\n // The handle under a lone cursor reaches over the next line; held there, the press is for that line's text.\n timer:\n kind === 'caret'\n ? window.setTimeout(() => {\n if (!handlePress) return\n const { x, y } = handlePress\n const taken = handlePress.hold\n clearHandlePress()\n const at = select('word', posAtCoords({ x, y }), false)\n startDrag({ clientX: x, clientY: y }, 'word', at, taken, {})\n }, 450)\n : 0,\n }\n window.addEventListener('pointermove', onHandleMove)\n window.addEventListener('pointerup', onHandleUp)\n window.addEventListener('pointercancel', endHandlePress)\n}\n\nfunction clearHandlePress() {\n if (handlePress) clearTimeout(handlePress.timer)\n handlePress = null\n window.removeEventListener('pointermove', onHandleMove)\n window.removeEventListener('pointerup', onHandleUp)\n window.removeEventListener('pointercancel', endHandlePress)\n}\n\nfunction endHandlePress() {\n handlePress?.hold.release()\n clearHandlePress()\n}\n\nfunction onHandleMove(event: PointerEvent) {\n const press = handlePress\n if (!press || event.pointerId !== press.pointer) return\n if (Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) return\n const { kind, hold, x, y } = press\n clearHandlePress()\n const main = mainRange(state.value.selection)\n const pos = kind === 'start' ? rangeFrom(main) : kind === 'end' ? rangeTo(main) : main.head\n const fixed = kind === 'start' ? rangeTo(main) : kind === 'end' ? rangeFrom(main) : pos\n const at = coordsAtPos(pos)\n if (!at) return hold.release()\n // The end being dragged becomes the head, so the drag moves it.\n if (kind !== 'caret') dispatch(transaction().select(fixed, pos).setMeta({ scroll: false }))\n menuOpen.value = false\n // From where the finger went down, so the handle keeps its place under it.\n const offset = { x: x - at.left, y: y - (at.top + lineHeight.value / 2) }\n startDrag(event, 'char', { from: fixed, to: fixed }, hold, { caret: kind === 'caret', offset })\n onDragMove(event)\n}\n\nfunction onHandleUp(event: PointerEvent) {\n const press = handlePress\n if (!press || event.pointerId !== press.pointer) return\n endHandlePress()\n if (press.kind !== 'caret') return\n // The handle reaches over the next line: a tap there is for that line's text, as if the handle were not there.\n const pos = posAtCoords({ x: event.clientX, y: event.clientY })\n const line = doc.value.lineAt(pos).number\n if (line !== doc.value.lineAt(mainRange(state.value.selection).head).number) {\n select('char', pos, false)\n menuOpen.value = false\n showInfo(pos, false)\n return focusInput()\n }\n // A tap on the handle under the cursor opens the toolbar, or puts it away.\n menuOpen.value = !menuOpen.value\n}\n\n/** Room between the toolbar or magnifier and what they point at. */\nconst GAP = 8\n/** How high a handle reaches below its line, which the toolbar keeps clear of. */\nconst HANDLE = 24\n\nconst menuEl = ref<HTMLElement>()\nconst menuSize = ref({ width: 0, height: 0 })\nconst canPaste = typeof navigator !== 'undefined' && !!navigator.clipboard?.readText\n\n/** The toolbar's buttons for the selection now. */\nconst menuItems = computed(() => {\n if (!menuOpen.value || !focused.value || props.disabled) return []\n const m = messages.value\n const main = mainRange(state.value.selection)\n const empty = isEmptyRange(main)\n const editable = !target.readonly\n const items: Array<{ key: string; label: string; run: () => void }> = []\n if (!empty && editable) items.push({ key: 'cut', label: m.cut, run: () => copySelection(true) })\n if (!empty) items.push({ key: 'copy', label: m.copy, run: () => copySelection(false) })\n if (editable && canPaste) items.push({ key: 'paste', label: m.paste, run: pasteFromClipboard })\n if (rangeFrom(main) > 0 || rangeTo(main) < doc.value.length)\n items.push({\n key: 'all',\n label: m.selectAll,\n run: () => {\n run(selectAll)\n menuOpen.value = true\n },\n })\n for (const extension of extensions.value) {\n if (!extension.menu) continue\n extension.menu(context).forEach((item, i) =>\n items.push({\n key: `${extension.name}/${i}`,\n label: item.label,\n run: () => {\n menuOpen.value = false\n item.run(context)\n },\n }),\n )\n }\n return items\n})\n\n// Above the selection; below it (past its handle) when there is no room; always in view.\nconst menuStyle = computed(() => {\n if (!menuItems.value.length) return null\n const main = mainRange(state.value.selection)\n let start = pointOf(rangeFrom(main))\n let end = pointOf(rangeTo(main))\n let view = visibleBox()\n let frame = view\n if (floatingTarget.value) {\n start = start && toPage(start) && { ...start, ...toPage(start)! }\n end = end && toPage(end) && { ...end, ...toPage(end)! }\n view = pageBox()\n frame = frameInPage()\n }\n if (!start && !end) return null\n const { width, height } = menuSize.value\n const lh = lineHeight.value\n const sameRow = start && end && start.top === end.top\n const x = sameRow ? (start!.x + end!.x) / 2 : (frame.left + frame.right) / 2\n const above = start ? start.top - GAP - height : -Infinity\n const below = (end ?? start)!.top + lh + HANDLE + GAP\n let top = above >= view.top + GAP ? above : below\n top = Math.max(view.top + GAP, Math.min(top, view.bottom - height - GAP))\n const left = Math.max(view.left + GAP, Math.min(x - width / 2, view.right - width - GAP))\n return { transform: `translate(${Math.round(left)}px, ${Math.round(top)}px)` }\n})\n\nwatch(\n [menuEl, menuItems],\n () => {\n const el = menuEl.value\n if (el) menuSize.value = { width: el.offsetWidth, height: el.offsetHeight }\n },\n { flush: 'post' },\n)\n\n/** Copies through the textarea, which hands the selection to the copy event. */\nfunction copyFromInput() {\n focusInput()\n document.execCommand('copy')\n}\n\nfunction writeClipboard(text: string) {\n const fallback = copyFromInput\n if (navigator.clipboard?.writeText) navigator.clipboard.writeText(text).catch(fallback)\n else fallback()\n}\n\nfunction copySelection(cut: boolean) {\n const text = selectedText()\n if (!text) return\n writeClipboard(text)\n if (cut && !target.readonly)\n dispatch(transaction().replaceSelection('').setMeta({ action: 'cut' }))\n menuOpen.value = false\n}\n\nfunction pasteFromClipboard() {\n menuOpen.value = false\n navigator.clipboard\n .readText()\n .then((text) => pasteText(text))\n .catch(() => {})\n}\n\n/** The editor's variables the boxes use, carried to them when they are drawn above the page. */\nconst FRAME_VARS = [\n '--dou-code-editor-font-size',\n '--dou-code-editor-line-height',\n '--dou-code-editor-bg',\n '--dou-code-editor-error',\n '--dou-code-editor-warning',\n '--dou-code-editor-info',\n '--dou-code-editor-selection',\n] as const\nconst frameVars = shallowRef<Record<string, string>>({})\n/** The editor's font, for the magnifier when it is drawn above the page. */\nconst frameFont = shallowRef<Record<string, string>>({})\nfunction readFrameFont() {\n const el = root.value\n if (!el) return\n const style = getComputedStyle(el)\n const vars: Record<string, string> = {}\n for (const name of FRAME_VARS) {\n const value = style.getPropertyValue(name).trim()\n if (value) vars[name] = value\n }\n frameVars.value = vars\n frameFont.value = {\n fontFamily: style.fontFamily,\n fontSize: style.fontSize,\n '--dou-code-editor-line-height': `${lineHeight.value}px`,\n '--dou-code-editor-tab-size': String(props.tabSize),\n }\n}\n\n/** The magnifier over a finger dragging the selection: the row at the moving end, larger. */\nconst MAGNIFIER = { width: 128, scale: 1.5 }\nconst magnifier = computed(() => {\n if (!touchDrag.value) return null\n void metrics.value\n const head = mainRange(state.value.selection).head\n const inside = pointOf(head)\n if (!inside) return null\n const row = rows.value.find((r) => r.n === inside.n)\n if (!row) return null\n const outside = !!floatingTarget.value\n const page = outside ? toPage(inside) : inside\n if (!page) return null\n const at = { ...inside, x: page.x, top: page.top }\n const lh = lineHeight.value\n const height = Math.round(lh * MAGNIFIER.scale) + 8\n const view = outside ? pageBox() : visibleBox()\n const { width } = MAGNIFIER\n const above = at.top - GAP - height\n const top = above >= view.top + 4 ? above : at.top + lh + HANDLE + GAP\n const left = Math.max(view.left + 4, Math.min(at.x - width / 2, view.right - width - 4))\n const parts = row.wrapped.breaks.length\n ? rowParts(row, at.sub)\n : row.tokens || row.marks || row.inlines\n ? partsOf(row)\n : ([[row.text, null]] as Part[])\n // The text, scaled from the row's left edge, slid so the moving end sits under the caret.\n const x = inside.x - pad.x\n const caret = Math.max(4, Math.min(width - 4, at.x - left))\n return {\n parts,\n inlines: row.inlines ?? [],\n indent: at.sub ? row.wrapped.indent : 0,\n style: {\n transform: `translate(${Math.round(left)}px, ${Math.round(top)}px)`,\n height: `${height}px`,\n // Above the page, it takes the editor's font with it.\n ...(outside ? frameFont.value : null),\n },\n textStyle: {\n transform: `translateX(${caret - x * MAGNIFIER.scale}px) scale(${MAGNIFIER.scale})`,\n },\n caret,\n }\n})\n\n// ---------------------------------------------------------------- touch: keyboard\n\nconst keysList = computed(() => (Array.isArray(props.keys) ? props.keys : undefined))\nconst keysEditor = { run }\nconst { next: nextZIndex } = useZIndex()\nconst keysZIndex = ref<number>()\nwatch(showKeys, (shown) => {\n if (shown) keysZIndex.value = nextZIndex()\n})\n/**\n * The bar of keys sits in the page below the editor, and scrolls with it:\n * it never follows the keyboard, whose bars and panels each browser draws\n * its own way. A finger moves it anywhere by its grip, and it keeps that\n * place by the editor while the editor is in use.\n */\nconst KEYS_HEIGHT = 44\nconst KEYS_GAP = 8\nconst keysEl = ref<HTMLElement>()\n/** Where the bar is, from the editor's top left corner; `null` until it first shows. */\nconst keysAt = ref<{ x: number; y: number } | null>(null)\n/** Whether a finger or a key moved the bar: then it stays put, even as the keyboard comes up. */\nlet keysMoved = false\nconst keysShift = ref({ x: 0, y: 0 })\nfunction readKeysShift() {\n const el = keysEl.value\n if (!el) return\n const rect = el.getBoundingClientRect()\n const at = keysClient.value\n if (!at) return\n // Moves the bar so that it lands where it is placed in the window, wherever its box starts.\n keysShift.value = {\n x: keysShift.value.x + at.x - rect.left,\n y: keysShift.value.y + at.y - rect.top,\n }\n}\n\n/** The editor's box in the window, as of the last scroll. */\nfunction rootInPage() {\n void viewportTick.value\n return root.value?.getBoundingClientRect() ?? null\n}\n\n/** The bar's width: the editor's, within the window. */\nconst keysWidth = computed(() => {\n const rect = rootInPage()\n if (!rect) return 0\n return Math.max(0, Math.min(rect.width, visibleViewport().width - KEYS_GAP * 2))\n})\n\n/** Keeps the bar within the part of the page in view. */\nfunction clampKeys(at: { x: number; y: number }) {\n const rect = rootInPage()\n if (!rect) return at\n const view = visibleViewport()\n const x = rect.left + at.x\n const y = rect.top + at.y\n const left = Math.max(\n view.left + KEYS_GAP,\n Math.min(x, view.left + view.width - keysWidth.value - KEYS_GAP),\n )\n const top = Math.max(\n view.top + KEYS_GAP,\n Math.min(y, view.top + view.height - KEYS_HEIGHT - KEYS_GAP),\n )\n return { x: left - rect.left, y: top - rect.top }\n}\n\n/** Below the editor, a gap apart, or as low as the page in view goes. */\nfunction placeKeys() {\n const rect = rootInPage()\n if (!rect) return\n keysAt.value = clampKeys({ x: 0, y: rect.height + KEYS_GAP })\n}\n\nconst keysClient = computed(() => {\n const rect = rootInPage()\n const at = keysAt.value\n return rect && at ? { x: rect.left + at.x, y: rect.top + at.y } : null\n})\n\nconst keysStyle = computed(() => {\n const at = keysClient.value\n if (!at) return { visibility: 'hidden' as const, zIndex: keysZIndex.value }\n return {\n // Not rounded: the shift is read from the box as drawn, and rounding twice would be a pixel off.\n transform: `translate(${at.x + keysShift.value.x}px, ${at.y + keysShift.value.y}px)`,\n width: `${keysWidth.value}px`,\n zIndex: keysZIndex.value,\n }\n})\n\nwatch(showKeys, (shown) => {\n if (!shown) keysFocused.value = false\n else if (typeof window !== 'undefined') settleKeys()\n})\n\n/**\n * Brings the bar into the page in view: not moved yet, to its place below\n * the editor; moved, only as far as it takes to be seen again.\n */\nfunction settleKeys() {\n if (!showKeys.value) return\n if (keysMoved && keysAt.value) keysAt.value = clampKeys(keysAt.value)\n else placeKeys()\n}\n\n/** How much of the bottom of the page in view the bar takes, when it sits there. */\nfunction keysRoom() {\n const rect = showKeys.value && keysAt.value ? root.value?.getBoundingClientRect() : null\n if (!rect || !keysAt.value) return 0\n const view = visibleViewport()\n const bottom = view.top + view.height\n const top = rect.top + keysAt.value.y\n return top + KEYS_HEIGHT >= bottom - KEYS_GAP - 1 ? bottom - top + KEYS_GAP : 0\n}\n\nconst TABBABLE =\n 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]'\n\n/** Tab out of the bar goes on to what follows the editor; Shift+Tab, or Escape, back into it. */\nfunction onKeysKeydown(event: KeyboardEvent) {\n const bar = keysEl.value\n if (!bar) return\n if (event.key === 'Escape') {\n event.preventDefault()\n input.value?.focus()\n return\n }\n if (event.key !== 'Tab') return\n const inside = [...bar.querySelectorAll<HTMLElement>(TABBABLE)].filter((el) => el.tabIndex >= 0)\n const here = inside.indexOf(document.activeElement as HTMLElement)\n if (event.shiftKey && here <= 0) {\n event.preventDefault()\n input.value?.focus()\n } else if (!event.shiftKey && here === inside.length - 1) {\n event.preventDefault()\n const from = document.activeElement as HTMLElement | null\n for (const el of document.querySelectorAll<HTMLElement>(TABBABLE)) {\n if (\n el.tabIndex < 0 ||\n bar.contains(el) ||\n !root.value ||\n root.value.contains(el) ||\n !(root.value.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING)\n ) {\n continue\n }\n // Hidden ones take no focus: on to the next.\n el.focus()\n if (document.activeElement === el) return\n }\n from?.blur()\n }\n}\n\nfunction onKeysFocusOut(event: FocusEvent) {\n // On to another key of the bar, it stays.\n if (!keysEl.value?.contains(event.relatedTarget as Node | null)) keysFocused.value = false\n}\n// After drawing, from the box as drawn: wherever the page scrolled, the bar's own box starts.\nwatch([showKeys, viewportTick], () => readKeysShift(), { flush: 'post' })\n\n/** A finger on the bar's grip: where it went down, and where the bar was then. */\nlet keysDrag: {\n pointer: number\n x: number\n y: number\n from: { x: number; y: number }\n hold: ReturnType<typeof holdPointer>\n} | null = null\n\nfunction onKeysGripDown(event: PointerEvent) {\n if (event.button !== 0 || !keysAt.value) return\n event.preventDefault()\n const hold = holdPointer(event, keysEl.value, endKeysDrag)\n hold.grab()\n keysDrag = {\n pointer: event.pointerId,\n x: event.clientX,\n y: event.clientY,\n from: keysAt.value,\n hold,\n }\n window.addEventListener('pointermove', onKeysGripMove)\n window.addEventListener('pointerup', endKeysDrag)\n window.addEventListener('pointercancel', endKeysDrag)\n}\n\nfunction onKeysGripMove(event: PointerEvent) {\n const press = keysDrag\n if (!press || event.pointerId !== press.pointer) return\n keysMoved = true\n keysAt.value = clampKeys({\n x: press.from.x + event.clientX - press.x,\n y: press.from.y + event.clientY - press.y,\n })\n}\n\nfunction endKeysDrag() {\n keysDrag?.hold.release()\n keysDrag = null\n window.removeEventListener('pointermove', onKeysGripMove)\n window.removeEventListener('pointerup', endKeysDrag)\n window.removeEventListener('pointercancel', endKeysDrag)\n}\n\n/** The grip moves by the arrow keys too, a step at a time. */\nfunction onKeysGripKey(event: KeyboardEvent) {\n const step = { ArrowUp: [0, -1], ArrowDown: [0, 1], ArrowLeft: [-1, 0], ArrowRight: [1, 0] }[\n event.key\n ]\n if (!step || !keysAt.value) return\n event.preventDefault()\n keysMoved = true\n const by = event.shiftKey ? 40 : 8\n keysAt.value = clampKeys({ x: keysAt.value.x + step[0]! * by, y: keysAt.value.y + step[1]! * by })\n}\n\n/**\n * Keeps the main cursor clear of the phone's keyboard:\n * scrolls the editor when the cursor can move inside it, else the page.\n */\nfunction followViewport() {\n const vv = window.visualViewport\n const el = scroller.value\n if (!vv || !el || !focused.value) return\n const at = coordsAtPos(mainRange(state.value.selection).head)\n if (!at) return\n const lh = lineHeight.value\n // Room below the cursor for its handle too.\n const room = lh / 2 + (handles.value.length ? HANDLE : 0)\n const rect = el.getBoundingClientRect()\n const view = visibleViewport()\n // The bar of keys at the bottom of the view covers what is behind it.\n const covered = keysRoom()\n const bottom = view.top + view.height - covered\n const visibleTop = Math.max(rect.top, view.top)\n const visibleBottom = Math.min(rect.bottom, bottom)\n if (at.bottom + room > visibleBottom && visibleBottom - visibleTop >= lh * 3) {\n el.scrollTop += (at.bottom + room - visibleBottom) / ratio.value\n onScroll()\n } else if (at.top - lh / 2 < visibleTop && visibleBottom - visibleTop >= lh * 3) {\n el.scrollTop -= (visibleTop - at.top + lh / 2) / ratio.value\n onScroll()\n }\n // Whatever the editor couldn't scroll, the page does.\n const after = coordsAtPos(mainRange(state.value.selection).head)\n if (!after || after.bottom + room <= bottom) return\n const before = window.scrollY\n window.scrollBy(0, after.bottom + room - bottom)\n // The bar at the bottom of the view stays there as the page goes up under it.\n if (covered && keysAt.value) {\n keysAt.value = { x: keysAt.value.x, y: keysAt.value.y + window.scrollY - before }\n }\n}\n\n/** How much of the window the keyboard took when last seen. */\nlet keyboardHeight = 0\nfunction readKeyboard() {\n const vv = window.visualViewport\n // Zoomed in, the view is smaller by the zoom, not by a keyboard.\n return vv ? Math.max(0, window.innerHeight - vv.height * vv.scale) : 0\n}\n\n/**\n * Follows the keyboard as it comes up or grows (a row of candidates, another\n * layout), and only then: the view also resizes while the page scrolls, as\n * the browser's own bars shrink and grow, and scrolling the page back to the\n * cursor then would fight the finger.\n */\nfunction onViewportChange() {\n const now = readKeyboard()\n const grew = now > keyboardHeight + 1\n keyboardHeight = now\n if (!grew || fingerScrolling) return\n // The bar first finds its place in view above the keyboard, so the cursor can keep clear of it.\n settleKeys()\n followViewport()\n}\n\n/**\n * A finger scrolls the page, by dragging or by the glide after it: the view\n * resizing meanwhile is the browser's bars, never a reason to scroll back.\n * The browser scrolling to the cursor on its own, as a tap brings the\n * keyboard up, has no finger moving and leaves the editor free to follow.\n */\nlet fingerScrolling = false\nlet pageScrollTimer = 0\nfunction settleLater() {\n clearTimeout(pageScrollTimer)\n pageScrollTimer = window.setTimeout(() => (fingerScrolling = false), 160)\n}\nfunction onPageScroll() {\n if (fingerScrolling) settleLater()\n}\nfunction onFingerMove() {\n fingerScrolling = true\n settleLater()\n}\n\n/** On a touch screen the keyboard comes and goes with focus; the view follows it meanwhile. */\nconst following = computed(() => coarse.value && focused.value)\nfunction unfollow() {\n if (typeof window === 'undefined') return\n const vv = window.visualViewport\n vv?.removeEventListener('resize', onViewportChange)\n window.removeEventListener('scroll', onPageScroll)\n window.removeEventListener('touchmove', onFingerMove)\n clearTimeout(pageScrollTimer)\n fingerScrolling = false\n}\nwatch(following, (on) => {\n const vv = window.visualViewport\n if (on) {\n keyboardHeight = readKeyboard()\n vv?.addEventListener('resize', onViewportChange)\n window.addEventListener('scroll', onPageScroll, { passive: true })\n window.addEventListener('touchmove', onFingerMove, { passive: true })\n } else unfollow()\n})\n\n// ---------------------------------------------------------------- minimap\n\n/** Height of a row in the minimap, and width of a character, in px. */\nconst MINI_ROW = 2\nconst MINI_CELL = 1\n/** The minimap's width, padding included. */\nconst MINI_WIDTH = 96\nconst MINI_PAD = 6\nconst minimapCanvas = ref<HTMLCanvasElement>()\n/** The editor's own width, minimap included. */\nconst rootWidth = ref(0)\nconst minimapOn = computed(() => !!props.minimap && mounted.value && rootWidth.value >= 480)\n\n/** Where the minimap is: the row at its top (fractional), and the part in view as a box. */\nconst minimap = computed(() => {\n if (!minimapOn.value) return null\n const track = viewHeight.value\n const lh = lineHeight.value || 1\n const height = layout.value.total * MINI_ROW\n const textTop = scrollTop.value * ratio.value\n const first = rowAtTextY(Math.max(0, textTop - pad.y))\n const last = rowAtTextY(Math.max(0, textTop + track - pad.y))\n const range = Math.max(1, total.value + pad.y * 2 - track)\n const progress = Math.min(1, Math.max(0, textTop / range))\n const top = height > track ? progress * (height - track) : 0\n const firstFraction = first + ((textTop - pad.y - rowTop(first)) / lh || 0)\n return {\n top,\n track,\n height,\n slider: {\n top: Math.max(0, firstFraction) * MINI_ROW - top,\n height: Math.max(MINI_ROW * 4, (last - first + 1) * MINI_ROW),\n },\n }\n})\n\n/** Whether a character is drawn two cells wide: CJK, Hangul, full-width forms. */\nconst isWideCode = (code: number) =>\n (code >= 0x1100 && code <= 0x115f) ||\n (code >= 0x2e80 && code <= 0xa4cf) ||\n (code >= 0xac00 && code <= 0xd7a3) ||\n (code >= 0xf900 && code <= 0xfaff) ||\n (code >= 0xfe30 && code <= 0xfe4f) ||\n (code >= 0xff00 && code <= 0xff60) ||\n (code >= 0xffe0 && code <= 0xffe6)\n\n/** The token colors, read from the theme when it changes. */\nlet miniColors: { key: string; text: string; types: string[] } | null = null\nfunction minimapColors(canvas: HTMLCanvasElement) {\n const style = getComputedStyle(canvas)\n const key = `${style.color}|${style.getPropertyValue('--dou-color-syntax-keyword')}`\n if (miniColors?.key === key) return miniColors\n const swatch = document.createElement('span')\n swatch.style.display = 'none'\n canvas.parentElement!.append(swatch)\n const types = tokenTypes.map((type) => {\n swatch.style.color = `var(--dou-color-syntax-${type}, currentColor)`\n return getComputedStyle(swatch).color\n })\n swatch.remove()\n miniColors = { key, text: style.color, types }\n return miniColors\n}\n\nlet miniFrame = 0\nfunction drawMinimap() {\n miniFrame = 0\n const canvas = minimapCanvas.value\n const map = minimap.value\n if (!canvas || !map) return\n const dpr = window.devicePixelRatio || 1\n const width = MINI_WIDTH\n const height = map.track\n if (canvas.width !== Math.round(width * dpr) || canvas.height !== Math.round(height * dpr)) {\n canvas.width = Math.round(width * dpr)\n canvas.height = Math.round(height * dpr)\n }\n const ctx = canvas.getContext('2d')\n if (!ctx) return\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n ctx.clearRect(0, 0, width, height)\n const colors = minimapColors(canvas)\n const text = doc.value\n const lay = layout.value\n const hl = highlighter\n const cols = Math.floor((width - MINI_PAD * 2) / MINI_CELL)\n const tab = props.tabSize\n const firstRow = Math.max(0, Math.floor(map.top / MINI_ROW))\n const lastRow = Math.min(lay.total - 1, Math.ceil((map.top + height) / MINI_ROW))\n const mark = MINI_ROW * 0.75\n ctx.globalAlpha = 0.7\n let row = firstRow\n while (row <= lastRow) {\n const { n, sub } = lay.lineAtRow(row)\n const rowText = text.lineText(n)\n const breaks = wrapRows ? wrapOf(rowText).breaks : []\n const tokens = hl && (hl.ready(n) || n - hl.frontier <= SYNTAX_REACH) ? hl.line(n) : null\n const rowsHere = lay.rowsOf(n)\n for (let k = sub; k < rowsHere && row <= lastRow; k++, row++) {\n const start = k ? breaks[k - 1]! : 0\n const end = k < breaks.length ? breaks[k]! : rowText.length\n const y = row * MINI_ROW - map.top\n let col = 0\n let runFrom = -1\n let runColor = ''\n let t = 0\n const flush = () => {\n if (runFrom < 0) return\n ctx.fillStyle = runColor\n ctx.fillRect(MINI_PAD + runFrom * MINI_CELL, y, (col - runFrom) * MINI_CELL, mark)\n runFrom = -1\n }\n for (let i = start; i < end && col < cols; i++) {\n const code = rowText.charCodeAt(i)\n if (code === 32 || code === 9) {\n flush()\n col += code === 9 ? tab - (col % tab) : 1\n continue\n }\n let color = colors.text\n if (tokens) {\n while (t < tokens.length && tokens[t]! <= i) t += 2\n const type = t < tokens.length ? tokens[t + 1]! : -1\n if (type >= 0) color = colors.types[type]!\n }\n if (runFrom >= 0 && color !== runColor) flush()\n if (runFrom < 0) {\n runFrom = col\n runColor = color\n }\n // CJK and other wide characters take two cells, as they do in the text\n col += code >= 0x1100 && isWideCode(code) ? 2 : 1\n }\n flush()\n }\n }\n}\nfunction scheduleMinimap() {\n if (!miniFrame && minimapOn.value) miniFrame = requestAnimationFrame(drawMinimap)\n}\nwatch([minimap, doc, layout, syntaxTick, () => props.tabSize], () => scheduleMinimap(), {\n flush: 'post',\n})\n// The colors come from the theme: switching it (a class on the page, or the system's) draws again.\nlet themeWatch: (() => void) | null = null\nwatch(minimapOn, (on) => {\n themeWatch?.()\n themeWatch = null\n if (!on || typeof MutationObserver === 'undefined') return\n const observer = new MutationObserver(scheduleMinimap)\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['class', 'style', 'data-dou-theme'],\n })\n const dark = matchMedia?.('(prefers-color-scheme: dark)')\n dark?.addEventListener?.('change', scheduleMinimap)\n themeWatch = () => {\n observer.disconnect()\n dark?.removeEventListener?.('change', scheduleMinimap)\n }\n})\nonBeforeUnmount(() => {\n if (miniFrame) cancelAnimationFrame(miniFrame)\n themeWatch?.()\n})\n\n/** Scrolls so that minimap row `row` is in the middle of the view. */\nfunction scrollToMiniRow(row: number) {\n const el = scroller.value\n if (!el) return\n const lay = layout.value\n const at = Math.max(0, Math.min(lay.total - 1, Math.floor(row)))\n const y = pad.y + rowTop(at) - el.clientHeight / 2\n el.scrollTop = Math.max(0, y / ratio.value)\n onScroll()\n}\n\nlet miniDrag: { y: number; scroll: number; pointer: number } | null = null\nfunction onMinimapDown(event: PointerEvent) {\n const map = minimap.value\n const canvas = event.currentTarget as HTMLElement\n if (!map || event.button !== 0) return\n event.preventDefault()\n const box = canvas.getBoundingClientRect()\n const y = event.clientY - box.top\n // A press beside the mark goes there first; dragging then moves the mark.\n if (y < map.slider.top || y > map.slider.top + map.slider.height)\n scrollToMiniRow((map.top + y) / MINI_ROW)\n miniDrag = { y: event.clientY, scroll: scroller.value?.scrollTop ?? 0, pointer: event.pointerId }\n canvas.setPointerCapture?.(event.pointerId)\n}\nfunction onMinimapMove(event: PointerEvent) {\n const map = minimap.value\n const el = scroller.value\n if (!miniDrag || !map || !el || event.pointerId !== miniDrag.pointer) return\n const dy = event.clientY - miniDrag.y\n const max = el.scrollHeight - el.clientHeight\n // The mark follows the pointer: over a short text it moves with the rows, over a long one along the track.\n const room =\n map.height > map.track ? map.track - map.slider.height : map.height - map.slider.height\n el.scrollTop = Math.max(0, Math.min(max, miniDrag.scroll + (dy * max) / Math.max(1, room)))\n onScroll()\n}\nfunction onMinimapUp(event: PointerEvent) {\n if (miniDrag?.pointer === event.pointerId) miniDrag = null\n}\n\n// ---------------------------------------------------------------- scrolling\n\nfunction onScroll() {\n const el = scroller.value\n if (!el) return\n // iOS reports positions past either end while the content bounces back\n const { top, left } = scrollPositionOf(el)\n scrollTop.value = top\n scrollLeft.value = left\n updateClip()\n}\n\n/** Keeps a position in view, with a line of room around it. */\nfunction scrollIntoView(pos = mainRange(state.value.selection).head) {\n const el = scroller.value\n if (!el) return\n const line = doc.value.lineAt(pos)\n const lh = lineHeight.value\n const view = el.clientHeight\n if (view < lh * 3) return\n const at = place(line.number, line.text, pos - line.from)\n const y = at.top - shift.value\n const top = el.scrollTop * ratio.value\n const margin = Math.min(lh, view / 4)\n if (y - margin < top) el.scrollTop = Math.max(0, (y - margin) / ratio.value)\n else if (y + lh + margin > top + view) el.scrollTop = (y + lh + margin - view) / ratio.value\n const x = pad.x + at.x\n const width = el.clientWidth - gutterWidth.value\n if (x - measure.cell * 2 < el.scrollLeft) el.scrollLeft = Math.max(0, x - measure.cell * 4)\n else if (x + measure.cell * 2 > el.scrollLeft + width)\n el.scrollLeft = x + measure.cell * 4 - width\n onScroll()\n}\n\nlet clipFrame = 0\n/** For an editor taller than the window, draws only the lines inside the window. */\nfunction updateClip() {\n const el = scroller.value\n if (!el) return\n if (el.clientHeight <= window.innerHeight) {\n if (clip.value) clip.value = null\n return\n }\n const rect = el.getBoundingClientRect()\n const top = Math.max(0, -rect.top)\n const bottom = Math.max(top, Math.min(el.clientHeight, window.innerHeight - rect.top))\n if (clip.value?.top !== top || clip.value?.bottom !== bottom) clip.value = { top, bottom }\n}\nfunction onWindowScroll(event: Event) {\n if (event.target === scroller.value || clipFrame) return\n clipFrame = requestAnimationFrame(() => {\n clipFrame = 0\n updateClip()\n })\n}\n\nlet resize: ResizeObserver | undefined\nfunction refreshMetrics() {\n measure.refresh(props.tabSize)\n pad.y = measure.padY\n pad.x = measure.padX\n readFrameFont()\n metrics.value++\n syncInput()\n}\n\nwatch(\n () => props.tabSize,\n () => refreshMetrics(),\n)\n\nonMounted(() => {\n refreshMetrics()\n const el = scroller.value!\n viewHeight.value = el.clientHeight\n viewWidth.value = el.clientWidth\n rootWidth.value = root.value?.clientWidth ?? 0\n if (typeof ResizeObserver !== 'undefined') {\n resize = new ResizeObserver(() => {\n viewHeight.value = el.clientHeight\n viewWidth.value = el.clientWidth\n rootWidth.value = root.value?.clientWidth ?? 0\n updateClip()\n })\n resize.observe(el)\n if (root.value) resize.observe(root.value)\n }\n updateClip()\n mounted.value = true\n window.addEventListener('scroll', onWindowScroll, { capture: true, passive: true })\n window.addEventListener('resize', onWindowScroll, { passive: true })\n document.addEventListener('selectionchange', onSelectionChange)\n // Web fonts change the cell width once they arrive.\n document.fonts?.ready.then(() => root.value && refreshMetrics())\n document.fonts?.addEventListener?.('loadingdone', refreshMetrics)\n if (props.autofocus) focusInput()\n for (const extension of extensions.value) startExtension(extension)\n runLint()\n})\n\n/** What each extension's `setup` returned, to run when it goes. */\nconst cleanups = new Map<CodeExtension, () => void>()\nfunction startExtension(extension: CodeExtension) {\n if (cleanups.has(extension)) return\n const cleanup = extension.setup?.(context)\n cleanups.set(extension, typeof cleanup === 'function' ? cleanup : () => {})\n}\nlet restarts: number[] = []\nlet restartWarned = false\n/** An extension made in the template is new on every render, and set up again each time. */\nfunction warnRestarts() {\n if (process.env.NODE_ENV === 'production' || restartWarned) return\n const now = Date.now()\n restarts = [...restarts.filter((time) => now - time < 1000), now]\n if (restarts.length < 4) return\n restartWarned = true\n console.warn(\n '[@dou-ui/code] the extensions keep being set up again, which also starts their state over (such as a shared undo history). Create them once in <script setup> instead of in the template.',\n )\n}\nwatch(extensions, (next) => {\n if (!mounted.value) return\n let restarted = false\n for (const [extension, cleanup] of cleanups)\n if (!next.includes(extension)) {\n cleanup()\n cleanups.delete(extension)\n restarted = true\n }\n for (const extension of next) startExtension(extension)\n if (restarted) warnRestarts()\n})\n\nonBeforeUnmount(() => {\n if (syntaxJob) cancelIdle(syntaxJob)\n clearTimeout(searchTimer)\n resize?.disconnect()\n widgetObserver?.disconnect()\n inlineObserver?.disconnect()\n endDrag()\n onPointerCancel()\n endHandlePress()\n unfollow()\n clearTimeout(lintTimer)\n clearTimeout(problemTimer)\n for (const cleanup of cleanups.values()) cleanup()\n cleanups.clear()\n cancelAnimationFrame(clipFrame)\n window.removeEventListener('scroll', onWindowScroll, { capture: true })\n window.removeEventListener('resize', onWindowScroll)\n document.removeEventListener('selectionchange', onSelectionChange)\n document.fonts?.removeEventListener?.('loadingdone', refreshMetrics)\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n syncInput()\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n // A press or drag never outlives the focus: the page must scroll again once the keyboard is away.\n onPointerCancel()\n endHandlePress()\n endDrag()\n focused.value = false\n menuOpen.value = false\n // A finger's box goes with the keyboard; a mouse's stays while the mouse is over it.\n if (problemBox.value?.keyboard || touchUi.value) closeProblems()\n closeCompletion()\n closeSignature()\n closeHistory()\n if (lazyDirty) {\n lazyDirty = false\n emit('update:modelValue', textOf(doc.value))\n }\n emit('blur', event)\n}\n\nconst api: CodeExtensionContext = {\n get state() {\n return state.value\n },\n get doc() {\n return state.value.doc\n },\n get selection() {\n return state.value.selection\n },\n transact,\n run,\n undo,\n redo,\n get canUndo() {\n if (historyHandler.value) return historyHandler.value.canUndo()\n void historyTick.value\n return history.canUndo\n },\n get canRedo() {\n if (historyHandler.value) return historyHandler.value.canRedo()\n void historyTick.value\n return history.canRedo\n },\n select(anchor, head) {\n const selection = typeof anchor === 'number' ? selectionOf(anchor, head) : anchor\n dispatch(\n transaction()\n .select(normalizeSelection(selection, doc.value.length))\n .setMeta({ scroll: true }),\n )\n },\n scrollIntoView,\n coordsAtPos,\n posAtCoords,\n focus: focusInput,\n blur: () => input.value?.blur(),\n openSearch: (given) => openSearch(false, given),\n closeSearch,\n fold: (line) => folding.fold(line),\n unfold: (line) => folding.unfold(line),\n foldAll: () => folding.foldAll(),\n unfoldAll: () => folding.unfoldAll(),\n get folds() {\n return foldStarts.value\n },\n get diagnostics() {\n return diagnostics.value\n },\n get visible() {\n return { from: visibleFrom.value, to: visibleTo.value }\n },\n get focused() {\n return focused.value\n },\n get messages() {\n return messages.value\n },\n announce,\n relint: (name) => {\n if (mounted.value) runLint(name)\n },\n}\ncontext = api\nprovide(CODE_EDITOR_KEY, api)\n// only for this editor's own widgets: an editor inside one of them reports to no one\nprovide(WIDGET_HEIGHT_KEY, null)\ndefineExpose<CodeEditorExpose>(api)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n ns.is('focused', focused),\n ns.is('readonly', !!readonly),\n ns.is('disabled', !!disabled),\n ns.is('foldable', foldable),\n ns.is('wrap', wrap),\n ns.is('bordered', bordered),\n ]\"\n :style=\"{\n '--dou-code-editor-gutter': `${gutterWidth}px`,\n '--dou-code-editor-gutter-cells': `${gutterCells}px`,\n '--dou-code-editor-tab-size': tabSize,\n }\"\n >\n <div v-if=\"searchOpen\" :class=\"ns.e('search')\">\n <DouFindReplace\n ref=\"panel\"\n :search=\"query.search\"\n :replace=\"query.replace ?? ''\"\n v-model:replacing=\"showReplace\"\n :count=\"matches.length\"\n :current=\"currentMatch\"\n :capped=\"capped\"\n :error=\"searchError && common('findReplace.invalidRegexp')\"\n :readonly=\"readonly || disabled\"\n @update:search=\"query = { ...query, search: $event }\"\n @update:replace=\"query = { ...query, replace: $event }\"\n @next=\"nextMatch()\"\n @previous=\"previousMatch()\"\n @replace-one=\"replaceOne\"\n @replace-all=\"replaceAll\"\n @close=\"closeSearch\"\n >\n <template #options>\n <DouTooltip\n v-for=\"option in searchOptions\"\n :key=\"option.key\"\n :content=\"common(`findReplace.${option.key}`)\"\n >\n <DouToggle\n :pressed=\"!!query[option.key]\"\n size=\"sm\"\n :aria-label=\"common(`findReplace.${option.key}`)\"\n @update:pressed=\"query = { ...query, [option.key]: $event }\"\n >\n <component :is=\"option.icon\" />\n </DouToggle>\n </DouTooltip>\n </template>\n </DouFindReplace>\n </div>\n <div v-if=\"problemMarks.length\" :class=\"ns.e('marks')\" aria-hidden=\"true\">\n <div\n v-for=\"mark in problemMarks\"\n :key=\"`${mark.top}${mark.severity}`\"\n :class=\"[ns.e('mark'), ns.e('problem-mark'), ns.is(mark.severity, true)]\"\n :style=\"{ top: `${mark.top}%` }\"\n />\n </div>\n <div v-if=\"searchMarks.length\" :class=\"ns.e('marks')\" aria-hidden=\"true\">\n <div\n v-for=\"mark in searchMarks\"\n :key=\"`${mark.top}${mark.current ? 'c' : ''}`\"\n :class=\"[ns.e('mark'), ns.is('current', mark.current)]\"\n :style=\"{ top: `${mark.top}%` }\"\n />\n </div>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ announcement }}</div>\n <div v-if=\"panels.top.length\" :class=\"[ns.e('panels'), ns.is('top', true)]\">\n <RenderPart v-for=\"panel in panels.top\" :key=\"panel.key\" :render=\"panel.render\" />\n </div>\n <div :class=\"ns.e('body')\">\n <div ref=\"scroller\" :class=\"ns.e('scroller')\" @scroll.passive=\"onScroll\">\n <div\n :class=\"ns.e('sizer')\"\n :style=\"{\n height: `${sizerHeight}px`,\n minWidth: `max(100%, ${contentWidth + gutterWidth}px)`,\n }\"\n >\n <div\n v-if=\"gutter && (lineNumbers || foldable || gutterCells)\"\n :class=\"ns.e('gutter')\"\n @pointerdown=\"onPointerDown($event, 'gutter')\"\n @pointermove=\"onPointerMove\"\n @pointerup=\"onPointerUp($event, 'gutter')\"\n @pointercancel=\"onPointerCancel\"\n @pointerenter=\"gutterHover = true\"\n @pointerleave=\"gutterHover = false\"\n @mousedown.prevent\n >\n <div\n :class=\"ns.e('numbers')\"\n :style=\"{ transform: `translateY(${yOf(visibleFrom)}px)` }\"\n >\n <div\n v-for=\"row in rows\"\n :key=\"row.n\"\n :class=\"[\n ns.e('number'),\n ns.is('active', row.n === activeLineNumber),\n ns.is('hovered', row.n === hoveredLine),\n ]\"\n :style=\"{\n height: row.wrapped.breaks.length\n ? `${(row.wrapped.breaks.length + 1) * lineHeight}px`\n : undefined,\n marginTop: gapBefore(row.n) ? `${gapBefore(row.n)}px` : undefined,\n }\"\n >\n <span v-if=\"gutterCells\" :class=\"ns.e('cells')\">\n <span\n v-for=\"(column, c) in gutterColumns\"\n :key=\"column.name\"\n :class=\"[\n ns.e('cell'),\n ns.is('on-hover', gutterMarkers[c]?.get(row.n)?.visible === 'hover'),\n gutterMarkers[c]?.get(row.n)?.class,\n ]\"\n :style=\"{ width: `${column.width}px` }\"\n :title=\"gutterMarkers[c]?.get(row.n)?.title\"\n :data-gutter-cell=\"\n column.onPress &&\n (column.pressOn !== 'markers' || gutterMarkers[c]?.has(row.n))\n ? c\n : undefined\n \"\n :data-line=\"row.n\"\n v-bind=\"\n column.onPress && gutterMarkers[c]?.get(row.n) && !disabled\n ? {\n role: 'button',\n // one stop in the tab order: the marker on the cursor's line\n tabindex: row.n === activeLineNumber ? 0 : -1,\n 'aria-label': gutterMarkers[c]!.get(row.n)!.title,\n }\n : { 'aria-hidden': 'true' }\n \"\n @keydown=\"onCellKeydown($event, c, row.n)\"\n >\n <template v-if=\"gutterMarkers[c]?.get(row.n)\">\n <component\n :is=\"gutterMarkers[c]!.get(row.n)!.icon\"\n v-if=\"gutterMarkers[c]!.get(row.n)!.icon\"\n />\n <template v-else>{{ gutterMarkers[c]!.get(row.n)!.text }}</template>\n </template>\n </span>\n </span>\n <span v-if=\"lineNumbers\" aria-hidden=\"true\">{{ row.n }}</span>\n <span\n v-if=\"foldable && (row.folded || foldableLines.has(row.n))\"\n :class=\"[ns.e('fold-toggle'), ns.is('folded', row.folded)]\"\n :data-fold=\"row.n\"\n aria-hidden=\"true\"\n >\n <ChevronRightIcon v-if=\"row.folded\" />\n <ChevronDownIcon v-else />\n </span>\n </div>\n </div>\n </div>\n <div\n ref=\"content\"\n :class=\"ns.e('content')\"\n @pointerdown=\"onPointerDown($event, 'text')\"\n @pointermove=\"(onPointerMove($event), onContentHover($event))\"\n @pointerup=\"onPointerUp($event, 'text')\"\n @pointercancel=\"onPointerCancel\"\n @pointerleave=\"onContentLeave\"\n @mousedown.prevent\n >\n <div ref=\"probe\" :class=\"ns.e('probe')\" aria-hidden=\"true\" />\n <div\n v-if=\"activeLine && activeLineTop !== null && !disabled\"\n :class=\"ns.e('active-line')\"\n :style=\"{\n transform: `translateY(${activeLineTop}px)`,\n height: activeLineRows > 1 ? `${activeLineRows * lineHeight}px` : undefined,\n }\"\n />\n <div :class=\"ns.e('matches')\" aria-hidden=\"true\">\n <div\n v-for=\"box in matchBoxes\"\n :key=\"box.key\"\n :class=\"[ns.e('match'), ns.is('current', box.current)]\"\n :style=\"{\n transform: `translate(${box.left}px, ${box.top}px)`,\n width: `${box.width}px`,\n }\"\n />\n </div>\n <div :class=\"ns.e('brackets')\" aria-hidden=\"true\">\n <div\n v-for=\"box in bracketBoxes\"\n :key=\"box.key\"\n :class=\"[ns.e('bracket'), ns.is('unmatched', !box.matched)]\"\n :style=\"{\n transform: `translate(${box.left}px, ${box.top}px)`,\n width: `${box.width}px`,\n }\"\n />\n </div>\n <div :class=\"ns.e('selections')\" aria-hidden=\"true\">\n <div\n v-for=\"box in selectionBoxes\"\n :key=\"box.key\"\n :class=\"ns.e('selection')\"\n :style=\"{\n transform: `translate(${box.left}px, ${box.top}px)`,\n width: `${box.width}px`,\n }\"\n />\n </div>\n <div\n :class=\"ns.e('lines')\"\n aria-hidden=\"true\"\n :style=\"{ transform: `translateY(${yOf(visibleFrom)}px)` }\"\n >\n <div\n v-for=\"row in rows\"\n :key=\"row.n\"\n v-memo=\"[\n row.text,\n row.tokens,\n row.compose?.join('\\u0000'),\n row.wrapped,\n row.folded,\n row.marksKey,\n row.inlinesKey,\n row.lineClass,\n gapBefore(row.n),\n ]\"\n :class=\"[\n ns.e('line'),\n ns.is('wrapped', !!row.wrapped.breaks.length),\n row.lineClass,\n ]\"\n :style=\"gapBefore(row.n) ? { marginTop: `${gapBefore(row.n)}px` } : undefined\"\n >\n <template v-if=\"row.compose\"\n >{{ row.compose[0] }}<span :class=\"ns.e('compose')\">{{ row.compose[1] }}</span\n >{{ row.compose[2] }}</template\n >\n <template v-else-if=\"row.wrapped.breaks.length\"\n ><div\n v-for=\"(_, sub) in row.wrapped.breaks.length + 1\"\n :key=\"sub\"\n :class=\"ns.e('row')\"\n :style=\"sub ? { paddingLeft: `${row.wrapped.indent}px` } : undefined\"\n >\n <template v-for=\"(part, i) in rowParts(row, sub)\" :key=\"i\"\n ><span\n v-if=\"part[3] !== undefined\"\n :ref=\"\n (el) =>\n observeInline(\n el as Element | null,\n row.inlines![part[3]!]!.key,\n row.inlines![part[3]!]!.width,\n )\n \"\n :class=\"ns.e('inline')\"\n :style=\"\n row.inlines![part[3]!]!.width !== undefined\n ? { width: `${row.inlines![part[3]!]!.width}px` }\n : undefined\n \"\n ><RenderPart :render=\"row.inlines![part[3]!]!.render\" /></span\n ><span\n v-else-if=\"part[1]\"\n :class=\"part[1]\"\n :title=\"part[2]\"\n :style=\"part[4]\"\n >{{ part[0] }}</span\n ><template v-else>{{ part[0] }}</template></template\n ><span\n v-if=\"row.folded && sub === row.wrapped.breaks.length\"\n :class=\"ns.e('fold-marker')\"\n :data-unfold=\"row.n\"\n :title=\"messages.unfold\"\n >⋯</span\n >\n </div></template\n >\n <template v-else-if=\"row.tokens || row.marks || row.inlines\"\n ><template v-for=\"(part, i) in partsOf(row)\" :key=\"i\"\n ><span\n v-if=\"part[3] !== undefined\"\n :ref=\"\n (el) =>\n observeInline(\n el as Element | null,\n row.inlines![part[3]!]!.key,\n row.inlines![part[3]!]!.width,\n )\n \"\n :class=\"ns.e('inline')\"\n :style=\"\n row.inlines![part[3]!]!.width !== undefined\n ? { width: `${row.inlines![part[3]!]!.width}px` }\n : undefined\n \"\n ><RenderPart :render=\"row.inlines![part[3]!]!.render\" /></span\n ><span v-else-if=\"part[1]\" :class=\"part[1]\" :title=\"part[2]\" :style=\"part[4]\">{{\n part[0]\n }}</span\n ><template v-else>{{ part[0] }}</template></template\n ></template\n >\n <template v-else>{{ row.text }}</template>\n <span\n v-if=\"row.folded && !row.wrapped.breaks.length\"\n :class=\"ns.e('fold-marker')\"\n :data-unfold=\"row.n\"\n :title=\"messages.unfold\"\n >⋯</span\n >\n </div>\n </div>\n <div\n v-if=\"placeholder && !doc.length && !composing\"\n :class=\"ns.e('placeholder')\"\n aria-hidden=\"true\"\n >\n {{ placeholder }}\n </div>\n <div v-if=\"focused\" :key=\"blink\" :class=\"ns.e('cursors')\" aria-hidden=\"true\">\n <div\n v-for=\"cursor in cursors\"\n :key=\"cursor.key\"\n :class=\"ns.e('cursor')\"\n :style=\"{ transform: `translate(${cursor.left - 1}px, ${cursor.top}px)` }\"\n />\n </div>\n <!-- The boxes about the text and the touch handles: above the page, or inside the frame. -->\n <Teleport :to=\"floatingTarget || 'body'\" :disabled=\"!floatingTarget\">\n <div\n ref=\"floatingEl\"\n :class=\"[\n ns.e('floating'),\n ns.is('outside', !!floatingTarget),\n ns.is('fixed', !!floatingTarget && anchorMode === 'fixed'),\n ns.is('scrolling', !!floatingTarget && boxScrolling),\n ]\"\n :style=\"\n floatingTarget\n ? {\n ...frameVars,\n zIndex: floatingZ,\n transform: `translate(${layerShift.x}px, ${layerShift.y}px)`,\n }\n : undefined\n \"\n >\n <div\n v-if=\"problemStyle\"\n ref=\"problemEl\"\n :class=\"ns.e('problems')\"\n role=\"group\"\n :aria-label=\"problemBox!.problems.length ? messages.problems : messages.details\"\n :style=\"problemStyle\"\n @pointerdown.stop.prevent\n @pointermove.stop\n @pointerenter=\"keepProblems\"\n @pointerleave=\"onContentLeave\"\n >\n <div\n v-for=\"(item, i) in problemBox!.info\"\n :key=\"`info-${i}`\"\n :class=\"ns.e('hover')\"\n >\n <template v-if=\"typeof item === 'string'\">{{ item }}</template>\n <RenderPart v-else :render=\"item\" />\n </div>\n <div\n v-for=\"(problem, i) in problemBox!.problems\"\n :key=\"i\"\n :class=\"[ns.e('problem-item'), ns.is(problem.severity, true)]\"\n >\n <component\n :is=\"SEVERITY_ICON[problem.severity]\"\n :class=\"ns.e('problem-severity')\"\n />\n <span :class=\"ns.e('problem-message')\"\n >{{ problem.message\n }}<span v-if=\"problem.source\" :class=\"ns.e('problem-source')\">\n {{ problem.source }}</span\n ></span\n >\n </div>\n <div v-if=\"fixes.length\" :class=\"ns.e('fixes')\">\n <button\n v-for=\"(fix, i) in fixes\"\n :key=\"i\"\n type=\"button\"\n tabindex=\"-1\"\n :class=\"[ns.e('fix'), ns.is('active', i === problemBox!.index)]\"\n :aria-current=\"i === problemBox!.index || undefined\"\n @click=\"runFix(i)\"\n >\n {{ fix.action.label }}\n </button>\n </div>\n </div>\n <div\n v-if=\"completionStyle\"\n ref=\"completionEl\"\n :class=\"ns.e('completions')\"\n :style=\"completionStyle\"\n @pointerdown.stop.prevent\n @pointermove.stop\n >\n <div\n :id=\"completionId\"\n ref=\"completionList\"\n :class=\"ns.e('completion-list')\"\n role=\"listbox\"\n :aria-label=\"messages.completions\"\n >\n <div\n v-for=\"(item, i) in completion!.items\"\n :id=\"`${completionId}-${i}`\"\n :key=\"i\"\n role=\"option\"\n :aria-selected=\"i === completion!.index\"\n :class=\"[ns.e('completion'), ns.is('active', i === completion!.index)]\"\n @click=\"acceptCompletion(i)\"\n >\n <component\n :is=\"KIND_ICON[item.option.kind ?? 'text']\"\n :class=\"[ns.e('completion-kind'), ns.is(item.option.kind ?? 'text', true)]\"\n aria-hidden=\"true\"\n />\n <span :class=\"ns.e('completion-label')\"\n ><template v-for=\"(part, j) in labelParts(item)\" :key=\"j\"\n ><mark v-if=\"part[1]\" :class=\"ns.e('completion-match')\">{{\n part[0]\n }}</mark\n ><template v-else>{{ part[0] }}</template></template\n ></span\n >\n <span v-if=\"item.option.detail\" :class=\"ns.e('completion-detail')\">{{\n item.option.detail\n }}</span>\n </div>\n </div>\n <div\n v-if=\"completion!.items[completion!.index]?.option.info\"\n :class=\"ns.e('completion-info')\"\n >\n <template\n v-if=\"typeof completion!.items[completion!.index]!.option.info === 'string'\"\n >{{ completion!.items[completion!.index]!.option.info }}</template\n >\n <RenderPart\n v-else\n :render=\"\n completion!.items[completion!.index]!.option.info as () => VNodeChild\n \"\n />\n </div>\n </div>\n <div\n v-if=\"signatureStyle\"\n ref=\"signatureEl\"\n :class=\"ns.e('signature')\"\n role=\"note\"\n :aria-label=\"messages.signature\"\n :style=\"signatureStyle\"\n @pointerdown.stop.prevent\n >\n <div :class=\"ns.e('signature-label')\">\n <template v-for=\"(part, i) in signatureParts\" :key=\"i\"\n ><span v-if=\"part[1]\" :class=\"ns.e('signature-active')\">{{ part[0] }}</span\n ><template v-else>{{ part[0] }}</template></template\n >\n </div>\n <div v-if=\"signature!.result.info\" :class=\"ns.e('signature-info')\">\n <template v-if=\"typeof signature!.result.info === 'string'\">{{\n signature!.result.info\n }}</template>\n <RenderPart v-else :render=\"signature!.result.info\" />\n </div>\n </div>\n <div\n v-for=\"handle in handles\"\n :key=\"handle.kind\"\n :class=\"[ns.e('handle'), ns.is(handle.kind, true)]\"\n :style=\"{ transform: `translate(${handle.left}px, ${handle.top}px)` }\"\n aria-hidden=\"true\"\n @pointerdown=\"onHandleDown($event, handle.kind)\"\n />\n <div\n v-if=\"magnifier\"\n :class=\"ns.e('magnifier')\"\n :style=\"magnifier.style\"\n aria-hidden=\"true\"\n >\n <div\n :class=\"ns.e('magnifier-text')\"\n :style=\"[magnifier.textStyle, { paddingLeft: `${magnifier.indent}px` }]\"\n >\n <template v-for=\"(part, i) in magnifier.parts\" :key=\"i\"\n ><span\n v-if=\"part[3] !== undefined\"\n :class=\"ns.e('inline')\"\n :style=\"{ width: `${widthOf(magnifier.inlines[part[3]!]!)}px` }\"\n ><RenderPart :render=\"magnifier.inlines[part[3]!]!.render\" /></span\n ><span\n v-else-if=\"part[1]\"\n :class=\"part[1]\"\n :title=\"part[2]\"\n :style=\"part[4]\"\n >{{ part[0] }}</span\n ><template v-else>{{ part[0] }}</template></template\n >\n </div>\n <div\n :class=\"ns.e('magnifier-caret')\"\n :style=\"{ left: `${magnifier.caret - 1}px` }\"\n />\n </div>\n <div\n v-if=\"menuStyle\"\n ref=\"menuEl\"\n :class=\"ns.e('menu')\"\n role=\"toolbar\"\n :aria-label=\"messages.editMenu\"\n :style=\"menuStyle\"\n @pointerdown.stop.prevent\n >\n <button\n v-for=\"item in menuItems\"\n :key=\"item.key\"\n type=\"button\"\n tabindex=\"-1\"\n :class=\"ns.e('menu-button')\"\n @click=\"item.run()\"\n >\n {{ item.label }}\n </button>\n </div>\n </div>\n </Teleport>\n <textarea\n ref=\"input\"\n :class=\"ns.e('input')\"\n :style=\"{\n top: `${inputBox.top}px`,\n left: `${inputBox.left}px`,\n height: `${inputBox.height}px`,\n }\"\n :aria-label=\"ariaLabel\"\n :aria-placeholder=\"placeholder || undefined\"\n :aria-autocomplete=\"hasCompletion ? 'list' : undefined\"\n :aria-controls=\"completion ? completionId : undefined\"\n :readonly=\"readonly\"\n :disabled=\"disabled\"\n wrap=\"off\"\n autocomplete=\"off\"\n autocorrect=\"off\"\n autocapitalize=\"off\"\n spellcheck=\"false\"\n enterkeyhint=\"enter\"\n @keydown=\"onKeydown\"\n @beforeinput=\"onBeforeInput\"\n @input=\"onInput\"\n @compositionstart=\"onCompositionStart\"\n @compositionend=\"onCompositionEnd\"\n @copy=\"onCopy\"\n @cut=\"onCut\"\n @paste=\"onPaste\"\n @focus=\"onFocus\"\n @blur=\"onBlur\"\n />\n <!-- After the textarea, so Escape then Tab reaches what is inside the widgets. -->\n <div\n v-if=\"shownWidgets.length\"\n :class=\"ns.e('widgets')\"\n @pointerdown.stop\n @pointermove.stop\n @mousedown.stop\n >\n <div\n v-for=\"widget in shownWidgets\"\n :key=\"widget.key\"\n :ref=\"(el) => observeWidget(el as Element | null, widget.key)\"\n :class=\"ns.e('widget')\"\n :role=\"widget.label ? 'group' : undefined\"\n :aria-label=\"widget.label\"\n :style=\"{\n transform: `translate(${scrollLeft}px, ${widget.top}px)`,\n width: `${Math.max(0, viewWidth - gutterWidth)}px`,\n }\"\n >\n <RenderPart :render=\"widget.render\" />\n </div>\n </div>\n </div>\n </div>\n </div>\n <div\n v-if=\"minimapOn && minimap\"\n :class=\"ns.e('minimap')\"\n aria-hidden=\"true\"\n @pointerdown=\"onMinimapDown\"\n @pointermove=\"onMinimapMove\"\n @pointerup=\"onMinimapUp\"\n @pointercancel=\"onMinimapUp\"\n >\n <canvas ref=\"minimapCanvas\" :class=\"ns.e('minimap-canvas')\" />\n <div\n :class=\"ns.e('minimap-view')\"\n :style=\"{\n transform: `translateY(${minimap.slider.top}px)`,\n height: `${minimap.slider.height}px`,\n }\"\n />\n </div>\n </div>\n <div v-if=\"panels.bottom.length\" :class=\"[ns.e('panels'), ns.is('bottom', true)]\">\n <RenderPart v-for=\"panel in panels.bottom\" :key=\"panel.key\" :render=\"panel.render\" />\n </div>\n <Teleport to=\"body\">\n <div\n v-if=\"showKeys\"\n ref=\"keysEl\"\n :class=\"[\n ns.e('keys'),\n ns.is('fixed', anchorMode === 'fixed'),\n ns.is('scrolling', boxScrolling),\n ]\"\n :style=\"keysStyle\"\n @focusin=\"keysFocused = true\"\n @focusout=\"onKeysFocusOut\"\n @keydown=\"onKeysKeydown\"\n >\n <button\n type=\"button\"\n :class=\"ns.e('keys-grip')\"\n :aria-label=\"messages.moveKeys\"\n :title=\"messages.moveKeys\"\n aria-keyshortcuts=\"ArrowUp ArrowDown ArrowLeft ArrowRight\"\n @pointerdown=\"onKeysGripDown\"\n @keydown=\"onKeysGripKey\"\n @mousedown.prevent\n >\n <GripVerticalIcon />\n </button>\n <CodeKeys :editor=\"keysEditor\" :keys=\"keysList\" :messages=\"messages\" />\n </div>\n </Teleport>\n </div>\n</template>\n"],"mappings":""}
|