diff --git a/client/codemirror/editor_state.ts b/client/codemirror/editor_state.ts index 89a42eb9..0d1fe1ec 100644 --- a/client/codemirror/editor_state.ts +++ b/client/codemirror/editor_state.ts @@ -50,6 +50,7 @@ import { readOnlyCursorActive } from "./util.ts"; import { buildExtendedMarkdownLanguage } from "../markdown_parser/parser.ts"; import { safeRun } from "@silverbulletmd/silverbullet/lib/async"; import { codeCopyPlugin } from "../codemirror/code_copy.ts"; +import { externalPresence } from "./external_presence.ts"; import { disableSpellcheck } from "../codemirror/spell_checking.ts"; import type { ClickEvent } from "@silverbulletmd/silverbullet/type/client"; import { @@ -160,6 +161,7 @@ export function createEditorState( }), inlineContentPlugin(client), codeCopyPlugin(client), + externalPresence(), highlightSpecialChars(), undoHistory, dropCursor(), diff --git a/client/codemirror/external_presence.test.ts b/client/codemirror/external_presence.test.ts new file mode 100644 index 00000000..f1152742 --- /dev/null +++ b/client/codemirror/external_presence.test.ts @@ -0,0 +1,198 @@ +import { describe, expect, it } from "vitest"; +import { EditorState, Transaction } from "@codemirror/state"; +import { + expirePresence, + externalPresenceField, + externalSource, + externalUndoField, +} from "./external_presence.ts"; + +function stateWithDoc(doc: string) { + return EditorState.create({ doc, extensions: [externalPresenceField] }); +} + +describe("externalPresenceField", () => { + it("records inserted ranges from externally-annotated transactions", () => { + const state = stateWithDoc("Hello\n"); + const tr = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: externalSource.of("external"), + }); + const hunks = tr.state.field(externalPresenceField).hunks; + expect(hunks).toHaveLength(1); + expect(hunks[0].from).toBe(6); + expect(hunks[0].to).toBe(15); + expect(hunks[0].source).toBe("external"); + }); + + it("ignores ordinary transactions", () => { + const state = stateWithDoc("Hello\n"); + const tr = state.update({ changes: { from: 6, insert: "typing" } }); + expect(tr.state.field(externalPresenceField).hunks).toHaveLength(0); + }); + + it("maps hunk positions through subsequent edits", () => { + const state = stateWithDoc("Hello\n"); + const tr1 = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: externalSource.of("external"), + }); + // User types at the very start, shifting everything by 3 + const tr2 = tr1.state.update({ changes: { from: 0, insert: "Hi " } }); + const hunks = tr2.state.field(externalPresenceField).hunks; + expect(hunks[0].from).toBe(9); + expect(hunks[0].to).toBe(18); + }); + + it("records a zero-width hunk for a pure deletion", () => { + const state = stateWithDoc("Hello External\n"); + const tr = state.update({ + changes: { from: 6, to: 11, insert: "" }, + annotations: externalSource.of("external"), + }); + const hunks = tr.state.field(externalPresenceField).hunks; + expect(hunks).toHaveLength(1); + expect(hunks[0].from).toBe(6); + expect(hunks[0].to).toBe(6); + }); + + it("drops hunks whose age exceeds the TTL when swept", () => { + const state = stateWithDoc("Hello\n"); + const tr1 = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: externalSource.of("external"), + }); + expect(tr1.state.field(externalPresenceField).hunks).toHaveLength(1); + + const hunkTime = tr1.state.field(externalPresenceField).hunks[0].time; + const tr2 = tr1.state.update({ + effects: expirePresence.of(hunkTime + 5001), + }); + expect(tr2.state.field(externalPresenceField).hunks).toHaveLength(0); + }); + + it("keeps hunks that are still within the TTL when swept", () => { + const state = stateWithDoc("Hello\n"); + const tr1 = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: externalSource.of("external"), + }); + const hunkTime = tr1.state.field(externalPresenceField).hunks[0].time; + const tr2 = tr1.state.update({ + effects: expirePresence.of(hunkTime + 1000), + }); + expect(tr2.state.field(externalPresenceField).hunks).toHaveLength(1); + }); + + it("stays referentially stable across unrelated transactions once empty", () => { + const state = stateWithDoc("Hello\n"); + const tr = state.update({ changes: { from: 6, insert: "typing" } }); + expect(tr.state.field(externalPresenceField)).toBe( + state.field(externalPresenceField), + ); + }); +}); + +describe("externalUndoField", () => { + function stateWithField(doc: string) { + return EditorState.create({ doc, extensions: [externalUndoField] }); + } + + it("tracks an external edit and produces no correction for an unrelated change", () => { + const state = stateWithField("Hello\n"); + const tr = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: externalSource.of("external"), + }); + expect(tr.state.field(externalUndoField).pendingUndo).toHaveLength(1); + expect(tr.state.field(externalUndoField).correction).toBeUndefined(); + }); + + it("computes a correction when a transaction's changes match the tracked external edit's inverse, tagged undo", () => { + let state = stateWithField("Hello\n"); + state = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: externalSource.of("external"), + }).state; + expect(state.sliceDoc()).toBe("Hello\nExternal\n"); + + // Simulate what history's pop() does for an undo: apply the inverse of + // the tracked edit, tagged as a "undo" user event -- without going + // through @codemirror/commands, to keep this test focused purely on the + // field's matching logic. + const inverse = state.field(externalUndoField).pendingUndo[0]; + const tr = state.update({ + changes: inverse, + userEvent: "undo", + }); + + expect(tr.state.sliceDoc()).toBe("Hello\n"); + expect(tr.state.field(externalUndoField).correction).toBeDefined(); + expect(tr.state.field(externalUndoField).pendingUndo).toHaveLength(0); + expect(tr.state.field(externalUndoField).pendingRedo).toHaveLength(1); + }); + + it("does not produce a correction for an undo-tagged transaction that doesn't match the tracked edit", () => { + let state = stateWithField("Hello\n"); + state = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: externalSource.of("external"), + }).state; + + // A local edit's own undo -- same userEvent, unrelated changes. + const tr = state.update({ + changes: { from: 0, to: 5, insert: "" }, + userEvent: "undo", + }); + + expect(tr.state.field(externalUndoField).correction).toBeUndefined(); + // The tracked external edit is untouched by an undo that isn't reverting it. + expect(tr.state.field(externalUndoField).pendingUndo).toHaveLength(1); + }); + + it("clears the redo stack when a genuine new edit lands", () => { + let state = stateWithField("Hello\n"); + state = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: externalSource.of("external"), + }).state; + const inverse = state.field(externalUndoField).pendingUndo[0]; + state = state.update({ changes: inverse, userEvent: "undo" }).state; + expect(state.field(externalUndoField).pendingRedo).toHaveLength(1); + + // The user now types something new instead of redoing. + state = state.update({ changes: { from: 0, insert: "x" } }).state; + expect(state.field(externalUndoField).pendingRedo).toHaveLength(0); + }); + + it("does not carry a stale correction into a later, unrelated transaction", () => { + let state = stateWithField("Hello\n"); + state = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: externalSource.of("external"), + }).state; + const inverse = state.field(externalUndoField).pendingUndo[0]; + state = state.update({ changes: inverse, userEvent: "undo" }).state; + expect(state.field(externalUndoField).correction).toBeDefined(); + + // A later, unrelated selection-only transaction must not still carry + // (and thus re-trigger a dispatch of) the old correction. + state = state.update({ selection: { anchor: 0 } }).state; + expect(state.field(externalUndoField).correction).toBeUndefined(); + }); + + it("does not push addToHistory:false transactions onto the tracked stack", () => { + const state = stateWithField("Hello\n"); + const tr = state.update({ + changes: { from: 6, insert: "External\n" }, + annotations: [ + externalSource.of("external"), + Transaction.addToHistory.of(false), + ], + }); + // Still tracked (externalSource is what matters for tracking, not + // history membership) -- but this exercises the branch that must not + // clear pendingRedo for addToHistory:false transactions. + expect(tr.state.field(externalUndoField).pendingUndo).toHaveLength(1); + }); +}); diff --git a/client/codemirror/external_presence.ts b/client/codemirror/external_presence.ts new file mode 100644 index 00000000..0acb8f17 --- /dev/null +++ b/client/codemirror/external_presence.ts @@ -0,0 +1,330 @@ +import { + Annotation, + type ChangeSet, + type EditorSelection, + type Extension, + type Range, + RangeSet, + StateEffect, + StateField, + Transaction, +} from "@codemirror/state"; +import { + Decoration, + type DecorationSet, + EditorView, + gutter, + GutterMarker, + WidgetType, +} from "@codemirror/view"; + +// How long the presence cursor will appear +const PRESENCE_TTL_MS = 5000; + + +/** Source label of an externally-applied change */ +export const externalSource = Annotation.define(); + +export type PresenceHunk = { + from: number; + to: number; + time: number; + source: string; +}; + +type PresenceState = { hunks: PresenceHunk[] }; + +const emptyPresenceState: PresenceState = { hunks: [] }; + +/** Payload: the `Date.now()` the sweep ran at, so filtering stays pure. */ +export const expirePresence = StateEffect.define(); + +export const externalPresenceField = StateField.define({ + create: () => emptyPresenceState, + + update(value, tr) { + let hunks = value.hunks; + + if (tr.docChanged && hunks.length > 0) { + hunks = hunks + .map((h) => ({ + ...h, + from: tr.changes.mapPos(h.from, 1), + to: tr.changes.mapPos(h.to, -1), + })) + .filter((h) => h.to >= h.from); + } + + const source = tr.annotation(externalSource); + if (source !== undefined) { + const now = Date.now(); + const added: PresenceHunk[] = []; + tr.changes.iterChanges((_fromA, _toA, fromB, toB) => { + added.push({ from: fromB, to: toB, time: now, source }); + }); + if (added.length > 0) { + hunks = [...hunks, ...added]; + } + } + + for (const effect of tr.effects) { + if (effect.is(expirePresence)) { + hunks = hunks.filter((h) => effect.value - h.time < PRESENCE_TTL_MS); + } + } + + return hunks === value.hunks ? value : { hunks }; + }, +}); + +const MAX_TRACKED_EXTERNAL_EDITS = 100; + +export type ExternalUndoState = { + pendingUndo: readonly ChangeSet[]; + pendingRedo: readonly ChangeSet[]; + /** Set only on the transaction that just undid/redid an external edit. */ + correction?: EditorSelection; +}; + +const emptyExternalUndoState: ExternalUndoState = { + pendingUndo: [], + pendingRedo: [], +}; + +// ChangeSet.toJSON() nests arrays (insertions are encoded as sub-arrays), so +// this needs a deep compare, not a shallow one. +function changesEqual(a: ChangeSet, b: ChangeSet): boolean { + return JSON.stringify(a.toJSON()) === JSON.stringify(b.toJSON()); +} + +// What CodeMirror's own history records for any doc-changing transaction +// (see HistEvent.fromTransaction in @codemirror/commands): the changes that +// would revert it, computed against the document it started from. +function invertOf(tr: Transaction): ChangeSet { + return tr.changes.invert(tr.startState.doc); +} + +/** + * Tracks external edits through undo/redo so a revert of one of them can + * keep the user's current cursor instead of CodeMirror's default of + * restoring the selection recorded before the edit landed -- for an edit + * applied before the user has touched the page, that's wherever the cursor + * happened to sit on load (see externalUndoCursorFix below). Local edits are + * untouched: their own pre-edit selection is exactly what undo should + * restore, so only transactions carrying externalSource are tracked here. + * + * pendingUndo/pendingRedo mirror the same two ChangeSet, kept mapped + * forward through every doc change exactly like CodeMirror's own history + * does internally (see mapEvent), so that by the time a real undo/redo of + * a tracked edit arrives, its tr.changes is structurally identical to our + * stored entry -- that structural match is how "this undo/redo is reverting + * an external edit" is recognized. + */ +export const externalUndoField = StateField.define({ + create: () => emptyExternalUndoState, + + update(value, tr) { + let pendingUndo = value.pendingUndo; + let pendingRedo = value.pendingRedo; + let correction: EditorSelection | undefined; + + if (tr.docChanged) { + const topUndo = pendingUndo[pendingUndo.length - 1]; + const topRedo = pendingRedo[pendingRedo.length - 1]; + + if ( + tr.isUserEvent("undo") && topUndo && changesEqual(tr.changes, topUndo) + ) { + pendingUndo = pendingUndo.slice(0, -1).map((cs) => cs.map(tr.changes)); + pendingRedo = [ + ...pendingRedo.map((cs) => cs.map(tr.changes)), + invertOf(tr), + ]; + correction = tr.startState.selection.map(tr.changes); + } else if ( + tr.isUserEvent("redo") && topRedo && changesEqual(tr.changes, topRedo) + ) { + pendingRedo = pendingRedo.slice(0, -1).map((cs) => cs.map(tr.changes)); + pendingUndo = [ + ...pendingUndo.map((cs) => cs.map(tr.changes)), + invertOf(tr), + ]; + correction = tr.startState.selection.map(tr.changes); + } else { + pendingUndo = pendingUndo.map((cs) => cs.map(tr.changes)).filter(( + cs, + ) => !cs.empty); + pendingRedo = pendingRedo.map((cs) => cs.map(tr.changes)).filter(( + cs, + ) => !cs.empty); + + if ( + !tr.isUserEvent("undo") && !tr.isUserEvent("redo") && + tr.annotation(Transaction.addToHistory) !== false + ) { + // A genuine new edit invalidates whatever could previously be + // redone, same as CodeMirror's own history. + pendingRedo = []; + } + + if (tr.annotation(externalSource) !== undefined && !tr.changes.empty) { + pendingUndo = [...pendingUndo, invertOf(tr)]; + } + } + + if (pendingUndo.length > MAX_TRACKED_EXTERNAL_EDITS) { + pendingUndo = pendingUndo.slice(-MAX_TRACKED_EXTERNAL_EDITS); + } + if (pendingRedo.length > MAX_TRACKED_EXTERNAL_EDITS) { + pendingRedo = pendingRedo.slice(-MAX_TRACKED_EXTERNAL_EDITS); + } + } + + if ( + pendingUndo === value.pendingUndo && pendingRedo === value.pendingRedo && + correction === undefined && value.correction === undefined + ) { + return value; + } + return { pendingUndo, pendingRedo, correction }; + }, +}); + +// CodeMirror's undo/redo transactions are dispatched with `filter: false` +// (see HistoryState.pop in @codemirror/commands), which skips the +// EditorState.transactionFilter facet entirely, so there's no way to rewrite +// their selection in place. Instead, externalUndoField above recognizes a +// matching undo/redo as it happens, and this listener issues a follow-up, +// non-historical, selection-only transaction right after. EditorView resets +// updateState to Idle before running update listeners (see +// EditorView.update), so dispatching here is safe and lands within the same +// synchronous flush as the undo/redo -- no visible flicker. +const externalUndoCursorFix = EditorView.updateListener.of((update) => { + const { correction } = update.state.field(externalUndoField); + if (!correction) { + return; + } + update.view.dispatch({ + selection: correction, + annotations: Transaction.addToHistory.of(false), + }); +}); + +class GhostCaretWidget extends WidgetType { + constructor(readonly source: string) { + super(); + } + + override eq(other: GhostCaretWidget) { + return other.source === this.source; + } + + override toDOM() { + const el = document.createElement("span"); + el.className = "sb-external-caret"; + el.setAttribute("data-source", this.source); + return el; + } +} + +class DeletionGutterMarker extends GutterMarker { + override toDOM() { + const el = document.createElement("span"); + el.className = "sb-external-delete-marker"; + return el; + } +} + +const deletionMarker = new DeletionGutterMarker(); + +function buildDecorations(state: PresenceState): DecorationSet { + if (state.hunks.length === 0) { + return Decoration.none; + } + + const decos: Range[] = []; + let newest: PresenceHunk | undefined; + for (const h of state.hunks) { + if (h.to > h.from) { + decos.push( + Decoration.mark({ class: "sb-external-edit" }).range(h.from, h.to), + ); + } + if (!newest || h.time >= newest.time) { + newest = h; + } + } + if (newest) { + decos.push( + Decoration.widget({ + widget: new GhostCaretWidget(newest.source), + side: 1, + }).range(newest.to), + ); + } + return Decoration.set(decos, true); +} + +// A pure deletion collapses to a zero-width hunk (fromB === toB in +// tr.changes.iterChanges), so we mark the line it landed on rather than +// drawing an inline artifact for text that's no longer there. +function buildDeletionMarkers(view: EditorView): RangeSet { + const { hunks } = view.state.field(externalPresenceField); + if (hunks.length === 0) { + return RangeSet.empty; + } + + const docLength = view.state.doc.length; + const lineStarts = new Set(); + for (const h of hunks) { + if (h.to !== h.from) { + continue; + } + const pos = Math.min(Math.max(h.from, 0), docLength); + lineStarts.add(view.state.doc.lineAt(pos).from); + } + if (lineStarts.size === 0) { + return RangeSet.empty; + } + + const ranges = [...lineStarts] + .sort((a, b) => a - b) + .map((pos) => deletionMarker.range(pos)); + return RangeSet.of(ranges); +} + +// Runs once per relevant update rather than off a single owned interval; +// redundant sweeps are cheap and idempotent, and the empty-field early +// return means nothing is scheduled once hunks drain -- no per-view +// instance state is needed to dedupe overlapping timers. +const presenceExpiry = EditorView.updateListener.of((update) => { + const { hunks } = update.state.field(externalPresenceField); + if (hunks.length === 0) { + return; + } + const oldest = Math.min(...hunks.map((h) => h.time)); + const wait = Math.max(50, oldest + PRESENCE_TTL_MS - Date.now()); + setTimeout(() => { + try { + update.view.dispatch({ effects: expirePresence.of(Date.now()) }); + } catch { + // View was destroyed before the sweep fired. + } + }, wait); +}); + +export function externalPresence(): Extension { + return [ + externalPresenceField, + EditorView.decorations.compute([externalPresenceField], (state) => + buildDecorations(state.field(externalPresenceField)), + ), + gutter({ + class: "sb-external-gutter", + markers: buildDeletionMarkers, + }), + presenceExpiry, + externalUndoField, + externalUndoCursorFix, + ]; +} diff --git a/client/styles/editor.scss b/client/styles/editor.scss index 099c4247..39e7ba41 100644 --- a/client/styles/editor.scss +++ b/client/styles/editor.scss @@ -89,6 +89,52 @@ border-right: none; } + .sb-external-gutter .cm-gutterElement { + padding: 0 3px; + } + + .sb-external-delete-marker { + display: block; + margin: 0 auto; + width: 4px; + height: 4px; + border-radius: 50%; + background-color: var(--editor-external-caret-color); + } + + .sb-external-edit { + background-color: var(--editor-external-edit-color); + transition: background-color 3s ease-out 1s; + } + + .sb-external-caret { + position: relative; + border-left: 2px solid var(--editor-external-caret-color); + margin-left: -1px; + animation: sb-external-caret-blink 1s steps(1) infinite; + + &::after { + content: attr(data-source); + position: absolute; + top: -1.1em; + left: -2px; + font-size: 0.65em; + line-height: 1.3; + padding: 0 4px; + border-radius: 3px; + background-color: var(--editor-external-caret-color); + color: var(--ui-accent-contrast-color); + white-space: nowrap; + pointer-events: none; + } + } + + @keyframes sb-external-caret-blink { + 50% { + border-left-color: transparent; + } + } + .cm-foldPlaceholder { background-color: transparent; border: 0; diff --git a/client/styles/theme.scss b/client/styles/theme.scss index 7397f60f..864781eb 100644 --- a/client/styles/theme.scss +++ b/client/styles/theme.scss @@ -125,6 +125,8 @@ html { --editor-code-background-color: var(--subtle-background-color); --editor-struct-color: darkred; --editor-highlight-background-color: var(--highlight-color); + --editor-external-edit-color: rgba(255, 191, 71, 0.28); + --editor-external-caret-color: #e8a33d; --editor-code-comment-color: var(--meta-subtle-color); --editor-code-variable-color: #024866; --editor-code-typename-color: #038138; @@ -308,6 +310,8 @@ html[data-theme="dark"] { --editor-code-background-color: var(--subtle-background-color); --editor-struct-color: #d6222e; --editor-highlight-background-color: var(--highlight-color); + --editor-external-edit-color: rgba(255, 191, 71, 0.18); + --editor-external-caret-color: #d99a2b; --editor-code-comment-color: var(--meta-subtle-color); --editor-code-variable-color: #41a3ce; --editor-code-typename-color: #038138;