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 Doranad55624e1538
diff --git a/apps/client/src/widgets/type_widgets/code/snippets.spec.ts b/apps/client/src/widgets/type_widgets/code/snippets.spec.tsindex 0459d6bb74..31fbfddac4 100644--- a/apps/client/src/widgets/type_widgets/code/snippets.spec.ts+++ b/apps/client/src/widgets/type_widgets/code/snippets.spec.ts@@ -11,7 +11,9 @@ vi.mock("../../../services/search.js", () => ({import search from "../../../services/search.js";import * as ws from "../../../services/ws.js";import { buildNote } from "../../../test/easy-froca";-import { getCodeSnippets, isCodeSnippetChange, isSnippetFor, snippetCommand } from "./snippets.js";+import {+ type CodeSnippet, getCodeSnippets, isCodeSnippetChange, isSnippetFor, snippetCommand+} from "./snippets.js";interface NoteStub {noteId: string;@@ -171,6 +173,33 @@ describe("getCodeSnippets", () => {expect(search.searchForNotes).toHaveBeenCalledTimes(2);});+ it("searches again for changes that arrive while a search runs, once for every editor", async () => {+ const deferred = () => {+ let resolve: (notes: FNote[]) => void = () => {};+ const promise = new Promise<FNote[]>((done) => { resolve = done; });+ return { promise, resolve };+ };+ const first = deferred();+ const second = deferred();+ vi.mocked(search.searchForNotes)+ .mockReturnValueOnce(first.promise)+ .mockReturnValueOnce(second.promise);+ const changes = makeLoadResults({ attrs: [ { type: "label", name: "snippet" } ] });+ const noteIds = (snippets: CodeSnippet[]) => snippets.map((snippet) => snippet.noteId);++ const before = getCodeSnippets(() => true);+ const after = [ getCodeSnippets(() => true, changes), getCodeSnippets(() => true, changes) ];+ first.resolve([ makeNote({ noteId: "old" }) ]);+ expect(search.searchForNotes).toHaveBeenCalledTimes(2);+ expect(noteIds(await before)).toEqual([ "old" ]);++ // The older search finishing leaves the newer one shared.+ after.push(getCodeSnippets(() => true));+ second.resolve([ makeNote({ noteId: "old" }), makeNote({ noteId: "new" }) ]);+ expect(search.searchForNotes).toHaveBeenCalledTimes(2);+ expect((await Promise.all(after)).map(noteIds)).toEqual(Array(3).fill([ "old", "new" ]));+ });+it("returns an empty list and logs when loading fails", async () => {vi.mocked(search.searchForNotes).mockRejectedValue(new Error("boom"));const logError = vi.spyOn(ws, "logError");diff --git a/apps/client/src/widgets/type_widgets/code/snippets.ts b/apps/client/src/widgets/type_widgets/code/snippets.tsindex f55e8bd5e9..c322acbc43 100644--- a/apps/client/src/widgets/type_widgets/code/snippets.ts+++ b/apps/client/src/widgets/type_widgets/code/snippets.ts@@ -25,13 +25,16 @@ export interface CodeSnippet {* Loads the code snippets (notes carrying `#snippet`) accepted by `matches`, pre-fetching their* content and optional `#snippetDescription` so callers can insert them synchronously. The `matches`* predicate selects which snippets are relevant to a given editor (e.g. `note.isMarkdown()` for the- * Markdown editor, or a MIME comparison for a code editor).+ * Markdown editor, or a MIME comparison for a code editor). `changes` are the reloaded entities+ * that called for the load, which a search started before them can miss.*/-export async function getCodeSnippets(matches: (note: FNote) => boolean): Promise<CodeSnippet[]> {+export async function getCodeSnippets(+ matches: (note: FNote) => boolean, changes?: LoadResults+): Promise<CodeSnippet[]> {try {// The `search` route includes archived notes, so drop archived ones; also skip protected// snippets whose content isn't available (no active protected session) — they can't be inserted.- const notes = (await searchSnippetNotes())+ const notes = (await searchSnippetNotes(changes)).filter((note) => matches(note) && !note.isArchived && note.isContentAvailable());return await Promise.all(notes.map(async (note) => ({@@ -46,15 +49,23 @@ export async function getCodeSnippets(matches: (note: FNote) => boolean): Promis}}-/** The `#snippet` notes. Editors that load them at the same time share one search. */-function searchSnippetNotes() {- pendingSearch ??= search.searchForNotes("#snippet").finally(() => {- pendingSearch = null;+/**+ * The `#snippet` notes. Editors that load them at the same time share one search, unless the+ * search started before `changes`.+ */+function searchSnippetNotes(changes?: LoadResults) {+ if (pendingSearch && (!changes || pendingSearch.changes === changes)) {+ return pendingSearch.notes;+ }++ const notes = search.searchForNotes("#snippet").finally(() => {+ if (pendingSearch?.notes === notes) pendingSearch = null;});- return pendingSearch;+ pendingSearch = { notes, changes };+ return notes;}-let pendingSearch: Promise<FNote[]> | null = null;+let pendingSearch: { notes: Promise<FNote[]>; changes?: LoadResults } | null = null;/*** Whether the reloaded entities could change the snippet list — a snippet was created, deleted,@@ -119,13 +130,13 @@ export function useCodeSnippets(mime: string, isEnabled = true) {// Monotonic id so a slow fetch that resolves after a newer reload is discarded (avoids stale data).const reloadCountRef = useRef(0);- const reload = useCallback(() => {+ const reload = useCallback((changes?: LoadResults) => {const reloadId = ++reloadCountRef.current;if (!isEnabled) {snippetsRef.current = [];return;}- void getCodeSnippets((note) => isSnippetFor(note, mime)).then((snippets) => {+ void getCodeSnippets((note) => isSnippetFor(note, mime), changes).then((snippets) => {if (reloadId === reloadCountRef.current) {snippetsRef.current = snippets;}@@ -138,7 +149,7 @@ export function useCodeSnippets(mime: string, isEnabled = true) {if (!isEnabled) return;const knownNoteIds = new Set(snippetsRef.current.map((snippet) => snippet.noteId));if (isCodeSnippetChange(loadResults, knownNoteIds)) {- reload();+ reload(loadResults);}});diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 83fa2f10d6..45e3c67b94 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -712,6 +712,27 @@ describe("content_renderer", () => {expect(result.content).not.toContain("hljs");});+ it("numbers the lines of an embedded code note unless its embed turns them off", async () => {+ await ensureShareHighlighting();+ buildShareNotes([+ { id: "pylines", type: "code", mime: "text/x-python", content: "x = 1" }+ ]);+ const hasLineNumbers = (attributes: string) => {+ const result = getContent(buildShareNote({+ content: `<section class="include-note" data-note-id="pylines"${attributes}>`+ + " </section>"+ }));+ if (typeof result.content !== "string") throw new Error("expected string content");+ const preview = parse(result.content).querySelector("pre.code-preview");+ if (!preview) throw new Error("expected a code preview");+ return !preview.classList.contains("code-preview-no-line-numbers");+ };++ expect(hasLineNumbers("")).toBe(true);+ expect(hasLineNumbers(' data-code-line-numbers="true"')).toBe(true);+ expect(hasLineNumbers(' data-code-line-numbers="false"')).toBe(false);+ });+it("renders a picture or drawing embed as an image, any other embed as a download", () => {const embed = (id: string) =>`<section class="include-note" data-attachment-id="${id}"> </section>`;diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 446fb8df0a..2e420c4782 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -500,6 +500,8 @@ export interface ShareRenderOptions {* out, and a missing block renders as a broken reference.*/block?: string;+ /** Whether a code note numbers its lines, as its embed's `data-code-line-numbers` sets. */+ hasCodeLineNumbers?: boolean;}export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}) {@@ -522,7 +524,7 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}} else if (note.type === "code" && note.mime === "text/x-markdown") {renderMarkdown(result, note);} else if (note.type === "code") {- renderCode(result, note.mime, note);+ renderCode(result, note.mime, note, options.hasCodeLineNumbers);} else if (note.type === "mermaid") {renderMermaid(result, note);hostNoteView(result, note, options);@@ -654,7 +656,8 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptconst embeddedResult = getContent(embeddedNote, {...getNestedEmbedOptions(embedContext, embed.block),- canAccessEmbed: options.canAccessEmbed+ canAccessEmbed: options.canAccessEmbed,+ hasCodeLineNumbers: embedEl.getAttribute("data-code-line-numbers") !== "false"});if (typeof embeddedResult.content !== "string") continue;@@ -927,8 +930,11 @@ async function loadCodePreviews(mimeTypes: MimeType[]) {* has loaded the renderer. Until then the code is escaped in a `<pre><code>`.** @param note the note whose `#wrapLines` label sets the line wrapping, over the option.+ * @param hasLineNumbers whether the lines are numbered.*/-export function renderCode(result: Result, mime?: string, note?: SNote | BNote) {+export function renderCode(+ result: Result, mime?: string, note?: SNote | BNote, hasLineNumbers = true+) {if (typeof result.content !== "string" || !result.content?.trim()) {result.isEmpty = true;} else if (codePreviews) {@@ -937,7 +943,7 @@ export function renderCode(result: Result, mime?: string, note?: SNote | BNote)? module.getLoadedPreviewLanguage(mime) ?? null: null;result.content = module.renderCodePreview(result.content, {- themes, language, isWrapped: isLineWrapped(note)+ themes, language, isWrapped: isLineWrapped(note), hasLineNumbers});} else {// Escape the raw code so that any `<`/`>` it contains are not later re-parsed as HTML.