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: add support for editable excerpts
Adorian Doran74eae2783e9e
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.tsindex 568bb4c98d..844a6b1ea4 100644--- a/apps/client/src/services/content_renderer.spec.ts+++ b/apps/client/src/services/content_renderer.spec.ts@@ -488,17 +488,31 @@ describe("getRenderedContent editable code", () => {expect(rendered(again)).toBe("<p>Edited</p>");});- it("renders the blocks of a text note without an editor", async () => {- const note = buildNote({ title: "Doc", type: "text", content: "<p>Hi</p>" });-- const { $renderedContent } = await getRenderedContent(note, {+ it("mounts TextEmbed for blocks, with an editor where they can be edited apart", async () => {+ const content = "<ul><li><p>Intro</p><p data-trilium-block-id=\"a\">A</p></li></ul>"+ + "<p data-trilium-block-id=\"b\">B</p>";+ const note = buildNote({ title: "Doc", type: "text", content });+ const onBlockChange = vi.fn();+ const renderBlocks = (block: string) => getRenderedContent(note, {interactive: true,noteEditor: buildEditor(),- block: "b1"+ block,+ onBlockChange});- expect($renderedContent.find(".from-render-text").length).toBe(1);- expect(textEmbedComponent).not.toHaveBeenCalled();+ await renderBlocks("b");+ const props = textEmbedComponent.mock.lastCall?.[0];+ expect(props).toMatchObject({ content, block: "b", onBlockChange });+ expect(props.editor.canEdit()).toBe(true);+ expect(renderTextContent).toHaveBeenLastCalledWith(+ note, content, expect.anything(), expect.objectContaining({ block: "b" }));++ await props.renderPreview("<p>New</p>", "b:n");+ expect(renderTextContent).toHaveBeenLastCalledWith(+ note, "<p>New</p>", expect.anything(), expect.objectContaining({ block: "b:n" }));++ await renderBlocks("a:b");+ expect(textEmbedComponent.mock.lastCall?.[0].editor).toBeUndefined();});it("edits only code and text notes", async () => {diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex fced14293d..5430c4b936 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -3,6 +3,7 @@ import "./content_renderer.css";import {attachmentIcon,CANVAS_ATTACHMENT_MIME,+ getEditableBlockRun,getMimeTypeFromFileName,isAcceptedImageMime,isImageAttachmentRole,@@ -67,6 +68,8 @@ export interface RenderOptions {* out, and a missing block renders as a broken reference.*/block?: string;+ /** Points the embed of `block` at the blocks that its editor holds, once they change. */+ onBlockChange?: (block: string) => void;showTextRepresentation?: boolean;/*** If enabled, note types that have a richer live representation (currently only web views) are@@ -176,7 +179,7 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo// view type is excluded: it's the only view that re-propagates `interactive` to its tiles, so// skipping it here is what keeps an embedded collection from recursing into itself.await renderCollection(entity, $renderedContent);- } else if (type === "text" && options.interactive && options.noteEditor && !options.block+ } else if (type === "text" && options.interactive && options.noteEditor&& entity instanceof FNote) {await renderEditableText(entity, $renderedContent, options);} else if (type === "text" || type === "book") {@@ -263,17 +266,18 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo}/**- * Renders a text note that `TextEmbed` edits in place while the Editable toggle of its embed is- * on.+ * Renders a text note, or the blocks of it that `options.block` points at, which `TextEmbed`+ * edits in place while the Editable toggle of its embed is on. Blocks that cannot be edited apart+ * from the rest of the note stay read-only.*/async function renderEditableText(note: FNote,$renderedContent: JQuery<HTMLElement>,options: RenderOptions) {- const renderPreview = async (content: string) => {+ const renderPreview = async (content: string, block = options.block) => {const $preview = $("<div>");- await renderTextContent(note, content, $preview, options);+ await renderTextContent(note, content, $preview, { ...options, block });return $preview[0];};const [ blob, { default: TextEmbed } ] = await Promise.all([@@ -282,21 +286,29 @@ async function renderEditableText(]);const content = blob?.content ?? "";const preview = await renderPreview(content);+ const canEditBlocks = !options.block || isEditableBlockRange(content, options.block);const $container = $('<div class="text-embed">');const container = $container.get(0);if (container) {await mountInteractiveWidget(h(TextEmbed, {note,- editor: getContentEditor(note, options),+ editor: canEditBlocks ? getContentEditor(note, options) : undefined,content,+ block: options.block,preview,- renderPreview+ renderPreview,+ onBlockChange: options.onBlockChange}), container);}$renderedContent.append($container);}+function isEditableBlockRange(content: string, block: string) {+ const root = new DOMParser().parseFromString(content, "text/html").body;+ return !!getEditableBlockRun(root, block);+}+/*** Renders a markdown note by converting its source to CKEditor-compatible HTML,* then running the same post-render pipeline as text notes (embedded notes,diff --git a/apps/client/src/widgets/react/editor_save_race.spec.tsx b/apps/client/src/widgets/react/editor_save_race.spec.tsxindex 6c87a989a2..2fb5296573 100644--- a/apps/client/src/widgets/react/editor_save_race.spec.tsx+++ b/apps/client/src/widgets/react/editor_save_race.spec.tsx@@ -28,6 +28,7 @@ import server from "../../services/server";import type SpacedUpdate from "../../services/spaced_update";import { buildNote } from "../../test/easy-froca";import { type SavedData, useEditorSpacedUpdate } from "./hooks";+import { noteSavedDataStore } from "./NoteStore";import { ParentComponent } from "./react_utils";vi.stubGlobal("logError", vi.fn());@@ -255,3 +256,103 @@ describe("note switch save race (#9614)", () => {expect(flushed).toBe(true);});});++describe("editing some blocks of a note", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ currentSpacedUpdate = undefined;+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ it("reads and replaces the blocks, then the blocks that the last save held", async () => {+ const note = buildNote({ title: "Blocks", type: "text", content: "<p>Whole</p>" });+ const read = vi.spyOn(server, "getWithSilentNotFound")+ .mockImplementation(async (url: string) => ({ content: `<p>${url}</p>` }));+ const put = vi.spyOn(server, "put").mockResolvedValue({});+ const { editor, parent, cleanup } = await showBlockEditor(note, "a:b");+ const url = `notes/${note.noteId}/blocks`;++ expect(editor.content).toBe(`<p>${url}?block=a%3Ab</p>`);+ expect(noteSavedDataStore.get(note.noteId)).toBeUndefined();++ editor.content = "<p>Edited</p>";+ editor.block = "a:n";+ getSpacedUpdate().scheduleUpdate();+ await vi.advanceTimersByTimeAsync(1500);+ expect(put).toHaveBeenLastCalledWith(+ `${url}?block=a%3Ab`, { content: "<p>Edited</p>" }, parent.componentId+ );+ expect(noteSavedDataStore.get(note.noteId)).toBeUndefined();++ const loadResults = new LoadResults([]);+ loadResults.addNoteContent(note.noteId, "another-editor");+ await act(async () => {+ await parent.handleEvent("entitiesReloaded", { loadResults });+ });+ await vi.advanceTimersByTimeAsync(20);+ expect(read).toHaveBeenLastCalledWith(`${url}?block=a%3An`);+ expect(editor.content).toBe(`<p>${url}?block=a%3An</p>`);++ editor.content = "<p>Edited again</p>";+ editor.block = undefined;+ getSpacedUpdate().scheduleUpdate();+ await vi.advanceTimersByTimeAsync(1500);+ expect(put).toHaveBeenLastCalledWith(+ `${url}?block=a%3An`, { content: "<p>Edited again</p>" }, parent.componentId+ );+ cleanup();+ });++ it("saves nothing when the blocks cannot be read", async () => {+ const note = buildNote({ title: "Missing blocks", type: "text", content: "<p>Whole</p>" });+ vi.spyOn(server, "getWithSilentNotFound").mockRejectedValue(new Error("Not found"));+ const put = vi.spyOn(server, "put").mockResolvedValue({});+ const { editor, cleanup } = await showBlockEditor(note, "a:b");++ editor.content = "<p>Typed</p>";+ getSpacedUpdate().scheduleUpdate();+ await vi.advanceTimersByTimeAsync(1500);+ expect(put).not.toHaveBeenCalled();+ cleanup();+ });+});++/** Renders an editor of the blocks of `note` that `block` points at. */+async function showBlockEditor(note: FNote, block: string) {+ const editor: { content: string; block: string | undefined } = { content: "", block };+ const parent = new Component();+ const container = document.createElement("div");+ document.body.appendChild(container);++ function BlockEditor() {+ currentSpacedUpdate = useEditorSpacedUpdate({+ note,+ noteContext: null,+ noteType: "text",+ block,+ getData: () => ({ content: editor.content, block: editor.block }),+ onContentChange(newContent) {+ editor.content = newContent;+ }+ });+ return null;+ }++ await act(async () => {+ render(+ <ParentComponent.Provider value={parent}><BlockEditor /></ParentComponent.Provider>,+ container+ );+ });+ await vi.advanceTimersByTimeAsync(20);++ const cleanup = () => {+ render(null, container);+ container.remove();+ };+ return { editor, parent, cleanup };+}diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex b6d7efbf6c..8073c375c5 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -99,6 +99,8 @@ export function useSpacedUpdate(callback: () => void | Promise<void>, interval =export interface SavedData {content: string;+ /** The blocks that `content` holds, a `block` link parameter, for an editor of some blocks. */+ block?: string;attachments?: {/** The attachment to update. Without it, the attachment is matched by its title. */attachmentId?: string;@@ -111,7 +113,7 @@ export interface SavedData {}[];}-export function useEditorSpacedUpdate({ note, noteType, noteContext, getData, onContentChange, dataSaved, updateInterval }: {+export function useEditorSpacedUpdate({ note, noteType, noteContext, getData, onContentChange, dataSaved, updateInterval, block }: {noteType: NoteType;note: FNote | null | undefined,noteContext: NoteContext | null | undefined,@@ -119,9 +121,21 @@ export function useEditorSpacedUpdate({ note, noteType, noteContext, getData, ononContentChange: (newContent: string) => void,dataSaved?: (savedData: SavedData) => void,updateInterval?: number;+ /**+ * The blocks of the note to edit instead of the whole note, a `block` link parameter. Each+ * save replaces them, and the blocks that `getData()` reports are the ones the next save+ * replaces.+ */+ block?: string;}) {const parentComponent = useContext(ParentComponent);- const blob = useNoteBlob(note, parentComponent?.componentId, { reportLoadStateTo: noteContext });+ const blockRef = useRef(block ?? "");+ const blob = useNoteBlob(note, parentComponent?.componentId, {+ reportLoadStateTo: noteContext,+ load: block === undefined+ ? undefined+ : (loadedNote) => loadBlocks(loadedNote, blockRef.current)+ });// The note whose content is currently loaded in the editor. Editor instances are reused// across note switches, so until the new note's blob arrives the editor still holds the@@ -139,11 +153,17 @@ export function useEditorSpacedUpdate({ note, noteType, noteContext, getData, onprotected_session_holder.touchProtectedSessionIfNecessary(note);- await server.put(`notes/${note.noteId}/data`, data, parentComponent?.componentId);-- noteSavedDataStore.set(note.noteId, data.content);+ if (block === undefined) {+ await server.put(`notes/${note.noteId}/data`, data, parentComponent?.componentId);+ noteSavedDataStore.set(note.noteId, data.content);+ } else {+ const { block: savedBlock, ...blocks } = data;+ const url = `notes/${note.noteId}/blocks?block=${encodeURIComponent(blockRef.current)}`;+ await server.put(url, blocks, parentComponent?.componentId);+ blockRef.current = savedBlock ?? blockRef.current;+ }dataSaved?.(data);- }, [ note, dataSaved, noteType, parentComponent ]);+ }, [ note, dataSaved, noteType, parentComponent, block ]);const stateCallback = useCallback<StateCallback>((state) => {noteContext?.setContextData("saveState", {@@ -177,7 +197,9 @@ export function useEditorSpacedUpdate({ note, noteType, noteContext, getData, onif (!blob || !note) return;// Changes not saved here yet stay when another editor saves the note, and replace it.if (loadedNoteIdRef.current === note.noteId && spacedUpdate.hasUnsavedChanges()) return;- noteSavedDataStore.set(note.noteId, blob.content);+ if (block === undefined) {+ noteSavedDataStore.set(note.noteId, blob.content);+ }spacedUpdate.allowUpdateWithoutChange(() => onContentChange(blob.content));loadedNoteIdRef.current = note.noteId;}, [ blob ]);@@ -218,6 +240,17 @@ export function useSaveBeforeLeaving<T>(}, [ spacedUpdate ]);}+/** The blocks of `note` that `block` points at, or `null` when they cannot be read. */+async function loadBlocks(note: FNote, block: string) {+ try {+ return await server.getWithSilentNotFound<{ content: string }>(+ `notes/${note.noteId}/blocks?block=${encodeURIComponent(block)}`+ );+ } catch {+ return null;+ }+}+export function useBlobEditorSpacedUpdate({ note, noteType, noteContext, getData, onContentChange, dataSaved, updateInterval, replaceWithoutRevision }: {noteType: NoteType;note: FNote,@@ -835,7 +868,7 @@ export function useNoteLabelInt(note: FNote | undefined | null, labelName: Filte];}-export function useNoteBlob(note: FNote | null | undefined, componentId?: string, opts?: {+export function useNoteBlob<T extends { content: string } = FBlob>(note: FNote | null | undefined, componentId?: string, opts?: {/** Publish the fetch progress as `contentLoad` context data on the given note context, so* the note detail can show a loading state instead of the previous note's content. Should* only be set by widgets whose main content display is gated on this blob. (Passed@@ -851,8 +884,10 @@ export function useNoteBlob(note: FNote | null | undefined, componentId?: string* produced by a sibling under the same parent component (e.g. the read-only text view behind* the editor), own-component changes are somebody else's edits that must eventually show. */refreshOnShow?: boolean;-}): FBlob | null | undefined {- const [ blob, setBlob ] = useState<FBlob | null>();+ /** Reads the content instead of the blob of the note, resolving to `null` when it fails. */+ load?: (note: FNote) => Promise<T | null>;+}): T | null | undefined {+ const [ blob, setBlob ] = useState<T | null>();const requestIdRef = useRef(0);const missedContentChangeRef = useRef(false);@@ -868,7 +903,9 @@ export function useNoteBlob(note: FNote | null | undefined, componentId?: stringif (note) {reportLoadState("loading");}- const newBlob = await note?.getBlob();+ const newBlob = note && opts?.load+ ? await opts.load(note)+ : await note?.getBlob() as T | null | undefined;// Only update if this is the latest request.if (requestId === requestIdRef.current) {diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex ab9497e7ff..7791e9cc03 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -29,10 +29,12 @@ vi.mock("@triliumnext/ckeditor5", () => ({}));const {applyPendingAttachmentChanges,+ getBlockData,notifyAttachmentChanges,onNotificationInfo,onNotificationWarning,- showFileUploadProgress+ showFileUploadProgress,+ watchEditorBlocks} = await import("./EditableText");describe("onNotificationWarning", () => {@@ -208,3 +210,47 @@ describe("notifyAttachmentChanges", () => {expect(updateAttachmentLinks).not.toHaveBeenCalled();});});++describe("getBlockData", () => {+ it("reads all of the content, with the blocks at its edges", () => {+ const getRange = vi.fn()+ .mockReturnValueOnce({ startId: "a", endId: "n" })+ .mockReturnValueOnce(null);+ const getData = vi.fn(() => "<p data-trilium-block-id=\"a\"> </p>");+ const editor = {+ getData,+ plugins: { get: () => ({ getRange }) }+ } as unknown as CKTextEditor;++ expect(getBlockData(editor, "a:b")).toEqual({+ content: "<p data-trilium-block-id=\"a\"> </p>",+ block: "a:n"+ });+ expect(getData).toHaveBeenCalledWith({ trim: "none" });+ expect(getRange).toHaveBeenCalledWith({ startId: "a", endId: "b" });+ expect(getBlockData(editor, "a").block).toBeUndefined();+ });+});++describe("watchEditorBlocks", () => {+ it("reports the blocks of the editor each time they change", () => {+ const getRange = vi.fn();+ const editor = { plugins: { get: () => ({ getRange }) } } as unknown as CKTextEditor;+ const onBlockChange = vi.fn();+ const report = watchEditorBlocks("a:b", onBlockChange);++ for (const range of [+ { startId: "a", endId: "b" },+ { startId: "a", endId: "n" },+ { startId: "a", endId: "n" },+ null,+ { startId: "a", endId: "b" }+ ]) {+ getRange.mockReturnValueOnce(range);+ report(editor);+ }++ expect(onBlockChange.mock.calls).toEqual([ [ "a:n" ], [ "a:b" ] ]);+ expect(getRange).toHaveBeenCalledWith({ startId: "a", endId: "b" });+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 38cb6bcbdd..b16ad7aea7 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -9,7 +9,7 @@ import {type FileUploadEvent,SnippetDefinition} from "@triliumnext/ckeditor5";-import { deferred } from "@triliumnext/commons";+import { deferred, formatBlockRange, parseBlockRange } from "@triliumnext/commons";import { createPortal } from "preact";import { useCallback, useEffect, useRef, useState } from "preact/hooks";@@ -59,7 +59,16 @@ import {* - Ballon block mode, in which there is a floating toolbar for the selected text, but another floating button for the entire block (i.e. paragraph).* - Decoupled mode, in which the editing toolbar is actually added on the client side (in {@link ClassicEditorToolbar}), see https://ckeditor.com/docs/ckeditor5/latest/examples/framework/bottom-toolbar-editor.html for an example on how the decoupled editor works.*/-export default function EditableText({ note, parentComponent, ntxId, noteContext }: TypeWidgetProps) {+interface EditableTextProps extends TypeWidgetProps {+ /** The blocks of the note to edit instead of the whole note, a `block` link parameter. */+ block?: string;+ /** Receives the blocks that the editor of `block` holds, each time they change. */+ onBlockChange?: (block: string) => void;+}++export default function EditableText({+ note, parentComponent, ntxId, noteContext, block, onBlockChange+}: EditableTextProps) {const containerRef = useRef<HTMLDivElement>(null);const contentRef = useRef<string>("");/** The note `contentRef` holds the content of, so a restarted editor can be marked as holding it. */@@ -82,6 +91,9 @@ export default function EditableText({ note, parentComponent, ntxId, noteContexttextNoteEditorType});const initialized = useRef(deferred<void>());+ const [ reportBlocks ] = useState(() => (block !== undefined && onBlockChange+ ? watchEditorBlocks(block, onBlockChange)+ : undefined));const [ attachmentSaves ] = useState(() =>new AttachmentSaves(() => spacedUpdate.scheduleUpdate()));const noteEditor = useNoteEditor(noteContext);@@ -91,6 +103,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextnote,noteContext,noteType: "text",+ block,getData() {const editor = watchdogRef.current?.editor;if (!editor) {@@ -98,14 +111,18 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextreturn;}- const content = editor.getData() ?? "";const attachments = attachmentSaves.collect();+ const savedAttachments = attachments.length ? { attachments } : {};+ if (block !== undefined) {+ return { ...getBlockData(editor as CKTextEditor, block), ...savedAttachments };+ }+ const content = editor.getData() ?? "";// if content is only tags/whitespace (typically <p> </p>), then just make it empty,// this is important when setting a new note to codereturn {content: utils.isHtmlEmpty(content) ? "" : content,- ...(attachments.length ? { attachments } : {})+ ...savedAttachments};},onContentChange(newContent) {@@ -224,9 +241,14 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextnoteId: string,$el: JQuery<HTMLElement>,boxSize?: string,- block?: string+ embedBlock?: string,+ onBlockChange?: (block: string) => void) {- return loadEmbeddedNote(noteId, $el, boxSize, { noteEditor: embedNoteEditor, block });+ return loadEmbeddedNote(noteId, $el, boxSize, {+ noteEditor: embedNoteEditor,+ block: embedBlock,+ onBlockChange+ });},loadEmbeddedAttachment(attachmentId: string, $el: JQuery<HTMLElement>, boxSize?: string) {const isFocused = focusedAttachmentIdRef.current === attachmentId;@@ -577,7 +599,13 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextonNotificationWarning={onNotificationWarning}onNotificationInfo={onNotificationInfo}onWatchdogStateChange={onWatchdogStateChange}- onChange={() => spacedUpdate.scheduleUpdate()}+ onChange={() => {+ spacedUpdate.scheduleUpdate();+ const editor = watchdogRef.current?.editor;+ if (editor) {+ reportBlocks?.(editor as CKTextEditor);+ }+ }}onEditorInitialized={(editor) => {if (containerRef.current) {setupImageOpening(containerRef.current, false);@@ -591,6 +619,9 @@ export default function EditableText({ note, parentComponent, ntxId, noteContexteditor.plugins.get("FileUploadEditing").on<FileUploadEvent>("upload", showFileUploadProgress);+ if (block !== undefined) {+ editor.plugins.get("BlockReferenceEditing").editRange();+ }initialized.current.resolve();// Restore the data, either on the first render or if the editor crashes.// We are not using CKEditor's built-in watch dog content, instead we are using the data we store regularly in the spaced update (see `dataSaved`).@@ -615,6 +646,40 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext);}+/**+ * The content of an editor of the blocks of a note that `block` points at, and the blocks it holds+ * now. An empty editor still holds a block, whose id keeps the place of the blocks in the note.+ */+export function getBlockData(editor: CKTextEditor, block: string) {+ return {+ content: editor.getData({ trim: "none" }),+ block: getEditorBlocks(editor, block)+ };+}++/**+ * Calls `onBlockChange()` with the blocks that an editor of the blocks `block` holds, each time+ * they differ from the blocks it reported last.+ *+ * Exported for testing.+ */+export function watchEditorBlocks(block: string, onBlockChange: (block: string) => void) {+ let reportedBlock = block;+ return (editor: CKTextEditor) => {+ const editorBlock = getEditorBlocks(editor, block);+ if (editorBlock && editorBlock !== reportedBlock) {+ reportedBlock = editorBlock;+ onBlockChange(editorBlock);+ }+ };+}++/** 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));+ return range ? formatBlockRange(range) : undefined;+}+/** The number of icons per row of the picker in the editor's balloon. */const ICON_PICKER_COLUMNS = 9;diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsxindex 875eb921da..2bb3eb115c 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx@@ -25,6 +25,7 @@ let editorData = "";/** The text editor, which has a spec of its own. It listens for what a real editor listens for. */vi.mock("./EditableText", () => ({+ getBlockData: () => ({ content: editorData }),default: (props: TypeWidgetProps) => {const isNested = useContext(NestedEmbedContext);editorProps({ ...props, isNested });@@ -154,7 +155,8 @@ describe("TextEmbed", () => {await new Promise((resolve) => setTimeout(resolve, 50));});expect(shownPreview()).toBe("<div><p>Typed just now</p></div>");- expect(renderPreview).toHaveBeenCalledExactlyOnceWith("<p>Typed just now</p>");+ expect(renderPreview)+ .toHaveBeenCalledExactlyOnceWith("<p>Typed just now</p>", undefined);// Once the last save lands, the preview follows what the note holds.note.getBlob = async () => buildBlob("<p>Saved</p>");@@ -269,6 +271,35 @@ describe("TextEmbed", () => {});});+ it("edits the blocks it shows, and follows the blocks that its editor holds", async () => {+ const note = buildTextNote("blocks");+ const renderPreview = vi.fn(async (content: string) => buildPreview(content));+ const onBlockChange = vi.fn();+ const { figure } = await mount(note, buildEditor(), {+ isEditable: true, renderPreview, block: "a:b", onBlockChange+ });+ const lastEditorProps = () => editorProps.mock.lastCall?.[0] as {+ block?: string;+ onBlockChange?: (block: string) => void;+ };+ await vi.waitFor(() => expect(editorProps).toHaveBeenCalled(), { timeout: 5000 });+ expect(lastEditorProps().block).toBe("a:b");++ // The embed follows new blocks at the edges of the editor while it is open.+ act(() => lastEditorProps().onBlockChange?.("a:n"));+ expect(onBlockChange).toHaveBeenCalledExactlyOnceWith("a:n");+ expect(lastEditorProps().block).toBe("a:n");++ editorData = "<p>Blocks and a new one</p>";+ await act(async () => {+ delete figure.dataset.editable;+ await Promise.resolve();+ });+ await vi.waitFor(() => {+ expect(renderPreview).toHaveBeenLastCalledWith("<p>Blocks and a new one</p>", "a:n");+ });+ });+it("loads the note once the save of the editor it replaces lands", async () => {const note = buildTextNote("redrawn");const countEditors = () =>@@ -310,9 +341,11 @@ interface MountOptions {isEditable?: boolean;/** Whether the editor around the embed has a fixed toolbar, rather than a floating one. */hasFixedToolbar?: boolean;- renderPreview?: (content: string) => Promise<HTMLElement>;+ renderPreview?: (content: string, block?: string) => Promise<HTMLElement>;/** The content that the host read for the embed, instead of the content of the note. */content?: string;+ block?: string;+ onBlockChange?: (block: string) => void;}/** Renders `TextEmbed` in the markup of an embed, as the host does. */@@ -348,8 +381,10 @@ async function mount(note: FNote, editor: ContentEditor | undefined, options: Monote={note}editor={editor}content={content}+ block={options.block}preview={options.preview ?? buildPreview(content)}renderPreview={options.renderPreview ?? (async (html) => buildPreview(html))}+ onBlockChange={options.onBlockChange}/></ParentComponent.Provider>,boxdiff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsxindex 6030932f5d..d0d9ebe7da 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx@@ -17,10 +17,14 @@ interface TextEmbedProps {editor: ContentEditor | undefined;/** The content of the note that `preview` shows. */content: string;+ /** The blocks of the note that the embed shows, a `block` link parameter. */+ block?: string;/** The rendered note. */preview: HTMLElement;- /** Renders the note with `content`, after a change. */- renderPreview: (content: string) => Promise<HTMLElement>;+ /** Renders `content`, or its blocks that `block` points at, after a change. */+ renderPreview: (content: string, block?: string) => Promise<HTMLElement>;+ /** Points the embed at the blocks that its editor holds, each time they change. */+ onBlockChange?: (block: string) => void;}/**@@ -28,7 +32,8 @@ interface TextEmbedProps {* Editable toggle of its embed is on.*/export default function TextEmbed({- note, editor, content: initialContent, preview, renderPreview+ note, editor, content: initialContent, block: initialBlock, preview, renderPreview,+ onBlockChange}: TextEmbedProps) {const rootRef = useRef<HTMLDivElement>(null);const { isEditing } = useEditableEmbed(rootRef, {@@ -37,8 +42,13 @@ export default function TextEmbed({focusTarget: ".ck-editor__editable"});const [ content, onEditorClose ] = useShownContent(note, initialContent);+ const [ block, setBlock ] = useState(initialBlock);+ const onEditorBlockChange = useCallback((editorBlock: string) => {+ setBlock(editorBlock);+ onBlockChange?.(editorBlock);+ }, [ onBlockChange ]);const shownPreview =- useEmbedPreview(preview, content, () => renderPreview(content), isEditing);+ useEmbedPreview(preview, content, () => renderPreview(content, block), isEditing);return (<EditableEmbedContent@@ -49,6 +59,8 @@ export default function TextEmbed({><TextEmbedEditornote={note}+ block={block}+ onBlockChange={onEditorBlockChange}hasFixedToolbar={isEditing && hasFixedToolbarAround(rootRef.current)}onClose={onEditorClose}/>diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsxindex 5a2fcc5b2d..98dc05079b 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx@@ -12,12 +12,16 @@ import {} from "../../EmbeddedNotePane";import { SaveStatusBadge } from "../../layout/NoteBadges";import { useLegacyComponentElement, useNoteContext } from "../../react/hooks";-import EditableText from "./EditableText";+import EditableText, { getBlockData } from "./EditableText";import { findTextEditorIn, NestedEmbedContext, useEmbedBadgeSlot } from "./editable_embed";import { getClosingSave, trackClosingSave } from "./TextEmbed";interface TextEmbedEditorProps {note: FNote;+ /** The blocks of the note to edit, a `block` link parameter. The whole note when left out. */+ block?: string;+ /** Receives the blocks that the editor of `block` holds, each time they change. */+ onBlockChange?: (block: string) => void;/** Whether the editor around the embed has a fixed toolbar, rather than a floating one. */hasFixedToolbar: boolean;/**@@ -31,7 +35,9 @@ interface TextEmbedEditorProps {* The text editor of a text note in an embed. It has a note context and a component of its own,* as the note pane of a geo map does, and saves the note as a note tab does.*/-export default function TextEmbedEditor({ note, hasFixedToolbar, onClose }: TextEmbedEditorProps) {+export default function TextEmbedEditor({+ note, block, onBlockChange, hasFixedToolbar, onClose+}: TextEmbedEditorProps) {// The embed shows its preview until the editor that it replaces has saved the note.const closingSave = getClosingSave(note.noteId);if (closingSave) throw closingSave;@@ -50,16 +56,24 @@ export default function TextEmbedEditor({ note, hasFixedToolbar, onClose }: Text// A layout cleanup runs while the editor is still mounted, so it saves what is left.useLayoutEffect(() => () => {const save = trackClosingSave(note.noteId, saveWhatIsLeft(component, noteContext, ntxId));- const content = findTextEditorIn(rootRef.current)?.getData();- if (content !== undefined) {- onCloseRef.current(content, save);- }+ const editor = findTextEditorIn(rootRef.current);+ if (!editor) return;++ const content = block === undefined+ ? editor.getData()+ : getBlockData(editor, block).content;+ onCloseRef.current(content, save);}, [ component, noteContext, ntxId ]);return (<EmbeddedNoteScope component={component} noteContext={noteContext}><NestedEmbedContext.Provider value={true}>- <ScopedEditor rootRef={rootRef} note={note} />+ <ScopedEditor+ rootRef={rootRef}+ note={note}+ block={block}+ onBlockChange={onBlockChange}+ /></NestedEmbedContext.Provider></EmbeddedNoteScope>);@@ -68,10 +82,12 @@ export default function TextEmbedEditor({ note, hasFixedToolbar, onClose }: Textinterface ScopedEditorProps {rootRef: RefObject<HTMLDivElement | null>;note: FNote;+ block: string | undefined;+ onBlockChange: ((block: string) => void) | undefined;}/** The editor, once the note context of the embed holds `note`. */-function ScopedEditor({ rootRef, note }: ScopedEditorProps) {+function ScopedEditor({ rootRef, note, block, onBlockChange }: ScopedEditorProps) {const { note: contextNote, noteContext, ntxId, parentComponent } = useNoteContext();// The plugins of the editor find their host by the element of its component.useLegacyComponentElement(rootRef);@@ -86,6 +102,8 @@ function ScopedEditor({ rootRef, note }: ScopedEditorProps) {ntxId={ntxId ?? null}parentComponent={parentComponent}viewScope={noteContext.viewScope}+ block={block}+ onBlockChange={onBlockChange}/>)}{badgeSlot && createPortal(<SaveStatusBadge />, badgeSlot)}diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.tsindex 549b88e54e..3bd73c8485 100644--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts@@ -182,13 +182,14 @@ describe("loadEmbeddedNote of blocks", () => {figure.className = "include-note";figure.dataset.boxSize = "tiny";- await loadEmbeddedNote("noteY", $(wrapper), "medium", { block: "b1:b2" });+ const onBlockChange = vi.fn();+ await loadEmbeddedNote("noteY", $(wrapper), "medium", { block: "b1:b2", onBlockChange });const viewScope = { block: "b1:b2" };expect(link.createLink).toHaveBeenCalledWith("noteY", expect.objectContaining({ viewScope }));expect(content_renderer.getRenderedContent).toHaveBeenCalledWith(note,- expect.objectContaining({ block: "b1:b2" }));+ expect.objectContaining({ block: "b1:b2", onBlockChange }));expect(lastMount().props.viewScope).toEqual(viewScope);await loadEmbeddedNote("noteY", $(figure), undefined, { block: "b1" });diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex f9b472ea75..23b51d8998 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -19,6 +19,8 @@ interface EmbeddedNoteOptions {noteEditor?: NoteEditor;/** The blocks of the note to show, a `block` link parameter. The whole note when left out. */block?: string;+ /** Points the embed at the blocks that its editor holds, once they change. */+ onBlockChange?: (block: string) => void;}/**@@ -29,7 +31,7 @@ export async function loadEmbeddedNote(noteId: string,$el: JQuery<HTMLElement>,boxSize?: string,- { noteEditor, block }: EmbeddedNoteOptions = {}+ { noteEditor, block, onBlockChange }: EmbeddedNoteOptions = {}) {const note = await froca.getNote(noteId);if (!note) return;@@ -67,7 +69,8 @@ export async function loadEmbeddedNote(embedsAsReferenceLinks: true,mediaEnvironment: "embedded",noteEditor,- block+ block,+ onBlockChange});const box = h(ContentEmbed, {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 3db9d83091..776341ecd1 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@@ -24,12 +24,17 @@in a note being edited and select <em>Convert link to an included note</em>.The include shows only the referenced blocks, not the rest of the note.Converting the include back 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>If a referenced block was deleted, the include shows <em>Broken reference</em>.</p><h2>Limitations</h2><ul><li>References can be copied only from a note being edited, and not in themobile layout, since the block handle is not shown there.</li>- <li>An include of referenced blocks cannot be edited in place.</li>+ <li>An include of a range that covers only part of a list or a quote, such+ as from its second item to a paragraph after it, cannot be edited in place.</li><li>Deleting a block breaks the references to it.</li><li>Block references are not kept when exporting to Markdown. On a <a href="#root/_help_R9pX4DGra2Vt">shared page</a>,a block reference opens the whole note.</li>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 0a0014996b..9e7b39b7a7 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@@ -177,6 +177,8 @@with its theme, indentation and line wrapping settings.</li><li>The changes are saved as you type, to the included note or to the attachment,as they would be in its own tab.</li>+ <li>An include of <a class="reference-link" href="#root/_help_klC3ilXa9kUE">Block references</a> edits+ only the referenced blocks.</li><li>Editing is not available in a <a href="#root/_help_CoFPLs3dRlXc">read-only note</a>,for an included note marked <code>#readOnly</code>, or for an attachmentof another note.</li>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 e318ee997d..0e46a37970 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@@ -18,11 +18,13 @@ Clicking a block reference opens the note, scrolls to the referenced blocks andTo show the referenced blocks inside another note, right-click the link in a note being edited and select _Convert link to an included note_. The include shows only the referenced blocks, not the rest of the note. 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.+If a referenced block was deleted, the include shows _Broken reference_.## Limitations* References can be copied only from a note being edited, and not in the mobile layout, since the block handle is not shown there.-* An include of referenced blocks cannot be edited in place.+* An include of a range that covers only part of a list or a quote, such as from its second item to a paragraph after it, cannot be edited in place.* Deleting a block breaks the references to it.* Block references are not kept when exporting to Markdown. On a [shared page](../../Advanced%20Usage/Sharing.md), a block reference opens the whole note.\ No newline at end of filediff --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 2131d5e9c4..47640caa6a 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@@ -112,6 +112,7 @@ An included text note, an included code note and an embedded code file such as a* While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.* Code is edited in the same code editor as a <a class="reference-link" href="../Code.md">Code</a> note, with its theme, indentation and line wrapping settings.* The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.+* An include of <a class="reference-link" href="Block%20references.md">Block references</a> edits only the referenced blocks.* Editing is not available in a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), for an included note marked `#readOnly`, or for an attachment of another note.## Drawing canvasesdiff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 0488595ed4..5a41eb56d1 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -83,12 +83,16 @@ declare global {*/formatDateTime(date: Date, format?: string): string;loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;- /** Fills an embed with the note, or with the `block` of it, a `block` link parameter. */+ /**+ * Fills an embed with the note, or with the `block` of it, a `block` link parameter. An+ * editor of those blocks calls `onBlockChange()` once the blocks at its edges change.+ */loadEmbeddedNote(noteId: string,$el: JQuery<HTMLElement>,boxSize?: string,- block?: string+ block?: string,+ onBlockChange?: (block: string) => void): void;loadEmbeddedAttachment(attachmentId: string,diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.tsindex ebbb999c4d..87381aed43 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts@@ -215,6 +215,69 @@ describe("BlockReference", () => {});});+ describe("range editor", () => {+ it("gives an id to a new block at either edge, and returns the range", async () => {+ const editor = await createRangeEditor(+ "<p data-trilium-block-id=\"a\">one</p><p data-trilium-block-id=\"b\">two</p>"+ );+ const plugin = editor.plugins.get("BlockReferenceEditing");+ expect(plugin.getRange()).toEqual({ startId: "a", endId: "b" });++ editor.model.change((writer) => writer.setSelection(getBlock(editor, 1), "end"));+ editor.execute("enter");+ const endId = getBlock(editor, 2).getAttribute("blockId");+ expect(endId).toMatch(/^[A-Za-z0-9]{12}$/);+ expect(plugin.getRange()).toEqual({ startId: "a", endId });++ editor.model.change((writer) => writer.setSelection(getBlock(editor, 0), 0));+ editor.execute("enter");+ const startId = getBlock(editor, 0).getAttribute("blockId");+ expect(getBlock(editor, 1).getAttribute("blockId")).toBe("a");+ expect(getBlock(editor, 2).getAttribute("blockId")).toBe("b");+ expect(plugin.getRange()).toEqual({ startId, endId });+ expect(new Set([ startId, endId, "a", "b" ]).size).toBe(4);+ });++ it("prefers the given ids at an edge whose blocks have several", async () => {+ const editor = await createRangeEditor(+ "<blockquote data-trilium-block-id=\"q\"><p data-trilium-block-id=\"a\">one</p>"+ + "<p data-trilium-block-id=\"b\">two</p></blockquote>"+ );+ const plugin = editor.plugins.get("BlockReferenceEditing");++ expect(plugin.getRange()).toEqual({ startId: "q", endId: "q" });+ expect(plugin.getRange({ startId: "a", endId: "b" }))+ .toEqual({ startId: "a", endId: "b" });+ expect(plugin.getRange({ startId: "x", endId: "y" }))+ .toEqual({ startId: "q", endId: "q" });+ });++ it("gives an id to a table rather than to its cells", async () => {+ const editor = await createRangeEditor(+ "<figure class=\"table\"><table><tbody><tr><td>"+ + "<p data-trilium-block-id=\"c\">Cell</p></td></tr></tbody></table></figure>"+ );++ const tableId = getBlock(editor, 0).getAttribute("blockId");+ expect(tableId).toMatch(/^[A-Za-z0-9]{12}$/);+ expect(editor.plugins.get("BlockReferenceEditing").getRange())+ .toEqual({ startId: tableId, endId: tableId });+ });++ it("leaves an edge that cannot have an id, and a regular editor, without one", async () => {+ const editor = await createRangeEditor("<p>one</p>");+ editor.model.schema.register("divider", { allowIn: "$root" });+ editor.conversion.elementToElement({ model: "divider", view: "hr" });+ setModelData(editor.model, "<divider></divider>");+ expect(editor.plugins.get("BlockReferenceEditing").getRange()).toBeNull();++ const regularEditor = await createTestEditor(PLUGINS);+ regularEditor.setData("<p>one</p>");+ expect(regularEditor.getData()).toBe("<p>one</p>");+ expect(regularEditor.plugins.get("BlockReferenceEditing").getRange()).toBeNull();+ });+ });+describe("block handle menu", () => {it("asks the host to open the menu for the selected blocks", async () => {const openBlockHandleMenu = vi.fn();@@ -271,6 +334,13 @@ function getEditable(editor: ClassicEditor) {return editable;}+async function createRangeEditor(data: string) {+ const editor = await createTestEditor(PLUGINS);+ editor.plugins.get("BlockReferenceEditing").editRange();+ editor.setData(data);+ return editor;+}+function getBlock(editor: ClassicEditor, index: number) {const block = editor.model.document.getRoot()?.getChild(index);if (!block?.is("element")) {diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.tsindex 593881094a..0e99d51e10 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts@@ -1,4 +1,4 @@-import { BLOCK_ID_ATTRIBUTE, isValidBlockId } from "@triliumnext/commons";+import { BLOCK_ID_ATTRIBUTE, type BlockRange, isValidBlockId } from "@triliumnext/commons";import {Command, type Model, type ModelElement, type ModelWriter, Plugin, type ViewElement} from "ckeditor5";@@ -8,6 +8,9 @@ export const BLOCK_ID = "blockId";const BLOCK_ID_LENGTH = 12;const BLOCK_ID_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";+const EDGES = [ "first", "last" ] as const;++type Edge = typeof EDGES[number];/** The blocks that a reference made from the selection points at. */export interface BlockReferenceTarget {@@ -22,6 +25,8 @@ export interface BlockReferenceTarget {*/export default class BlockReferenceEditing extends Plugin {+ private isRangeEditor = false;+static get pluginName() {return "BlockReferenceEditing" as const;}@@ -54,8 +59,30 @@ export default class BlockReferenceEditing extends Plugin {editor.model.document.registerPostFixer((writer) =>removeDuplicateBlockIds(editor.model, writer));+ editor.model.document.registerPostFixer((writer) =>+ this.isRangeEditor && giveIdsToEdgeBlocks(editor.model, writer));editor.commands.add("assignBlockReference", new AssignBlockReferenceCommand(editor));}++ /**+ * Makes the editor hold a range of blocks of a note. Its first and its last block then always+ * have an id, which `getRange()` returns.+ */+ editRange() {+ this.isRangeEditor = true;+ }++ /**+ * The range from the first to the last block of the editor, or `null` while an edge has no+ * id. A block at an edge can start or end with other blocks, as a block quote does, and the+ * ids of `preferred` win among theirs.+ */+ getRange(preferred?: BlockRange | null): BlockRange | null {+ const model = this.editor.model;+ const startId = getEdgeId(model, "first", preferred?.startId);+ const endId = getEdgeId(model, "last", preferred?.endId);+ return startId && endId ? { startId, endId } : null;+ }}/** Gives ids to the first and the last block of the selection, and returns the reference. */@@ -138,6 +165,41 @@ function removeDuplicateBlockIds(model: Model, writer: ModelWriter) {return isChanged;}+function giveIdsToEdgeBlocks(model: Model, writer: ModelWriter) {+ let isChanged = false;+ for (const edge of EDGES) {+ const blocks = getEdgeBlocks(model, edge);+ if (blocks.length && !blocks.some((block) => block.hasAttribute(BLOCK_ID))) {+ writer.setAttribute(BLOCK_ID, generateBlockId(), blocks[0]);+ isChanged = true;+ }+ }++ return isChanged;+}++function getEdgeId(model: Model, edge: Edge, preferred: string | undefined) {+ const ids = getEdgeBlocks(model, edge).flatMap((block) =>+ block.hasAttribute(BLOCK_ID) ? [ block.getAttribute(BLOCK_ID) as string ] : []);+ return ids.find((id) => id === preferred) ?? ids[0];+}++/** The block at an edge of the root, then the blocks inside that it starts or ends with. */+function getEdgeBlocks(model: Model, edge: Edge) {+ const blocks: ModelElement[] = [];+ let node = getEdgeChild(model.document.getRoot() as ModelElement, edge);+ while (node?.is("element") && model.schema.checkAttribute(node, BLOCK_ID)) {+ blocks.push(node);+ node = model.schema.isObject(node) ? null : getEdgeChild(node, edge);+ }++ return blocks;+}++function getEdgeChild(element: ModelElement, edge: Edge) {+ return element.getChild(edge === "first" ? 0 : element.childCount - 1);+}+function getInsertedBlocksWithId(model: Model) {const blocks: ModelElement[] = [];for (const change of model.document.differ.getChanges()) {diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.tsindex 68311fa2fb..17e21fb60f 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts@@ -994,7 +994,7 @@ describe("ContentEmbed with attachments", () => {expect(findContentEmbed(editor)?.getAttribute("attachmentId")).toBe("att1");});- it("stores, saves and renders an embed of blocks, and redraws it when they change", () => {+ it("stores, saves and renders an embed of blocks, and points it at other blocks", async () => {const html = "<figure class=\"include-note\" data-note-id=\"noteAbc\" data-block=\"a1:b2\""+ " data-box-size=\"small\"> </figure>";editor.setData(html);@@ -1002,21 +1002,33 @@ describe("ContentEmbed with attachments", () => {expect(findContentEmbed(editor)?.getAttribute("block")).toBe("a1:b2");expect(editor.getData()).toBe(html);- expect(loadEmbeddedNote)- .toHaveBeenLastCalledWith("noteAbc", expect.anything(), "small", "a1:b2");+ expect(loadEmbeddedNote).toHaveBeenLastCalledWith(+ "noteAbc", expect.anything(), "small", "a1:b2", expect.any(Function)+ );- editor.model.change((writer) => {- const embed = findContentEmbed(editor);- if (embed) {- writer.setAttribute("block", "c3", embed);- }- });+ // The editor in the embed points it at other blocks, and keeps showing them.+ const setBlock = loadEmbeddedNote.mock.lastCall?.[4] as (block: string) => void;+ setBlock("c3");renderEmbeds();- expect(loadEmbeddedNote)- .toHaveBeenLastCalledWith("noteAbc", expect.anything(), "small", "c3");+ expect(loadEmbeddedNote).toHaveBeenCalledOnce();+ expect(editor.getData()).toBe(html.replace("a1:b2", "c3"));expect(editor.editing.view.getDomRoot()?.querySelector(".include-note")?.getAttribute("data-block")).toBe("c3");+ expect(editor.commands.get("undo")?.isEnabled).toBe(false);++ editor.model.change((writer) => writer.setSelection(findContentEmbed(editor), "on"));+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "medium" });+ expect(loadEmbeddedNote).toHaveBeenLastCalledWith(+ "noteAbc", expect.anything(), "medium", "c3", expect.any(Function)+ );++ editor.setData("<p>Removed</p>");+ setBlock("d4");+ expect(editor.getData()).toBe("<p>Removed</p>");++ await editor.destroy();+ expect(() => setBlock("e5")).not.toThrow();});it("turns a link to blocks into an embed of them, and the embed back into a link", async () => {diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex 994624c44d..516e17f6db 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -1126,7 +1126,7 @@ function showEmbeddedContent( editor: Editor, element: ModelElement, wrapper: HTwrapper.replaceChildren();}const boxSize = element.getAttribute( 'boxSize' ) as string | undefined;- loadEmbeddedContent( editor, element, $( wrapper ), boxSize );+ loadEmbeddedContent( editor, element, wrapper, boxSize );}/** Updates the `data-*` attribute of an embed's view to what it shows, and redraws it. */@@ -1165,9 +1165,10 @@ function getWrapperDom( editor: Editor, viewElement: ViewElement ) {function loadEmbeddedContent(editor: Editor,element: ModelElement,- $wrapper: JQuery<HTMLElement>,+ wrapper: HTMLElement,boxSize: string | undefined) {+ const $wrapper = $( wrapper );const editorEl = editor.editing.view.getDomRoot();const component = glob.getComponentByEl<EditorComponent>( editorEl );const attachmentId = element.getAttribute( 'attachmentId' ) as string | undefined;@@ -1177,8 +1178,25 @@ function loadEmbeddedContent(component.loadEmbeddedAttachment( attachmentId, $wrapper, boxSize );} else if ( noteId ) {const block = element.getAttribute( 'block' ) as string | undefined;- component.loadEmbeddedNote( noteId, $wrapper, boxSize, block );+ component.loadEmbeddedNote( noteId, $wrapper, boxSize, block, newBlock => {+ setEmbedBlock( editor, element, wrapper, newBlock );+ } );+ }+}++/**+ * Points the embed at other blocks of its note, unless it has left the document. Its `wrapper`+ * keeps what it shows, the editor that holds those blocks.+ */+function setEmbedBlock( editor: Editor, embed: ModelElement, wrapper: HTMLElement, block: string ) {+ if ( editor.state === 'destroyed' || embed.root !== editor.model.document.getRoot() ) {+ return;}++ editor.model.enqueueChange( { isUndoable: false }, writer => {+ writer.setAttribute( 'block', block, embed );+ shownContents.set( wrapper, JSON.stringify( getEmbeddedEntityAttributes( embed ) ) );+ } );}/**@@ -1196,7 +1214,7 @@ function reloadEmbeddedContent( editor: Editor, viewElement: ViewElement, modelEconst wrapperDom = getWrapperDom( editor, viewElement );if ( wrapperDom ) {- loadEmbeddedContent( editor, modelElement, $( wrapperDom ), boxSize );+ loadEmbeddedContent( editor, modelElement, wrapperDom, boxSize );}}diff --git a/packages/commons/src/lib/block_reference.spec.ts b/packages/commons/src/lib/block_reference.spec.tsindex eb57251d50..e1698fc4ae 100644--- a/packages/commons/src/lib/block_reference.spec.ts+++ b/packages/commons/src/lib/block_reference.spec.ts@@ -5,6 +5,7 @@ import {type BlockNode,encodeBlockParameter,formatBlockRange,+ getEditableBlockRun,isValidBlockId,parseBlockRange,resolveBlockRange,@@ -166,6 +167,75 @@ describe("sliceToBlockReference", () => {});});+describe("getEditableBlockRun", () => {+ it("finds a single block, and the blocks of a range with their nested ancestors", () => {+ const single = block("p", "a");+ const quote = el("blockquote", {}, el("p", {}), single, el("p", {}));+ const start = el("blockquote", {}, text(" "), block("p", "b"));+ const end = el("ul", {}, el("li", {}, block("p", "c")), text("\n"));+ const root = el("div", {}, quote, start, el("p", {}), end, el("p", {}));++ expect(getEditableBlockRun(root, "a")).toEqual({+ parent: quote, first: single, last: single+ });+ expect(getEditableBlockRun(root, "c:b")).toEqual({+ parent: root, first: start, last: end+ });+ });++ it("finds the items of a list, and a block that holds the end of the range", () => {+ const firstItem = el("li", {}, block("p", "a"));+ const lastItem = el("li", {}, block("p", "b"));+ const list = el("ol", {}, el("li", {}), firstItem, el("li", {}), lastItem);+ const quote = block("blockquote", "c", el("p", {}), block("p", "d"));+ const root = el("div", {}, list, quote);++ expect(getEditableBlockRun(root, "a:b")).toEqual({+ parent: list, first: firstItem, last: lastItem+ });+ expect(getEditableBlockRun(root, "a")).toEqual({+ parent: list, first: firstItem, last: firstItem+ });+ expect(getEditableBlockRun(root, "c:d")).toEqual({+ parent: root, first: quote, last: quote+ });+ });++ it("finds to-do items past their checkbox, and a block beside a nested list", () => {+ const todo = (id: string) => el("li", {}, el("label", {}, el("input", {})), block("p", id));+ const firstTask = todo("t1");+ const lastTask = todo("t2");+ const todoList = el("ul", { class: "todo-list" }, firstTask, lastTask);+ const paragraph = block("p", "p");+ const item = el("li", {}, paragraph, el("ul", {}, el("li", {})));+ const root = el("div", {}, todoList, el("ul", {}, item));++ expect(getEditableBlockRun(root, "t1:t2")).toEqual({+ parent: todoList, first: firstTask, last: lastTask+ });+ expect(getEditableBlockRun(root, "p")).toEqual({+ parent: item, first: paragraph, last: paragraph+ });+ });++ it("finds nothing for a missing block, or an ancestor that holds other content", () => {+ const root = el("div", {},+ el("ul", {},+ el("li", {}, el("p", {}), block("p", "a")),+ el("li", {}, block("p", "s")),+ el("li", {}, block("p", "b"), el("ul", {}))+ ),+ el("p", {}, block("span", "c"), text("after")),+ el("table", {}, el("tr", {}, block("td", "d"), block("td", "e")))+ );++ for (const value of [ "a:x", "a:s", "s:b", "c", "d:e" ]) {+ expect(getEditableBlockRun(root, value), value).toBeNull();+ }+ expect(getEditableBlockRun(root, "s")).not.toBeNull();+ });+});+class TestElement implements BlockNode {parentNode: BlockNode | null = null;childNodes: BlockNode[] = [];@@ -207,6 +277,10 @@ class TestText implements BlockNode {constructor(readonly text: string) {}+ get textContent() {+ return this.text;+ }+remove() {removeFromParent(this);}diff --git a/packages/commons/src/lib/block_reference.ts b/packages/commons/src/lib/block_reference.tsindex c3019396f1..abfe671170 100644--- a/packages/commons/src/lib/block_reference.ts+++ b/packages/commons/src/lib/block_reference.ts@@ -12,11 +12,19 @@ export interface BlockNode {parentNode: BlockNode | null;childNodes: ArrayLike<BlockNode>;tagName?: string;+ textContent?: string | null;getAttribute?(name: string): string | null | undefined;setAttribute?(name: string, value: string): unknown;remove?(): unknown;}+/** Sibling nodes, children of `parent`, from `first` to `last`. */+export interface BlockRun<T extends BlockNode> {+ parent: T;+ first: T;+ last: T;+}+/** Whether `id` can be a block id. An id can be any text without `:`, the range separator. */export function isValidBlockId(id: string | null | undefined): id is string {return !!id && !id.includes(":");@@ -91,6 +99,73 @@ export function sliceToBlockReference(root: BlockNode, value: string) {return true;}+/**+ * The sibling nodes under `root` that hold exactly the blocks that `value`, a `block` link+ * parameter, points at, so that they can be edited apart from the rest. Blocks that fill a list+ * item are its item. `null` when a block is missing, or when an ancestor of the blocks also holds+ * other content, as a list item does for a paragraph before the first block.+ */+export function getEditableBlockRun<T extends BlockNode>(+ root: T,+ value: string+): BlockRun<T> | null {+ const { start, end } = resolveBlockReference<T>(root, value);+ if (!start || !end) {+ return null;+ }++ const startPath = getPath(start, root);+ const endPath = getPath(end, root);+ let depth = 0;+ while (depth < startPath.length && startPath[depth] === endPath[depth]) {+ depth++;+ }++ const isNested = depth === startPath.length;+ const first = isNested ? start : startPath[depth];+ const last = isNested ? start : endPath[depth];+ const parent = first.parentNode as T;+ if (!isAtEdge(start, first, "first") || !isAtEdge(end, last, "last")) {+ return null;+ }++ if (isTag(parent, "LI") && isAtEdge(first, parent, "first") && isAtEdge(last, parent, "last")) {+ return { parent: parent.parentNode as T, first: parent, last: parent };+ }+ const isContainer = parent === root || RUN_CONTAINERS.has(String(parent.tagName).toUpperCase());+ return isContainer ? { parent, first, last } : null;+}++const RUN_CONTAINERS = new Set([+ "ASIDE", "BLOCKQUOTE", "DETAILS", "DIV", "LI", "OL", "SECTION", "UL"+]);++function getPath<T extends BlockNode>(node: T, root: BlockNode) {+ const path: T[] = [];+ for (let current: BlockNode = node; current !== root;) {+ path.unshift(current as T);+ current = current.parentNode as BlockNode;+ }+ return path;+}++function isAtEdge(node: BlockNode, ancestor: BlockNode, edge: "first" | "last") {+ for (let current = node; current !== ancestor;) {+ const parent = current.parentNode as BlockNode;+ const siblings = Array.from(parent.childNodes).filter(isContent);+ if (siblings.at(edge === "first" ? 0 : -1) !== current) {+ return false;+ }+ current = parent;+ }+ return true;+}++/** Whether `node` has text, or is an element other than a label, such as a to-do checkbox. */+function isContent(node: BlockNode) {+ return !!node.textContent?.trim() || (!!node.tagName && !isTag(node, "LABEL"));+}+function sliceToBlockRange(root: BlockNode, start: BlockNode, end: BlockNode) {for (let node = start; node !== root && node.parentNode; node = node.parentNode) {const siblings = Array.from(node.parentNode.childNodes);diff --git a/packages/trilium-core/src/routes/api/notes.spec.ts b/packages/trilium-core/src/routes/api/notes.spec.tsindex eb59086f81..0bfa3ac838 100644--- a/packages/trilium-core/src/routes/api/notes.spec.ts+++ b/packages/trilium-core/src/routes/api/notes.spec.ts@@ -172,6 +172,49 @@ describe("Notes API (core)", () => {});});+ describe("editing blocks", () => {+ const blocks = `<p data-trilium-block-id="a">A</p><p data-trilium-block-id="b">B</p>`;++ it("reads and replaces the blocks of a text note", async () => {+ const { noteId } = await createTextNote(api, {+ content: `<p>Before</p>${blocks}<p>After</p>`+ });++ const read = await api.get<{ content: string }>(`/api/notes/${noteId}/blocks`, {+ query: { block: "a:b" }+ });+ expect(read.status).toBe(200);+ expect(read.body.content).toBe(blocks);++ const update = await api.put(`/api/notes/${noteId}/blocks`, {+ query: { block: "a:b" },+ body: { content: `<p data-trilium-block-id="a">New</p>` }+ });+ expect(update.status).toBe(204);++ const blob = await api.get<{ content: string }>(`/api/notes/${noteId}/blob`);+ expect(blob.body.content)+ .toBe(`<p>Before</p><p data-trilium-block-id="a">New</p><p>After</p>`);+ });++ it("rejects missing blocks and malformed requests", async () => {+ const { noteId } = await createTextNote(api, { content: blocks });+ const url = `/api/notes/${noteId}/blocks`;+ const codeNote = await api.post<{ note: { noteId: string } }>(+ "/api/notes/root/children?target=into",+ { body: { title: "Code", type: "code", mime: "text/plain", content: blocks } }+ );+ const codeUrl = `/api/notes/${codeNote.body.note.noteId}/blocks`;++ expect((await api.get(url, { query: { block: "a:x" } })).status).toBe(404);+ expect((await api.get(url)).status).toBe(400);+ expect((await api.get(codeUrl, { query: { block: "a" } })).status).toBe(400);+ expect((await api.put(url, { query: { block: "a:x" }, body: { content: "" } })).status)+ .toBe(404);+ expect((await api.put(url, { query: { block: "a" }, body: {} })).status).toBe(400);+ });+ });+describe("deleting and undeleting", () => {it("soft-deletes a note, then undeletes it", async () => {const { noteId } = await createTextNote(api, { title: "To delete" });diff --git a/packages/trilium-core/src/routes/api/notes.ts b/packages/trilium-core/src/routes/api/notes.tsindex aed98f290e..37e5f8b1ad 100644--- a/packages/trilium-core/src/routes/api/notes.ts+++ b/packages/trilium-core/src/routes/api/notes.ts@@ -4,8 +4,9 @@ import { t } from "i18next";import type { Request } from "../../http_interface";import blobService from "../../services/blob";+import { getBlockRangeContent, replaceBlockRangeContent } from "../../services/block_ranges";import eraseService from "../../services/erase.js";-import { ValidationError } from "../../errors.js";+import { NotFoundError, ValidationError } from "../../errors.js";import becca from "../../becca/becca.js";import type BBranch from "../../becca/entities/bbranch.js";import { getLog } from "../../services/log.js";@@ -205,6 +206,52 @@ function updateNoteData(req: Request<{ noteId: string }>) {return noteService.updateNoteData(noteId, content, attachments);}+/** The blocks of a text note that the `block` query parameter points at, to edit apart. */+function getNoteBlocks(req: Request<{ noteId: string }>) {+ const { content, block } = getBlockRangeRequest(req);+ const blocks = getBlockRangeContent(content, block);+ if (blocks === null) {+ throw new NotFoundError(getBlockRangeError(req.params.noteId, block));+ }++ return { content: blocks };+}++/** Replaces the blocks of a text note that the `block` query parameter points at. */+function updateNoteBlocks(req: Request<{ noteId: string }>) {+ const { content, block } = getBlockRangeRequest(req);+ const { content: blocks, attachments } = req.body;+ if (typeof blocks !== "string") {+ throw new ValidationError("Missing the content of the blocks.");+ }++ const newContent = replaceBlockRangeContent(content, block, blocks);+ if (newContent === null) {+ throw new NotFoundError(getBlockRangeError(req.params.noteId, block));+ }++ noteService.updateNoteData(req.params.noteId, newContent, attachments);+}++function getBlockRangeRequest(req: Request<{ noteId: string }>) {+ const { block } = req.query;+ if (typeof block !== "string") {+ throw new ValidationError("Missing the 'block' parameter.");+ }++ const note = becca.getNoteOrThrow(req.params.noteId);+ const content = note.type === "text" && note.isContentAvailable() ? note.getContent() : null;+ if (typeof content !== "string") {+ throw new ValidationError(`Note '${note.noteId}' has no text content to edit.`);+ }++ return { content, block };+}++function getBlockRangeError(noteId: string, block: string) {+ return `Blocks '${block}' of note '${noteId}' do not exist or cannot be edited apart.`;+}+/*** @swagger* /api/notes/{noteId}:@@ -544,6 +591,8 @@ export default {getNoteMetadata,getNotesMetadata,updateNoteData,+ getNoteBlocks,+ updateNoteBlocks,deleteNote,undeleteNote,createNote,diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex ad68a475a6..00121b8b86 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -103,6 +103,8 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransapiRoute(GET, "/api/notes/:noteId/metadata", notesApiRoute.getNoteMetadata);apiRoute(PST, "/api/notes/metadata", notesApiRoute.getNotesMetadata);apiRoute(PUT, "/api/notes/:noteId/data", notesApiRoute.updateNoteData);+ apiRoute(GET, "/api/notes/:noteId/blocks", notesApiRoute.getNoteBlocks);+ apiRoute(PUT, "/api/notes/:noteId/blocks", notesApiRoute.updateNoteBlocks);apiRoute(DEL, "/api/notes/:noteId", notesApiRoute.deleteNote);apiRoute(PUT, "/api/notes/:noteId/undelete", notesApiRoute.undeleteNote);apiRoute(PST, "/api/notes/:noteId/revision", notesApiRoute.forceSaveRevision);diff --git a/packages/trilium-core/src/services/block_ranges.spec.ts b/packages/trilium-core/src/services/block_ranges.spec.tsnew file mode 100644index 0000000000..701719b7d7--- /dev/null+++ b/packages/trilium-core/src/services/block_ranges.spec.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from "vitest";++import { getBlockRangeContent, replaceBlockRangeContent } from "./block_ranges";++const BEFORE = `<h2 class='title'>Intro</h2><!-- kept -->\n<p>Skip me</p>`;+const RANGE = `<p data-trilium-block-id="a">A</p><ul><li>x</li></ul>`+ + `<p data-trilium-block-id='b'>B</p>`;+const AFTER = `<p data-trilium-block-id="c">C</p>`;+const NOTE = `${BEFORE}${RANGE}${AFTER}`;++const LIST = `<ol start="3" class="numbered">`+ + `<li><p data-trilium-block-id="x">3</p></li>\n`+ + `<li><p data-trilium-block-id="a">4</p></li>`+ + `<li><p data-trilium-block-id="b">5</p></li>`+ + `<li><p>6</p></li></ol>`;++describe("getBlockRangeContent", () => {+ it("returns the blocks as they are stored, and list items inside their list", () => {+ expect(getBlockRangeContent(NOTE, "a:b")).toBe(RANGE);+ expect(getBlockRangeContent(NOTE, "c")).toBe(AFTER);+ expect(getBlockRangeContent(`<p>Before</p>${LIST}`, "a:b")).toBe(+ `<ol start="4" class="numbered">`+ + `<li><p data-trilium-block-id="a">4</p></li>`+ + `<li><p data-trilium-block-id="b">5</p></li></ol>`+ );+ });++ it("returns nothing for missing blocks, or blocks that cannot be edited apart", () => {+ expect(getBlockRangeContent(NOTE, "a:z")).toBeNull();+ expect(getBlockRangeContent(`<ul><li><p>x</p><p data-trilium-block-id="a">A</p></li>`+ + `<li><p data-trilium-block-id="b">B</p></li></ul>`, "a:b")).toBeNull();+ });+});++describe("replaceBlockRangeContent", () => {+ it("replaces the blocks and keeps the rest of the content as it is", () => {+ const fragment = `<p data-trilium-block-id="a">New A</p><p data-trilium-block-id="n">N</p>`;++ expect(replaceBlockRangeContent(NOTE, "a:b", fragment)).toBe(`${BEFORE}${fragment}${AFTER}`);+ expect(replaceBlockRangeContent(NOTE, "a:z", fragment)).toBeNull();+ });++ it("drops the block ids that the rest of the content holds", () => {+ const fragment = `<p data-trilium-block-id="a">A</p><p data-trilium-block-id="c">Copy</p>`+ + `<p data-trilium-block-id="b">B</p>`;++ expect(replaceBlockRangeContent(NOTE, "a:b", fragment)).toBe(+ `${BEFORE}<p data-trilium-block-id="a">A</p><p>Copy</p>`+ + `<p data-trilium-block-id="b">B</p>${AFTER}`+ );+ });++ it("replaces list items inside their list", () => {+ const fragment = `<ol start="4" class="numbered">`+ + `<li><p data-trilium-block-id="a">Four</p></li>`+ + `<li><p data-trilium-block-id="b">Five</p></li></ol>`;++ expect(replaceBlockRangeContent(LIST, "a:b", fragment)).toBe(+ `<ol start="3" class="numbered">`+ + `<li><p data-trilium-block-id="x">3</p></li>\n`+ + `<li><p data-trilium-block-id="a">Four</p></li>`+ + `<li><p data-trilium-block-id="b">Five</p></li>`+ + `<li><p>6</p></li></ol>`+ );+ });++ it("splits the list around list items that change into other content", () => {+ const paragraph = `<p data-trilium-block-id="a">Not an item</p>`;+ const bullets = `<ul><li><p data-trilium-block-id="x">Bullet</p></li></ul>`;++ expect(replaceBlockRangeContent(LIST, "a:b", paragraph)).toBe(+ `<ol start="3" class="numbered"><li><p data-trilium-block-id="x">3</p></li>\n</ol>`+ + paragraph+ + `<ol start="3" class="numbered"><li><p>6</p></li></ol>`+ );+ expect(replaceBlockRangeContent(LIST, "x:a", bullets)).toBe(+ `${bullets}<ol start="3" class="numbered">`+ + `<li><p data-trilium-block-id="b">5</p></li><li><p>6</p></li></ol>`+ );+ });+});diff --git a/packages/trilium-core/src/services/block_ranges.ts b/packages/trilium-core/src/services/block_ranges.tsnew file mode 100644index 0000000000..f7a9f9b21a--- /dev/null+++ b/packages/trilium-core/src/services/block_ranges.ts@@ -0,0 +1,99 @@+import {+ BLOCK_ID_ATTRIBUTE, getEditableBlockRun, sliceToBlockReference+} from "@triliumnext/commons";+import { HTMLElement, parse } from "node-html-parser";++/**+ * The HTML of the blocks of `content` that `block`, a `block` link parameter, points at, to edit+ * apart from the rest: list items come inside a copy of their list. `null` when the blocks cannot+ * be edited apart, as `getEditableBlockRun()` decides.+ */+export function getBlockRangeContent(content: string, block: string) {+ const root = parse(content);+ const run = getEditableBlockRun<HTMLElement>(root, block);+ if (!run) {+ return null;+ }++ if (isList(run.parent)) {+ sliceToBlockReference(root, block);+ return run.parent.toString();+ }+ return content.slice(run.first.range[0], run.last.range[1]);+}++/**+ * `content` with `fragment`, the edited HTML of `getBlockRangeContent()`, in place of the blocks+ * that `block` points at, or `null` when they cannot be edited apart. The rest of `content` stays+ * byte for byte, and `fragment` loses the block ids that the rest holds already.+ */+export function replaceBlockRangeContent(content: string, block: string, fragment: string) {+ const root = parse(content);+ const run = getEditableBlockRun<HTMLElement>(root, block);+ if (!run) {+ return null;+ }++ const start = run.first.range[0];+ const end = run.last.range[1];+ const edited = parse(fragment);+ removeBlockIds(edited, getBlockIdsOutside(root, start, end));++ if (!isList(run.parent)) {+ return splice(content, start, end, edited.toString());+ }++ const list = run.parent;+ const editedList = getSameList(edited, list);+ if (editedList) {+ return splice(content, start, end, editedList.innerHTML);+ }++ // The edited items are no longer items of the list, which splits around them.+ const firstItem = list.childNodes[0];+ const lastItem = list.childNodes[list.childNodes.length - 1];+ const openTag = content.slice(list.range[0], firstItem.range[0]);+ const closeTag = content.slice(lastItem.range[1], list.range[1]);+ const wrap = (items: string) => (items.trim() ? `${openTag}${items}${closeTag}` : "");+ const before = wrap(content.slice(firstItem.range[0], start));+ const after = wrap(content.slice(end, lastItem.range[1]));+ return splice(content, list.range[0], list.range[1], `${before}${edited.toString()}${after}`);+}++function isList(node: HTMLElement) {+ return node.tagName === "UL" || node.tagName === "OL";+}++function getBlockIdsOutside(root: HTMLElement, start: number, end: number) {+ const ids = new Set<string>();+ for (const element of root.querySelectorAll(`[${BLOCK_ID_ATTRIBUTE}]`)) {+ if (element.range[0] < start || element.range[0] >= end) {+ ids.add(element.attributes[BLOCK_ID_ATTRIBUTE]);+ }+ }+ return ids;+}++function removeBlockIds(root: HTMLElement, ids: Set<string>) {+ for (const element of root.querySelectorAll(`[${BLOCK_ID_ATTRIBUTE}]`)) {+ if (ids.has(element.attributes[BLOCK_ID_ATTRIBUTE])) {+ element.removeAttribute(BLOCK_ID_ATTRIBUTE);+ }+ }+}++/** The list that `root` consists of, when it is a list of the same kind as `list`. */+function getSameList(root: HTMLElement, list: HTMLElement) {+ const nodes = root.childNodes+ .filter((node) => node instanceof HTMLElement || node.textContent.trim());+ const [ only ] = nodes;+ const isSame = nodes.length === 1+ && only instanceof HTMLElement+ && only.tagName === list.tagName+ && only.getAttribute("class") === list.getAttribute("class");+ return isSame ? only : null;+}++function splice(content: string, start: number, end: number, replacement: string) {+ return `${content.slice(0, start)}${replacement}${content.slice(end)}`;+}