Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: fix some issues

Adorian Doran3e3af5ee6eed
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
index da2881455f..da0da680d3 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
@@ -22,6 +22,8 @@ export interface CodeEmbedEditorProps {
useTabs: boolean | undefined;
/** Holds the CodeMirror view while the editor is open, and `null` once it goes away. */
viewRef: RefObject<VanillaCodeMirror | null>;
+ /** Whether the editor shows. "Search in note" skips a hidden one. Shown by default. */
+ isShown?: boolean;
/** Receives the edited content when the editor goes away. */
onClose: (content: string) => void;
/** Receives the content as it is edited. */
@@ -35,7 +37,8 @@ export interface CodeEmbedEditorProps {
* `editor`, the content is read-only.
*/
export default function CodeEmbedEditor({
- note, editor, content, mime, tabWidth, useTabs, viewRef, onClose, onChange, onReady
+ note, editor, content, mime, tabWidth, useTabs, viewRef, isShown = true, onClose, onChange,
+ onReady
}: CodeEmbedEditorProps) {
const isLoadingRef = useRef(false);
const [ vimKeymapEnabled ] = useTriliumOptionBool("vimKeymapEnabled");
@@ -45,12 +48,25 @@ export default function CodeEmbedEditor({
// Runs after the effects of `CodeMirror`, which creates the view.
useEffect(() => {
const view = viewRef.current;
- if (!view) return;
-
- onReady?.(view);
- return registerEmbedFindTarget(view.dom, new CodeMirrorFindTarget(view));
+ if (view) {
+ onReady?.(view);
+ }
}, []);
+ useEffect(() => {
+ const view = viewRef.current;
+ if (!view || !isShown) return;
+
+ const unregister = registerEmbedFindTarget(view.dom, new CodeMirrorFindTarget(view));
+ return () => {
+ unregister();
+ // Clears the search matches of an editor that is hidden rather than unmounted.
+ if (view.dom.isConnected) {
+ view.cleanSearch();
+ }
+ };
+ }, [ isShown ]);
+
// Runs after the effects of `CodeMirror`, which empties the document as it mounts.
useEffect(() => {
const view = viewRef.current;
diff --git a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx
index 36ac508604..801213f774 100644
--- a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx
@@ -1,3 +1,4 @@
+import type VanillaCodeMirror from "@triliumnext/codemirror";
import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -128,17 +129,46 @@ describe("MarkdownEmbed", () => {
});
expect(isEntered).toBe(true);
expect(view.hasFocus).toBe(true);
+ await getEmbedFindTarget(figure)?.find("a", { matchCase: false, wholeWord: false });
+ expect(view.getSearchMatches()).toHaveLength(1);
- await act(async () => {
- figure.dataset.displayMode = "preview";
- await Promise.resolve();
- });
- expect(figure.querySelector(".cm-editor")).toBeNull();
+ await showDisplayMode(figure, "preview");
expect(getEmbedFindTarget(figure)).toBeNull();
expect(enterContentEmbed(figure, "start")).toBe(false);
+ expect(view.getSearchMatches()).toHaveLength(0);
+
+ await showDisplayMode(figure, "split");
+ expect(getEmbedFindTarget(figure)).toBeInstanceOf(CodeMirrorFindTarget);
+ act(() => {
+ isEntered = enterContentEmbed(figure, "start");
+ });
+ expect(isEntered).toBe(true);
+ });
+
+ it("keeps the edited source, its undo history and cursor, behind the preview", async () => {
+ const { figure } = await mount(buildMarkdownNote("a"), buildEditor(), {
+ isEditable: true
+ });
+ const view = await findView(figure);
+ act(() => view.dispatch({ changes: { from: 1, insert: "b" }, selection: { anchor: 2 } }));
+
+ await showDisplayMode(figure, "preview");
+ await showDisplayMode(figure, "split");
+ expect(await findView(figure)).toBe(view);
+ expect(view.state.selection.main.head).toBe(2);
+ pressCtrl(view, "z");
+ expect(view.state.doc.toString()).toBe("a");
});
});
+/** Picks the display mode `mode` on the embed `figure`. */
+async function showDisplayMode(figure: HTMLElement, mode: string) {
+ await act(async () => {
+ figure.dataset.displayMode = mode;
+ await Promise.resolve();
+ });
+}
+
interface MountOptions {
isEditable?: boolean;
preview?: HTMLElement;
@@ -237,5 +267,5 @@ async function findView(figure: HTMLElement) {
expect(view).not.toBeNull();
}, { timeout: 5000 });
if (!view) throw new Error("CodeMirror did not mount.");
- return view as InstanceType<typeof EditorView>;
+ return view as VanillaCodeMirror;
}
diff --git a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx
index 85ce479333..483992261a 100644
--- a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx
@@ -70,6 +70,7 @@ export default function MarkdownEmbed({
useSyncedHighlight(shownView, previewElement, renderedContent);
useNoteLinkChips(shownView);
useMarkdownKeymap(isEditing ? shownView : null);
+ const caretNavigationRoot = isEditing && isSourceShown ? rootRef : null;
return (
<div
@@ -81,11 +82,11 @@ export default function MarkdownEmbed({
orientation={isDesktop() ? "horizontal" : "vertical"}
editor={(
<div className="note-detail-split-editor">
- {/* Split.js sizes this column, so it stays mounted. CodeMirror is mounted
- only while the source shows, so that "Search in note" and the arrow
- keys never act on a hidden editor. */}
- {isSourceShown && (
- <CaretNavigationContext.Provider value={isEditing ? rootRef : null}>
+ {/* An edited source stays mounted while the preview shows alone, which
+ keeps its undo history. "Search in note" and the arrow keys skip it
+ then. */}
+ {(isEditing || isSourceShown) && (
+ <CaretNavigationContext.Provider value={caretNavigationRoot}>
<CodeEmbedEditor
key={isEditing ? "editing" : "read-only"}
note={note}
@@ -95,6 +96,7 @@ export default function MarkdownEmbed({
tabWidth={tabWidth}
useTabs={useTabs}
viewRef={viewRef}
+ isShown={isSourceShown}
onClose={setContent}
onChange={setContent}
onReady={setView}
diff --git a/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx
index de99e3d47e..846c95e3e6 100644
--- a/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx
@@ -245,6 +245,9 @@ describe("useEmbedCaretNavigation", () => {
expect(leaveEmbed).toHaveBeenCalledExactlyOnceWith(
figure.querySelector(".caret-content"), "end"
);
+ expect(editor.prepareToLeave).toHaveBeenCalledOnce();
+ expect(editor.prepareToLeave.mock.invocationCallOrder[0])
+ .toBeLessThan(leaveEmbed.mock.invocationCallOrder[0]);
expect(onKeyDown).not.toHaveBeenCalled();
leaveEmbed.mockReturnValue(false);
@@ -252,10 +255,13 @@ describe("useEmbedCaretNavigation", () => {
editor.getEdgeLeftBy.mockReturnValue(null);
expect(pressKey()).toBe(false);
expect(leaveEmbed).toHaveBeenCalledTimes(2);
+ expect(editor.prepareToLeave).toHaveBeenCalledTimes(2);
expect(onKeyDown).toHaveBeenCalledTimes(2);
unmount();
- const outside = mountCaretProbe(buildCaretEditor("end"), { hasHost: false });
+ const outside = mountCaretProbe(
+ { focusAt: vi.fn(), getEdgeLeftBy: () => "end" }, { hasHost: false }
+ );
expect(outside.pressKey()).toBe(false);
outside.unmount();
});
@@ -338,7 +344,8 @@ function mountCaretProbe(
function buildCaretEditor(edge: EmbedEdge | null) {
return {
focusAt: vi.fn(),
- getEdgeLeftBy: vi.fn((_event: KeyboardEvent): EmbedEdge | null => edge)
+ getEdgeLeftBy: vi.fn((_event: KeyboardEvent): EmbedEdge | null => edge),
+ prepareToLeave: vi.fn()
};
}
diff --git a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
index aae8543efa..c4f0f3112b 100644
--- a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
@@ -110,6 +110,8 @@ export interface EmbeddedCaretEditor {
* its completions, takes the key.
*/
getEdgeLeftBy(event: KeyboardEvent): EmbedEdge | null;
+ /** Runs before the caret leaves the editor past an edge, while the editor has the focus. */
+ prepareToLeave?(): void;
}
/**
@@ -130,8 +132,12 @@ export function useEmbedCaretNavigation(
// The capture phase runs before the editor handles the key.
const onKeyDown = (event: KeyboardEvent) => {
- const edge = getEditorRef.current()?.getEdgeLeftBy(event);
- if (edge && leaveContentEmbed(root, edge)) {
+ const editor = getEditorRef.current();
+ const edge = editor?.getEdgeLeftBy(event);
+ if (!editor || !edge) return;
+
+ editor.prepareToLeave?.();
+ if (leaveContentEmbed(root, edge)) {
event.preventDefault();
event.stopPropagation();
}
diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.ts
index 5a7012a9e6..37c6ab7f22 100644
--- a/packages/codemirror/src/index.spec.ts
+++ b/packages/codemirror/src/index.spec.ts
@@ -411,6 +411,22 @@ describe("CodeMirror", () => {
expect(instance.getEdgeLeftBy(arrowLeft)).toBe(null);
});
+ it("drops the line-wrap side of the cursor before the caret leaves", () => {
+ const instance = build();
+ editor = instance;
+ instance.setText("ab\ncd");
+ instance.dispatch({ selection: EditorSelection.cursor(4, -1) });
+
+ instance.prepareToLeave();
+ expect(instance.state.selection.main).toMatchObject({ head: 4, assoc: 0 });
+ for (const selection of [ EditorSelection.cursor(4), EditorSelection.range(0, 1) ]) {
+ instance.dispatch({ selection });
+ const { state } = instance;
+ instance.prepareToLeave();
+ expect(instance.state).toBe(state);
+ }
+ });
+
it("leaves the arrow keys to an open completion list", async () => {
const instance = build();
editor = instance;
diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.ts
index cbb3d639a4..5d74bc91a2 100644
--- a/packages/codemirror/src/index.ts
+++ b/packages/codemirror/src/index.ts
@@ -358,6 +358,19 @@ export default class CodeMirror extends EditorView {
}
}
+ /**
+ * Drops the line-wrap side (`assoc`) of the cursor before the caret leaves the editor. On a
+ * focus change, CodeMirror moves the DOM selection to that side, which focuses the editor
+ * again.
+ */
+ prepareToLeave() {
+ const { main } = this.state.selection;
+ if (!main.empty || !main.assoc) return;
+
+ const cursor = EditorSelection.cursor(main.head);
+ this.dispatch({ selection: this.state.selection.replaceRange(cursor) });
+ }
+
/**
* Inserts a blank line at the very top of the document and places the cursor on it — the code-note
* analog of the Notion-like behavior when pressing Enter in the note title. If the first line is