Файли
openidea/src/features/vcs/diffScroll.ts
T
l0ng-ai e9f3aef5ae fix(markdown): keep the preview painted while scrolling (#6908)
Trackpad scrolling in the Markdown preview could leave a large part of it blank until the next scroll. The preview moves itself on each wheel event with scrollBy, and in WebKit a run of scrollBy calls can leave the compositor at an older, never-painted offset than the page's. Setting scrollTop/scrollLeft keeps them in step; the source editor's large wheel jumps and the diff divider's wheel did the same and now set offsets too.

A fenced code block overflowing by a pixel no longer counts as a vertical scroller, and a nested scroller keeps the wheel only while it can still move in that direction, so scrolling no longer stops over code blocks.
2026-11-30 10:31:45 +08:00

788 рядки
29 KiB
TypeScript

/**
* IDEA's side-by-side diff without alignment padding: each pane scrolls on its
* own, scrolling one carries the other along through the changes
* (SyncScrollSupport), and the divider between them draws a curved band per
* change (DiffDividerDrawUtil) with the ">>" / "<<" arrows on it. Changed lines
* tint their gutters instead of showing a change bar.
*/
import { RangeSetBuilder, type Extension } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { getChunks, type Chunk, type MergeView } from "@codemirror/merge";
import { changedLineGutters, chunkKind, type DiffKind } from "./cm";
import { arrowButton } from "./diffControls";
import styles from "./DiffEditor.module.css";
type Side = "a" | "b";
/** A stretch of both documents in document pixels: unchanged text, or a change. */
export interface Band {
a0: number;
a1: number;
b0: number;
b1: number;
changed: boolean;
}
/** Pixel [top, bottom] of a chunk's range in `view`; an empty range is the boundary it sits on. */
export function extent(view: EditorView, from: number, to: number): [number, number] {
const len = view.state.doc.length;
if (from > len) {
const end = view.lineBlockAt(len).bottom;
return [end, end];
}
const top = view.lineBlockAt(from).top;
return from >= to ? [top, top] : [top, view.lineBlockAt(Math.min(to - 1, len)).bottom];
}
/** First index in `[0, n)` for which `past` holds, given that it holds for a suffix. */
function firstIndex(n: number, past: (i: number) => boolean): number {
let lo = 0;
let hi = n;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (past(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}
/**
* The stretch of both documents around `y` of side `from`, from the top to
* `endA` / `endB`: unchanged text, or a change (BaseSyncScrollable.processHelper).
* Only the chunks next to `y` are measured.
*/
export function bandAt(
chunks: readonly Chunk[],
extentA: (c: Chunk) => [number, number],
extentB: (c: Chunk) => [number, number],
endA: number,
endB: number,
y: number,
from: Side,
): Band {
const master = from === "a" ? extentA : extentB;
const next = firstIndex(chunks.length, (i) => master(chunks[i]!)[0] > y);
let a = 0;
let b = 0;
const prev = chunks[next - 1];
if (prev) {
const [a0, a1] = extentA(prev);
const [b0, b1] = extentB(prev);
if (y < (from === "a" ? a1 : b1)) return { a0, a1, b0, b1, changed: true };
a = a1;
b = b1;
}
const c = chunks[next];
return c
? { a0: a, a1: extentA(c)[0], b0: b, b1: extentB(c)[0], changed: false }
: { a0: a, a1: endA, b0: b, b1: endB, changed: false };
}
/**
* The position on the other side matching `y` of side `from`
* (BaseSyncScrollable.transferLine, in pixels): unchanged text maps through,
* and inside a change the other side follows line by line, then waits at the
* end of its shorter part.
*/
export function transferY(bands: readonly Band[], y: number, from: Side): number {
const fromA = from === "a";
const band = bands.find((b) => y < (fromA ? b.a1 : b.b1)) ?? bands[bands.length - 1]!;
const [m0, m1, s0, s1] = fromA ? [band.a0, band.a1, band.b0, band.b1] : [band.b0, band.b1, band.a0, band.a1];
if (band.changed) return Math.min(s0 + (y - m0), s1);
return m1 > m0 ? s0 + ((y - m0) * (s1 - s0)) / (m1 - m0) : s0;
}
/** The divider band between [a0, a1] on the left and [b0, b1] on the right (DiffDrawUtil.makeCurve). */
export function bandPath(w: number, a0: number, a1: number, b0: number, b1: number): string {
// An empty side is a 2px sliver on its boundary.
if (a1 - a0 < 2) [a0, a1] = [a0 - 1, a0 + 1];
if (b1 - b0 < 2) [b0, b1] = [b0 - 1, b0 + 1];
const c1 = w * 0.3;
const c2 = w * 0.7;
return `M0 ${a0}C${c1} ${a0} ${c2} ${b0} ${w} ${b0}L${w} ${b1}C${c2} ${b1} ${c1} ${a1} 0 ${a1}Z`;
}
const gapMark = (kind: DiffKind, end: boolean) =>
Decoration.line({ class: `cm-diffGap cm-diffGap-${kind}${end ? " cm-diffGapEnd" : ""}` });
/** A line where the other side has lines this one lacks, as in IDEA's empty-side marker. */
function gapDeco(view: EditorView): DecorationSet {
const info = getChunks(view.state);
if (!info?.side) return Decoration.none;
const isA = info.side === "a";
const { doc } = view.state;
const { from: vpFrom, to: vpTo } = view.viewport;
const builder = new RangeSetBuilder<Decoration>();
for (const c of info.chunks) {
const [from, to] = isA ? [c.fromA, c.toA] : [c.fromB, c.toB];
if (from !== to) continue;
if (from > vpTo) break;
if (from < vpFrom) continue;
// Past the end of a document without a final line break: below its last line.
const line = doc.lineAt(Math.min(from, doc.length));
builder.add(line.from, line.from, gapMark(chunkKind(c), from > doc.length));
}
return builder.finish();
}
const gapMarks = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = gapDeco(view);
}
update(u: ViewUpdate) {
if (u.docChanged || u.viewportChanged || getChunks(u.startState)?.chunks !== getChunks(u.state)?.chunks)
this.decorations = gapDeco(u.view);
}
},
{ decorations: (v) => v.decorations },
);
const SVG = "http://www.w3.org/2000/svg";
const ARROW_HEIGHT = 16;
export interface UnalignedPanesOptions {
/** Scrolling one pane carries the other along. */
sync: boolean;
/** Divider arrows toward the editable sides; `apply` copies chunk `index` from `source`. */
arrows?: { toA: boolean; toB: boolean; apply(index: number, source: Side): void };
/** Initial left-pane share (percent); defaults to the persisted value, then 50. */
initialRatio?: number;
}
/** localStorage key for the side-by-side pane split, shared by every diff viewer. */
export const DIFF_SPLIT_STORAGE_KEY = "openidea:diff-pane-ratio";
const MIN_RATIO = 10;
const MAX_RATIO = 90;
function loadRatio(fallback = 50): number {
try {
const raw = localStorage.getItem(DIFF_SPLIT_STORAGE_KEY);
if (raw != null) {
const n = Number(raw);
if (Number.isFinite(n)) return Math.min(MAX_RATIO, Math.max(MIN_RATIO, n));
}
} catch {
/* Storage may be unavailable (private mode, SSR). */
}
return fallback;
}
/**
* The scroll machinery of a side-by-side diff's panes: added to both editors,
* attached to their MergeView, and torn down with the diff.
*/
export interface DiffPanes {
/** Extensions for both editors. */
extension: Extension;
attach(mv: MergeView): void;
/** Turns synchronized scrolling on (bringing the other pane along) or off. */
setSync(on: boolean): void;
/** Scrolls one pane, the other following. */
scrollTo(side: Side, options: ScrollToOptions): void;
destroy(): void;
}
/**
* Scroll synchronization for the padded panes of an aligned side-by-side diff:
* MergeView pads the panes so their lines lay out identically, so one `scrollTop`
* fits both. Each pane scrolls itself, which keeps its horizontal scrollbar at
* the pane's bottom edge — a content-tall scroller would render it at the bottom
* of the content, out of reach until the diff is scrolled to its end.
*/
export class PaddedPanes implements DiffPanes {
readonly extension: Extension;
private mv: MergeView | null = null;
private sync: boolean;
private scrolling: Side | null = null;
private scrollTimer: ReturnType<typeof setTimeout> | undefined;
private wheelLeader: Side | null = null;
private wheelTimer: ReturnType<typeof setTimeout> | undefined;
/** The scroll position a pane was last moved to by the other one, to tell its echo from the user. */
private readonly moved: Record<Side, number | null> = { a: null, b: null };
private readonly cleanup: (() => void)[] = [];
constructor(sync: boolean) {
this.sync = sync;
this.extension = EditorView.updateListener.of((u) => {
if (u.heightChanged && !u.docChanged && this.mv) {
const side: Side | null = u.view === this.mv.a ? "a" : u.view === this.mv.b ? "b" : null;
if (side && this.moved[side] !== null) this.moved[side] = u.view.scrollDOM.scrollTop;
}
});
}
attach(mv: MergeView) {
this.mv = mv;
for (const side of ["a", "b"] as const) {
const el = this.view(side).scrollDOM;
const onScroll = () => this.scrolled(side);
const onWheel = () => {
this.interruptScroll();
this.leadWheel(side);
};
const onPointer = () => {
this.interruptScroll();
this.clearWheel();
};
el.addEventListener("scroll", onScroll, { passive: true });
el.addEventListener("wheel", onWheel, { passive: true });
el.addEventListener("pointerdown", onPointer);
this.cleanup.push(() => {
el.removeEventListener("scroll", onScroll);
el.removeEventListener("wheel", onWheel);
el.removeEventListener("pointerdown", onPointer);
});
}
this.resync();
}
/** Brings the left pane in line with the right one. */
resync() {
if (this.mv && this.sync) this.follow("b");
}
setSync(on: boolean) {
if (on === this.sync) return;
this.interruptScroll();
this.clearWheel();
this.sync = on;
this.resync();
}
scrollTo(side: Side, options: ScrollToOptions) {
this.interruptScroll();
this.clearWheel();
this.scrolling = this.sync ? side : null;
this.releaseScroll();
this.view(side).scrollDOM.scrollTo(options);
}
/**
* Marks `side` as the source of a layout-driven scroll (a soft-wrap toggle re-anchors it), so the
* other pane's delayed reflow follows it instead of being mistaken for a user scroll pulling back.
*/
leadScroll(side: Side) {
this.clearWheel();
this.scrolling = this.sync ? side : null;
this.releaseScroll();
}
destroy() {
clearTimeout(this.scrollTimer);
clearTimeout(this.wheelTimer);
for (const f of this.cleanup) f();
this.mv = null;
}
private view(side: Side): EditorView {
return side === "a" ? this.mv!.a : this.mv!.b;
}
private scrolled(from: Side) {
if (this.scrolling) {
// A follower's delayed layout scroll must not pull back the navigation source.
this.follow(this.scrolling);
this.releaseScroll();
return;
}
if (this.wheelLeader) {
this.moved[from] = null;
if (from === this.wheelLeader) {
this.leadWheel(from);
if (this.sync) this.follow(from);
} else if (this.sync) {
this.follow(this.wheelLeader);
}
return;
}
const el = this.view(from).scrollDOM;
const moved = this.moved[from];
const echo = moved !== null && Math.abs(el.scrollTop - moved) <= 1;
this.moved[from] = null;
if (!echo && this.sync) this.follow(from);
}
private leadWheel(side: Side) {
this.wheelLeader = this.sync ? side : null;
clearTimeout(this.wheelTimer);
if (this.wheelLeader) this.wheelTimer = setTimeout(() => (this.wheelLeader = null), 150);
}
private clearWheel() {
this.wheelLeader = null;
clearTimeout(this.wheelTimer);
}
private follow(from: Side) {
const to: Side = from === "a" ? "b" : "a";
const el = this.view(to).scrollDOM;
const top = this.view(from).scrollDOM.scrollTop;
if (Math.abs(el.scrollTop - top) < 1) return;
const before = el.scrollTop;
el.scrollTop = top;
if (el.scrollTop !== before) this.moved[to] = el.scrollTop;
}
private releaseScroll() {
clearTimeout(this.scrollTimer);
if (this.scrolling) this.scrollTimer = setTimeout(() => (this.scrolling = null), 150);
}
private interruptScroll() {
const side = this.scrolling;
this.scrolling = null;
clearTimeout(this.scrollTimer);
if (side && this.mv) {
const el = this.view(side).scrollDOM;
el.scrollTo({ top: el.scrollTop, behavior: "instant" });
}
}
}
/**
* Scroll synchronization and the divider for a MergeView whose panes are not
* padded into alignment. Add `extension` to both editors, then `attach` the view.
*/
export class UnalignedPanes implements DiffPanes {
readonly extension: Extension;
private mv: MergeView | null = null;
private readonly divider = document.createElement("div");
private readonly svg = document.createElementNS(SVG, "svg");
private readonly bandLayer = document.createElementNS(SVG, "g");
private readonly arrowEls = new Map<string, HTMLButtonElement>();
/** Scroll position each pane was last moved to by the other one, to tell its echo from the user. */
private readonly moved: Record<Side, { top: number | null; left: number | null }> = {
a: { top: null, left: null },
b: { top: null, left: null },
};
/** Where a passed-on wheel left a pane, past (in direction `dir`) where the pane the wheel was over maps it. */
private readonly passed: Record<Side, { top: number; dir: number } | null> = { a: null, b: null };
private sync: boolean;
private scrolling: Side | null = null;
private scrollTimer: ReturnType<typeof setTimeout> | undefined;
private wheelLeader: Side | null = null;
private wheelTimer: ReturnType<typeof setTimeout> | undefined;
private frame = -1;
private resize: ResizeObserver | null = null;
private readonly cleanup: (() => void)[] = [];
/** Left pane share (percent) of the side-by-side split; dragging the divider updates it. */
private ratio: number;
constructor(private readonly opts: UnalignedPanesOptions) {
this.sync = opts.sync;
this.ratio =
opts.initialRatio != null && Number.isFinite(opts.initialRatio)
? Math.min(MAX_RATIO, Math.max(MIN_RATIO, opts.initialRatio))
: loadRatio();
this.extension = [
gapMarks,
changedLineGutters,
EditorView.updateListener.of((u) => {
// When CodeMirror's measure adjusts a follower pane's scrollTop after line heights resolve,
// update the expected echo so the layout adjustment is not mistaken for a user scroll.
if (u.heightChanged && !u.docChanged && this.mv) {
const side: Side | null = u.view === this.mv.a ? "a" : u.view === this.mv.b ? "b" : null;
if (side && this.moved[side].top !== null) this.moved[side].top = u.view.scrollDOM.scrollTop;
const passed = side && this.passed[side];
if (passed) passed.top = u.view.scrollDOM.scrollTop;
}
this.schedule();
}),
];
this.divider.className = "cm-diffDivider";
// A lone arrow is centred in the divider; a pair keeps to the two edges.
this.divider.classList.toggle("cm-diffDivider-lone", !!opts.arrows && opts.arrows.toA !== opts.arrows.toB);
this.divider.setAttribute("data-wheel-scroll", "");
this.divider.setAttribute("role", "separator");
this.divider.setAttribute("aria-orientation", "vertical");
this.divider.setAttribute("aria-label", "Resize diff panes");
this.divider.setAttribute("title", "Drag to resize panes (double-click to reset)");
this.divider.tabIndex = 0;
this.svg.setAttribute("aria-hidden", "true");
this.svg.appendChild(this.bandLayer);
this.divider.appendChild(this.svg);
}
attach(mv: MergeView) {
this.mv = mv;
// MergeView pads the panes into alignment on each measure; these panes stay unpadded.
(mv as unknown as { measure(): void }).measure = () => {};
mv.a.dom.parentElement!.after(this.divider);
for (const side of ["a", "b"] as const) {
const el = this.view(side).scrollDOM;
const onScroll = () => this.scrolled(side);
const onWheel = (e: WheelEvent) => {
this.interruptScroll();
this.leadWheel(side);
this.passOn(side, e);
};
const onPointer = () => {
this.interruptScroll();
this.clearWheel();
};
el.addEventListener("scroll", onScroll, { passive: true });
el.addEventListener("wheel", onWheel, { passive: true });
el.addEventListener("pointerdown", onPointer);
this.cleanup.push(() => {
el.removeEventListener("scroll", onScroll);
el.removeEventListener("wheel", onWheel);
el.removeEventListener("pointerdown", onPointer);
});
}
this.applyRatio();
// Dragging the divider resizes the panes like IDEA's splitter (double-click resets).
let dragX: number | null = null;
let dragRatio = this.ratio;
const persist = () => {
try {
localStorage.setItem(DIFF_SPLIT_STORAGE_KEY, String(this.ratio));
} catch {
/* Storage may be unavailable. */
}
};
const onPointerDown = (e: PointerEvent) => {
if (e.button !== 0 || (e.target as HTMLElement | null)?.closest?.("button")) return;
e.preventDefault();
dragX = e.clientX;
dragRatio = this.ratio;
try {
this.divider.setPointerCapture(e.pointerId);
} catch {
/* jsdom / touch without capture support. */
}
};
const onPointerMove = (e: PointerEvent) => {
if (dragX === null || !this.mv) return;
const editors = this.divider.parentElement;
const total = (editors?.clientWidth ?? 0) - this.divider.offsetWidth || 1;
const next = dragRatio + ((e.clientX - dragX) / total) * 100;
this.ratio = Math.min(MAX_RATIO, Math.max(MIN_RATIO, next));
this.applyRatio();
};
const endDrag = () => {
if (dragX === null) return;
dragX = null;
persist();
this.schedule();
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
e.preventDefault();
this.ratio = Math.min(MAX_RATIO, Math.max(MIN_RATIO, this.ratio + (e.key === "ArrowRight" ? 2 : -2)));
this.applyRatio();
persist();
this.schedule();
};
const onDblClick = (e: MouseEvent) => {
if ((e.target as HTMLElement | null)?.closest?.("button")) return;
this.ratio = 50;
this.applyRatio();
persist();
this.schedule();
};
this.divider.addEventListener("pointerdown", onPointerDown);
this.divider.addEventListener("pointermove", onPointerMove);
this.divider.addEventListener("pointerup", endDrag);
this.divider.addEventListener("pointercancel", endDrag);
this.divider.addEventListener("keydown", onKeyDown);
this.divider.addEventListener("dblclick", onDblClick);
this.cleanup.push(() => {
this.divider.removeEventListener("pointerdown", onPointerDown);
this.divider.removeEventListener("pointermove", onPointerMove);
this.divider.removeEventListener("pointerup", endDrag);
this.divider.removeEventListener("pointercancel", endDrag);
this.divider.removeEventListener("keydown", onKeyDown);
this.divider.removeEventListener("dblclick", onDblClick);
});
// The divider scrolls the right pane (and, when synchronized, through it the left one).
const onWheel = (e: WheelEvent) => {
e.preventDefault();
this.interruptScroll();
this.leadWheel("b");
this.passOn("b", e);
// Offsets rather than scrollBy, which can leave WebKit's compositor at a stale, unpainted offset.
const scroller = mv.b.scrollDOM;
scroller.scrollLeft += e.deltaX;
scroller.scrollTop += e.deltaY;
};
this.divider.addEventListener("wheel", onWheel, { passive: false });
this.cleanup.push(() => this.divider.removeEventListener("wheel", onWheel));
if (typeof ResizeObserver !== "undefined") {
this.resize = new ResizeObserver(() => this.schedule());
this.resize.observe(this.divider);
}
const editors = this.divider.parentElement!;
const measuring = styles.measuringPanes!;
editors.classList.add(measuring);
// Both editors have queued their initial measurements. Reveal the panes with the first divider
// drawing after those measurements, so estimated gutter positions never reach the screen.
this.frame = requestAnimationFrame(() => {
if (this.sync) this.follow("b");
this.draw();
editors.classList.remove(measuring);
});
this.cleanup.push(() => editors.classList.remove(measuring));
}
/** Brings the left pane in line with the right one. */
resync() {
if (this.mv && this.sync) this.follow("b");
this.schedule();
}
/** Turns synchronized scrolling on (bringing the left pane in line) or off. */
setSync(on: boolean) {
if (on === this.sync) return;
this.interruptScroll();
this.clearWheel();
this.sync = on;
this.resync();
}
scrollTo(side: Side, options: ScrollToOptions) {
this.interruptScroll();
this.clearWheel();
this.scrolling = this.sync ? side : null;
this.releaseScroll();
this.view(side).scrollDOM.scrollTo(options);
}
private leadWheel(side: Side) {
this.wheelLeader = this.sync ? side : null;
clearTimeout(this.wheelTimer);
if (this.wheelLeader) this.wheelTimer = setTimeout(() => (this.wheelLeader = null), 150);
}
private clearWheel() {
this.wheelLeader = null;
clearTimeout(this.wheelTimer);
}
private releaseScroll() {
clearTimeout(this.scrollTimer);
if (this.scrolling) this.scrollTimer = setTimeout(() => (this.scrolling = null), 150);
}
private interruptScroll() {
const side = this.scrolling;
this.scrolling = null;
clearTimeout(this.scrollTimer);
if (side && this.mv) {
const el = this.view(side).scrollDOM;
el.scrollTo({ top: el.scrollTop, behavior: "instant" });
}
}
destroy() {
clearTimeout(this.scrollTimer);
clearTimeout(this.wheelTimer);
if (this.frame >= 0) cancelAnimationFrame(this.frame);
this.resize?.disconnect();
for (const f of this.cleanup) f();
this.divider.remove();
this.mv = null;
}
/** Applies the current split to the two pane wrappers (flex-grow shares of the free width). */
private applyRatio() {
const mv = this.mv;
if (!mv) return;
const left = mv.a.dom.parentElement;
const right = mv.b.dom.parentElement;
if (!left || !right) return;
left.style.flex = `${this.ratio} 1 0`;
right.style.flex = `${100 - this.ratio} 1 0`;
this.divider.setAttribute("aria-valuenow", String(Math.round(this.ratio)));
}
private view(side: Side): EditorView {
return side === "a" ? this.mv!.a : this.mv!.b;
}
/**
* A synchronized vertical wheel over `side` at its end scrolls the other pane, or else a deleted
* tail is reachable only with the pointer over the longer pane. `side` keeps leading, and
* `follow` leaves the other pane past where `side` maps it while the wheel lasts. A wheel back
* closes that overshoot over the next notches rather than in one jump (WebKit lets no wheel of
* a trackpad gesture but the first be cancelled, so `side` scrolls natively meanwhile).
*/
private passOn(side: Side, e: WheelEvent) {
if (!this.mv || !this.sync || e.shiftKey || !(Math.abs(e.deltaY) > Math.abs(e.deltaX))) return;
const view = this.view(side);
const el = view.scrollDOM;
const to: Side = side === "a" ? "b" : "a";
const other = this.view(to).scrollDOM;
const dy = e.deltaMode === 1 ? e.deltaY * view.defaultLineHeight : e.deltaY;
const room = dy > 0 ? el.scrollHeight - el.clientHeight - el.scrollTop : el.scrollTop;
const scroll = (by: number, dir: number) => {
const before = other.scrollTop;
other.scrollTop += by;
if (other.scrollTop !== before) this.passed[to] = { top: other.scrollTop, dir };
};
const passed = this.passed[to];
if (passed && dy * passed.dir < 0) {
// Twice as far as `side` scrolls, so the gap closes; no further than where `side` will map it.
const native = Math.min(Math.abs(dy), Math.max(0, room));
const gap = Math.abs(this.followTop(side) - other.scrollTop);
scroll(Math.sign(dy) * Math.min(Math.abs(dy) + native, gap + native), passed.dir);
} else if (room <= 1) scroll(dy, Math.sign(dy));
}
private scrolled(side: Side) {
const el = this.view(side).scrollDOM;
// Scrolled by the user since the wheel that was passed on to it.
const passed = this.passed[side];
if (passed && Math.abs(el.scrollTop - passed.top) > 1) this.passed[side] = null;
if (this.scrolling) {
// A follower's delayed layout scroll must not pull back the navigation source.
this.follow(this.scrolling);
this.releaseScroll();
this.schedule();
return;
}
if (this.wheelLeader) {
// Keep the actively wheel-scrolled pane in charge so follower measure adjustments never pull it back.
const moved = this.moved[side];
moved.top = moved.left = null;
if (side === this.wheelLeader) {
this.leadWheel(side);
if (this.sync) this.follow(side);
} else if (this.sync) {
this.follow(this.wheelLeader);
}
this.schedule();
return;
}
const moved = this.moved[side];
const echo =
(moved.top !== null || moved.left !== null) &&
(moved.top === null || Math.abs(el.scrollTop - moved.top) <= 1) &&
(moved.left === null || Math.abs(el.scrollLeft - moved.left) <= 1);
moved.top = moved.left = null;
if (!echo && this.sync) this.follow(side);
this.schedule();
}
private bandAt(y: number, from: Side): Band {
const { a, b, chunks } = this.mv!;
return bandAt(
chunks,
(c) => extent(a, c.fromA, c.toA),
(c) => extent(b, c.fromB, c.toB),
a.lineBlockAt(a.state.doc.length).bottom,
b.lineBlockAt(b.state.doc.length).bottom,
y,
from,
);
}
/** Where the other pane scrolls to match `from`, anchored a third down the pane (SyncScrollSupport). */
private followTop(from: Side): number {
const master = this.view(from);
const slave = this.view(from === "a" ? "b" : "a");
const anchor = master.scrollDOM.clientHeight / 3;
const at = master.scrollDOM.scrollTop + anchor - docOffset(master);
const y = transferY([this.bandAt(at, from)], at, from);
const el = slave.scrollDOM;
return Math.max(0, Math.min(y + docOffset(slave) - anchor, el.scrollHeight - el.clientHeight));
}
/** Scrolls the other pane to match `from`. */
private follow(from: Side) {
const to: Side = from === "a" ? "b" : "a";
const master = this.view(from);
const el = this.view(to).scrollDOM;
const top = this.followTop(from);
const moved = this.moved[to];
const passed = this.passed[to];
// While wheeling, a pane a passed-on wheel took past `top` stays there: wheels back close the gap.
const keep = !!passed && !!this.wheelLeader && (el.scrollTop - top) * passed.dir > 1;
if (!keep) this.passed[to] = null;
if (!keep && Math.abs(el.scrollTop - top) >= 1) {
const before = el.scrollTop;
el.scrollTop = top;
if (el.scrollTop !== before) moved.top = el.scrollTop;
}
const left = master.scrollDOM.scrollLeft;
if (el.scrollLeft !== left) {
const before = el.scrollLeft;
el.scrollLeft = left;
if (el.scrollLeft !== before) moved.left = el.scrollLeft;
}
}
private schedule() {
if (this.frame < 0 && this.mv) this.frame = requestAnimationFrame(() => this.draw());
}
private draw() {
this.frame = -1;
const mv = this.mv;
if (!mv) return;
const rect = this.divider.getBoundingClientRect();
const w = rect.width;
const h = rect.height;
if (!w || !h) return;
this.svg.setAttribute("width", String(w));
this.svg.setAttribute("height", String(h));
this.svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
const offA = mv.a.documentTop - rect.top;
const offB = mv.b.documentTop - rect.top;
const lineHeight = mv.a.defaultLineHeight;
const arrowTop = (y0: number, y1: number) =>
y1 - y0 < 2 ? y0 - ARROW_HEIGHT / 2 : y0 + (Math.min(lineHeight, y1 - y0) - ARROW_HEIGHT) / 2;
const arrows = this.opts.arrows;
const shown = new Set<string>();
let paths = "";
const { chunks } = mv;
// Chunks run down both panes in order: start at the first one reaching into either.
const first = Math.min(
firstIndex(chunks.length, (i) => extent(mv.a, chunks[i]!.fromA, chunks[i]!.toA)[1] + offA >= -1),
firstIndex(chunks.length, (i) => extent(mv.b, chunks[i]!.fromB, chunks[i]!.toB)[1] + offB >= -1),
);
for (let i = first; i < chunks.length; i++) {
const c = chunks[i]!;
const [a0, a1] = extent(mv.a, c.fromA, c.toA).map((y) => y + offA) as [number, number];
const [b0, b1] = extent(mv.b, c.fromB, c.toB).map((y) => y + offB) as [number, number];
if (a0 > h + 1 && b0 > h + 1) break;
if (a1 < -1 && b1 < -1) continue;
const kind = chunkKind(c);
const mid = (a0 + a1) / 2;
const midB = (b0 + b1) / 2;
paths +=
`<path class="cm-diffBand cm-diffBand-${kind}" d="${bandPath(w, a0, a1, b0, b1)}"/>` +
`<path class="cm-diffBandLine cm-diffBand-${kind}" d="M0 ${mid}C${w * 0.3} ${mid} ${w * 0.7} ${midB} ${w} ${midB}"/>`;
if (arrows?.toB) this.placeArrow(shown, i, "a-to-b", arrowTop(a0, a1), h);
if (arrows?.toA) this.placeArrow(shown, i, "b-to-a", arrowTop(b0, b1), h);
}
this.bandLayer.innerHTML = paths;
for (const [key, el] of this.arrowEls)
if (!shown.has(key)) {
el.remove();
this.arrowEls.delete(key);
}
}
private placeArrow(shown: Set<string>, index: number, dir: "a-to-b" | "b-to-a", top: number, h: number) {
if (top < -ARROW_HEIGHT || top > h) return;
const key = `${index}${dir}`;
let el = this.arrowEls.get(key);
if (!el) {
el = arrowButton(dir, (i) => this.opts.arrows?.apply(i, dir === "a-to-b" ? "a" : "b"));
this.arrowEls.set(key, el);
this.divider.appendChild(el);
}
el.dataset.chunk = String(index);
el.style.top = `${top}px`;
shown.add(key);
}
}
/** Offset of the document's top within the pane's scrolled content. */
export function docOffset(view: EditorView): number {
return view.documentTop - view.scrollDOM.getBoundingClientRect().top + view.scrollDOM.scrollTop;
}