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/include notes: preselect the widget size according to the included content type
Adorian Doran212386f89480
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.tsindex e969aa8527..66e1bc7762 100644--- a/apps/client/src/menus/link_context_menu.spec.ts+++ b/apps/client/src/menus/link_context_menu.spec.ts@@ -16,14 +16,15 @@ const mocks = vi.hoisted(() => ({hasActiveContext: true,getAttachmentOfNote: vi.fn(),getAttachmentActionGroups: vi.fn(),- getTextEditorContaining: vi.fn()+ getTextEditorContaining: vi.fn(),+ getIncludeBoxSize: vi.fn()}));vi.mock("./text_editor_context_menu", () => ({getTextEditorContaining: mocks.getTextEditorContaining}));-vi.mock("../services/options", () => ({ default: { get: () => "expandable" } }));+vi.mock("../services/content_renderer", () => ({ getIncludeBoxSize: mocks.getIncludeBoxSize }));vi.mock("./context_menu", () => ({ default: { show: mocks.show } }));@@ -256,7 +257,9 @@ describe("openContextMenu", () => {it("ends with converting an attachment link to an embed, only in a note being edited", async () => {const execute = vi.fn();- mocks.getAttachmentOfNote.mockResolvedValue({ attachmentId: "att-1" });+ const attachment = { attachmentId: "att-1" };+ mocks.getAttachmentOfNote.mockResolvedValue(attachment);+ mocks.getIncludeBoxSize.mockReturnValue("small");mocks.getAttachmentActionGroups.mockReturnValue([[ { title: "Download", icon: "bx bx-download", run: vi.fn() } ]]);@@ -280,9 +283,10 @@ describe("openContextMenu", () => {{ title: "link_context_menu.convert_link_to_embed" }]);items.at(-1).handler();+ expect(mocks.getIncludeBoxSize).toHaveBeenCalledWith(attachment);expect(execute).toHaveBeenCalledWith("embedAttachmentLink", {domElement: link,- boxSize: "expandable"+ boxSize: "small"});editable.removeAttribute("contenteditable");diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.tsindex eca6f0777c..36f19fa4dc 100644--- a/apps/client/src/menus/link_context_menu.ts+++ b/apps/client/src/menus/link_context_menu.ts@@ -3,10 +3,10 @@ import type { CKTextEditor } from "@triliumnext/ckeditor5";import type { GeoMouseEvent } from "../widgets/collections/geomap/map.js";import appContext, { type CommandNames } from "../components/app_context.js";+import type FAttachment from "../entities/fattachment.js";import froca from "../services/froca.js";import { t } from "../services/i18n.js";import type { ViewScope } from "../services/link.js";-import options from "../services/options.js";import utils, { isMobile } from "../services/utils.js";import { getClosestNtxId } from "../widgets/widget_utils.js";import contextMenu, {@@ -159,27 +159,31 @@ async function getAttachmentItems(}))]);- const conversionItems = [ getConvertToEmbedItem(e, editor), getConvertToLinkItem(e, editor) ]+ const embedItem = await getConvertToEmbedItem(e, editor, attachment);+ const conversionItems = [ embedItem, getConvertToLinkItem(e, editor) ].filter((item) => item !== null);return [ ...actionItems, ...conversionItems ];}/** "Convert link to an embed", for an attachment link in a text note open for editing. */-function getConvertToEmbedItem(+async function getConvertToEmbedItem(e: ContextMenuEvent,- editor: CKTextEditor | null-): MenuItem<CommandNames> | null {+ editor: CKTextEditor | null,+ attachment: FAttachment+): Promise<MenuItem<CommandNames> | null> {const link = getTarget(e)?.closest<HTMLElement>("a.reference-link");if (!link || !editor?.commands.get("embedAttachmentLink")?.isEnabled) {return null;}+ // Imported on demand: `content_renderer` imports `link`, which imports this module.+ const { getIncludeBoxSize } = await import("../services/content_renderer.js");return {title: t("link_context_menu.convert_link_to_embed"),uiIcon: "bx bx-window-alt",handler: () => editor.execute("embedAttachmentLink", {domElement: link,- boxSize: options.get("includeNoteDefaultBoxSize")+ boxSize: getIncludeBoxSize(attachment)})};}diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.tsindex b87ab9fe2b..9648a41bf5 100644--- a/apps/client/src/services/content_renderer.spec.ts+++ b/apps/client/src/services/content_renderer.spec.ts@@ -111,7 +111,12 @@ vi.mock("@triliumnext/commons/src/lib/markdown_renderer", async (orig) => ({import appContext from "../components/app_context.js";import FAttachment from "../entities/fattachment.js";import { buildNote } from "../test/easy-froca.js";-import { disposeInteractiveContent, getRenderedContent as rawGetRenderedContent } from "./content_renderer.js";+import {+ disposeInteractiveContent,+ getIncludeBoxSize,+ getRenderedContent as rawGetRenderedContent,+ getUploadBoxSize+} from "./content_renderer.js";import froca from "./froca.js";import server from "./server.js";@@ -151,6 +156,54 @@ beforeEach(() => {(window as any).electronApi = undefined;});+describe("getIncludeBoxSize", () => {+ it("sizes an include by what it previews: none, audio, code or anything else", () => {+ const protectedCode = buildNote({ title: "Secret", type: "code", mime: "text/javascript" });+ protectedCode.isProtected = true;++ expect([+ buildNote({ title: "Map", type: "relationMap" }),+ buildNote({ title: "Launcher", type: "launcher" }),+ buildNote({ title: "Blank page", type: "webView" }),+ buildNote({ title: "Archive", type: "file", mime: "application/zip" }),+ buildAttachment({ role: "file", mime: "application/zip" }),+ buildAttachment({ role: "canvasLibraryItem", mime: "application/json" })+ ].map(getIncludeBoxSize)).toEqual(Array(6).fill("tiny"));++ expect([+ buildNote({ title: "Song", type: "file", mime: "audio/mpeg" }),+ buildAttachment({ role: "file", mime: "audio/ogg" })+ ].map(getIncludeBoxSize)).toEqual([ "small", "small" ]);++ expect([+ buildNote({ title: "Script", type: "code", mime: "text/javascript" }),+ protectedCode,+ buildAttachment({ role: "file", mime: "application/json" })+ ].map(getIncludeBoxSize)).toEqual([ "full", "full", "full" ]);+ expect(touchProtectedSession).not.toHaveBeenCalled();++ expect([+ buildNote({ title: "Text", type: "text" }),+ buildNote({ title: "Readme", type: "code", mime: "text/x-markdown" }),+ buildNote({ title: "Books", type: "book" }),+ buildNote({ title: "Diagram", type: "mermaid" }),+ buildNote({ title: "Site", type: "webView", "#webViewSrc": "https://example.com" }),+ buildNote({ title: "Clip", type: "file", mime: "video/mp4" }),+ buildAttachment({ role: "file", mime: "application/pdf" }),+ buildAttachment({ role: "image", mime: "image/png" })+ ].map(getIncludeBoxSize)).toEqual(Array(8).fill("medium"));+ });++ it("sizes an upload by its media type, as the attachment it becomes", () => {+ expect([+ "application/zip", "", "audio/mpeg", "application/json", "application/pdf",+ "image/png", "video/mp4"+ ].map(getUploadBoxSize)).toEqual([+ "tiny", "tiny", "small", "full", "medium", "medium", "medium"+ ]);+ });+});+describe("getRenderedContent dispatch", () => {it("renders text/book via renderText and applies css class", async () => {const note = buildNote({ title: "T", type: "text", "#cssClass": "my-class" });diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 6db8faa379..e627f2b207 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -2,6 +2,7 @@ import "./content_renderer.css";import {attachmentIcon,+ isAcceptedImageMime,isImageAttachmentRole,isOfficeMimeType,normalizeMimeTypeForCKEditor,@@ -16,6 +17,7 @@ import imageContextMenuService from "../menus/image_context_menu.js";import { t } from "../services/i18n.js";import { type MediaEnvironment, showsFileActions } from "../widgets/type_widgets/file/media_environment.js";import type { LlmChatContent, StoredMessage } from "../widgets/type_widgets/llm_chat/llm_chat_types.js";+import type { BoxSize } from "../widgets/type_widgets/text/CKEditorWithWatchdog.js";import renderText, { postProcessRichContent, renderChildrenList } from "./content_renderer_text.js";import renderDoc from "./doc_renderer.js";import { getMermaidConfig, postprocessMermaidSvg } from "./mermaid.js";@@ -83,6 +85,15 @@ export interface RenderOptions {const CODE_MIME_TYPES = new Set(["application/json"]);+/**+ * The content types that an interactive `getRenderedContent()` previews; it shows any other as an+ * icon, or as the actions of a file. Keep in step with the branches there.+ */+const PREVIEWED_TYPES = new Set([+ "book", "search", "text", "markdown", "code", "iconPack", "image", "canvas", "mindMap",+ "spreadsheet", "office", "pdf", "audio", "video", "mermaid", "render", "doc", "llmChat"+]);+export async function getRenderedContent(this: {} | { ctx: string }, entity: FNote | FAttachment, options: RenderOptions = {}) {options = Object.assign(@@ -660,52 +671,82 @@ async function showRenderError($content: JQuery<HTMLElement>, error: unknown, no}}+/**+ * The box size a new include of `entity` starts with: `tiny` when the include shows no preview of+ * it, `small` for audio, `full` for code and `medium` for the rest.+ */+export function getIncludeBoxSize(entity: FNote | FAttachment): BoxSize {+ const type = getContentType(entity);+ const hasPreview = type === "webView"+ ? entity instanceof FNote && entity.hasLabel("webViewSrc")+ : PREVIEWED_TYPES.has(type);++ return getBoxSize(type, hasPreview);+}++/** The box size of a new embed of a file being uploaded, from the attachment it becomes. */+export function getUploadBoxSize(mime: string): BoxSize {+ const type = isAcceptedImageMime(mime) ? "image" : getFileContentType("file", mime);+ return getBoxSize(type, PREVIEWED_TYPES.has(type));+}++function getBoxSize(type: string, hasPreview: boolean): BoxSize {+ if (!hasPreview) return "tiny";+ if (type === "audio") return "small";+ if (type === "code") return "full";+ return "medium";+}+function getRenderingType(entity: FNote | FAttachment) {- let type: string = "";- if ("type" in entity) {- type = entity.type;- } else if ("role" in entity) {- type = entity.role;- // "importSource" attachments (e.g. the OneNote debug source HTML/InkML) are plain files kept- // for reference; render them exactly like a "file" role.- if (type === "importSource") {- type = "file";- } else if (isImageAttachmentRole(type)) {- // A link preview's "favicon" is a picture like any other as far as showing it goes; the- // role only says where it came from. Without this it would fall through to the unknown- // type and list as a file with no preview.- type = "image";- }+ const type = getContentType(entity);+ if (!entity.isProtected) {+ return type;}- const mime = "mime" in entity && entity.mime;- const isIconPack = entity instanceof FNote && entity.isIconPack();+ if (protectedSessionHolder.isProtectedSessionAvailable()) {+ protectedSessionHolder.touchProtectedSession();+ return type;+ }+ return "protectedSession";+}- if (isIconPack) {+/** The kind of content `entity` holds, from its note type or attachment role and its media type. */+function getContentType(entity: FNote | FAttachment) {+ if (entity instanceof FNote && entity.isIconPack()) {// Icon packs (JSON `code`/`file` notes with #iconPack) render as their glyph grid, not as raw JSON.- type = "iconPack";- } else if (type === "file" && mime === "application/pdf") {- type = "pdf";- } else if (type === "code" && entity instanceof FNote && entity.isMarkdown()) {- type = "markdown";- } else if ((type === "file" || type === "viewConfig") && mime && CODE_MIME_TYPES.has(mime)) {- type = "code";- } else if (type === "file" && mime && mime.startsWith("audio/")) {- type = "audio";- } else if (type === "file" && mime && mime.startsWith("video/")) {- type = "video";- } else if (type === "file" && mime && isOfficeMimeType(mime)) {- type = "office";- }-- if (entity.isProtected) {- if (protectedSessionHolder.isProtectedSessionAvailable()) {- protectedSessionHolder.touchProtectedSession();- } else {- type = "protectedSession";- }+ return "iconPack";+ }+ if (entity instanceof FNote && entity.isMarkdown()) {+ return "markdown";}+ if ("type" in entity) {+ return getFileContentType(entity.type, entity.mime);+ }+ if (!("role" in entity)) {+ return "";+ }++ // "importSource" attachments (e.g. the OneNote debug source HTML/InkML) are plain files kept+ // for reference; render them exactly like a "file" role.+ if (entity.role === "importSource") {+ return getFileContentType("file", entity.mime);+ }+ // A link preview's "favicon" is a picture like any other as far as showing it goes; the+ // role only says where it came from. Without this it would fall through to the unknown+ // type and list as a file with no preview.+ if (isImageAttachmentRole(entity.role)) {+ return "image";+ }+ return getFileContentType(entity.role, entity.mime);+}+/** Narrows a file, or a `viewConfig` attachment, to the kind of file its media type names. */+function getFileContentType(type: string, mime: string) {+ if (type === "file" && mime === "application/pdf") return "pdf";+ if ((type === "file" || type === "viewConfig") && CODE_MIME_TYPES.has(mime)) return "code";+ if (type === "file" && mime.startsWith("audio/")) return "audio";+ if (type === "file" && mime.startsWith("video/")) return "video";+ if (type === "file" && isOfficeMimeType(mime)) return "office";return type;}diff --git a/apps/client/src/widgets/dialogs/include_note.spec.tsx b/apps/client/src/widgets/dialogs/include_note.spec.tsxnew file mode 100644index 0000000000..5b3159a987--- /dev/null+++ b/apps/client/src/widgets/dialogs/include_note.spec.tsx@@ -0,0 +1,97 @@+import { act } from "preact/test-utils";+import { beforeEach, describe, expect, it, vi } from "vitest";++import Component from "../../components/component";+import type FNote from "../../entities/fnote";+import type { Suggestion } from "../../services/note_autocomplete";+import { buildNote } from "../../test/easy-froca";+import { renderInto } from "../../test/render";+import { ParentComponent } from "../react/react_utils";+import IncludeNoteDialog from "./include_note";++const autocomplete = vi.hoisted(() => ({+ onChange: undefined as ((suggestion: Suggestion | null) => void) | undefined+}));++vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));+vi.mock("../../services/note_autocomplete", () => ({ triggerRecentNotes: vi.fn() }));+vi.mock("../react/NoteAutocomplete", () => ({+ default: ({ onChange }: { onChange: (suggestion: Suggestion | null) => void }) => {+ autocomplete.onChange = onChange;+ return <input />;+ }+}));++describe("IncludeNoteDialog", () => {+ let host: Component;+ let container: HTMLElement;+ const editorApi = { addIncludeNote: vi.fn(), addImage: vi.fn() };++ beforeEach(async () => {+ vi.clearAllMocks();+ host = new Component();+ container = renderInto(+ <ParentComponent.Provider value={host}>+ <IncludeNoteDialog />+ </ParentComponent.Provider>+ );+ await open();+ });++ async function open() {+ await act(async () => {+ void host.handleEventInChildren("showIncludeNoteDialog", { editorApi });+ });+ }++ async function pick(note: FNote) {+ await act(async () => {+ autocomplete.onChange?.({ notePath: `root/${note.noteId}` });+ });+ }++ function checkedSize() {+ return container.querySelector<HTMLInputElement>("input[type='radio']:checked")?.value;+ }++ async function choose(size: string) {+ const radio = container.querySelector<HTMLInputElement>(+ `input[type='radio'][value='${size}']`+ );+ if (!radio) throw new Error(`No radio for ${size}.`);+ await act(async () => {+ radio.checked = true;+ radio.dispatchEvent(new Event("change", { bubbles: true }));+ });+ }++ async function submit() {+ const form = container.querySelector("form");+ if (!form) throw new Error("The dialog has no form.");+ await act(async () => {+ form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));+ });+ }++ it("preselects the size that suits the picked note, until another size is chosen", async () => {+ const script = buildNote({ title: "Script", type: "code", mime: "text/javascript" });+ const song = buildNote({ title: "Song", type: "file", mime: "audio/mpeg" });+ expect(checkedSize()).toBe("medium");++ await pick(script);+ expect(checkedSize()).toBe("full");+ await choose("tiny");+ expect(checkedSize()).toBe("tiny");++ // Another note, or opening the dialog again, drops the size chosen by hand.+ await pick(song);+ expect(checkedSize()).toBe("small");+ await choose("expandable");+ await open();+ expect(checkedSize()).toBe("small");++ await choose("expandable");+ await submit();+ expect(editorApi.addIncludeNote).toHaveBeenCalledWith(song.noteId, "expandable");+ });+});diff --git a/apps/client/src/widgets/dialogs/include_note.tsx b/apps/client/src/widgets/dialogs/include_note.tsxindex bb58b1c201..4952630188 100644--- a/apps/client/src/widgets/dialogs/include_note.tsx+++ b/apps/client/src/widgets/dialogs/include_note.tsx@@ -1,4 +1,5 @@-import { useRef, useState } from "preact/hooks";+import { useCallback, useRef, useState } from "preact/hooks";+import { getIncludeBoxSize } from "../../services/content_renderer";import { t } from "../../services/i18n";import FormGroup from "../react/FormGroup";import FormRadioGroup from "../react/FormRadioGroup";@@ -8,7 +9,7 @@ import Button from "../react/Button";import { Suggestion, triggerRecentNotes } from "../../services/note_autocomplete";import tree from "../../services/tree";import froca from "../../services/froca";-import { useTriliumEvent, useTriliumOption } from "../react/hooks";+import { useNote, useTriliumEvent } from "../react/hooks";import type { BoxSize, CKEditorApi } from "../type_widgets/text/CKEditorWithWatchdog";export interface IncludeNoteOpts {@@ -18,16 +19,23 @@ export interface IncludeNoteOpts {export default function IncludeNoteDialog() {const editorApiRef = useRef<Pick<CKEditorApi, "addIncludeNote" | "addImage">>(null);const [suggestion, setSuggestion] = useState<Suggestion | null>(null);- const [defaultBoxSize, setDefaultBoxSize] = useTriliumOption("includeNoteDefaultBoxSize");- const [boxSize, setBoxSize] = useState<string>(defaultBoxSize);+ // The size chosen by hand, otherwise the one that suits the picked note.+ const [chosenBoxSize, setChosenBoxSize] = useState<BoxSize | null>(null);const [shown, setShown] = useState(false);+ const note = useNote(suggestion?.notePath ? tree.getNoteIdFromUrl(suggestion.notePath) : null);+ const boxSize = chosenBoxSize ?? (note ? getIncludeBoxSize(note) : "medium");useTriliumEvent("showIncludeNoteDialog", ({ editorApi }) => {editorApiRef.current = editorApi;- setBoxSize(defaultBoxSize); // Reset to default when opening dialog+ setChosenBoxSize(null);setShown(true);});+ const changeSuggestion = useCallback((newSuggestion: Suggestion | null) => {+ setSuggestion(newSuggestion);+ setChosenBoxSize(null);+ }, []);+const autoCompleteRef = useRef<HTMLInputElement>(null);return (@@ -40,11 +48,7 @@ export default function IncludeNoteDialog() {onSubmit={async () => {if (!suggestion?.notePath || !editorApiRef.current) return;setShown(false);- await includeNote(suggestion.notePath, editorApiRef.current, boxSize as BoxSize);- // Save the selected box size as the new default- if (boxSize !== defaultBoxSize) {- setDefaultBoxSize(boxSize);- }+ await includeNote(suggestion.notePath, editorApiRef.current, boxSize);}}footer={<Button text={t("include_note.button_include")} keyboardShortcut="Enter" />}show={shown}@@ -52,7 +56,7 @@ export default function IncludeNoteDialog() {<FormGroup name="note" label={t("include_note.label_note")}><NoteAutocompleteplaceholder={t("include_note.placeholder_search")}- onChange={setSuggestion}+ onChange={changeSuggestion}inputRef={autoCompleteRef}opts={{hideGoToSelectedNoteButton: true,@@ -64,7 +68,7 @@ export default function IncludeNoteDialog() {<FormGroup name="include-note-box-size" label={t("include_note.box_size_prompt")}><FormRadioGroupname="include-note-box-size"- currentValue={boxSize} onChange={setBoxSize}+ currentValue={boxSize} onChange={(value) => setChosenBoxSize(value as BoxSize)}values={[{ label: t("include_note.box_size_tiny"), value: "tiny" },{ label: t("include_note.box_size_small"), value: "small" },diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 4e4a84851a..bffefc6b3c 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -15,6 +15,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";import { consumeBookmark } from "../../../services/bookmark_jump";+import { getUploadBoxSize } from "../../../services/content_renderer";import dateNoteService from "../../../services/date_notes";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";@@ -196,9 +197,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextgetNoteId() {return note.noteId;},- getIncludeNoteDefaultBoxSize() {- return options.get("includeNoteDefaultBoxSize");- },+ getEmbedBoxSize: getUploadBoxSize,// Link preview functionality. The insert flow itself lives in the editor (a balloon form),// so the host only has to supply the metadata and the rendering.async fetchLinkMetadata(url: string) {diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.htmlindex 5b61fc7fd1..44a7058d27 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html@@ -75,8 +75,9 @@<li>To embed an attachment that is already linked, right-click a link to itin a text note being edited and select <em>Convert link to an embed</em>,at the end of the menu.</li>- <li>An embed takes the default box size of included notes. To change its size,- select the embed and use the box size menu in its toolbar.</li>+ <li>An embed gets the box size that suits the attachment, as a new included+ note does (see <em>Box sizes</em> there). To change its size, select the+ embed and use the box size menu in its toolbar.</li><li>To open the attachment in a new tab, press the <span class="tn-icon bx bx-link-external"></span> <em>Open in new tab</em> buttonat the end of the embed's title.</li><li>An embed of size <em>Tiny</em> shows only the title of the attachment anddiff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.htmlindex 2e4b4839f6..0924f3d389 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html@@ -10,10 +10,7 @@<p>An <a href="#root/_help_0vhv7lsOLy82">attachment</a> can be included thesame way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><h2>Box sizes</h2>-<p>The box size sets how much of the included note is shown. Choose it in- the dialog that includes the note, or later by selecting the include and- using the <em>Box size</em> menu in its toolbar. The size chosen in the dialog- becomes the default for the next include.</p>+<p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon,its title with the path to the note above it, and buttons to act on the@@ -24,6 +21,17 @@<li><em>Expandable</em> shows only the title until its <span class="tn-icon bx bx-chevron-right"></span> arrowis pressed.</li></ul>+<p>A new include gets the size that suits what it shows:</p>+<ul>+ <li><em>Tiny</em> for a note or an attachment that has no preview, such as+ a relation map or an archive.</li>+ <li><em>Small</em> for audio.</li>+ <li><em>Full</em> for a code note.</li>+ <li><em>Medium</em> for anything else.</li>+</ul>+<p>The dialog that includes a note selects that size once the note is picked,+ and you can choose another one there. To change the size later, select+ the include and use the <em>Box size</em> menu in its toolbar.</p><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class="tn-icon bx bx-link-external"></span> <em>Open in new tab</em> buttonat the end of its title. An embedded attachment has the same button.</p>diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.mdindex e3ebc62f92..0b4a006002 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md@@ -41,7 +41,7 @@ An attachment can be shown in the text instead of linked, the way <a class="ref* To attach files and embed them straight away, select _Attach and embed file_ from the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. Each file gets an embed of its own, which shows the file name while the file uploads.* To embed an attachment that is already linked, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu.-* An embed takes the default box size of included notes. To change its size, select the embed and use the box size menu in its toolbar.+* An embed gets the box size that suits the attachment, as a new included note does (see _Box sizes_ there). To change its size, select the embed and use the box size menu in its toolbar.* To open the attachment in a new tab, press the <span class="tn-icon bx bx-link-external"></span> _Open in new tab_ button at the end of the embed's title.* An embed of size _Tiny_ shows only the title of the attachment and its size, in a single row. Its buttons are <span class="tn-icon bx bx-file-find"></span> _Open externally_ and <span class="tn-icon bx bx-download"></span> _Download_.* To show an embed of size _Medium_ or _Full_ on the whole screen, press the <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_ button at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> _Exit fullscreen_ in the top-right corner, or <kbd>Esc</kbd>.diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.mdindex f44d02bddd..2a118313e7 100644--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md@@ -11,13 +11,22 @@ An [attachment](../../Basic%20Concepts%20and%20Features/Notes/Attachments.md) ca## Box sizes-The box size sets how much of the included note is shown. Choose it in the dialog that includes the note, or later by selecting the include and using the _Box size_ menu in its toolbar. The size chosen in the dialog becomes the default for the next include.+The box size sets how much of the included note is shown.* _Tiny_ shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note.* _Small_ and _Medium_ show the content in a box of limited height, which scrolls.* _Full_ shows the whole content.* _Expandable_ shows only the title until its <span class="tn-icon bx bx-chevron-right"></span> arrow is pressed.+A new include gets the size that suits what it shows:++* _Tiny_ for a note or an attachment that has no preview, such as a relation map or an archive.+* _Small_ for audio.+* _Full_ for a code note.+* _Medium_ for anything else.++The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the _Box size_ menu in its toolbar.+## Opening an included noteTo open an included note in a new tab, press the <span class="tn-icon bx bx-link-external"></span> _Open in new tab_ button at the end of its title. An embedded attachment has the same button.diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 041b361796..cb8b10efca 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -53,8 +53,11 @@ declare global {getAttachmentHref(attachmentId: string): Promise<string | null>;/** The note the editor holds. Hosts without a note of their own leave it out. */getNoteId?(): string | undefined;- /** The box size the user gives a new include. Hosts without includes leave it out. */- getIncludeNoteDefaultBoxSize?(): string;+ /**+ * The box size of a new embed of a file being uploaded, from its media type. Hosts without+ * includes leave it out.+ */+ getEmbedBoxSize?(mime: string): string;/*** Reads a page's preview metadata through the host. Never rejects: any failure — network* error, HTTP error, unparseable page — resolves as `{ unresolved: true }` withdiff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.tsindex 5dce35fd20..0c174fe9e7 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts@@ -146,9 +146,11 @@ describe("FileUploadCommand", () => {));});- it("inserts an embed placeholder per file, each a block in the host's default size", () => {+ it("inserts an embed placeholder per file, in the size the host gives its type", () => {installGlobMock({- getComponentByEl: () => ({ getIncludeNoteDefaultBoxSize: () => "expandable" })+ getComponentByEl: () => ({+ getEmbedBoxSize: (mime: string) => (mime === "image/png" ? "medium" : "tiny")+ })});setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");@@ -162,15 +164,15 @@ describe("FileUploadCommand", () => {expect(getModelData(editor.model)).toMatch(new RegExp("^<paragraph>foo</paragraph>" +- "<includeNote boxSize=\"expandable\" uploadFileName=\"a.txt\" uploadId=\"\\w+\">" ++ "<includeNote boxSize=\"tiny\" uploadFileName=\"a.txt\" uploadId=\"\\w+\">" +"</includeNote>" +- "<includeNote boxSize=\"expandable\" uploadFileName=\"b.png\" uploadId=\"\\w+\">" ++ "<includeNote boxSize=\"medium\" uploadFileName=\"b.png\" uploadId=\"\\w+\">" +"</includeNote>" +"<paragraph>\\[\\]bar</paragraph>$"));});- it("sizes the embeds medium for a host that names no default size", () => {+ it("sizes the embeds medium for a host that names no size", () => {installGlobMock({ getComponentByEl: () => ({}) });setModelData(editor.model, "<paragraph>[]</paragraph>");diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.tsindex 91d9dc541b..72949bfaa3 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts@@ -24,7 +24,6 @@ export default class FileUploadCommand extends Command {override execute({ file: files, asEmbed }: FileUploadOptions) {const model = this.editor.model;const fileRepository = this.editor.plugins.get(FileRepository);- const boxSize = asEmbed ? getDefaultBoxSize(this.editor) : undefined;model.change((writer) => {for (const file of files) {@@ -35,7 +34,8 @@ export default class FileUploadCommand extends Command {}uploadAsLink(loader);- if (boxSize) {+ if (asEmbed) {+ const boxSize = getEmbedBoxSize(this.editor, file);insertEmbedPlaceholder(writer, model, loader.id, file.name, boxSize);} else {insertPlaceholder(writer, model, loader.id, file.name);@@ -75,8 +75,8 @@ function insertEmbedPlaceholder(model.insertObject(placeholder, model.document.selection, null, { setSelection: "after" });}-/** The box size the user gives a new include, `medium` when the host does not say. */-function getDefaultBoxSize(editor: Editor) {+/** The box size the host gives an embed of `file`, `medium` when the host does not say. */+function getEmbedBoxSize(editor: Editor, file: File) {const component = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());- return component.getIncludeNoteDefaultBoxSize?.() ?? "medium";+ return component.getEmbedBoxSize?.(file.type) ?? "medium";}diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.tsindex 5d4048603e..f20f5ce265 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts@@ -593,7 +593,7 @@ describe("FileUploadEditing with embeds", () => {const loadIncludedAttachment = vi.fn();installGlobMock({getComponentByEl: () => ({- getIncludeNoteDefaultBoxSize: () => "small",+ getEmbedBoxSize: () => "small",loadIncludedAttachment})});diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 8e0ab1e645..d1c10d1f11 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -316,9 +316,6 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActiseenCallToActions: string;experimentalFeatures: string;- // Include note settings- includeNoteDefaultBoxSize: "tiny" | "small" | "medium" | "full" | "expandable";-// AI / LLM/** Whether the AI/LLM features (chat sidebar, LLM chat notes) are enabled. */aiEnabled: boolean;diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex aff5ae4709..778310120f 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -139,7 +139,6 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["textNoteAutoLinkPreviewsEnabled","textNoteHtmlSupportEnabled","clipboardImageEmbedEnabled",- "includeNoteDefaultBoxSize","layoutOrientation","backgroundEffects","allowedHtmlTags",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 63af5471f1..fc5584ac92 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -329,7 +329,6 @@ const defaultOptions: DefaultOption[] = [// them is worse than their absence. See `textNoteHtmlSupportEnabled` for what turning it off costs.{ name: "textNoteHtmlSupportEnabled", value: "false", isSynced: true },{ name: "clipboardImageEmbedEnabled", value: "true", isSynced: true },- { name: "includeNoteDefaultBoxSize", value: "medium", isSynced: true },// HTML import configuration{ name: "layoutOrientation", value: "vertical", isSynced: false },