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
client/text editor: fix some issues
Adorian Doran88d0a0f812f8
diff --git a/apps/client/src/services/block_excerpts.ts b/apps/client/src/services/block_excerpts.tsindex f070dd8a29..fec6acf46b 100644--- a/apps/client/src/services/block_excerpts.ts+++ b/apps/client/src/services/block_excerpts.ts@@ -150,7 +150,7 @@ function getText(element: Element) {}}- return (source.textContent ?? "").replace(/\s+/g, " ").trim();+ return (source.textContent as string).replace(/\s+/g, " ").trim();}function truncate(text: string, maxLength: number) {diff --git a/apps/client/src/widgets/dialogs/edit_link.tsx b/apps/client/src/widgets/dialogs/edit_link.tsxindex a9ea19c95c..b7721c227f 100644--- a/apps/client/src/widgets/dialogs/edit_link.tsx+++ b/apps/client/src/widgets/dialogs/edit_link.tsx@@ -412,7 +412,7 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {? opts.text || heading.title: linkTitle.trim() || null;opts.addLink(heading.createLinkPath(), title);- } else if (anchor) {+ } else {// A link without a text of its own reads as the anchor's name. `true` keeps the// href of an anchor link as it is.opts.addLink(`#${anchor}`, linkTitle.trim() || anchor, true);diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsxindex 74a5614074..50188465b6 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx@@ -1,4 +1,6 @@-import type { CKEditorError, CKTextEditor } from "@triliumnext/ckeditor5";+import type {+ CKEditorError, CKTextEditor, DocumentHeading, ModelElement+} from "@triliumnext/ckeditor5";import { createRef, render } from "preact";import { useRef } from "preact/hooks";import { act } from "preact/test-utils";@@ -14,7 +16,9 @@ const mocks = vi.hoisted(() => ({stopReportingErrors: vi.fn(),reportError: undefined as ((error: Error) => void) | undefined,reportingEditor: undefined as unknown,- note: undefined as { noteId: string; title: string } | undefined+ note: undefined as { noteId: string; title: string } | undefined,+ getHeadings: vi.fn((_editor: unknown): DocumentHeading[] => []),+ assignBlockId: vi.fn((_model: unknown, _element: unknown) => "new")}));vi.mock("@triliumnext/ckeditor5", () => {@@ -36,6 +40,8 @@ vi.mock("@triliumnext/ckeditor5", () => {CKTextEditor: class {},ClassicEditor: MockEditor,PopupEditor: MockEditor,+ getHeadings: mocks.getHeadings,+ assignBlockId: mocks.assignBlockId,onTextEditorError: (editor: unknown, callback: (error: Error) => void) => {mocks.reportingEditor = editor;mocks.reportError = callback;@@ -74,6 +80,8 @@ beforeEach(() => {mocks.stopReportingErrors.mockClear();mocks.reportError = undefined;mocks.reportingEditor = undefined;+ mocks.getHeadings.mockReset();+ mocks.assignBlockId.mockReset();host = document.body.appendChild(document.createElement("div"));});@@ -192,4 +200,33 @@ describe("CKEditor", () => {expect(opts?.getNoteId?.()).toBe("host2");});++ it("lists the headings of its editor and gives one a block id, while it has one", async () => {+ const props = {+ contentLanguage: null,+ editorRef: createRef<CKTextEditor>(),+ onChange: vi.fn(),+ editorApi: createRef<CKEditorApi>(),+ templates: []+ };+ await act(async () => {+ render(<CKEditor {...props} />, host);+ });+ await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());+ const api = props.editorApi.current;+ const editor = props.editorRef.current;+ const heading = { element: {} as ModelElement, level: 2, text: "Intro" };+ mocks.getHeadings.mockReturnValue([ heading ]);++ expect(api?.getHeadings()).toEqual([ heading ]);+ expect(mocks.getHeadings).toHaveBeenCalledExactlyOnceWith(editor);+ expect(api?.assignBlockId(heading)).toBe("new");+ expect(mocks.assignBlockId)+ .toHaveBeenCalledExactlyOnceWith(editor?.model, heading.element);++ await act(async () => render(null, host));+ await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalledOnce());+ expect(api?.getHeadings()).toEqual([]);+ expect(api?.assignBlockId(heading)).toBeUndefined();+ });});diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex 9f6b31618b..a12469c571 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -9,11 +9,18 @@import type {CKEditorError, CKTextEditor, DocumentHeading, FileUploadData, LinkAtSelection, ModelElement} from "@triliumnext/ckeditor5";+import { type ComponentProps, h } from "preact";+import { act } from "preact/test-utils";import { beforeEach, describe, expect, it, vi } from "vitest";+import type NoteContext from "../../../components/note_context";import type FAttachment from "../../../entities/fattachment";+import type FNote from "../../../entities/fnote";import froca from "../../../services/froca";import type LoadResults from "../../../services/load_results";+import { renderInto } from "../../../test/render";+import type { EditLinkBalloon } from "../../dialogs/edit_link";+import type CKEditor from "./CKEditor";const showError = vi.hoisted(() => vi.fn());const showErrorTitleAndMessage = vi.hoisted(() => vi.fn());@@ -41,7 +48,38 @@ vi.mock("./utils", async (importOriginal) => ({showsAttachmentSave}));+// Stand-ins for what `EditableText` renders, which keep the props they receive.+const rendered = vi.hoisted(() => ({+ editor: undefined as ComponentProps<typeof CKEditor> | undefined,+ balloon: undefined as ComponentProps<typeof EditLinkBalloon> | undefined+}));+vi.mock("./CKEditor", () => ({+ default: (props: ComponentProps<typeof CKEditor>) => {+ rendered.editor = props;+ return null;+ }+}));+vi.mock("../../dialogs/edit_link", () => ({+ EditLinkBalloon: (props: ComponentProps<typeof EditLinkBalloon>) => {+ rendered.balloon = props;+ return "edit link balloon";+ }+}));+vi.mock("./snippets.js", () => ({ default: async () => [], updateTemplateCache: vi.fn() }));+vi.mock("../../react/hooks", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../react/hooks")>(),+ useEditorSpacedUpdate: () => ({}),+ useLegacyImperativeHandlers: () => {},+ useNoteLabel: () => [ null ],+ useSameNoteSwitch: () => {},+ useSearchTermsConsumer: () => {},+ useTriliumEvent: () => {},+ useTriliumOption: () => [ "" ],+ useTriliumOptionBool: () => [ false ]+}));+const {+ default: EditableText,applyPendingAttachmentChanges,getEditLinkOpts,getBlockData,@@ -455,27 +493,41 @@ describe("parseLinkHref", () => {});});-describe("getEditLinkOpts", () => {- function createApi(- currentLink: LinkAtSelection | null, anchors: string[] = [],- headings: DocumentHeading[] = []- ) {- return {- hasSelection: vi.fn(() => true),- getSelectedText: vi.fn(() => "chosen words"),- getCurrentLink: vi.fn(() => currentLink),- getAnchors: vi.fn(() => anchors),- getHeadings: vi.fn(() => headings),- assignBlockId: vi.fn<(heading: DocumentHeading) => string | undefined>(() => "new"),- addLink: vi.fn(),- updateLink: vi.fn(),- addLinkPreview: vi.fn(),- addLinkToEditor: vi.fn(),- addHtmlToEditor: vi.fn(),- addContentEmbed: vi.fn(),- addImage: vi.fn(async () => {})+describe("EditableText", () => {+ it("opens the link balloon at the caret, on the headings of the note it edits", async () => {+ renderInto(h(EditableText, {+ note: { noteId: "abc" } as FNote,+ noteContext: { notePath: "root/abc" } as NoteContext,+ viewScope: undefined,+ ntxId: "ntx",+ parentComponent: undefined+ }));+ await vi.waitFor(() => expect(rendered.editor).toBeDefined());+ const heading = { element: {} as ModelElement, level: 2, text: "Intro" };+ const editorApi = rendered.editor?.editorApi;+ if (editorApi) {+ editorApi.current = createApi(null, [], [ heading ]);+ }+ const request = {+ container: document.createElement("div"), close: vi.fn(), target: "note" as const};- }++ let closeBalloon: (() => void) | null | undefined;+ act(() => {+ closeBalloon = rendered.editor?.showLinkDialog?.(request);+ });+ expect(request.container.textContent).toBe("edit link balloon");+ expect(rendered.balloon?.onClose).toBe(request.close);+ const opts = rendered.balloon?.opts;+ expect(opts).toMatchObject({ target: "note", headings: [ { title: "Intro" } ] });+ expect(opts?.headings?.[0]?.createLinkPath()).toBe("root/abc?block=new");++ act(() => closeBalloon?.());+ expect(request.container.textContent).toBe("");+ });+});++describe("getEditLinkOpts", () => {const ready = async () => {};it("edits the link at the caret, rewriting it on save", async () => {@@ -598,3 +650,23 @@ describe("getEditLinkOpts", () => {});});});++function createApi(+ currentLink: LinkAtSelection | null, anchors: string[] = [], headings: DocumentHeading[] = []+) {+ return {+ hasSelection: vi.fn(() => true),+ getSelectedText: vi.fn(() => "chosen words"),+ getCurrentLink: vi.fn(() => currentLink),+ getAnchors: vi.fn(() => anchors),+ getHeadings: vi.fn(() => headings),+ assignBlockId: vi.fn<(heading: DocumentHeading) => string | undefined>(() => "new"),+ addLink: vi.fn(),+ updateLink: vi.fn(),+ addLinkPreview: vi.fn(),+ addLinkToEditor: vi.fn(),+ addHtmlToEditor: vi.fn(),+ addContentEmbed: vi.fn(),+ addImage: vi.fn(async () => {})+ };+}