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/block references: customize the content embed widget for excerpts
Adorian Doranbfe5650e0dd7
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.tsindex 8946435733..5312a82ae7 100644--- a/apps/client/src/menus/link_context_menu.spec.ts+++ b/apps/client/src/menus/link_context_menu.spec.ts@@ -27,7 +27,10 @@ vi.mock("./text_editor_context_menu", () => ({getTextEditorContaining: mocks.getTextEditorContaining}));-vi.mock("../services/content_renderer", () => ({ getEmbedBoxSize: mocks.getEmbedBoxSize }));+vi.mock("../services/content_renderer", () => ({+ EXCERPT_BOX_SIZE: "full",+ getEmbedBoxSize: mocks.getEmbedBoxSize+}));vi.mock("./context_menu", () => ({ default: { show: mocks.show } }));@@ -379,11 +382,14 @@ describe("openContextMenu", () => {expect(mocks.show.mock.calls[1][0].items).toHaveLength(4);});- it("offers converting a link to blocks of a note to an excerpt", async () => {+ it("offers converting a link to blocks of a note to an excerpt of full size", async () => {+ const execute = vi.fn();+ mocks.getNote.mockResolvedValue({ noteId: "n1" });+ mocks.getEmbedBoxSize.mockReturnValue("medium");mocks.getTextEditorContaining.mockResolvedValue({commands: { get: () => ({ isEnabled: true }) },plugins: { get: () => ({ canConvertLinkToEmbed: () => true }) },- execute: vi.fn()+ execute});const editable = document.createElement("div");editable.className = "ck-editor__editable";@@ -396,10 +402,16 @@ describe("openContextMenu", () => {"root/n1", contextMenuEvent(link ?? undefined), { block: "b1" });- expect(mocks.show.mock.calls[0][0].items.at(-1)).toMatchObject({+ const item = mocks.show.mock.calls[0][0].items.at(-1);+ expect(item).toMatchObject({title: "link_context_menu.convert_link_to_note_excerpt",uiIcon: "bx bx-window-alt"});+ item.handler();+ expect(execute).toHaveBeenCalledWith("convertLinkToEmbed", {+ domElement: link,+ boxSize: "full"+ });});describe("opened on an embed in a note being edited", () => {diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.tsindex 54d7822221..986706e609 100644--- a/apps/client/src/menus/link_context_menu.ts+++ b/apps/client/src/menus/link_context_menu.ts@@ -210,7 +210,8 @@ async function getNoteItems(e, editor, isBlockReference? t("link_context_menu.convert_link_to_note_excerpt"): t("link_context_menu.convert_link_to_included_note"),- () => froca.getNote(noteId)+ () => froca.getNote(noteId),+ isBlockReference);return embedItem ? [ { kind: "separator" }, embedItem ] : [];}@@ -298,13 +299,15 @@ function runEmbedCommand(/*** The item titled `title` that converts a link to a note or an attachment into an embed, in a- * text note open for editing, for a link that the editor can convert.+ * text note open for editing, for a link that the editor can convert. `isExcerpt` is set for a+ * link to blocks of a note.*/async function getConvertToEmbedItem(e: LinkMenuOrigin,editor: CKTextEditor | null,title: string,- getLinkedEntity: () => Promise<FNote | FAttachment | null>+ getLinkedEntity: () => Promise<FNote | FAttachment | null>,+ isExcerpt = false): Promise<MenuItem<CommandNames> | null> {const link = getTarget(e)?.closest<HTMLElement>("a.reference-link");if (!link || !editor?.commands.get("convertLinkToEmbed")?.isEnabled@@ -313,7 +316,7 @@ async function getConvertToEmbedItem(}// Imported on demand: `content_renderer` imports `link`, which imports this module.- const [ entity, { getEmbedBoxSize } ] = await Promise.all([+ const [ entity, { EXCERPT_BOX_SIZE, getEmbedBoxSize } ] = await Promise.all([getLinkedEntity(),import("../services/content_renderer.js")]);@@ -326,7 +329,7 @@ async function getConvertToEmbedItem(uiIcon: "bx bx-window-alt",handler: () => editor.execute("convertLinkToEmbed", {domElement: link,- boxSize: getEmbedBoxSize(entity)+ boxSize: isExcerpt ? EXCERPT_BOX_SIZE : getEmbedBoxSize(entity)})};}diff --git a/apps/client/src/services/block_reference.spec.ts b/apps/client/src/services/block_reference.spec.tsindex f1dcfd559e..ecc73642e4 100644--- a/apps/client/src/services/block_reference.spec.ts+++ b/apps/client/src/services/block_reference.spec.ts@@ -28,7 +28,10 @@ vi.mock("../menus/context_menu.js", () => ({ default: { show: showMenu } }));vi.mock("../menus/text_editor_context_menu.js", () => ({ getTextEditorContaining }));vi.mock("./clipboard_ext.js", () => ({ copyHtmlWithToast }));vi.mock("./froca.js", () => ({ default: { getNote } }));-vi.mock("./content_renderer.js", () => ({ getEmbedBoxSize: () => "medium" }));+vi.mock("./content_renderer.js", () => ({+ EXCERPT_BOX_SIZE: "full",+ getEmbedBoxSize: () => "medium"+}));const scrollIntoView = vi.fn();const getComponentByEl = vi.fn();@@ -322,7 +325,7 @@ describe("buildBlockReferenceMenuItems", () => {expect(getNote).toHaveBeenCalledWith("note1", true);expect(pasteTarget.paste).toHaveBeenLastCalledWith("<figure class=\"include-note\" data-note-id=\"note1\" data-block=\"s1:e1\""- + " data-box-size=\"medium\"></figure>",+ + " data-box-size=\"full\"></figure>",href);});diff --git a/apps/client/src/services/block_reference.ts b/apps/client/src/services/block_reference.tsindex 0baff02feb..8852874dcf 100644--- a/apps/client/src/services/block_reference.ts+++ b/apps/client/src/services/block_reference.ts@@ -299,7 +299,7 @@ function getLinkHtml({ href }: ClipboardBlockReference) {async function getExcerptHtml({ noteId, block }: ClipboardBlockReference) {// Imported on demand: `content_renderer` imports `content_renderer_text`, which imports this// module.- const [ note, { getEmbedBoxSize } ] = await Promise.all([+ const [ note, { EXCERPT_BOX_SIZE } ] = await Promise.all([froca.getNote(noteId, true),import("./content_renderer.js")]);@@ -312,7 +312,7 @@ async function getExcerptHtml({ noteId, block }: ClipboardBlockReference) {embed.className = "include-note";embed.dataset.noteId = noteId;embed.dataset.block = block;- embed.dataset.boxSize = getEmbedBoxSize(note);+ embed.dataset.boxSize = EXCERPT_BOX_SIZE;return embed.outerHTML;}diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 6d21c71bd2..0e49c7f92a 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -161,6 +161,9 @@ const PREVIEWED_TYPES = new Set(["llmChat"]);+/** The box size a new embed of blocks of a note, an excerpt, starts with. */+export const EXCERPT_BOX_SIZE: BoxSize = "full";+export async function getRenderedContent(this: {} | { ctx: string }, entity: FNote | FAttachment, options: RenderOptions = {}) {options = Object.assign(diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 3316c5233c..e13602a17e 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4606,6 +4606,7 @@"not_found": "A referenced block could not be found. It might have been deleted.","untitled": "Block","excerpt": "Excerpt",- "excerpt_description": "You are currently seeing just a fragment of this note. Press the {{icon}} button to open the entire note in a new tab."+ "excerpt_description": "You are currently seeing just a fragment of this note. Press the {{icon}} button to open the entire note in a new tab.",+ "edit_excerpt": "Edit excerpt"}}diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsxindex 815f7f839a..a484f98e50 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx@@ -1,7 +1,7 @@import { Tooltip } from "bootstrap";import { render } from "preact";import { act } from "preact/test-utils";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";const {openTabWithNoteWithHoisting,@@ -39,6 +39,7 @@ vi.mock("../../../services/shortcuts", async (importOriginal) => ({removeIndividualBinding}));+import { registerContentEmbedTools } from "./content_embed_tools";import ContentEmbed, {getNoteActions,type ContentEmbedProps,@@ -158,6 +159,41 @@ function rightClick(target: Element | null) {return { opened, isTaken: event.defaultPrevented && stopPropagation.mock.calls.length > 0 };}+/** Tools of content with an editable mode, which adds the Editable toggle to its embed. */+const EDITABLE_TOOLS = {+ hasEditableFlag: true,+ getTools: () => [],+ execute: () => {},+ subscribe: () => () => {}+};++/**+ * Moves the box into an embed of a text editor, whose `ContentEmbed` plugin selects the embed for+ * the commands it runs.+ */+function placeInHostEditor() {+ const selectEmbedAt = vi.fn((_element: Element) => true);+ const execute = vi.fn();+ const focus = vi.fn();+ const editable = document.createElement("div");+ editable.className = "ck-editor__editable";+ Object.assign(editable, {+ ckeditorInstance: {+ plugins: { get: () => ({ selectEmbedAt }) },+ execute,+ editing: { view: { focus } }+ }+ });+ const embed = document.createElement("figure");+ embed.className = "include-note";+ editable.append(embed);+ embed.append(container);+ document.body.append(editable);+ onTestFinished(() => editable.remove());++ return { editor: { selectEmbedAt, execute, focus }, embed };+}+/** Clicks `target` and tells whether the click was kept from what surrounds the box. */function click(target: HTMLElement) {const event = new MouseEvent("click", { bubbles: true, cancelable: true });@@ -187,6 +223,23 @@ describe("ContentEmbed", () => {}});+ it("lays out an excerpt with an edit button in place of fullscreen", () => {+ const excerpt = [ "title", "badges", "open", "edit", "menu" ];+ const layouts: [ string, string[] ][] = [+ [ "small", excerpt ],+ [ "medium", excerpt ],+ [ "full", excerpt ],+ [ "expandable", [ "toggle", ...excerpt ] ]+ ];++ for (const [ boxSize, expected ] of layouts) {+ act(() => render(null, container));+ renderBox({ boxSize, isExcerpt: true });+ expect(titleRow(), boxSize).toEqual(expected.map((name) => `include-note-${name}`));+ expect(container.querySelector(".include-note-fullscreen-controls")).toBeNull();+ }+ });+it("shows its title and content, and swaps them on a new render", () => {const titleChildren = () => [...container.querySelector("h4.include-note-title")?.childNodes ?? []@@ -260,7 +313,7 @@ describe("ContentEmbed", () => {});it("marks an excerpt, with the icon of the button that opens the whole note", () => {- renderBox({ viewScope: { block: "blockA:blockB" } });+ renderBox({ viewScope: { block: "blockA:blockB" }, isExcerpt: true });const badge = container.querySelector<HTMLElement>(".include-note-badges > .excerpt-badge");expect(badge?.textContent).toBe("block_reference.excerpt");expect(titleRow()).toContain("include-note-badges");@@ -280,6 +333,61 @@ describe("ContentEmbed", () => {}});+ it("turns the editing of an excerpt on and off through the editor around it", async () => {+ const { editor, embed } = placeInHostEditor();+ const { content } = renderBox({ boxSize: "medium", isExcerpt: true });+ const edit = button("include-note-edit");+ expect(edit.className).toContain("bx-pencil");+ expect(tooltipOf(edit)).toBe("block_reference.edit_excerpt");+ expect(edit.disabled).toBe(true);++ let unregister = () => {};+ act(() => {+ unregister = registerContentEmbedTools(content, EDITABLE_TOOLS);+ });+ expect(edit.disabled).toBe(false);+ expect(edit.classList.contains("active")).toBe(false);++ expect(click(edit).isStopped).toBe(true);+ expect(editor.selectEmbedAt).toHaveBeenCalledWith(contentBox());+ expect(editor.execute).toHaveBeenCalledWith("toggleContentEmbedEditable");+ expect(document.activeElement).toBe(contentBox());++ await act(async () => {+ embed.dataset.editable = "true";+ });+ expect(edit.classList.contains("active")).toBe(true);+ click(edit);+ expect(editor.execute).toHaveBeenCalledTimes(2);+ expect(editor.focus).toHaveBeenCalledOnce();++ act(() => unregister());+ expect(edit.disabled).toBe(true);+ expect(edit.classList.contains("active")).toBe(false);+ });++ it("keeps the edit button of an excerpt disabled without an editor around it", () => {+ const { content } = renderBox({ boxSize: "medium", isExcerpt: true });+ act(() => {+ onTestFinished(registerContentEmbedTools(content, EDITABLE_TOOLS));+ });++ expect(button("include-note-edit").disabled).toBe(true);+ });++ it("opens an expandable excerpt to edit it", () => {+ placeInHostEditor();+ const { content } = renderBox({ boxSize: "expandable", isExcerpt: true });+ act(() => {+ onTestFinished(registerContentEmbedTools(content, EDITABLE_TOOLS));+ });+ expect(contentBox().hidden).toBe(true);++ click(button("include-note-edit"));++ expect(contentBox().hidden).toBe(false);+ });+it("gives its content the screen, and takes it back from the overlay button", async () => {const warn = vi.spyOn(console, "warn").mockImplementation(() => {});const exitFullscreen = vi.fn<() => Promise<void>>(async () => {});diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsxindex 8261d66d3a..f0e5814bde 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx@@ -14,7 +14,11 @@ import { Badge } from "../../react/Badge";import { useFocusWithin } from "../../react/hooks";import Icon from "../../react/Icon";import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";-import { type ContentEmbedEvent, showContentEmbedFullscreen } from "./content_embed_tools";+import {+ type ContentEmbedEvent, getContentEmbedTools, showContentEmbedFullscreen,+ useIsContentEmbedEditable, watchContentEmbedTools+} from "./content_embed_tools";+import { findTextEditorAround } from "./editable_embed";/** An action on the embedded note or attachment, offered as a button in the title row. */export interface ContentEmbedAction {@@ -33,6 +37,8 @@ export interface ContentEmbedProps {/** The note opened by the buttons in the title row. */notePath: string;viewScope?: ViewScope;+ /** Whether the embed shows only some blocks of its note, from a block reference. */+ isExcerpt?: boolean;/** Gives the focus to the content once mounted, as for a canvas drawing just added. */isFocusedOnMount?: boolean;}@@ -52,7 +58,7 @@ export interface TinyContentEmbedProps {/** The title row and the content of an embedded note or attachment. */export default function ContentEmbed({- boxSize, title, content, contentType, notePath, viewScope, isFocusedOnMount+ boxSize, title, content, contentType, notePath, viewScope, isExcerpt, isFocusedOnMount}: ContentEmbedProps) {const contentRef = useRef<HTMLDivElement>(null);const bodyRef = useRef<HTMLDivElement>(null);@@ -62,7 +68,7 @@ export default function ContentEmbed({useWindowShortcuts(contentRef);const [ isExpanded, setIsExpanded ] = useState(false);const isExpandable = boxSize === "expandable";- const hasFullscreen = boxSize === "medium" || boxSize === "full";+ const hasFullscreen = !isExcerpt && (boxSize === "medium" || boxSize === "full");useLayoutEffect(() => {contentRef.current?.append(content);@@ -101,12 +107,19 @@ export default function ContentEmbed({<ContentEmbedTitle title={title} />{/* The content of the embed puts badges here, such as its save status. */}<div className="note-badges include-note-badges">- {viewScope?.block && <ExcerptBadge />}+ {isExcerpt && <ExcerptBadge />}</div><ContentEmbedActionButtonclassName="include-note-open"action={getOpenInNewTabAction(notePath, viewScope)}/>+ {isExcerpt && (+ <ExcerptEditButton+ contentRef={contentRef}+ content={content}+ onEdit={() => setIsExpanded(true)}+ />+ )}{hasFullscreen && (<ActionButtonclassName="include-note-fullscreen"@@ -236,6 +249,67 @@ function ExcerptBadge() {);}+/**+ * Turns the editing of an excerpt on and off, as the Editable toggle of its embed does. Disabled+ * while the content has no editable mode, as in a read-only note or for blocks that cannot be+ * edited in place. Opening the editor gives it the focus, and `onEdit` runs first.+ */+function ExcerptEditButton({ contentRef, content, onEdit }: {+ contentRef: RefObject<HTMLDivElement | null>;+ content: HTMLElement;+ onEdit: () => void;+}) {+ const isEditing = useIsContentEmbedEditable(contentRef);+ const hasEditableMode = useHasEditableMode(contentRef, content);++ return (+ <ActionButton+ className="include-note-edit"+ icon="bx bx-pencil"+ text={t("block_reference.edit_excerpt")}+ active={hasEditableMode && isEditing}+ disabled={!hasEditableMode}+ onClick={(e) => {+ e.stopPropagation();+ const box = contentRef.current;+ const editor = findTextEditorAround(box);+ if (!box || !editor?.plugins.get("ContentEmbed").selectEmbedAt(box)) return;++ editor.execute("toggleContentEmbedEditable");+ if (isEditing) {+ editor.editing.view.focus();+ } else {+ onEdit();+ // `useEditableEmbed()` moves the focus on to the editor once it renders.+ box.focus({ preventScroll: true });+ }+ }}+ />+ );+}++/**+ * Whether the content in `contentRef` has an editable mode, which it tells by adding the Editable+ * toggle to its embed, and a text editor holds the embed to turn it on. Checked again for new+ * `content`, which can add the toggle before it is in the box.+ */+function useHasEditableMode(contentRef: RefObject<HTMLElement | null>, content: HTMLElement) {+ const [ hasEditableMode, setHasEditableMode ] = useState(false);++ useEffect(() => {+ const box = contentRef.current;+ if (!box) return;++ const update = () => setHasEditableMode(+ !!getContentEmbedTools(box)?.hasEditableFlag && !!findTextEditorAround(box)+ );+ update();+ return watchContentEmbedTools(box, update);+ }, [ contentRef, content ]);++ return hasEditableMode;+}+const FOCUSABLE_SELECTOR = "[tabindex], a[href], iframe, webview, "+ ":is(button, input, select, textarea):not(:disabled)";diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex 7791e9cc03..08c3b95f61 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -33,6 +33,7 @@ const {notifyAttachmentChanges,onNotificationInfo,onNotificationWarning,+ revealLinkTargetWhenReady,showFileUploadProgress,watchEditorBlocks} = await import("./EditableText");@@ -254,3 +255,28 @@ describe("watchEditorBlocks", () => {expect(getRange).toHaveBeenCalledWith({ startId: "a", endId: "b" });});});++describe("revealLinkTargetWhenReady", () => {+ it("reveals a bookmark or blocks once the editor is ready, as in a new tab", async () => {+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {+ callback(0);+ return 0;+ });+ const reveal = vi.fn();+ let markReady = () => {};+ const ready = new Promise<void>((resolve) => {+ markReady = resolve;+ });++ revealLinkTargetWhenReady({ block: "a:b" }, ready, reveal);+ revealLinkTargetWhenReady({ bookmark: "intro" }, ready, reveal);+ revealLinkTargetWhenReady({ viewMode: "default" }, ready, reveal);+ await Promise.resolve();+ expect(reveal).not.toHaveBeenCalled();++ markReady();+ await ready;+ await Promise.resolve();+ expect(reveal).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 7aa036fcd4..04933fe045 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -21,7 +21,7 @@ import { consumeBookmark } from "../../../services/bookmark_jump";import { getUploadBoxSize } from "../../../services/content_renderer";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";-import link, { parseNavigationStateFromUrl } from "../../../services/link";+import link, { parseNavigationStateFromUrl, type ViewScope } from "../../../services/link";import type LoadResults from "../../../services/load_results";import note_create from "../../../services/note_create";import options from "../../../services/options";@@ -143,10 +143,9 @@ export default function EditableText({consumeSearchTerms(noteContext, ntxId, initialized.current);// Scroll to the bookmark or the blocks a link points at.- const viewScope = noteContext?.viewScope;- if (viewScope?.bookmark || viewScope?.block) {- requestAnimationFrame(revealLinkTarget);- }+ revealLinkTargetWhenReady(+ noteContext?.viewScope, initialized.current, revealLinkTarget+ );},dataSaved(savedData) {// Store back the saved data in order to retrieve it in case the CKEditor crashes.@@ -678,6 +677,22 @@ export function watchEditorBlocks(block: string, onBlockChange: (block: string)};}+/**+ * Calls `reveal()` to scroll to the bookmark or the blocks that `viewScope` points at, once+ * `ready` resolves. The editor of a new tab can still be starting when the content arrives.+ *+ * Exported for testing.+ */+export function revealLinkTargetWhenReady(+ viewScope: ViewScope | undefined,+ ready: Promise<unknown>,+ reveal: () => void+) {+ if (viewScope?.bookmark || viewScope?.block) {+ void ready.then(() => requestAnimationFrame(reveal));+ }+}+/** The blocks that an editor of the blocks `block` holds, preferring the ids of `block`. */function getEditorBlocks(editor: CKTextEditor, block: string) {const range = editor.plugins.get("BlockReferenceEditing").getRange(parseBlockRange(block));diff --git a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts b/apps/client/src/widgets/type_widgets/text/content_embed_tools.tsindex b1c00faa72..9b9b7726b8 100644--- a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts+++ b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts@@ -60,19 +60,17 @@ export function registerContentEmbedTools(provider: ContentEmbedToolProvider) {providers.set(element, provider);- for (const { container, callback } of watchers) {- if (container.contains(element)) {- callback();- }- }+ notifyWatchers(element);return () => {providers.delete(element);+ notifyWatchers(element);};}/**- * Calls `callback` when content inside `container` adds its buttons, as a canvas drawing does- * once it renders after its embed was selected. Stops when the returned function is called.+ * Calls `callback` when content inside `container` adds or removes its buttons, as a canvas+ * drawing adds them once it renders after its embed was selected. Stops when the returned function+ * is called.*/export function watchContentEmbedTools(container: HTMLElement, callback: () => void) {const watcher = { container, callback };@@ -92,6 +90,14 @@ export function getContentEmbedTools(embed: HTMLElement) {return null;}+function notifyWatchers(element: HTMLElement) {+ for (const { container, callback } of watchers) {+ if (container.contains(element)) {+ callback();+ }+ }+}+/** Shows the content box of the embed that contains `element` in fullscreen. */export function showContentEmbedFullscreen(element: Element | null) {element?.closest(".include-note-content")?.requestFullscreen().catch((error: unknown) => {diff --git a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.tsxindex b74cd3527f..44504aa844 100644--- a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx@@ -193,8 +193,12 @@ export function useEmbedBadgeSlot(rootRef: RefObject<HTMLElement | null>, isShow* rather than in a floating one.*/export function hasFixedToolbarAround(element: HTMLElement | null) {- const editable = element?.closest<EditorRootElement>(EDITOR_ROOT_SELECTOR);- return !!editable?.ckeditorInstance?.ui.view.toolbar;+ return !!findTextEditorAround(element)?.ui.view.toolbar;+}++/** The text editor whose editable root contains `element`, as the editor around an embed. */+export function findTextEditorAround(element: HTMLElement | null) {+ return element?.closest<EditorRootElement>(EDITOR_ROOT_SELECTOR)?.ckeditorInstance;}/** The text editor whose editable root is in `element`, as the editor of an included note. */diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.tsindex 3bd73c8485..8f98a6a2ce 100644--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts@@ -134,7 +134,8 @@ describe("loadEmbeddedNote", () => {title,content,contentType: "pdf",- notePath: "noteY"+ notePath: "noteY",+ isExcerpt: false});});@@ -190,12 +191,24 @@ describe("loadEmbeddedNote of blocks", () => {.toHaveBeenCalledWith("noteY", expect.objectContaining({ viewScope }));expect(content_renderer.getRenderedContent).toHaveBeenCalledWith(note,expect.objectContaining({ block: "b1:b2", onBlockChange }));- expect(lastMount().props.viewScope).toEqual(viewScope);+ expect(lastMount().props).toMatchObject({ viewScope, isExcerpt: true });await loadEmbeddedNote("noteY", $(figure), undefined, { block: "b1" });expect(lastMount().type).toBe(TinyContentEmbed);expect(lastMount().props.viewScope).toEqual({ block: "b1" });+ expect(lastMount().container.classList.contains("excerpt")).toBe(true);+ });++ it("marks the wrapper of an excerpt, and unmarks it for a whole note", async () => {+ const wrapper = createWrapper();++ await loadEmbeddedNote("noteY", $(wrapper), "medium", { block: "b1" });+ expect(wrapper.className).toBe("include-note-wrapper excerpt");++ await loadEmbeddedNote("noteY", $(wrapper), "medium");+ expect(wrapper.className).toBe("include-note-wrapper");+ expect(lastMount().props.isExcerpt).toBe(false);});});@@ -430,7 +443,7 @@ describe("watchContentEmbeds", () => {expect(disposed()).toHaveLength(2);});- it("updates the editor when content in an embed adds buttons to its toolbar", () => {+ it("updates the editor when content in an embed adds or removes toolbar buttons", () => {const provider = { getTools: () => [], execute: vi.fn(), subscribe: () => () => {} };const [ inside, outside ] = [ container, document.body ].map((parent) => {const element = document.createElement("div");@@ -440,16 +453,16 @@ describe("watchContentEmbeds", () => {update.mockClear();const stop = watchContentEmbeds(container, editor);- const unregister = [ registerContentEmbedTools(inside, provider) ];+ const unregisterInside = registerContentEmbedTools(inside, provider);expect(update).toHaveBeenCalledTimes(1);- unregister.push(registerContentEmbedTools(outside, provider));- stop();- unregister.push(registerContentEmbedTools(inside, provider));+ registerContentEmbedTools(outside, provider)();expect(update).toHaveBeenCalledTimes(1);+ unregisterInside();+ expect(update).toHaveBeenCalledTimes(2);- for (const stopRegistration of unregister) {- stopRegistration();- }+ stop();+ registerContentEmbedTools(inside, provider)();+ expect(update).toHaveBeenCalledTimes(2);outside.remove();});});diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex 23b51d8998..184e7216e0 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -39,6 +39,7 @@ export async function loadEmbeddedNote(const el = $el[0];const size = boxSize ?? getEmbedBoxSize(el);const viewScope: ViewScope | undefined = block ? { block } : undefined;+ const isExcerpt = !!block;if (size === "tiny") {const $link = await link.createLink(note.noteId, {showTooltip: false,@@ -52,7 +53,7 @@ export async function loadEmbeddedNote(viewScope,actions: getNoteActions(note.noteId)});- await mountEmbedBox(el, box);+ await mountEmbedBox(el, box, undefined, isExcerpt);return;}@@ -79,9 +80,10 @@ export async function loadEmbeddedNote(content: $renderedContent[0],contentType: type,notePath: note.noteId,- viewScope+ viewScope,+ isExcerpt});- await mountEmbedBox(el, box, $renderedContent);+ await mountEmbedBox(el, box, $renderedContent, isExcerpt);}interface EmbeddedAttachmentOptions {@@ -151,7 +153,16 @@ export async function loadEmbeddedAttachment(* Mounts `box` in the embed `el`. An embed that left the page while it loaded gets no box,* and `content` rendered for it is disposed: `watchContentEmbeds()` has already passed it.*/-async function mountEmbedBox(el: HTMLElement, box: JSX.Element, content?: JQuery<HTMLElement>) {+/**+ * Mounts `box` in the wrapper of the embed `el`, which carries the `excerpt` class while+ * `isExcerpt`. The class is not saved with the note.+ */+async function mountEmbedBox(+ el: HTMLElement,+ box: JSX.Element,+ content?: JQuery<HTMLElement>,+ isExcerpt = false+) {if (!el.isConnected) {if (content) {content_renderer.disposeInteractiveContent(content);@@ -159,7 +170,9 @@ async function mountEmbedBox(el: HTMLElement, box: JSX.Element, content?: JQueryreturn;}- await content_renderer.mountInteractiveWidget(box, getWrapper(el));+ const wrapper = getWrapper(el);+ wrapper.classList.toggle("excerpt", isExcerpt);+ await content_renderer.mountInteractiveWidget(box, wrapper);}function getEmbedBoxSize(el: HTMLElement) {diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.htmlindex 9c2b71a7a8..a8d6d61fad 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html@@ -36,14 +36,19 @@in a note being edited and select <em>Convert link to note excerpt</em>,or paste the copied reference with <em>Paste</em> → <em>Paste reference as an excerpt</em>.The include shows only the referenced blocks, not the rest of the note,- and marks them with an <em>Excerpt</em> badge in its title. To see the whole- note, press the <span class="tn-icon bx bx-link-external"></span> button+ and marks them with an <em>Excerpt</em> badge in its title. It starts at+ the <em>Full</em> box size, so all the referenced blocks are visible. To+ see the whole note, press the <span class="tn-icon bx bx-link-external"></span> buttonin the same title, which opens the note in a new tab. Converting the includeback to a link keeps the reference.</p>-<p>To edit the referenced blocks without leaving the note, turn on <em>Editable</em> in- the toolbar of the include, as for any <a class="reference-link" href="#root/_help_nBAXQFj20hS1">Include Note</a>.- The changes are saved to the referenced blocks, and the rest of the note- stays as it is.</p>+<p>To edit the referenced blocks without leaving the note, press the <span+ class="tn-icon bx bx-pencil"></span> <em>Edit excerpt</em> button in the+ title of the include, or turn on <em>Editable</em> in its toolbar, as for+ any <a class="reference-link" href="#root/_help_nBAXQFj20hS1">Include Note</a>.+ Press the button again to stop editing. The changes are saved to the referenced+ blocks, and the rest of the note stays as it is. The button is grayed out+ where the blocks cannot be edited, such as in a read-only note. An excerpt+ has no <em>Fullscreen</em> button.</p><p>If a referenced block was deleted, the include shows <em>Broken reference</em>.</p><h2>Limitations</h2><ul>diff --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 c27f3eff3e..02efe888f7 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@@ -36,7 +36,8 @@<li><em>Tiny</em> for a note or an attachment that has no preview, such asa relation map or an archive.</li><li><em>Small</em> for audio.</li>- <li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment.</li>+ <li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment,+ and for an excerpt of the blocks of a text 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,@@ -109,7 +110,10 @@menu.</p><p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen,press the <span class="tn-icon bx bx-fullscreen"></span> <em>Fullscreen</em> button- at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> <em>Exit fullscreen</em> in+ at the end of its title. An excerpt of the blocks of a note has an <span+ class="tn-icon bx bx-pencil"></span> <em>Edit excerpt</em> button there instead;+ see <a class="reference-link" href="#root/_help_klC3ilXa9kUE">Block references</a>.+ To return, press <span class="tn-icon bx bx-exit"></span> <em>Exit fullscreen</em> inthe top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul>diff --git a/docs/User Guide/User Guide/Note Types/Text/Block references.md b/docs/User Guide/User Guide/Note Types/Text/Block references.mdindex da1c931fc8..3f4abd8eaa 100644--- a/docs/User Guide/User Guide/Note Types/Text/Block references.md+++ b/docs/User Guide/User Guide/Note Types/Text/Block references.md@@ -23,9 +23,9 @@ Clicking a block reference opens the note, scrolls to the referenced blocks and## Including the referenced blocks-To show the referenced blocks inside another note, right-click the link in a note being edited and select _Convert link to note excerpt_, or paste the copied reference with _Paste_ → _Paste reference as an excerpt_. The include shows only the referenced blocks, not the rest of the note, and marks them with an _Excerpt_ badge in its title. To see the whole note, press the <span class="tn-icon bx bx-link-external"></span> button in the same title, which opens the note in a new tab. Converting the include back to a link keeps the reference.+To show the referenced blocks inside another note, right-click the link in a note being edited and select _Convert link to note excerpt_, or paste the copied reference with _Paste_ → _Paste reference as an excerpt_. The include shows only the referenced blocks, not the rest of the note, and marks them with an _Excerpt_ badge in its title. It starts at the _Full_ box size, so all the referenced blocks are visible. To see the whole note, press the <span class="tn-icon bx bx-link-external"></span> button in the same title, which opens the note in a new tab. Converting the include back to a link keeps the reference.-To edit the referenced blocks without leaving the note, turn on _Editable_ in the toolbar of the include, as for any <a class="reference-link" href="Include%20Note.md">Include Note</a>. The changes are saved to the referenced blocks, and the rest of the note stays as it is.+To edit the referenced blocks without leaving the note, press the <span class="tn-icon bx bx-pencil"></span> _Edit excerpt_ button in the title of the include, or turn on _Editable_ in its toolbar, as for any <a class="reference-link" href="Include%20Note.md">Include Note</a>. Press the button again to stop editing. The changes are saved to the referenced blocks, and the rest of the note stays as it is. The button is grayed out where the blocks cannot be edited, such as in a read-only note. An excerpt has no _Fullscreen_ button.If a referenced block was deleted, the include shows _Broken reference_.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 f60ad7e631..2676cc53bc 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@@ -26,7 +26,7 @@ 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 or a code file, such as a `.js`, `.py` or `.txt` attachment.+* _Full_ for a code note or a code file, such as a `.js`, `.py` or `.txt` attachment, and for an excerpt of the blocks of a text 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, or the _Size_ submenu of its _More actions_ menu.@@ -68,7 +68,7 @@ The <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ butIn a note being edited, the menu also has the commands of the include's toolbar: the _Size_ submenu, _Show title_ and _Show caption_, each checked while it is in effect, and _Convert to link_ at the end. A drawing canvas, an included text or code note and an embedded code file also have _Editable_, above _Size_. For an embedded attachment they follow its first group of actions; for an included note they end the menu.-To show an include 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>.+To show an include 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. An excerpt of the blocks of a note has an <span class="tn-icon bx bx-pencil"></span> _Edit excerpt_ button there instead; see <a class="reference-link" href="Block%20references.md">Block references</a>. To return, press <span class="tn-icon bx bx-exit"></span> _Exit fullscreen_ in the top-right corner, or <kbd>Esc</kbd>.A _Tiny_ include has these buttons instead, followed by the same _More actions_ button: