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
refactor: make the rendered-image attachment titles a single source of truth
Elian Dorand1c28dfe8ff1
diff --git a/apps/client/src/widgets/type_widgets/MindMap.tsx b/apps/client/src/widgets/type_widgets/MindMap.tsxindex 1a80000d39..4130942e55 100644--- a/apps/client/src/widgets/type_widgets/MindMap.tsx+++ b/apps/client/src/widgets/type_widgets/MindMap.tsx@@ -4,6 +4,7 @@ import "./MindMap.css";// allow node-menu plugin css to be bundled by webpackimport nodeMenu from "@mind-elixir/node-menu";+import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import { snapdom } from "@zumer/snapdom";import { t } from "i18next";import { DARK_THEME, default as VanillaMindElixir, MindElixirData, MindElixirInstance, Operation, THEME as LIGHT_THEME } from "mind-elixir";@@ -117,7 +118,7 @@ export default function MindMap({ note, ntxId, noteContext }: TypeWidgetProps) {attachments: [{role: "image",- title: "mindmap-export.svg",+ title: NOTE_TYPE_IMAGE_ATTACHMENTS.mindMap,mime: "image/svg+xml",content: svgContent,position: 0diff --git a/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts b/apps/client/src/widgets/type_widgets/canvas/image_attachments.tsindex 2908565b47..b74f9a101a 100644--- a/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts+++ b/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts@@ -1,4 +1,5 @@import type { BinaryFileData } from "@excalidraw/excalidraw/types";+import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import type FNote from "../../../entities/fnote";import { parseImageDataUrl } from "../../../services/image_upload";@@ -17,7 +18,7 @@ export interface ImageAttachmentMetadata {*/export const IMAGE_ROLE = "image";/** Fixed title of the SVG export attachment; canvas images are titled with their `fileId` instead. */-export const CANVAS_EXPORT_TITLE = "canvas-export.svg";+export const CANVAS_EXPORT_TITLE = NOTE_TYPE_IMAGE_ATTACHMENTS.canvas;/*** Loads the note's image attachments (every `image`-role attachment except the SVG export) anddiff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsxindex aed0cb25a3..4e4978eae1 100644--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx@@ -12,9 +12,10 @@ import SplitEditor, { PreviewButton, SplitEditorProps } from "./SplitEditor";interface SvgSplitEditorProps extends Omit<SplitEditorProps, "previewContent"> {/**- * The name of the note attachment (without .svg extension) that will be used for storing the preview.+ * The title of the note attachment used for storing the preview, extension included. Take it from+ * `NOTE_TYPE_IMAGE_ATTACHMENTS` so that the `api/images` endpoints can find it again.*/- attachmentName: string;+ attachmentTitle: string;/*** Called upon when the SVG preview needs refreshing, such as when the editor has switched to a new note or the content has switched.*@@ -36,7 +37,7 @@ interface SvgSplitEditorProps extends Omit<SplitEditorProps, "previewContent"> {* - Automatically saves the SVG attachment.**/-export default function SvgSplitEditor({ ntxId, note, attachmentName, renderSvg, ...props }: SvgSplitEditorProps) {+export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvg, ...props }: SvgSplitEditorProps) {const [ svg, setSvg ] = useState<string>();const [ error, setError ] = useState<string | null | undefined>();const containerRef = useRef<HTMLDivElement>(null);@@ -68,25 +69,25 @@ export default function SvgSplitEditor({ ntxId, note, attachmentName, renderSvg,const payload = {role: "image",- title: `${attachmentName}.svg`,+ title: attachmentTitle,mime: "image/svg+xml",content: svg,position: 0};server.post(`notes/${note.noteId}/attachments?matchBy=title`, payload);- }, [ svg, attachmentName, note.noteId ]);+ }, [ svg, attachmentTitle, note.noteId ]);// Save the SVG when entering a note only when it does not have an attachment.useEffect(() => {if (!svg) return; // Wait until SVG is renderednote?.getAttachments().then((attachments) => {- if (!attachments.find((a) => a.title === `${attachmentName}.svg`)) {+ if (!attachments.find((a) => a.title === attachmentTitle)) {onSave();}}).catch(e => console.error("Failed to get attachments for SVGSplitEditor", e));- }, [ note, svg, attachmentName, onSave ]);+ }, [ note, svg, attachmentTitle, onSave ]);// Import/exportuseTriliumEvent("exportSvg", async({ ntxId: eventNtxId }) => {diff --git a/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx b/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsxindex a70ff9c523..e6b14b548d 100644--- a/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx+++ b/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx@@ -1,4 +1,5 @@import type CodeMirror from "@triliumnext/codemirror";+import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import { useCallback } from "preact/hooks";import { t } from "../../../services/i18n";@@ -37,7 +38,7 @@ export default function Mermaid(props: TypeWidgetProps) {return (<SvgSplitEditor- attachmentName="mermaid-export"+ attachmentTitle={NOTE_TYPE_IMAGE_ATTACHMENTS.mermaid}renderSvg={renderSvg}editorRef={setupEditor}noteType="mermaid"diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsxindex 048235b107..6caf09d602 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx+++ b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx@@ -1,3 +1,4 @@+import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import { SHEET_DRAWING_RESOURCE } from "@triliumnext/commons/src/lib/spreadsheet/workbook_model";import { CommandType, FUniver, IDisposable, IWorkbookData, LocaleType } from "@univerjs/presets";import { MutableRef, useEffect, useRef } from "preact/hooks";@@ -188,7 +189,7 @@ export default function usePersistence(note: FNote, noteContext: NoteContext | nconst base64 = dataUrl.split(",")[1];attachments.push({role: "image",- title: "spreadsheet-export.png",+ title: NOTE_TYPE_IMAGE_ATTACHMENTS.spreadsheet,mime: "image/png",content: base64,position: 0,diff --git a/apps/server/src/share/routes.ts b/apps/server/src/share/routes.tsindex 99564e3d2c..d9c71f8a5e 100644--- a/apps/server/src/share/routes.ts+++ b/apps/server/src/share/routes.ts@@ -1,3 +1,4 @@+import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import { search as searchService, SearchContext, utils } from "@triliumnext/core";import type { NextFunction, Request, Response, Router } from "express";import safeCompare from "safe-compare";@@ -297,11 +298,11 @@ function register(router: Router) {res.send(image.getContent());}} else if (image.type === "canvas") {- renderImageAttachment(image, res, "canvas-export.svg");+ renderImageAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.canvas);} else if (image.type === "mermaid") {- renderImageAttachment(image, res, "mermaid-export.svg");+ renderImageAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.mermaid);} else if (image.type === "mindMap") {- renderImageAttachment(image, res, "mindmap-export.svg");+ renderImageAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.mindMap);} else {res.status(400).json({ message: "Requested note is not a shareable image" });}diff --git a/packages/commons/src/lib/notes.spec.ts b/packages/commons/src/lib/notes.spec.tsindex a178b9e1ab..0783112515 100644--- a/packages/commons/src/lib/notes.spec.ts+++ b/packages/commons/src/lib/notes.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { getNoteIcon, NOTE_TYPE_ICONS } from "./notes.js";+import { getImageAttachmentTitle, getNoteIcon, NOTE_TYPE_ICONS, NOTE_TYPE_IMAGE_ATTACHMENTS } from "./notes.js";import { NoteType } from "./rows.js";function buildArgs(overrides: {@@ -34,6 +34,30 @@ describe("NOTE_TYPE_ICONS", () => {});});+describe("getImageAttachmentTitle", () => {+ // These titles are a wire contract: the type widgets write attachments under them, the+ // `api/images` routes look them up by title, and the ZIP export/import pair resolves embeds+ // through them. Spelled out literally rather than read back off the table, so a typo in+ // NOTE_TYPE_IMAGE_ATTACHMENTS fails here instead of silently breaking every one of them.+ it("resolves the note types whose image lives in a generated attachment", () => {+ expect(getImageAttachmentTitle("canvas")).toBe("canvas-export.svg");+ expect(getImageAttachmentTitle("mermaid")).toBe("mermaid-export.svg");+ expect(getImageAttachmentTitle("mindMap")).toBe("mindmap-export.svg");+ expect(getImageAttachmentTitle("spreadsheet")).toBe("spreadsheet-export.png");++ // Indexing the table directly narrows to the literal, for statically known types.+ expect(NOTE_TYPE_IMAGE_ATTACHMENTS.mermaid).toBe("mermaid-export.svg");+ });++ it("returns undefined for note types that carry their image as content, and for no type", () => {+ // An image note is served straight from its own content, so it has no such attachment.+ expect(getImageAttachmentTitle("image")).toBeUndefined();+ expect(getImageAttachmentTitle("text")).toBeUndefined();+ expect(getImageAttachmentTitle(null)).toBeUndefined();+ expect(getImageAttachmentTitle(undefined)).toBeUndefined();+ });+});+describe("getNoteIcon", () => {it("returns the explicit iconClass when provided", () => {const icon = getNoteIcon(buildArgs({ iconClass: "bx bx-custom", workspaceIconClass: "bx bx-ws" }));diff --git a/packages/commons/src/lib/notes.ts b/packages/commons/src/lib/notes.tsindex 4f25751b94..3b2e12f24a 100644--- a/packages/commons/src/lib/notes.ts+++ b/packages/commons/src/lib/notes.ts@@ -25,6 +25,35 @@ export const NOTE_TYPE_ICONS = {llmChat: "bx bx-message-square-dots"};+/**+ * Note types that can be embedded as an image but are not images themselves, mapped to the title of+ * the attachment holding their rendered picture. The type widgets write these attachments, the+ * `api/images/<noteId>` routes serve them in place of the note's own content, the ZIP export writes+ * them out beside the note and the importer resolves them back, and note orphan-erasure exempts+ * them. Everything keys off this one table so those five places cannot drift apart.+ */+export const NOTE_TYPE_IMAGE_ATTACHMENTS = {+ canvas: "canvas-export.svg",+ mermaid: "mermaid-export.svg",+ mindMap: "mindmap-export.svg",+ spreadsheet: "spreadsheet-export.png"+} as const satisfies Partial<Record<NoteType, string>>;++/**+ * The title of the attachment holding the rendered image of the given note type, or `undefined` if+ * notes of that type carry their image as content and are served directly.+ *+ * Prefer indexing {@link NOTE_TYPE_IMAGE_ATTACHMENTS} directly when the note type is known+ * statically — it narrows to the exact title instead of `string | undefined`.+ */+export function getImageAttachmentTitle(type: NoteType | null | undefined): string | undefined {+ if (!type) {+ return undefined;+ }++ return (NOTE_TYPE_IMAGE_ATTACHMENTS as Partial<Record<NoteType, string>>)[type];+}+const FILE_MIME_MAPPINGS = {"application/pdf": "bx bxs-file-pdf","application/vnd.oasis.opendocument.text": "bx bxs-file-doc",diff --git a/packages/trilium-core/src/routes/api/image.ts b/packages/trilium-core/src/routes/api/image.tsindex 536f66a80f..0b07a91fb1 100644--- a/packages/trilium-core/src/routes/api/image.ts+++ b/packages/trilium-core/src/routes/api/image.ts@@ -1,3 +1,4 @@+import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import type { Request, Response } from "express";import type { File } from "../../services/import/common.js";@@ -32,13 +33,13 @@ function returnImageInt(image: BNote | BRevision | null, res: Response) {}if (image.type === "canvas") {- renderSvgAttachment(image, res, "canvas-export.svg");+ renderSvgAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.canvas);} else if (image.type === "mermaid") {- renderSvgAttachment(image, res, "mermaid-export.svg");+ renderSvgAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.mermaid);} else if (image.type === "mindMap") {- renderSvgAttachment(image, res, "mindmap-export.svg");+ renderSvgAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.mindMap);} else if (image.type === "spreadsheet") {- renderPngAttachment(image, res, "spreadsheet-export.png");+ renderPngAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.spreadsheet);} else {res.set("Content-Type", image.mime);res.set("Cache-Control", "no-cache, no-store, must-revalidate");diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.tsindex 59cd76e0aa..b10f7eb7bd 100644--- a/packages/trilium-core/src/services/export/zip.ts+++ b/packages/trilium-core/src/services/export/zip.ts@@ -1,4 +1,4 @@-import { NoteType } from "@triliumnext/commons";+import { getImageAttachmentTitle, NoteType } from "@triliumnext/commons";import sanitize from "sanitize-filename";import packageInfo from "../../../package.json" with { type: "json" };@@ -6,7 +6,6 @@ import becca from "../../becca/becca.js";import BBranch from "../../becca/entities/bbranch.js";import type BNote from "../../becca/entities/bnote.js";import dateUtils from "../utils/date.js";-import { getImageAttachmentTitle } from "../image_attachments.js";import { getLog } from "../log.js";import protectedSessionService from "../protected_session.js";import TaskContext from "../task_context.js";diff --git a/packages/trilium-core/src/services/image_attachments.ts b/packages/trilium-core/src/services/image_attachments.tsdeleted file mode 100644index 44fb9d4a0b..0000000000--- a/packages/trilium-core/src/services/image_attachments.ts+++ /dev/null@@ -1,21 +0,0 @@-import { NoteType } from "@triliumnext/commons";--/**- * Note types that can be embedded as an image but are not images themselves: `api/images/<noteId>`- * serves a generated attachment for them rather than the note's own content. Kept in sync with the- * routes that serve those attachments (`routes/api/image.ts` and the share `routes.ts`).- */-const NOTE_TYPE_TO_IMAGE_ATTACHMENT_TITLE: Partial<Record<NoteType, string>> = {- canvas: "canvas-export.svg",- mermaid: "mermaid-export.svg",- mindMap: "mindmap-export.svg",- spreadsheet: "spreadsheet-export.png"-};--/**- * The title of the attachment holding the rendered image of the given note type, or `undefined`- * if notes of that type are served as images directly.- */-export function getImageAttachmentTitle(type: NoteType | null | undefined): string | undefined {- return type ? NOTE_TYPE_TO_IMAGE_ATTACHMENT_TITLE[type] : undefined;-}diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.tsindex 2b0a8e4364..413439505c 100644--- a/packages/trilium-core/src/services/import/zip.ts+++ b/packages/trilium-core/src/services/import/zip.ts@@ -1,4 +1,4 @@-import { ALLOWED_NOTE_TYPES, type NoteType } from "@triliumnext/commons";+import { ALLOWED_NOTE_TYPES, getImageAttachmentTitle, type NoteType } from "@triliumnext/commons";import { basename, dirname } from "../utils/path.js";import { getZipProvider, type ZipSource } from "../zip_provider.js";@@ -8,7 +8,6 @@ import BAttribute from "../../becca/entities/battribute.js";import BBranch from "../../becca/entities/bbranch.js";import type BNote from "../../becca/entities/bnote.js";import attributeService from "../../services/attributes.js";-import { getImageAttachmentTitle } from "../../services/image_attachments.js";import { getLog } from "../../services/log.js";import noteService from "../../services/notes.js";import { getNoteTitle, newEntityId, removeFileExtension, unescapeHtml } from "../../services/utils/index.js";diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex 0ea0d27b17..ae1cc76dea 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -1,4 +1,4 @@-import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, type NoteRow, type NoteType } from "@triliumnext/commons";+import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType } from "@triliumnext/commons";import { t } from "i18next";import { parse as parseHtml } from "node-html-parser";import url from "url";@@ -438,20 +438,6 @@ function protectNote(note: BNote, protect: boolean) {}}-/**- * Title of the spreadsheet preview image. Unlike the inline drawing images, this attachment is not- * referenced from the note content — it is the note's rendered thumbnail, looked up by title by the- * image endpoint — so it must be exempt from the orphan-erasure scheduling below.- */-const SPREADSHEET_PREVIEW_ATTACHMENT_TITLE = "spreadsheet-export.png";--/**- * Title of the canvas SVG export image. Like the spreadsheet thumbnail, it is the note's rendered- * preview (looked up by title, not referenced from the scene JSON), so it must be exempt from the- * orphan-erasure scheduling below.- */-const CANVAS_EXPORT_ATTACHMENT_TITLE = "canvas-export.svg";-export function checkImageAttachments(note: BNote, content: string) {// Canvas references images by the Excalidraw fileId stored as the attachment *title* in its// scene JSON, so orphans are detected by title; every other type references them by attachmentId@@ -496,14 +482,15 @@ export function checkImageAttachments(note: BNote, content: string) {continue;}- // The spreadsheet preview thumbnail is never referenced from the content, so leave it alone- // (otherwise it would be scheduled for erasure on every save).- if (note.type === "spreadsheet" && attachment.title === SPREADSHEET_PREVIEW_ATTACHMENT_TITLE) {+ // The spreadsheet preview thumbnail is never referenced from the content — it is the note's+ // rendered image, looked up by title by the image endpoint — so leave it alone (otherwise it+ // would be scheduled for erasure on every save).+ if (note.type === "spreadsheet" && attachment.title === NOTE_TYPE_IMAGE_ATTACHMENTS.spreadsheet) {continue;}- // Likewise for the canvas SVG export preview.- if (isCanvas && attachment.title === CANVAS_EXPORT_ATTACHMENT_TITLE) {+ // Likewise for the canvas SVG export preview, which the scene JSON never references.+ if (isCanvas && attachment.title === NOTE_TYPE_IMAGE_ATTACHMENTS.canvas) {continue;}