Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(text): offer to reload the editor after an error
Elian Doranbd6e75e0a229
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 92a49bd510..41067ef76e 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1558,7 +1558,8 @@"nothing_selected_to_cut": "Select some text first to cut it into a sub-note.","uploading_attachment": "Uploading attachment","editor_error_title": "The text editor ran into an error",- "editor_error_content": "The editor is still open, but it might not work correctly until you reload Trilium. If anything looks wrong, copy your latest changes somewhere safe first."+ "editor_error_content": "The editor might not show your latest changes correctly. Reload the editor to continue: your changes are saved first.",+ "editor_error_reload_button": "Reload editor"},"empty": {"open_note_instruction": "Open a note by typing the note's title into the input below or choose a note in the tree.",diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsxindex 8782d588bd..db4328ec43 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx@@ -117,6 +117,34 @@ describe("CKEditor", () => {expect(mocks.reportingEditor).toBe(props.editorRef.current);});+ it("rebuilds the editor for a new rebuildKey, even when destroying the old one fails", async () => {+ const props = {+ contentLanguage: null,+ editorRef: createRef<CKTextEditor>(),+ onChange: vi.fn(),+ editorApi: createRef<CKEditorApi>(),+ templates: []+ };+ await act(async () => {+ render(<CKEditor {...props} rebuildKey={0} />, host);+ });+ await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());+ const crashedEditor = props.editorRef.current;++ mocks.destroy.mockRejectedValueOnce(new Error("destroy failed"));+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ await act(async () => {+ render(<CKEditor {...props} rebuildKey={1} />, host);+ });++ await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledTimes(2));+ expect(mocks.destroy).toHaveBeenCalledOnce();+ expect(props.editorRef.current).not.toBeNull();+ expect(props.editorRef.current).not.toBe(crashedEditor);+ expect(warn).toHaveBeenCalledWith("CKEditor destroy failed", expect.any(Error));+ warn.mockRestore();+ });+it("hands the errors of its editor to onEditorError, until it destroys the editor", async () => {const onEditorError = vi.fn();const props = {diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsxindex 56a8202dc1..b20792d829 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx@@ -55,10 +55,12 @@ interface CKEditorProps extends Pick<HTMLAttributes<HTMLDivElement>, "className"onEditorInitialized?: (editor: CKTextEditor) => void;editorApi: RefObject<CKEditorApi | null>;templates: SnippetDefinition[];+ /** Rebuilds the editor each time it changes, e.g. to recover from an error. */+ rebuildKey?: number;containerRef?: RefObject<HTMLDivElement | null>;}-export default function CKEditor({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, editorRef: externalEditorRef, onNotificationWarning, onNotificationInfo, onEditorError, onChange, onEditorInitialized, editorApi, templates }: CKEditorProps) {+export default function CKEditor({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, editorRef: externalEditorRef, onNotificationWarning, onNotificationInfo, onEditorError, onChange, onEditorInitialized, editorApi, templates, rebuildKey }: CKEditorProps) {const containerRef = useSyncedRef<HTMLDivElement>(externalContainerRef, null);const editorRef = useRef<CKTextEditor>(null);const stopReportingErrorsRef = useRef<() => void>(undefined);@@ -274,7 +276,7 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLaconst scrollContainer = container.closest<HTMLElement>(".scrolling-container");const scrollTop = scrollContainer?.scrollTop ?? 0;- await destroyEditor();+ await destroyEditor().catch((e) => console.warn("CKEditor destroy failed", e));if (isStale) return;const editor = await buildEditor(container, !!isClassicEditor, {@@ -341,7 +343,7 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLacontentLanguage, uiLanguage, isClassicEditor, multilineToolbar, mathFieldEnabled,doubleQuoteStyle, singleQuoteStyle, punctuationReplacements, mathReplacements, symbolReplacements,customReplacements, defaultContentLanguage, htmlSupportEnabled, allowedHtmlTags,- aiEnabled, llmProviders+ aiEnabled, llmProviders, rebuildKey]);// Destroys the editor when the component goes away, after a build still in progress.diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex de519c3ce2..140bf146c3 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -43,13 +43,14 @@ const {} = await import("./EditableText");describe("reportEditorError", () => {- it("shows a toast that opens the details, leaving the log to the global handler", () => {+ it("shows a toast that reloads the editor or opens the details, leaving the log to the global handler", () => {vi.clearAllMocks();const logError = vi.fn();vi.stubGlobal("logError", logError);const error = new Error("unexpected-error Original error: TypeError: boom") as CKEditorError;+ const reloadEditor = vi.fn();- reportEditorError(error);+ reportEditorError(error, reloadEditor);expect(logError).not.toHaveBeenCalled();expect(showPersistent).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({@@ -58,9 +59,21 @@ describe("reportEditorError", () => {message: "editable_text.editor_error_content"}));- const [ { buttons } ] = showPersistent.mock.calls[0];+ const [ { buttons, timeout } ] = showPersistent.mock.calls[0];+ expect(timeout).toBeUndefined();+ expect(buttons.map((button: { text: string }) => button.text)).toEqual([+ "editable_text.editor_error_reload_button",+ "editable_text.editor_crashed_details_button"+ ]);++ const dismissReload = vi.fn();+ buttons[0].onClick({ dismissToast: dismissReload });+ expect(dismissReload).toHaveBeenCalledOnce();+ expect(reloadEditor).toHaveBeenCalledOnce();+ expect(showInfoDialog).not.toHaveBeenCalled();+const dismissToast = vi.fn();- buttons[0].onClick({ dismissToast });+ buttons[1].onClick({ dismissToast });expect(dismissToast).toHaveBeenCalledOnce();expect(showInfoDialog).toHaveBeenCalledExactlyOnceWith(expect.anything(),diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 043b46c331..8ecfa1ccb0 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -154,6 +154,16 @@ export default function EditableText({}});const templates = useTemplates();+ const [ editorRebuildKey, setEditorRebuildKey ] = useState(0);++ /** Saves what the model holds, then builds a new editor from the saved content. */+ async function reloadEditor() {+ try {+ await spacedUpdate.updateNowIfNecessary();+ } finally {+ setEditorRebuildKey((key) => key + 1);+ }+ }useSearchTermsConsumer(note, noteContext, ntxId);// A hidden widget leaves the link target to the one on display.@@ -601,7 +611,8 @@ export default function EditableText({templates={templates}onNotificationWarning={onNotificationWarning}onNotificationInfo={onNotificationInfo}- onEditorError={reportEditorError}+ onEditorError={(error) => reportEditorError(error, reloadEditor)}+ rebuildKey={editorRebuildKey}onChange={() => {spacedUpdate.scheduleUpdate();const editor = editorRef.current;@@ -750,13 +761,13 @@ function useTemplates() {}/**- * Tells the user about an error that escaped the editor in a toast, which opens the error details- * for a bug report. The editor keeps running, so a later error replaces the toast. The global error- * handlers in `glob.ts` log the error.+ * Tells the user about an error that escaped the editor in a toast, which offers to reload the+ * editor and opens the error details for a bug report. The editor keeps running until then, so a+ * later error replaces the toast. The global error handlers in `glob.ts` log the error.** Exported for testing.*/-export function reportEditorError(error: CKEditorError) {+export function reportEditorError(error: CKEditorError, reloadEditor: () => void) {const details = JSON.stringify({message: error.message,stack: error.stack,@@ -769,6 +780,13 @@ export function reportEditorError(error: CKEditorError) {title: t("editable_text.editor_error_title"),message: t("editable_text.editor_error_content"),buttons: [+ {+ text: t("editable_text.editor_error_reload_button"),+ onClick: ({ dismissToast }) => {+ dismissToast();+ reloadEditor();+ }+ },{text: t("editable_text.editor_crashed_details_button"),onClick: ({ dismissToast }) => {@@ -784,8 +802,7 @@ export function reportEditorError(error: CKEditorError) {});}}- ],- timeout: 20_000+ ]});}