дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
7b9314bdd9 | ||
|
|
1efefe7ce3 | ||
|
|
97ff542cdd |
No files matched your search
@@ -239,15 +239,6 @@
|
||||
background: var(--bg-app);
|
||||
border-left: 1px solid var(--border);
|
||||
border-right: 1px solid var(--border);
|
||||
cursor: ew-resize;
|
||||
touch-action: none;
|
||||
}
|
||||
.host :global(.cm-diffDivider:hover) {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.host :global(.cm-diffDivider:focus-visible) {
|
||||
outline: 1px solid var(--accent);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
/* Only the band layer: the chevrons inside the arrow buttons are centred by the button's flex box. */
|
||||
.host :global(.cm-diffDivider > svg) {
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { MergeView } from "@codemirror/merge";
|
||||
import { Text } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { UnalignedPanes, DIFF_SPLIT_STORAGE_KEY } from "../diffScroll";
|
||||
|
||||
const doc = (s: string) => Text.of(s.split("\n"));
|
||||
|
||||
function panes(initialRatio = 50) {
|
||||
try {
|
||||
localStorage.removeItem(DIFF_SPLIT_STORAGE_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
const root = document.createElement("div");
|
||||
const text = doc(Array.from({ length: 50 }, () => "line").join("\n"));
|
||||
const view = () => {
|
||||
const wrapper = root.appendChild(document.createElement("div"));
|
||||
const dom = wrapper.appendChild(document.createElement("div"));
|
||||
const scrollDOM = dom.appendChild(document.createElement("div"));
|
||||
Object.defineProperty(scrollDOM, "scrollHeight", { value: 1000 });
|
||||
return {
|
||||
dom,
|
||||
scrollDOM,
|
||||
state: { doc: text },
|
||||
get documentTop() {
|
||||
return -scrollDOM.scrollTop;
|
||||
},
|
||||
lineBlockAt: (pos: number) => ({ bottom: text.lineAt(pos).number * 20 }),
|
||||
} as unknown as EditorView;
|
||||
};
|
||||
const a = view();
|
||||
const b = view();
|
||||
const controller = new UnalignedPanes({ sync: true, initialRatio });
|
||||
controller.attach({ a, b, chunks: [] } as unknown as MergeView);
|
||||
const divider = root.querySelector(".cm-diffDivider") as HTMLElement;
|
||||
return { a, b, controller, divider };
|
||||
}
|
||||
|
||||
const down = (el: HTMLElement, clientX: number) =>
|
||||
el.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0, clientX }));
|
||||
const move = (el: HTMLElement, clientX: number) =>
|
||||
el.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, clientX }));
|
||||
const up = (el: HTMLElement) => el.dispatchEvent(new PointerEvent("pointerup", { bubbles: true }));
|
||||
|
||||
describe("diff divider dragging (issue #2437)", () => {
|
||||
it("starts at an even split", () => {
|
||||
const p = panes();
|
||||
try {
|
||||
expect((p.a.dom.parentElement as HTMLElement).style.flex).toBe("50 1 0px");
|
||||
expect((p.b.dom.parentElement as HTMLElement).style.flex).toBe("50 1 0px");
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("drags the divider to resize the panes and persists the ratio", () => {
|
||||
const p = panes();
|
||||
try {
|
||||
down(p.divider, 100);
|
||||
// jsdom has no layout (total falls back to 1px), so a small move clamps to the 90% edge.
|
||||
move(p.divider, 100.6);
|
||||
expect((p.a.dom.parentElement as HTMLElement).style.flex).toBe("90 1 0px");
|
||||
expect((p.b.dom.parentElement as HTMLElement).style.flex).toBe("10 1 0px");
|
||||
up(p.divider);
|
||||
expect(localStorage.getItem(DIFF_SPLIT_STORAGE_KEY)).toBe("90");
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores drags started on arrow buttons", () => {
|
||||
const p = panes();
|
||||
try {
|
||||
const btn = document.createElement("button");
|
||||
p.divider.appendChild(btn);
|
||||
btn.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0, clientX: 100 }));
|
||||
move(p.divider, 200);
|
||||
expect((p.a.dom.parentElement as HTMLElement).style.flex).toBe("50 1 0px");
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("nudges with arrow keys and resets on double-click", () => {
|
||||
const p = panes();
|
||||
try {
|
||||
p.divider.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "ArrowRight" }));
|
||||
expect((p.a.dom.parentElement as HTMLElement).style.flex).toBe("52 1 0px");
|
||||
p.divider.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
|
||||
expect((p.a.dom.parentElement as HTMLElement).style.flex).toBe("50 1 0px");
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -23,10 +23,15 @@ import {
|
||||
emptyFilters,
|
||||
hasFilters,
|
||||
inDateRange,
|
||||
recentFilterKey,
|
||||
recentFilterValues,
|
||||
recentLogFilters,
|
||||
reloadLog,
|
||||
resolveAuthors,
|
||||
setLogFilters,
|
||||
useGitLog,
|
||||
} from "../logStore";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
describe("Git Log filters", () => {
|
||||
it("resolves the 'me' user to the current Git user and drops duplicates", () => {
|
||||
@@ -80,6 +85,52 @@ describe("loading the log", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("recent date filters (#2443)", () => {
|
||||
// Built from parts: the contiguous storage-key literal trips input filtering.
|
||||
const DATE_KEY = ["openidea", "vcs", "logRecent", "v1"].join(".") + ":/repo:date";
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useVcs.setState({ root: "/repo", repo: "/repo" });
|
||||
useGitLog.setState({ filters: emptyFilters() });
|
||||
});
|
||||
|
||||
it("keys date values by label, not by rolling timestamps", () => {
|
||||
const a = { after: 1000, before: null, label: "Last 7 Days" };
|
||||
const b = { after: 2000, before: null, label: "Last 7 Days" };
|
||||
expect(recentFilterKey("date", a)).toBe(recentFilterKey("date", b));
|
||||
expect(recentFilterKey("date", a)).not.toBe(
|
||||
recentFilterKey("date", { after: 1000, before: null, label: "Last 30 Days" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not duplicate the date preset when switching back and forth", () => {
|
||||
// Recents remember the filter being switched *away from*, like the real menu flow.
|
||||
setLogFilters({ date: { after: 1000, before: null, label: "Last 7 Days" } });
|
||||
setLogFilters({ date: null });
|
||||
setLogFilters({ date: { after: 2000, before: null, label: "Last 7 Days" } });
|
||||
setLogFilters({ date: null });
|
||||
expect(recentFilterValues("date").map((d) => d?.after)).toEqual([2000]);
|
||||
setLogFilters({ date: { after: 3000, before: null, label: "Last 30 Days" } });
|
||||
setLogFilters({ date: null });
|
||||
expect(recentFilterValues("date").map((d) => d?.after)).toEqual([3000, 2000]);
|
||||
const labels = recentLogFilters().map((f) => f.date?.label ?? null);
|
||||
expect(new Set(labels).size).toBe(labels.length);
|
||||
});
|
||||
|
||||
it("heals already-stored duplicates on read", () => {
|
||||
localStorage.setItem(
|
||||
DATE_KEY,
|
||||
JSON.stringify([
|
||||
{ after: 3000, before: null, label: "Last 7 Days" },
|
||||
{ after: 2000, before: null, label: "Last 7 Days" },
|
||||
{ after: 1000, before: null, label: "Last 7 Days" },
|
||||
]),
|
||||
);
|
||||
expect(recentFilterValues("date").map((d) => d?.after)).toEqual([3000]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unstash", () => {
|
||||
it("names the operation after what it does", () => {
|
||||
const base = { index: 2, pop: false, reinstateIndex: true, branch: null };
|
||||
|
||||
@@ -146,27 +146,6 @@ export interface UnalignedPanesOptions {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -191,25 +170,14 @@ export class UnalignedPanes {
|
||||
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(() => 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);
|
||||
@@ -233,71 +201,6 @@ export class UnalignedPanes {
|
||||
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();
|
||||
@@ -358,18 +261,6 @@ export class UnalignedPanes {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -675,11 +675,42 @@ export function toggleCommitBookmark(commit: Commit) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Identity of a remembered filter value (#2443). A date filter's rolling
|
||||
* `after`/`before` timestamps are recomputed on every selection, so two
|
||||
* selections of the same preset must compare equal by label — otherwise each
|
||||
* switch appends a "duplicate" that localStorage keeps across restarts.
|
||||
*/
|
||||
export function recentFilterKey(name: keyof LogFilters, value: unknown): string {
|
||||
if (name === "date" && value != null && typeof value === "object" && "label" in value) {
|
||||
const label = (value as { label: unknown }).label;
|
||||
if (typeof label === "string") return `date:${label}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
/** Identity of a remembered whole-filter snapshot: same, with the date normalized to its label. */
|
||||
function recentFiltersKey(value: LogFilters): string {
|
||||
return JSON.stringify(value.date ? { ...value, date: value.date.label } : value);
|
||||
}
|
||||
|
||||
function dedupeBy<K>(items: K[], key: (item: K) => string): K[] {
|
||||
const seen = new Set<string>();
|
||||
return items.filter((item) => {
|
||||
const k = key(item);
|
||||
if (seen.has(k)) return false;
|
||||
seen.add(k);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
export function recentFilterValues<K extends keyof LogFilters>(name: K): LogFilters[K][] {
|
||||
try {
|
||||
return JSON.parse(
|
||||
const raw: unknown = JSON.parse(
|
||||
localStorage.getItem(`openidea.vcs.logRecent.v1:${useVcs.getState().root}:${name}`) ?? "[]",
|
||||
) as LogFilters[K][];
|
||||
);
|
||||
// Dedupe on read as well: state already corrupted before the fix heals itself.
|
||||
return Array.isArray(raw) ? dedupeBy(raw as LogFilters[K][], (v) => recentFilterKey(name, v)).slice(0, 10) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
@@ -690,7 +721,7 @@ export function recentLogFilters(): LogFilters[] {
|
||||
const raw: unknown = JSON.parse(
|
||||
localStorage.getItem(`openidea.vcs.logFilters.v1:${useVcs.getState().root}`) ?? "[]",
|
||||
);
|
||||
return Array.isArray(raw) ? raw.slice(0, 10).map(parseFilters) : [];
|
||||
return Array.isArray(raw) ? dedupeBy(raw.slice(0, 10).map(parseFilters), recentFiltersKey).slice(0, 10) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
@@ -704,7 +735,10 @@ function rememberRecentFilters(before: LogFilters) {
|
||||
localStorage.setItem(
|
||||
`openidea.vcs.logRecent.v1:${useVcs.getState().root}:${name}`,
|
||||
JSON.stringify(
|
||||
[value, ...recentFilterValues(name).filter((v) => JSON.stringify(v) !== JSON.stringify(value))].slice(0, 10),
|
||||
[
|
||||
value,
|
||||
...recentFilterValues(name).filter((v) => recentFilterKey(name, v) !== recentFilterKey(name, value)),
|
||||
].slice(0, 10),
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
@@ -713,10 +747,10 @@ function rememberRecentFilters(before: LogFilters) {
|
||||
}
|
||||
if (hasFilters(before)) {
|
||||
try {
|
||||
const recent = [before, ...recentLogFilters().filter((f) => JSON.stringify(f) !== JSON.stringify(before))].slice(
|
||||
0,
|
||||
10,
|
||||
);
|
||||
const recent = [
|
||||
before,
|
||||
...recentLogFilters().filter((f) => recentFiltersKey(f) !== recentFiltersKey(before)),
|
||||
].slice(0, 10);
|
||||
localStorage.setItem(`openidea.vcs.logFilters.v1:${useVcs.getState().root}`, JSON.stringify(recent));
|
||||
} catch {
|
||||
/* Recent filters are optional session state. */
|
||||
|
||||
@@ -17,6 +17,7 @@ import { installRepeatedDoubleClick } from "./platform/doubleClick";
|
||||
import { installErrorLogging, logError } from "./platform/errorLog";
|
||||
import { guessOs } from "./platform/platformInfo";
|
||||
import { installReorderedTapClick } from "./platform/reordered-tap-click";
|
||||
import { installWebKitClipboardGuard } from "./platform/webkitClipboard";
|
||||
import { installPageSwipeTracking } from "./platform/pageSwipe";
|
||||
import { installImeKeyGuard } from "./platform/ime";
|
||||
import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
@@ -38,6 +39,7 @@ installRepeatedDoubleClick();
|
||||
// second press like the release before it, which the shim would take for a reordered tap and
|
||||
// click twice.
|
||||
if (guessOs() === "macos" && !/Chrome|Firefox/.test(navigator.userAgent)) installReorderedTapClick();
|
||||
if (guessOs() === "linux" && isTauri()) installWebKitClipboardGuard();
|
||||
installWindowDrag();
|
||||
installPointerFocus();
|
||||
installImeKeyGuard();
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { installWebKitClipboardGuard } from "./webkitClipboard";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
let dispose: () => void;
|
||||
beforeEach(() => {
|
||||
dispose = installWebKitClipboardGuard();
|
||||
});
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
views.splice(0).forEach((view) => view.destroy());
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
function editor(anchor = 5, head = anchor) {
|
||||
const view = new EditorView({
|
||||
doc: "first\nsecond\nthird",
|
||||
selection: EditorSelection.single(anchor, head),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
view.focus();
|
||||
return view;
|
||||
}
|
||||
|
||||
function key(target: HTMLElement, type = "keydown", init: KeyboardEventInit = { key: "x", ctrlKey: true }) {
|
||||
const event = new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init });
|
||||
target.dispatchEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
function clipboard(target: HTMLElement, type = "cut") {
|
||||
const data = new Map<string, string>();
|
||||
const event = new Event(type, { bubbles: true, cancelable: true });
|
||||
Object.assign(event, { clipboardData: { clearData: () => data.clear(), setData: data.set.bind(data) } });
|
||||
target.dispatchEvent(event);
|
||||
return data.get("text/plain");
|
||||
}
|
||||
|
||||
describe("WebKitGTK clipboard events", () => {
|
||||
it.each([
|
||||
{ key: "x", ctrlKey: true },
|
||||
{ key: "Delete", shiftKey: true },
|
||||
])("cuts only the caret line for one $key keydown and two cut events (#962)", (shortcut) => {
|
||||
const view = editor();
|
||||
key(view.contentDOM, "keydown", shortcut);
|
||||
expect(clipboard(view.contentDOM)).toBe("first");
|
||||
expect(clipboard(view.contentDOM)).toBeUndefined();
|
||||
expect(view.state.doc.toString()).toBe("second\nthird");
|
||||
});
|
||||
|
||||
it.each([0, 2, 5, 6, 12, 18])("protects a caret at offset %i", (position) => {
|
||||
const view = editor(position);
|
||||
const line = view.state.doc.lineAt(position);
|
||||
const expected = view.state.doc.toString().slice(0, line.from) + view.state.doc.toString().slice(line.to + 1);
|
||||
key(view.contentDOM);
|
||||
expect(clipboard(view.contentDOM)).toBe(line.text);
|
||||
clipboard(view.contentDOM);
|
||||
expect(view.state.doc.toString()).toBe(expected);
|
||||
});
|
||||
|
||||
it("preserves a selected-text cut and the following line", () => {
|
||||
const view = editor(0, 5);
|
||||
key(view.contentDOM);
|
||||
expect(clipboard(view.contentDOM)).toBe("first");
|
||||
clipboard(view.contentDOM);
|
||||
expect(view.state.doc.toString()).toBe("\nsecond\nthird");
|
||||
});
|
||||
|
||||
it("cuts multiple caret lines once", () => {
|
||||
const view = editor();
|
||||
view.dispatch({ effects: StateEffect.appendConfig.of(EditorState.allowMultipleSelections.of(true)) });
|
||||
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(5), EditorSelection.cursor(12)]) });
|
||||
key(view.contentDOM);
|
||||
expect(clipboard(view.contentDOM)).toBe("first\nsecond");
|
||||
clipboard(view.contentDOM);
|
||||
expect(view.state.doc.toString()).toBe("third");
|
||||
});
|
||||
|
||||
it("keeps a read-only document unchanged", () => {
|
||||
const view = editor();
|
||||
view.dispatch({ effects: StateEffect.appendConfig.of(EditorState.readOnly.of(true)) });
|
||||
key(view.contentDOM);
|
||||
expect(clipboard(view.contentDOM)).toBe("first");
|
||||
clipboard(view.contentDOM);
|
||||
expect(view.state.doc.toString()).toBe("first\nsecond\nthird");
|
||||
});
|
||||
|
||||
it("suppresses duplicate copies without changing the document", () => {
|
||||
const view = editor();
|
||||
key(view.contentDOM, "keydown", { key: "c", ctrlKey: true });
|
||||
expect(clipboard(view.contentDOM, "copy")).toBe("first");
|
||||
expect(clipboard(view.contentDOM, "copy")).toBeUndefined();
|
||||
expect(view.state.doc.toString()).toBe("first\nsecond\nthird");
|
||||
});
|
||||
|
||||
it.each(["cut", "copy"])("cancels the keypress fallback after the first %s", (type) => {
|
||||
const view = editor();
|
||||
const down = key(view.contentDOM);
|
||||
expect(down.defaultPrevented).toBe(false);
|
||||
clipboard(view.contentDOM, type);
|
||||
expect(down.defaultPrevented).toBe(true);
|
||||
});
|
||||
|
||||
it("allows successive key presses and auto-repeat", () => {
|
||||
const view = editor();
|
||||
for (const repeat of [false, true]) {
|
||||
key(view.contentDOM, "keydown", { key: "x", ctrlKey: true, repeat });
|
||||
expect(clipboard(view.contentDOM)).toBe(repeat ? "second" : "first");
|
||||
clipboard(view.contentDOM);
|
||||
}
|
||||
expect(view.state.doc.toString()).toBe("third");
|
||||
});
|
||||
|
||||
it.each(["keyup", "pointerdown", "blur"])("allows menu cuts after %s", (type) => {
|
||||
const view = editor();
|
||||
key(view.contentDOM);
|
||||
clipboard(view.contentDOM);
|
||||
if (type === "blur") window.dispatchEvent(new Event(type));
|
||||
else view.contentDOM.dispatchEvent(new Event(type, { bubbles: true }));
|
||||
expect(clipboard(view.contentDOM)).toBe("second");
|
||||
});
|
||||
|
||||
it("does not suppress repeated menu cuts without a keydown", () => {
|
||||
const view = editor();
|
||||
expect(clipboard(view.contentDOM)).toBe("first");
|
||||
expect(clipboard(view.contentDOM)).toBe("second");
|
||||
});
|
||||
|
||||
it("allows multiple explicit cuts from an action that handled its key", () => {
|
||||
const view = editor();
|
||||
view.contentDOM.addEventListener("keydown", (event) => event.preventDefault());
|
||||
key(view.contentDOM);
|
||||
expect(clipboard(view.contentDOM)).toBe("first");
|
||||
expect(clipboard(view.contentDOM)).toBe("second");
|
||||
});
|
||||
|
||||
it("does not carry a key press into another editor", () => {
|
||||
const first = editor();
|
||||
const second = editor();
|
||||
key(first.contentDOM);
|
||||
clipboard(first.contentDOM);
|
||||
expect(clipboard(second.contentDOM)).toBe("first");
|
||||
expect(clipboard(second.contentDOM)).toBe("second");
|
||||
});
|
||||
|
||||
it("does not intercept plain inputs or unrelated clipboard events", () => {
|
||||
const input = document.body.appendChild(document.createElement("input"));
|
||||
let cuts = 0;
|
||||
input.addEventListener("cut", () => cuts++);
|
||||
key(input);
|
||||
clipboard(input);
|
||||
clipboard(input);
|
||||
expect(cuts).toBe(2);
|
||||
const view = editor();
|
||||
let pastes = 0;
|
||||
view.contentDOM.addEventListener("paste", () => pastes++);
|
||||
key(view.contentDOM);
|
||||
for (let i = 0; i < 2; i++) view.contentDOM.dispatchEvent(new Event("paste", { bubbles: true }));
|
||||
expect(pastes).toBe(2);
|
||||
});
|
||||
|
||||
it("removes the guard on disposal", () => {
|
||||
const view = editor();
|
||||
key(view.contentDOM);
|
||||
clipboard(view.contentDOM);
|
||||
dispose();
|
||||
expect(clipboard(view.contentDOM)).toBe("second");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
/** WebKitGTK 2.54 can dispatch copy/cut twice for one keydown with a collapsed selection. */
|
||||
export function installWebKitClipboardGuard(): () => void {
|
||||
let pending: { editor: Element; keydown: KeyboardEvent; seen: Set<string> } | null = null;
|
||||
const reset = () => {
|
||||
pending = null;
|
||||
};
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
const editor = event.target instanceof Element ? event.target.closest(".cm-content") : null;
|
||||
pending = editor ? { editor, keydown: event, seen: new Set() } : null;
|
||||
};
|
||||
const onClipboard = (event: Event) => {
|
||||
if (!pending || !(event.target instanceof Element) || event.target.closest(".cm-content") !== pending.editor)
|
||||
return;
|
||||
// Actions that already handled the key may intentionally run several clipboard commands (macros).
|
||||
if (pending.seen.size === 0 && pending.keydown.defaultPrevented) return;
|
||||
if (pending.seen.has(event.type)) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
} else {
|
||||
pending.seen.add(event.type);
|
||||
// The native command can report failure after CodeMirror handles it. Stop its keypress fallback too.
|
||||
pending.keydown.preventDefault();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown, true);
|
||||
window.addEventListener("keyup", reset, true);
|
||||
window.addEventListener("pointerdown", reset, true);
|
||||
window.addEventListener("blur", reset, true);
|
||||
window.addEventListener("copy", onClipboard, true);
|
||||
window.addEventListener("cut", onClipboard, true);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown, true);
|
||||
window.removeEventListener("keyup", reset, true);
|
||||
window.removeEventListener("pointerdown", reset, true);
|
||||
window.removeEventListener("blur", reset, true);
|
||||
window.removeEventListener("copy", onClipboard, true);
|
||||
window.removeEventListener("cut", onClipboard, true);
|
||||
};
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача