/** * The three editors of the resolve view (M4.8): ours (left, read-only), * the result (middle, editable) and theirs (right, read-only). * * - **Blocks:** built by `merge3` (`diff3.ts`). Non-conflicting changes are * in the result from the start; each conflict is a chunk whose range in * the result starts as the base's lines. * - **Chunks in the result:** a state field keeps each chunk's range, * mapped through every edit (the start sticks before text inserted at it, * the end after, so typing at a chunk's edge extends it). Its state comes * from its text: open while it is the base's, taken from ours or theirs * while it equals that side, edited by hand otherwise. * - **Accepting:** {@link ResolveView.accept} replaces a chunk's range with * that side's lines; it is one undoable change of the result, and undo * opens the chunk again. The side * panes show a button in the gutter at the first line of every open * chunk ("»" left, "«" right); a click accepts it. * - **Colours:** only `--lt-*` tokens: open conflicts tinted with * `--lt-vcs-conflicted`, accepted chunks and non-conflicting changes with * `--lt-vcs-modified`. * - **Navigation:** {@link ResolveView.go} moves to the next or previous * open chunk (wrapping), selects it in the result and scrolls all three * editors to it. */ import { EditorState, RangeSetBuilder, StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; import { Decoration, EditorView, GutterMarker, gutter, type DecorationSet } from "@codemirror/view"; import { basicSetup } from "codemirror"; import { lutraEditorTheme } from "../../editor/extensions"; import { languageExtensions } from "../../editor/language"; import { merge3, resultUnits, splitUnits, type MergeBlock } from "./diff3"; /** Which side a chunk was taken from, or how else it was settled. */ export type ChunkState = "open" | "ours" | "theirs" | "edited"; /** A conflict chunk: its text on each side and its place in each document. */ export interface Chunk { /** Our text. */ ours: string; /** Their text. */ theirs: string; /** Range in the ours document. */ oursFrom: number; /** End in the ours document. */ oursTo: number; /** Range in the theirs document. */ theirsFrom: number; /** End in the theirs document. */ theirsTo: number; } /** A chunk's live range in the result. */ interface Range { /** Start in the result. */ from: number; /** End in the result. */ to: number; } /** A chunk's live range and state in the result. */ export interface Live extends Range { /** Its state, read from the text in its range. */ state: ChunkState; } /** A highlighted range of a side document. */ interface Marked { /** Start. */ from: number; /** End. */ to: number; /** A conflict (else a non-conflicting change). */ conflict: boolean; } /** The laid-out merge: documents, chunks and highlights. */ export interface Layout { /** The ours document. */ ours: string; /** The theirs document. */ theirs: string; /** The initial result. */ result: string; /** The conflict chunks in order. */ chunks: Chunk[]; /** Initial result range of each chunk. */ resultRanges: { from: number; to: number }[]; /** Highlights of the ours document. */ oursMarks: Marked[]; /** Highlights of the theirs document. */ theirsMarks: Marked[]; } /** * Lays out a merge of the three texts. * * @param base - the base text, null when there is none. * @param ours - our text. * @param theirs - their text. */ export function layout(base: string | null, ours: string, theirs: string): Layout { const blocks: MergeBlock[] = merge3(base === null ? null : splitUnits(base), splitUnits(ours), splitUnits(theirs)); const out: Layout = { ours: "", theirs: "", result: "", chunks: [], resultRanges: [], oursMarks: [], theirsMarks: [] }; for (const block of blocks) { const oursText = block.ours.join(""); const theirsText = block.theirs.join(""); const resultText = resultUnits(block).join(""); const oursFrom = out.ours.length; const theirsFrom = out.theirs.length; const resultFrom = out.result.length; out.ours += oursText; out.theirs += theirsText; out.result += resultText; if (block.kind === "conflict") { out.chunks.push({ ours: oursText, theirs: theirsText, oursFrom, oursTo: out.ours.length, theirsFrom, theirsTo: out.theirs.length, }); out.resultRanges.push({ from: resultFrom, to: out.result.length }); } if (block.kind === "conflict" || block.kind === "ours" || block.kind === "both") { out.oursMarks.push({ from: oursFrom, to: out.ours.length, conflict: block.kind === "conflict" }); } if (block.kind === "conflict" || block.kind === "theirs" || block.kind === "both") { out.theirsMarks.push({ from: theirsFrom, to: out.theirs.length, conflict: block.kind === "conflict" }); } } return out; } /** Marks the chunks resolved in a side pane (`true` = open). */ const setOpen = StateEffect.define(); /** Line decorations by class. */ const lineDecos = { conflict: Decoration.line({ class: "lt-merge-conflict" }), change: Decoration.line({ class: "lt-merge-change" }), resolved: Decoration.line({ class: "lt-merge-resolved" }), }; /** * Adds line decorations for the lines a range covers (one line for an * empty range). * * @param doc - the document. * @param from - start of the range. * @param to - end of the range. * @param add - receives each line start. */ function eachLine(doc: Text, from: number, to: number, add: (lineStart: number) => void): void { const first = doc.lineAt(Math.min(from, doc.length)); const last = to > from ? doc.lineAt(Math.min(Math.max(to - 1, from), doc.length)) : first; for (let n = first.number; n <= last.number; n += 1) { add(doc.line(n).from); } } /** * Builds line decorations from ranges. * * @param doc - the document. * @param ranges - ranges with their decoration, in document order. */ function lineSet(doc: Text, ranges: { from: number; to: number; deco: Decoration }[]): DecorationSet { const builder = new RangeSetBuilder(); let last = -1; for (const range of ranges) { eachLine(doc, range.from, range.to, (start) => { if (start > last) { builder.add(start, start, range.deco); last = start; } }); } return builder.finish(); } /** The accept button in a side pane's gutter. */ class AcceptMarker extends GutterMarker { /** * @param glyph - `»` or `«`. * @param label - its accessible name. */ constructor( readonly glyph: string, readonly label: string, ) { super(); } /** @param other - another marker. */ override eq(other: GutterMarker): boolean { return other instanceof AcceptMarker && other.glyph === this.glyph && other.label === this.label; } /** The button. */ override toDOM(): Node { const button = document.createElement("button"); button.type = "button"; button.className = "lt-merge-accept"; button.textContent = this.glyph; button.title = this.label; button.setAttribute("aria-label", this.label); button.tabIndex = -1; return button; } } /** Colours of the three editors, from tokens only. */ export const resolveTheme: Extension = EditorView.theme({ ".lt-merge-conflict": { backgroundColor: "color-mix(in srgb, var(--lt-vcs-conflicted) 18%, var(--lt-editor-bg))" }, ".lt-merge-change": { backgroundColor: "color-mix(in srgb, var(--lt-vcs-modified) 12%, var(--lt-editor-bg))" }, ".lt-merge-resolved": { backgroundColor: "color-mix(in srgb, var(--lt-vcs-modified) 18%, var(--lt-editor-bg))" }, ".lt-merge-accept": { font: "inherit", lineHeight: "1", padding: "0 4px", border: "1px solid var(--lt-border)", borderRadius: "3px", color: "var(--lt-fg)", background: "var(--lt-bg)", cursor: "pointer", }, ".lt-merge-accept:hover": { background: "color-mix(in srgb, var(--lt-accent) 25%, var(--lt-bg))" }, }); /** Labels of the gutter buttons. */ export interface ResolveLabels { /** The ours pane's button. */ acceptOurs: string; /** The theirs pane's button. */ acceptTheirs: string; } /** Where the three editors go and what they report. */ export interface ResolveOptions { /** The file's path, for its language. */ path: string; /** The base text, null when there is none. */ base: string | null; /** Our text. */ ours: string; /** Their text. */ theirs: string; /** Element of the ours editor. */ oursHost: HTMLElement; /** Element of the result editor. */ resultHost: HTMLElement; /** Element of the theirs editor. */ theirsHost: HTMLElement; /** Gutter button labels. */ labels: ResolveLabels; /** Called after every change of a chunk's state, with the open count. */ onChange: (open: number) => void; } /** The three editors of one file. */ export class ResolveView { /** The ours editor. */ readonly oursView: EditorView; /** The result editor. */ readonly resultView: EditorView; /** The theirs editor. */ readonly theirsView: EditorView; /** The laid-out merge. */ readonly layout: Layout; /** The chunk navigated to last; -1 before any. */ current = -1; /** Reports changes. */ private readonly onChange: (open: number) => void; /** The chunks' field in the result. */ private readonly field: StateField; /** Each chunk's initial text in the result (the base's lines). */ private readonly bases: string[]; /** The open flags' field of the side panes. */ private readonly openField: StateField; /** @param options - hosts, texts and callbacks. */ constructor(options: ResolveOptions) { this.onChange = options.onChange; const lay = layout(options.base, options.ours, options.theirs); this.layout = lay; const base = lay.resultRanges.map((r) => lay.result.slice(r.from, r.to)); this.bases = base; const field = StateField.define({ create: () => lay.resultRanges.map((r) => ({ ...r })), update(ranges, tr) { if (!tr.docChanged) { return ranges; } return ranges.map((range) => { const from = tr.changes.mapPos(range.from, -1); return { from, to: Math.max(from, tr.changes.mapPos(range.to, 1)) }; }); }, provide: (f) => EditorView.decorations.from(f, (ranges) => (view: EditorView) => lineSet( view.state.doc, ranges.map((r, i) => ({ from: r.from, to: r.to, deco: view.state.doc.sliceString(r.from, r.to) === base[i] ? lineDecos.conflict : lineDecos.resolved, })), ), ), }); this.field = field; const openField = StateField.define({ create: () => lay.chunks.map(() => true), update(flags, tr) { for (const effect of tr.effects) { if (effect.is(setOpen)) { return effect.value; } } return flags; }, }); this.openField = openField; const language = languageExtensions(options.path); const readOnly = [EditorState.readOnly.of(true), EditorView.editable.of(false)]; const side = (which: "ours" | "theirs"): Extension => { const marks = which === "ours" ? lay.oursMarks : lay.theirsMarks; const marker = new AcceptMarker(which === "ours" ? "»" : "«", which === "ours" ? options.labels.acceptOurs : options.labels.acceptTheirs); const starts = lay.chunks.map((c) => (which === "ours" ? c.oursFrom : c.theirsFrom)); return [ basicSetup, lutraEditorTheme, language, resolveTheme, readOnly, openField, StateField.define({ create: (state) => lineSet( state.doc, marks.map((m) => ({ from: m.from, to: m.to, deco: m.conflict ? lineDecos.conflict : lineDecos.change })), ), update: (set) => set, provide: (f) => EditorView.decorations.from(f), }), gutter({ class: "lt-merge-gutter", lineMarker: (view, line) => { const flags = view.state.field(openField); const index = starts.findIndex( (start, i) => flags[i] === true && view.state.doc.lineAt(Math.min(start, view.state.doc.length)).from === line.from, ); return index >= 0 ? marker : null; }, lineMarkerChange: (update) => update.transactions.some((tr) => tr.effects.some((e) => e.is(setOpen))), domEventHandlers: { mousedown: (view, line) => { const flags = view.state.field(openField); const index = starts.findIndex( (start, i) => flags[i] === true && view.state.doc.lineAt(Math.min(start, view.state.doc.length)).from === line.from, ); if (index < 0) { return false; } this.accept(index, which); return true; }, }, }), ]; }; this.oursView = new EditorView({ parent: options.oursHost, state: EditorState.create({ doc: lay.ours, extensions: side("ours") }) }); this.theirsView = new EditorView({ parent: options.theirsHost, state: EditorState.create({ doc: lay.theirs, extensions: side("theirs") }) }); this.resultView = new EditorView({ parent: options.resultHost, state: EditorState.create({ doc: lay.result, extensions: [ basicSetup, lutraEditorTheme, language, resolveTheme, field, EditorView.updateListener.of((update) => { if (update.docChanged) { this.report(); } }), ], }), }); } /** * The chunks' live ranges and states. A chunk is open while its text is * still the base's, taken from a side while it equals that side's, and * edited otherwise; so undo and redo need no bookkeeping. */ get chunks(): readonly Live[] { const state = this.resultView.state; return state.field(this.field).map((range, i) => { const text = state.doc.sliceString(range.from, range.to); const chunk = this.layout.chunks[i]; const kind: ChunkState = text === this.bases[i] ? "open" : text === chunk?.ours ? "ours" : text === chunk?.theirs ? "theirs" : "edited"; return { ...range, state: kind }; }); } /** How many chunks are still open. */ get open(): number { return this.chunks.filter((c) => c.state === "open").length; } /** The result text. */ get result(): string { return this.resultView.state.doc.toString(); } /** Tells the side panes which chunks are open and reports the count. */ private report(): void { const flags = this.chunks.map((c) => c.state === "open"); for (const view of [this.oursView, this.theirsView]) { const before = view.state.field(this.openField); if (before.length !== flags.length || before.some((f, i) => f !== flags[i])) { view.dispatch({ effects: setOpen.of(flags) }); } } this.onChange(this.open); } /** * Takes one side's text for a chunk. * * @param index - the chunk. * @param side - which side. */ accept(index: number, side: "ours" | "theirs"): void { const live = this.chunks[index]; const chunk = this.layout.chunks[index]; if (!live || !chunk) { return; } const insert = side === "ours" ? chunk.ours : chunk.theirs; this.resultView.dispatch({ changes: { from: live.from, to: live.to, insert }, userEvent: "input.merge", }); this.current = index; } /** * Takes one side's text for every open chunk, last first so earlier * ranges stay valid. * * @param side - which side. */ acceptAll(side: "ours" | "theirs"): void { const open = this.chunks.map((c, i) => ({ c, i })).filter(({ c }) => c.state === "open"); for (const { i } of open.reverse()) { this.accept(i, side); } } /** * Takes one side for the chunk navigated to last, else the first open one. * * @param side - which side. */ acceptCurrent(side: "ours" | "theirs"): void { const chunks = this.chunks; const index = chunks[this.current]?.state === "open" ? this.current : chunks.findIndex((c) => c.state === "open"); if (index >= 0) { this.accept(index, side); } } /** * Moves to the next or previous open chunk, wrapping. * * @param direction - 1 or -1. * @returns whether there was one. */ go(direction: 1 | -1): boolean { const chunks = this.chunks; const count = chunks.length; for (let step = 1; step <= count; step += 1) { const index = (((this.current < 0 && direction < 0 ? 0 : this.current) + direction * step) % count + count) % count; const live = chunks[index]; const chunk = this.layout.chunks[index]; if (live?.state === "open" && chunk) { this.current = index; this.resultView.dispatch({ selection: { anchor: live.from, head: live.to }, effects: EditorView.scrollIntoView(live.from, { y: "center" }), }); this.oursView.dispatch({ effects: EditorView.scrollIntoView(Math.min(chunk.oursFrom, this.oursView.state.doc.length), { y: "center" }) }); this.theirsView.dispatch({ effects: EditorView.scrollIntoView(Math.min(chunk.theirsFrom, this.theirsView.state.doc.length), { y: "center" }), }); return true; } } return false; } /** Destroys the three editors. */ destroy(): void { this.oursView.destroy(); this.resultView.destroy(); this.theirsView.destroy(); } }