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: fix some issues
Adorian Doran3945f053a9ac
diff --git a/apps/client/src/widgets/note_wrapper.spec.ts b/apps/client/src/widgets/note_wrapper.spec.tsindex 501d9217a7..12b9ba2b60 100644--- a/apps/client/src/widgets/note_wrapper.spec.ts+++ b/apps/client/src/widgets/note_wrapper.spec.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import type NoteContext from "../components/note_context";import type FNote from "../entities/fnote";@@ -55,6 +55,19 @@ describe("NoteWrapperWidget", () => {expect(widget.$widget.hasClass("last-visible")).toBe(true);});+ it("adds the classes of a note split at any whitespace", () => {+ // A browser refuses a class with whitespace in `classList.add()`; happy-dom accepts it.+ const add = vi.spyOn(Object.getPrototypeOf(document.body.classList) as DOMTokenList, "add");+ const widget = new NoteWrapperWidget();+ widget.render();+ showNote(widget, buildNote({ title: "Styled", type: "text", "#cssClass": "a\tb\nc\r\nd" }));+ const added = add.mock.calls.flat();+ add.mockRestore();++ expect(added).toEqual(expect.arrayContaining([ "a", "b", "c", "d", "type-text" ]));+ expect(added.filter((cls) => /\s/.test(cls))).toEqual([]);+ });+it("marks the split as translucent (bgfx) for the note types that render on a bare background", () => {expect(hasBackgroundEffects(buildNote({ title: "Photo", type: "image" }))).toBe(true);diff --git a/apps/client/src/widgets/note_wrapper.ts b/apps/client/src/widgets/note_wrapper.tsindex 6822e21483..ea48f5ddd9 100644--- a/apps/client/src/widgets/note_wrapper.ts+++ b/apps/client/src/widgets/note_wrapper.ts@@ -46,7 +46,7 @@ export default class NoteWrapperWidget extends FlexContainer<BasicWidget> {}refresh() {- const classes = new Set(this.getClasses().join(" ").split(" ").filter(Boolean));+ const classes = new Set(this.getClasses().join(" ").split(/[\t\n\f\r ]+/).filter(Boolean));// Only the difference is applied: a class change on the split restyles the whole note.const classList = this.$widget[0].classList;@@ -62,7 +62,7 @@ export default class NoteWrapperWidget extends FlexContainer<BasicWidget> {}}- /** The classes of the split, each entry holding one or more space-separated class names. */+ /** The classes of the split, each entry holding one or more class names split by whitespace. */private getClasses() {// These are owned by SplitNoteContainer, not by the note, so they are kept as they are.const classes = CONTAINER_OWNED_CLASSES.filter((cls) => this.$widget.hasClass(cls));diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsxindex f4652478de..58404b3826 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.spec.tsx@@ -744,9 +744,16 @@ describe("useCanvasDrawingPersistence", () => {act(() => render(null, other));});- it("keeps the picture of a save made while it checks the loaded picture", async () => {+ it.each([+ [ "the scene", { elements: [ { id: "r1", type: "rectangle", version: 4 } ] } ],+ [ "the background alone", { appState: { viewBackgroundColor: "#ffc9c9" } } ]+ ])("keeps the picture of a save of %s made while it checks the loaded picture", async (+ _,+ edit: { elements?: FakeElement[]; appState?: object }+ ) => {vi.useFakeTimers();const post = vi.spyOn(server, "post").mockResolvedValue(undefined);+ vi.mocked(exportToSvg).mockClear();let finishCheck = () => {};const pictures = new Promise((resolve) => {finishCheck = () => resolve([@@ -762,7 +769,8 @@ describe("useCanvasDrawingPersistence", () => {sceneElements = loaded;change();- sceneElements = [ { ...loaded[0], version: 4 } ];+ sceneElements = edit.elements ?? sceneElements;+ appState = { ...appState, ...edit.appState };change();const [ getContent, onSaved ] = editor.scheduleSave.mock.calls[0];const saved = getContent();@@ -772,8 +780,9 @@ describe("useCanvasDrawingPersistence", () => {finishCheck();await vi.advanceTimersByTimeAsync(30000);});- expect(vi.mocked(exportToSvg).mock.calls.map(([ { elements } ]) => elements))- .toEqual([ sceneElements ]);+ expect(vi.mocked(exportToSvg).mock.calls.map(([ { elements, appState } ]) =>+ ({ elements, background: appState?.viewBackgroundColor })))+ .toEqual([ { elements: sceneElements, background: appState.viewBackgroundColor } ]);expect(post).toHaveBeenCalledOnce();post.mockRestore();});diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.tsindex 07051e42da..79349217c8 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts@@ -29,7 +29,7 @@ import { type DrawingView, getBoundedView, getFittedView } from "./drawing_view"import {buildNewImageAttachments, CANVAS_EXPORT_TITLE, IMAGE_ROLE, loadImageAttachments, loadImageFiles} from "./image_attachments";-import { schedulePicture } from "./picture_schedule";+import { schedulePicture, watchPictures } from "./picture_schedule";interface AttachmentMetadata {title: string;@@ -900,8 +900,9 @@ async function saveNotePicture(noteId: string, scene: PictureScene, files: Binar}/**- * Schedules a picture of `scene`, loaded from `note`, when the saved one is missing or older.- * `isCurrent()` returns `false` once a change replaced the scene, which then gets no picture.+ * Schedules a picture of `scene`, loaded from `note`, when the saved one is missing or older. None+ * is scheduled once a change replaced the scene, as `isCurrent()` tells, or once a save scheduled a+ * picture of its own.*/async function refreshNotePicture(note: FNote,@@ -910,11 +911,12 @@ async function refreshNotePicture(isCurrent: () => boolean) {if (!(scene.elements ?? []).some((element) => !element.isDeleted)) return;+ const isUnscheduled = watchPictures(note.noteId);try {const picture = await getPicture(note, CANVAS_EXPORT_TITLE);const isOutdated = !picture|| picture.utcDateModified < (await note.getMetadata()).utcDateModified;- if (isOutdated && isCurrent()) {+ if (isOutdated && isCurrent() && isUnscheduled()) {scheduleNotePicture(note.noteId, scene, files);}} catch (e) {@@ -933,7 +935,8 @@ function scheduleDrawingPicture(drawing: FAttachment, content: string, files: Bi/*** Schedules a picture of `drawing`, saved as `content`, when the saved one is missing or older.- * `isCurrent()` returns `false` once a change replaced the content, which then gets no picture.+ * None is scheduled once a change replaced the content, as `isCurrent()` tells, or once a save from+ * any view of the drawing scheduled a picture of its own.*/async function refreshDrawingPicture(drawing: FAttachment,@@ -941,12 +944,13 @@ async function refreshDrawingPicture(files: BinaryFiles,isCurrent: () => boolean) {+ const isUnscheduled = watchPictures(drawing.attachmentId);try {const owner = await froca.getNote(drawing.ownerId);if (!owner) return;const picture = await getPicture(owner, getDrawingPictureTitle(drawing.attachmentId));const isOutdated = !picture || picture.utcDateModified < drawing.utcDateModified;- if (isOutdated && isCurrent()) {+ if (isOutdated && isCurrent() && isUnscheduled()) {scheduleDrawingPicture(drawing, content, files);}} catch (e) {diff --git a/apps/client/src/widgets/type_widgets/canvas/picture_schedule.spec.ts b/apps/client/src/widgets/type_widgets/canvas/picture_schedule.spec.tsindex 501ce5c0f1..943030a302 100644--- a/apps/client/src/widgets/type_widgets/canvas/picture_schedule.spec.ts+++ b/apps/client/src/widgets/type_widgets/canvas/picture_schedule.spec.ts@@ -2,12 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";describe("schedulePicture", () => {let schedulePicture: typeof import("./picture_schedule").schedulePicture;+ let watchPictures: typeof import("./picture_schedule").watchPictures;beforeEach(async () => {vi.useFakeTimers();// A new module, without the input and the pictures of the other tests.vi.resetModules();- ({ schedulePicture } = await import("./picture_schedule"));+ ({ schedulePicture, watchPictures } = await import("./picture_schedule"));});afterEach(() => {@@ -88,4 +89,19 @@ describe("schedulePicture", () => {await vi.advanceTimersByTimeAsync(0);expect(order).toEqual([ "first started", "first failed", "second started" ]);});++ it("tells whether a picture of the drawing was scheduled since the watch began", () => {+ const draw = async () => {};+ schedulePicture("d1", draw, 1000);+ const isUnscheduled = watchPictures("d1");+ const isOtherUnscheduled = watchPictures("d2");++ schedulePicture("d2", draw, 1000);+ expect(isUnscheduled()).toBe(true);+ expect(isOtherUnscheduled()).toBe(false);++ schedulePicture("d1", draw, 1000);+ expect(isUnscheduled()).toBe(false);+ expect(watchPictures("d1")()).toBe(true);+ });});diff --git a/apps/client/src/widgets/type_widgets/canvas/picture_schedule.ts b/apps/client/src/widgets/type_widgets/canvas/picture_schedule.tsindex 6e35e4b9cf..a9a78b7e98 100644--- a/apps/client/src/widgets/type_widgets/canvas/picture_schedule.ts+++ b/apps/client/src/widgets/type_widgets/canvas/picture_schedule.ts@@ -11,6 +11,8 @@ const INPUT_EVENTS = [ "pointerdown", "pointermove", "wheel", "keydown" ];const pendingPictures = new Map<string, PendingPicture>();/** The latest draw of each drawing, which the next draw of the drawing waits for. */const runningDraws = new Map<string, Promise<void>>();+/** How many pictures of each drawing were scheduled, which `watchPictures()` compares. */+const scheduleCounts = new Map<string, number>();let lastInputTime = 0;let isWatchingPage = false;@@ -21,6 +23,7 @@ let isWatchingPage = false;* until the user is idle.*/export function schedulePicture(key: string, draw: () => Promise<void>, delay: number) {+ scheduleCounts.set(key, (scheduleCounts.get(key) ?? 0) + 1);const pending = pendingPictures.get(key);if (pending) {clearTimeout(pending.timer);@@ -32,6 +35,15 @@ export function schedulePicture(key: string, draw: () => Promise<void>, delay: n}}+/**+ * Returns a check that is `true` until a picture of the drawing `key` is scheduled. A picture of a+ * loaded drawing must not replace the picture of a save made while it loads.+ */+export function watchPictures(key: string) {+ const count = scheduleCounts.get(key);+ return () => scheduleCounts.get(key) === count;+}+/** Draws the picture of `key` that waits, or waits until the user's input pauses. */function drawWhenIdle(key: string) {const pending = pendingPictures.get(key);diff --git a/packages/trilium-e2e/src/note_types/text.spec.ts b/packages/trilium-e2e/src/note_types/text.spec.tsindex d283ed419f..7ac048f1c0 100644--- a/packages/trilium-e2e/src/note_types/text.spec.ts+++ b/packages/trilium-e2e/src/note_types/text.spec.ts@@ -85,5 +85,5 @@ test("Displays math popup", async ({ page, context }) => {}, { timeout: 5000 });await expect(preview.locator('.katex')).toBeVisible();- await expect(preview).toMatchAriaSnapshot("- math: e = m c 2");+ await expect(preview).toMatchAriaSnapshot(`- img "e=mc^2"`);});