Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into feat/mind-map-node-panel

Elian Doran92574f77a7cc
diff --cc apps/client/src/widgets/react/SegmentedChoice.tsx
index dcbbc79a01,55ec28b756..b9e7890226
--- a/apps/client/src/widgets/react/SegmentedChoice.tsx
+++ b/apps/client/src/widgets/react/SegmentedChoice.tsx
@@@ -1,41 -1,57 +1,64 @@@
+ import "./SegmentedChoice.css";
+
import clsx from "clsx";
+ import SimpleBadge from "./Badge";
import Button, { ButtonGroup } from "./Button";
- interface SegmentedChoiceOption<T extends string> {
-interface SegmentedChoiceProps<T extends string> {
- options: SegmentedChoiceOption<T>[];
- /**
- * Kept a plain string rather than {@link T}: callers routinely hold the value as a raw option
- * string, and a value outside the options simply highlights nothing.
- */
- currentValue: string;
- onChange: (newValue: T) => void;
- className?: string;
-}
-
+ export interface SegmentedChoiceOption<T extends string> {
value: T;
- label: string;
+ /** Left out where the option is shown as an icon alone, which then wants a {@link title}. */
+ label?: string;
+ /** An icon class without its `bx` prefix, e.g. `bx-square`. */
+ icon?: string;
+ /** What the option is called, for an option that shows as an icon alone. */
+ title?: string;
+ /**
+ * How much the option holds, shown as a badge after its name.
+ *
+ * For a choice between views of the same things, where the size of the one not on show is part of
+ * the decision to look at it — and where writing it into the label instead ("Yours (3)") reads as
+ * part of the name rather than as a quantity. Zero is a count like any other and is shown: an
+ * option offering nothing is worth saying so, and hiding it would leave the group's widths moving
+ * as the last item goes.
+ */
+ count?: number;
}
+interface SegmentedChoiceProps<T extends string> {
+ options: SegmentedChoiceOption<T>[];
+ /**
+ * Kept a plain string rather than {@link T}: callers routinely hold the value as a raw option
+ * string, and a value outside the options simply highlights nothing.
+ */
+ currentValue: string;
+ onChange: (newValue: T) => void;
+ className?: string;
+}
+
/**
* A row of buttons acting as one exclusive choice, the current one highlighted — for switching
* between a few named views or sections where a dropdown would hide the alternatives.
*/
export default function SegmentedChoice<T extends string>({ options, currentValue, onChange, className }: SegmentedChoiceProps<T>) {
return (
- <ButtonGroup size="sm" className={className}>
- {options.map(({ value, label, icon, title }) => (
+ <ButtonGroup size="sm" className={clsx("tn-segmented-choice", className)}>
- {options.map(({ value, label, count }) => (
++ {options.map(({ value, label, icon, title, count }) => (
<Button
key={value}
- text={label ?? ""}
+ // Name and count share one inline box, rather than being two children of the
+ // button: the button is a flex row, so a badge left as a child of its own is laid
+ // out against the row's centre line instead of against the text, and lands a
+ // pixel above it. Inside a line box it aligns to the text itself, in the text's
+ // own units.
+ text={count !== undefined ? (
+ <span class="tn-segmented-choice-label">
+ {label}
+ <SimpleBadge className="tn-segmented-choice-count" title={count} />
+ </span>
- ) : label}
++ ) : (label ?? "")}
+ icon={icon}
+ title={title}
size="small"
className={clsx(currentValue === value && "active")}
onClick={() => onChange(value)}
diff --cc packages/commons/src/lib/notes.spec.ts
index 63a6723cb9,196f9180df..a0d82d205b
--- a/packages/commons/src/lib/notes.spec.ts
+++ b/packages/commons/src/lib/notes.spec.ts
@@@ -1,6 -1,6 +1,6 @@@
import { describe, expect, it } from "vitest";
- import { getImageAttachmentTitle, getNoteIcon, NOTE_TYPE_ICONS, NOTE_TYPE_IMAGE_ATTACHMENTS, parseMindMapNoteLink } from "./notes.js";
-import { getImageAttachmentTitle, getMimeIcon, getNoteIcon, NOTE_TYPE_ICONS, NOTE_TYPE_IMAGE_ATTACHMENTS } from "./notes.js";
++import { getImageAttachmentTitle, getMimeIcon, getNoteIcon, NOTE_TYPE_ICONS, NOTE_TYPE_IMAGE_ATTACHMENTS, parseMindMapNoteLink } from "./notes.js";
import { NoteType } from "./rows.js";
function buildArgs(overrides: {
@@@ -140,24 -140,28 +140,50 @@@ describe("getNoteIcon", () =>
});
});
+describe("parseMindMapNoteLink", () => {
+ it("tells a link to a note from one pointing outside Trilium", () => {
+ expect(parseMindMapNoteLink("#root/abc123")).toEqual({ notePath: "root/abc123", noteId: "abc123" });
+ // The whole path is kept — it is what places the note — and the note is the end of it.
+ expect(parseMindMapNoteLink("#root/parent/abc123")).toEqual({ notePath: "root/parent/abc123", noteId: "abc123" });
+ expect(parseMindMapNoteLink("#root")).toEqual({ notePath: "root", noteId: "root" });
+
+ for (const link of [
+ null, undefined, "", 42,
+ "https://example.com",
+ // An address of its own that happens to carry a note path is still a page elsewhere.
+ "https://example.com/#root/abc123",
+ "#rootless/abc",
+ // The address as Mind Elixir would hold it, or not at all.
+ "root/abc123",
+ "#root/abc123?bookmark=x"
+ ]) {
+ expect(parseMindMapNoteLink(link)).toBeNull();
+ }
+ });
+});
++
+ describe("getMimeIcon", () => {
+ it("reads a media type the way a note of that content is read", () => {
+ // Same answers as the file/image branches above, which now go through here: a PDF is a PDF
+ // whether it arrived as a note or as an attachment.
+ expect(getMimeIcon("application/pdf")).toBe("bx bxs-file-pdf");
+ expect(getMimeIcon("video/mp4")).toBe("bx bx-video");
+ expect(getMimeIcon("audio/mpeg")).toBe("bx bx-music");
+ expect(getMimeIcon("image/gif")).toBe("bx bxs-file-gif");
+ expect(getMimeIcon("image/png")).toBe("bx bx-image");
+ expect(getMimeIcon("text/plain")).toBe("bx bx-file");
+ });
+
+ it("falls back to the file icon when there is no media type to read", () => {
+ expect(getMimeIcon(undefined)).toBe("bx bx-file");
+ expect(getMimeIcon(null)).toBe("bx bx-file");
+ expect(getMimeIcon("")).toBe("bx bx-file");
+ });
+
+ it("does not answer with something off the mapping tables' prototype", () => {
+ // The media type is whatever was stored. Read off a table rather than checked against it,
+ // these return a function, which survives the `??` and is handed on as an icon class.
+ expect(getMimeIcon("constructor")).toBe("bx bx-file");
+ expect(getMimeIcon("toString")).toBe("bx bx-file");
+ });
+ });
diff --cc packages/trilium-core/src/services/notes.spec.ts
index 7115e58fee,c053af830a..8a76546b01
--- a/packages/trilium-core/src/services/notes.spec.ts
+++ b/packages/trilium-core/src/services/notes.spec.ts
@@@ -390,29 -391,37 +391,58 @@@ describe("notes service (real DB)", ()
expect(newContent).toContain(`attachmentId=${attachments[0].attachmentId}`);
expect(newContent).not.toContain("data:image/png;base64");
});
+
+ it("relates a mind map to the notes its nodes link to, and lets go of the ones dropped", () => {
+ const target = createNote("root", { title: "spec-map-target" });
+ const map = createNote("root", {
+ title: "spec-map",
+ type: "mindMap",
+ mime: "application/json",
+ content: `{"nodeData":{"id":"root","topic":"Root"}}`
+ });
+ const buildMap = (hyperLink: string) =>
+ JSON.stringify({ nodeData: { id: "root", topic: "Root", children: [{ id: "a", topic: "A", hyperLink }] } });
+
+ getContext().init(() => saveLinks(map.note, buildMap(`#root/${target.note.noteId}`)));
+
+ const relation = map.note.getRelations().find((r) => r.name === "internalLink");
+ expect(relation?.value).toBe(target.note.noteId);
+
+ // Pointed elsewhere, the node no longer relates the two notes.
+ getContext().init(() => saveLinks(map.note, buildMap("https://example.com")));
+ expect(map.note.getRelations().some((r) => r.name === "internalLink" && !r.isDeleted)).toBe(false);
+ });
});
+ describe("asyncPostProcessContent", () => {
+ it("sets the link preview picture download going", async () => {
+ // The pass itself is covered in image_download.spec.ts. What matters here is the wiring:
+ // saving content is the only thing that starts it.
+ const asked: string[] = [];
+ initRequest({
+ exec: async () => { throw new Error("Not used by this test."); },
+ getImage: async (address: string) => {
+ asked.push(address);
+ const png = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC",
+ "base64"
+ );
+ return png.buffer.slice(png.byteOffset, png.byteOffset + png.byteLength) as ArrayBuffer;
+ }
+ });
+
+ const { note } = createNote("root", {
+ title: "spec-preview-wiring",
+ content: `<section class="link-embed" data-url="https://example.com/p" data-favicon="https://example.com/f.png"></section>`
+ });
+
+ await getContext().init(() => noteService.asyncPostProcessContent(note, note.getContent()));
+
+ expect(asked).toEqual([ "https://example.com/f.png" ]);
+ expect(note.getAttachments().map((a) => a.role)).toStrictEqual([ "favicon" ]);
+ });
+ });
+
describe("updateNoteData", () => {
it("persists new content and extracts link relations", () => {
const target = createNote("root", { title: "spec-update-target" });
diff --cc packages/trilium-core/src/services/notes.ts
index d3dd3b89ca,1e6a93dbd0..b6d55bfc9a
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@@ -1,7 -1,6 +1,6 @@@
- import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType, parseMindMapNoteLink } from "@triliumnext/commons";
-import { type AttachmentRow, attachmentRoleTraits, type AttributeRow, type BranchRow, dayjs, isEmbeddedAttachmentRole, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType } from "@triliumnext/commons";
++import { type AttachmentRow, attachmentRoleTraits, type AttributeRow, type BranchRow, dayjs, isEmbeddedAttachmentRole, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType, parseMindMapNoteLink } from "@triliumnext/commons";
import { t } from "i18next";
import { parse as parseHtml } from "node-html-parser";
- import url from "url";
import becca from "../becca/becca.js";
import BAttachment from "../becca/entities/battachment.js";
@@@ -452,15 -456,14 +456,15 @@@ export function checkImageAttachments(n
if (!isCanvas) {
let match;
- // Spreadsheet content is JSON storing inline images as bare `api/attachments/{id}/image/...`
- // URLs (no `src="..."` wrapper), so it scans with the same loose pattern as Markdown.
- const patterns: { pattern: RegExp, previewPicture?: boolean }[] = (note.isMarkdown() || note.type === "spreadsheet")
+ // Spreadsheet and mind map content is JSON storing images as bare
+ // `api/attachments/{id}/image/...` URLs (no `src="..."` wrapper), so they scan with the same
+ // loose pattern as Markdown.
- const patterns = (note.isMarkdown() || note.type === "spreadsheet" || note.type === "mindMap")
++ const patterns: { pattern: RegExp, previewPicture?: boolean }[] = (note.isMarkdown() || note.type === "spreadsheet" || note.type === "mindMap")
? [
// ![...](api/attachments/{id}/image/...) or similar markdown image syntax
- /api\/attachments\/([a-zA-Z0-9_]+)\/image/g,
+ { pattern: /api\/attachments\/([a-zA-Z0-9_]+)\/image/g },
// [...](#root/{noteId}?viewMode=attachments&attachmentId={id})
- /attachmentId=([a-zA-Z0-9_]+)/g
+ { pattern: /attachmentId=([a-zA-Z0-9_]+)/g }
]
: [
// <img src="api/attachments/{id}/image/...">
@@@ -789,197 -811,7 +817,48 @@@ function findRelationMapLinks(content:
}
}
+/**
+ * Collects the notes a mind map's nodes link to.
+ *
+ * A node carries one link of its own, and what makes it a link to a note is
+ * {@link parseMindMapNoteLink}'s to say; anything else is an address outside Trilium. The whole map
+ * is walked rather than only its nodes, so that a link stays found wherever Mind Elixir comes to
+ * keep one.
+ */
+export function findMindMapLinks(content: string, foundLinks: FoundLink[]) {
+ try {
+ collectMindMapLinks(JSON.parse(content), foundLinks);
+ } catch (e: any) {
+ getLog().error(`Could not scan for mind map links: ${e.message}`);
+ }
+}
+
+function collectMindMapLinks(value: unknown, foundLinks: FoundLink[]) {
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ collectMindMapLinks(item, foundLinks);
+ }
+ return;
+ }
+
+ if (!value || typeof value !== "object") {
+ return;
+ }
+
+ const record = value as Record<string, unknown>;
+ const noteId = parseMindMapNoteLink(record.hyperLink)?.noteId;
+ if (noteId) {
+ foundLinks.push({
+ name: "internalLink",
+ value: noteId
+ });
+ }
+
+ for (const key of Object.keys(record)) {
+ collectMindMapLinks(record[key], foundLinks);
+ }
+}
- const imageUrlToAttachmentIdMapping: Record<string, string> = {};
-
- async function downloadImage(noteId: string, imageUrl: string) {
- const unescapedUrl = unescapeHtml(imageUrl);
-
- // SSRF protection: only allow http(s) URLs and block file:// and other schemes.
- try {
- const parsed = new URL(unescapedUrl);
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
- getLog().error(`Download of '${imageUrl}' for note '${noteId}' rejected: only http/https URLs are allowed.`);
- return;
- }
- } catch {
- getLog().error(`Download of '${imageUrl}' for note '${noteId}' rejected: invalid URL.`);
- return;
- }
-
- try {
- const imageBuffer = new Uint8Array(await request.getImage(unescapedUrl));
-
- const parsedUrl = url.parse(unescapedUrl);
- const title = basename(parsedUrl.pathname || "");
-
- const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, title, true, true);
-
- if (attachment.attachmentId) {
- imageUrlToAttachmentIdMapping[imageUrl] = attachment.attachmentId;
- } else {
- getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed due to no attachment ID.`);
- }
-
- getLog().info(`Download of '${imageUrl}' succeeded and was saved as image attachment '${attachment.attachmentId}' of note '${noteId}'`);
- } catch (e: any) {
- getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed with error: ${e.message} ${e.stack}`);
- }
- }
-
- /** url => download promise */
- const downloadImagePromises: Record<string, Promise<void>> = {};
-
- function replaceUrl(content: string, url: string, attachment: Attachment) {
- const quotedUrl = quoteRegex(url);
-
- return content.replace(new RegExp(`\\s+src=[\"']${quotedUrl}[\"']`, "ig"), ` src="api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}"`);
- }
-
- function downloadImages(noteId: string, content: string) {
- const imageRe = /<img[^>]*?\ssrc=['"]([^'">]+)['"]/gi;
- let imageMatch;
-
- while ((imageMatch = imageRe.exec(content))) {
- const url = imageMatch[1];
- const inlineImageMatch = /^data:image\/[a-z]+;base64,/.exec(url);
-
- if (inlineImageMatch) {
- const imageBase64 = url.substring(inlineImageMatch[0].length);
- const imageBuffer = decodeBase64(imageBase64);
-
- const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, "inline image", true, true);
-
- const encodedTitle = encodeURIComponent(attachment.title);
-
- content = `${content.substring(0, imageMatch.index)}<img src="api/attachments/${attachment.attachmentId}/image/${encodedTitle}"${content.substring(imageMatch.index + imageMatch[0].length)}`;
- } else if (
- !url.includes("api/images/") &&
- !/api\/attachments\/.+\/image\/?.*/.test(url) &&
- // this is an exception for the web clipper's "imageId"
- (url.length !== 20 || url.toLowerCase().startsWith("http"))
- ) {
- if (!optionService.getOptionBool("downloadImagesAutomatically")) {
- continue;
- }
-
- if (url in imageUrlToAttachmentIdMapping) {
- const attachment = becca.getAttachment(imageUrlToAttachmentIdMapping[url]);
-
- if (!attachment) {
- delete imageUrlToAttachmentIdMapping[url];
- } else {
- content = replaceUrl(content, url, attachment);
- continue;
- }
- }
-
- if (url in downloadImagePromises) {
- // download is already in progress
- continue;
- }
-
- // this is done asynchronously, it would be too slow to wait for the download
- // given that save can be triggered very often
- downloadImagePromises[url] = downloadImage(noteId, url);
- }
- }
-
- Promise.all(Object.values(downloadImagePromises)).then(() => {
- setTimeout(() => {
- // the normal expected flow of the offline image saving is that users will paste the image(s)
- // which will get asynchronously downloaded, during that time they keep editing the note
- // once the download is finished, the image note representing the downloaded image will be used
- // to replace the IMG link.
- // However, there's another flow where the user pastes the image and leaves the note before the images
- // are downloaded and the IMG references are not updated. For this occasion we have this code
- // which upon the download of all the images will update the note if the links have not been fixed before
-
- cls.getContext().init(() => {
- getSql().transactional(() => {
- const imageNotes = becca.getNotes(Object.values(imageUrlToAttachmentIdMapping), true);
- const log = getLog();
-
- const origNote = becca.getNote(noteId);
-
- if (!origNote) {
- log.error(`Cannot find note '${noteId}' to replace image link.`);
- return;
- }
-
- const origContent = origNote.getContent();
- let updatedContent = origContent;
-
- if (typeof updatedContent !== "string") {
- log.error(`Note '${noteId}' has a non-string content, cannot replace image link.`);
- return;
- }
-
- for (const url in imageUrlToAttachmentIdMapping) {
- const imageNote = imageNotes.find((note) => note.noteId === imageUrlToAttachmentIdMapping[url]);
-
- if (imageNote) {
- updatedContent = replaceUrl(updatedContent, url, imageNote);
- }
- }
-
- // update only if the links have not been already fixed.
- if (updatedContent !== origContent) {
- origNote.setContent(updatedContent);
-
- asyncPostProcessContent(origNote, updatedContent);
-
- console.log(`Fixed the image links for note '${noteId}' to the offline saved.`);
- }
- });
- });
- }, 5000);
- });
-
- return content;
- }
-
/**
* Derives a plain-text attachment title from the inner HTML of an inline
* attachment's link label: strips tags, decodes HTML entities, collapses