Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: fix some issues

Adorian Doranebf0611bf363
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index e325bad4fb..e30d40d99a 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -218,6 +218,12 @@ describe("getEmbedBoxSize", () => {
].map(getEmbedBoxSize)).toEqual(Array(9).fill("medium"));
});
+ it("shows an upload too large to highlight as a file", () => {
+ expect(getUploadBoxSize("text/plain", 256 * 1024)).toBe("full");
+ expect(getUploadBoxSize("text/plain", 256 * 1024 + 1)).toBe("tiny");
+ expect(getUploadBoxSize("application/json", 10_000_000)).toBe("tiny");
+ });
+
it("sizes an upload by its media type, as the attachment it becomes", () => {
expect([
"application/zip", "", "audio/mpeg", "application/json", "application/pdf",
@@ -342,11 +348,24 @@ describe("getRenderedContent editable code", () => {
canEdit: vi.fn(() => true),
getUnsavedContent: vi.fn((): string | undefined => undefined),
scheduleSave: vi.fn(),
- release: vi.fn(),
- componentId: "host"
+ release: vi.fn()
};
}
+ it("renders an attached code file too large to highlight as a file", async () => {
+ const large = buildAttachment({ role: "file", mime: "text/plain", contentLength: 256 * 1024 + 1 });
+ large.getBlob = vi.fn(async () => ({ content: "x" })) as any;
+
+ const { type } = await getRenderedContent(large, { interactive: true });
+ expect(type).toBe("file");
+ const largeSource = buildAttachment({
+ role: "importSource", mime: "text/html", contentLength: 256 * 1024 + 1
+ });
+ expect((await getRenderedContent(largeSource)).type).toBe("file");
+ expect(large.getBlob).not.toHaveBeenCalled();
+ expect(applySingleBlockSyntaxHighlight).not.toHaveBeenCalled();
+ });
+
it("renders an attached code file as code, highlighted by the language of its name", async () => {
const att = buildAttachment({ role: "file", mime: "text/x-python", title: "a.py" });
att.getBlob = (async () => ({ content: "print(1)" })) as any;
@@ -394,7 +413,6 @@ describe("getRenderedContent editable code", () => {
props.editor.scheduleSave(getContent);
props.editor.release();
expect(props.editor.canEdit()).toBe(true);
- expect(props.editor.componentId).toBe("host");
expect(noteEditor.canEdit).toHaveBeenCalledWith(note);
expect(noteEditor.getUnsavedContent).toHaveBeenCalledWith(note.noteId);
expect(noteEditor.scheduleSave).toHaveBeenCalledWith(note, getContent);
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index c313ffbbfb..c7838c7a1c 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -119,12 +119,13 @@ export interface NoteEditor {
scheduleSave(note: FNote, getContent: () => string): void;
/** Reads the unsaved content of the note now, before its editor unmounts. */
release(noteId: string): void;
- /** The component that saves the changes, which the reload of a saved change names. */
- readonly componentId: string | undefined;
}
const CODE_MIME_TYPES = new Set(["application/json"]);
+/** The size of an attached text or code file above which it shows as a file: highlighting is slow. */
+const MAX_ATTACHED_CODE_SIZE = 256 * 1024;
+
/** The types of the notes that an embed can edit in place. */
const EDITABLE_NOTE_TYPES = new Set<string>([ "code", "text" ]);
@@ -402,8 +403,6 @@ export interface ContentEditor {
getUnsavedContent(): string | undefined;
scheduleSave(getContent: () => string): void;
release(): void;
- /** The component that saves the changes, for a note. */
- componentId?: string;
}
/** `editor`, saving the changes to `attachment`. */
@@ -433,8 +432,7 @@ function getContentEditor(
canEdit: () => editor.canEdit(entity),
getUnsavedContent: () => editor.getUnsavedContent(entity.noteId),
scheduleSave: (getContent) => editor.scheduleSave(entity, getContent),
- release: () => editor.release(entity.noteId),
- componentId: editor.componentId
+ release: () => editor.release(entity.noteId)
} : undefined;
}
@@ -922,8 +920,8 @@ export function hasRenderedPreview(entity: FNote | FAttachment) {
}
/** The box size of a new embed of a file being uploaded, from the attachment it becomes. */
-export function getUploadBoxSize(mime: string): BoxSize {
- const type = isAcceptedImageMime(mime) ? "image" : getAttachedFileContentType(mime);
+export function getUploadBoxSize(mime: string, size?: number): BoxSize {
+ const type = isAcceptedImageMime(mime) ? "image" : getAttachedFileContentType(mime, size);
return getBoxSize(type, PREVIEWED_TYPES.has(type));
}
@@ -966,7 +964,7 @@ function getContentType(entity: FNote | FAttachment) {
// "importSource" attachments (e.g. the OneNote debug source HTML/InkML) are plain files kept
// for reference; render them exactly like a "file" role.
if (entity.role === "importSource") {
- return getAttachedFileContentType(entity.mime);
+ return getAttachedFileContentType(entity.mime, entity.contentLength);
}
// A link preview's "favicon" is a picture like any other as far as showing it goes; the
// role only says where it came from. Without this it would fall through to the unknown
@@ -975,16 +973,20 @@ function getContentType(entity: FNote | FAttachment) {
return "image";
}
return entity.role === "file"
- ? getAttachedFileContentType(entity.mime)
+ ? getAttachedFileContentType(entity.mime, entity.contentLength)
: getFileContentType(entity.role, entity.mime);
}
-/** The kind of file an attachment holds, which is code for text and the code media types. */
-function getAttachedFileContentType(mime: string) {
+/**
+ * The kind of file an attachment holds, which is code for text and the code media types up to
+ * `MAX_ATTACHED_CODE_SIZE`.
+ */
+function getAttachedFileContentType(mime: string, size = 0) {
const type = getFileContentType("file", mime);
- return type === "file" && (mime.startsWith("text/") || ATTACHED_CODE_MIME_TYPES.has(mime))
- ? "code"
- : type;
+ const isCode = type === "code"
+ || (type === "file" && (mime.startsWith("text/") || ATTACHED_CODE_MIME_TYPES.has(mime)));
+ if (!isCode) return type;
+ return size <= MAX_ATTACHED_CODE_SIZE ? "code" : "file";
}
/** Narrows a file, or a `viewConfig` attachment, to the kind of file its media type names. */
diff --git a/apps/client/src/services/froca_updater.spec.ts b/apps/client/src/services/froca_updater.spec.ts
index 7f9f67573c..95ad7f4d47 100644
--- a/apps/client/src/services/froca_updater.spec.ts
+++ b/apps/client/src/services/froca_updater.spec.ts
@@ -603,6 +603,8 @@ describe("froca_updater - attachment changes", () => {
contentLength: 0
});
froca.attachments[att.attachmentId] = att;
+ froca.blobPromises["attachments-att-upd"] = Promise.resolve(null);
+ froca.blobPromises["attachments-other"] = Promise.resolve(null);
await process([ec({
entityName: "attachments",
@@ -620,6 +622,9 @@ describe("froca_updater - attachment changes", () => {
} as any
})]);
expect(froca.attachments["att-upd"].title).toBe("new");
+ // The next read of its content fetches it again.
+ expect("attachments-att-upd" in froca.blobPromises).toBe(false);
+ expect("attachments-other" in froca.blobPromises).toBe(true);
});
it("creates a new attachment on its owner note when not previously loaded", async () => {
diff --git a/apps/client/src/services/froca_updater.ts b/apps/client/src/services/froca_updater.ts
index 06b12cc983..243795bc65 100644
--- a/apps/client/src/services/froca_updater.ts
+++ b/apps/client/src/services/froca_updater.ts
@@ -306,6 +306,7 @@ function processAttachment(loadResults: LoadResults, ec: EntityChange) {
}
if (ec.entity) {
+ delete froca.blobPromises[`attachments-${ec.entityId}`];
if (attachment) {
attachment.update(ec.entity as FAttachmentRow);
} else {
diff --git a/apps/client/src/services/spaced_update.spec.ts b/apps/client/src/services/spaced_update.spec.ts
index e5926442cb..8d6a48b9fb 100644
--- a/apps/client/src/services/spaced_update.spec.ts
+++ b/apps/client/src/services/spaced_update.spec.ts
@@ -270,6 +270,39 @@ describe("SpacedUpdate", () => {
]);
});
+ it("reads a pending change at once when a save is asked for while another one runs", async () => {
+ const editor = { content: "first" };
+ const commits: string[] = [];
+ let finishFirstCommit = () => {};
+ const firstCommitDone = new Promise<void>((resolve) => {
+ finishFirstCommit = resolve;
+ });
+ const spacedUpdate = new SpacedUpdate<string>({
+ key: "A",
+ prepare: () => editor.content,
+ commit: async (data) => {
+ commits.push(data);
+ if (commits.length === 1) await firstCommitDone;
+ }
+ }, 50);
+
+ spacedUpdate.scheduleUpdate();
+ const firstSave = spacedUpdate.updateNowIfNecessary();
+ editor.content = "second";
+ spacedUpdate.scheduleUpdate();
+ const secondSave = spacedUpdate.updateNowIfNecessary();
+ // The editor goes away right after asking, as an unmounted one does.
+ editor.content = "gone";
+
+ // Unsaved until the commit that holds the change lands.
+ expect(spacedUpdate.hasUnsavedChanges()).toBe(true);
+ finishFirstCommit();
+ await firstSave;
+ await secondSave;
+ expect(commits).toEqual([ "first", "second" ]);
+ expect(spacedUpdate.hasUnsavedChanges()).toBe(false);
+ });
+
it("retries a failed commit with the frozen snapshot, not the live state", async () => {
const editor = { content: "typed into A" };
const commits: string[] = [];
diff --git a/apps/client/src/services/spaced_update.ts b/apps/client/src/services/spaced_update.ts
index a17d95aa0c..35020ce053 100644
--- a/apps/client/src/services/spaced_update.ts
+++ b/apps/client/src/services/spaced_update.ts
@@ -111,11 +111,30 @@ export default class SpacedUpdate<T = void> {
this.commit = commit;
}
- /** Flushes the pending change (if any) and waits until all queued snapshots are persisted. */
+ /**
+ * Flushes the pending change (if any) and waits until all queued snapshots are persisted. The
+ * pending change is read at once, also while another save runs, so its source can go away.
+ */
updateNowIfNecessary(): Promise<void> {
+ if (this.drainPromise) {
+ try {
+ // The running save waits for an asynchronous snapshot and handles its failure.
+ const snapshotted = this.snapshotPending();
+ if (snapshotted instanceof Promise) {
+ snapshotted.catch(() => {});
+ }
+ } catch (e) {
+ return Promise.reject(e);
+ }
+ }
return this.drain();
}
+ /** Whether a change made under the current binding is not saved yet. */
+ hasUnsavedChanges() {
+ return this.changed || this.pendingCommits.has(this.bindingKey);
+ }
+
isAllSavedAndTriggerUpdate() {
const allSaved = !this.changed
&& this.pendingCommits.size === 0
diff --git a/apps/client/src/widgets/react/editor_save_race.spec.tsx b/apps/client/src/widgets/react/editor_save_race.spec.tsx
index 48e5fa06af..6c87a989a2 100644
--- a/apps/client/src/widgets/react/editor_save_race.spec.tsx
+++ b/apps/client/src/widgets/react/editor_save_race.spec.tsx
@@ -23,6 +23,7 @@ import Component from "../../components/component";
import NoteContext from "../../components/note_context";
import FBlob from "../../entities/fblob";
import type FNote from "../../entities/fnote";
+import LoadResults from "../../services/load_results";
import server from "../../services/server";
import type SpacedUpdate from "../../services/spaced_update";
import { buildNote } from "../../test/easy-froca";
@@ -183,6 +184,56 @@ describe("note switch save race (#9614)", () => {
// Note B must not be overwritten with note A's content + the new keystrokes.
expect(putsTo(noteB)).toEqual([]);
+
+ });
+
+ it("loads the next note even when keystrokes typed over the previous one wait for a save", async () => {
+ const harness = setupEditorHarness({ withParent: true });
+ cleanupContainer = harness.container;
+ const { noteA, noteB, editor, pendingBlobB, blobB, show } = harness;
+
+ await show(noteA);
+ await show(noteB);
+ editor.content = "AAA plus keystrokes meant for B";
+ getSpacedUpdate().scheduleUpdate();
+
+ // Note B's content arrives within the debounce of the save.
+ await act(async () => {
+ pendingBlobB.resolve(blobB);
+ });
+ await vi.advanceTimersByTimeAsync(20);
+ expect(editor.content).toBe("BBB");
+ });
+
+ it("keeps unsaved changes when another editor saves the note, and reloads an editor without any", async () => {
+ const harness = setupEditorHarness({ withParent: true });
+ cleanupContainer = harness.container;
+ const { noteA, editor, parent, show } = harness;
+ await show(noteA);
+ const savedElsewhere = async (content: string) => {
+ noteA.getBlob = async () => new FBlob({
+ blobId: `blob-${content}`,
+ content,
+ contentLength: content.length,
+ dateModified: "",
+ utcDateModified: ""
+ });
+ const loadResults = new LoadResults([]);
+ loadResults.addNoteContent(noteA.noteId, "another-editor");
+ await act(async () => {
+ await parent?.handleEvent("entitiesReloaded", { loadResults });
+ });
+ await vi.advanceTimersByTimeAsync(20);
+ };
+
+ editor.content = "AAA typed here";
+ getSpacedUpdate().scheduleUpdate();
+ await savedElsewhere("AAA typed elsewhere");
+ expect(editor.content).toBe("AAA typed here");
+
+ await vi.advanceTimersByTimeAsync(1500);
+ await savedElsewhere("AAA typed elsewhere again");
+ expect(editor.content).toBe("AAA typed elsewhere again");
});
it("awaits async event handlers registered by React components (the contract NoteContext.setNote relies on)", async () => {
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 0e3b8e6a45..e9e5c09387 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -175,6 +175,8 @@ export function useEditorSpacedUpdate({ note, noteType, noteContext, getData, on
// React to note/blob changes.
useEffect(() => {
if (!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);
spacedUpdate.allowUpdateWithoutChange(() => onContentChange(blob.content));
loadedNoteIdRef.current = note.noteId;
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
index 1342d27a33..5a56585957 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
@@ -2,10 +2,13 @@ import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
+import Component from "../../../components/component";
import FAttachment from "../../../entities/fattachment";
+import FBlob from "../../../entities/fblob";
import type FNote from "../../../entities/fnote";
import type { ContentEditor } from "../../../services/content_renderer";
import froca from "../../../services/froca";
+import LoadResults from "../../../services/load_results";
import options from "../../../services/options";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
@@ -22,7 +25,7 @@ vi.mock("../../../services/content_renderer", () => ({ renderCodePreview }));
// `CodeEditor` reads the theme as a string.
options.set("codeNoteTheme", "");
-const parent = { registerHandler() {}, removeHandler() {}, componentId: "embed-test" } as any;
+const parent = new Component();
const figures: HTMLElement[] = [];
afterEach(() => {
@@ -114,6 +117,36 @@ describe("CodeEmbed", () => {
});
});
+ it("follows each save of its note or attachment, its own included, while it has no changes", async () => {
+ const note = buildCodeNote("one");
+ const editor = buildEditor();
+ const { figure } = await mount(note, editor, { content: "one", isEditable: true });
+ const view = await findView(figure);
+
+ // A save of this embed, or of another embed of the same note.
+ note.getBlob = async () => buildBlob("two");
+ const noteSaved = new LoadResults([]);
+ noteSaved.addNoteContent(note.noteId, "any-component");
+ await act(async () => {
+ await parent.handleEvent("entitiesReloaded", { loadResults: noteSaved });
+ });
+ await vi.waitFor(() => expect(view.state.doc.toString()).toBe("two"));
+
+ const attachment = buildAttachment("script.py");
+ const { figure: attachmentFigure } = await mount(attachment, buildEditor(), {
+ content: "a",
+ isEditable: true
+ });
+ const attachmentView = await findView(attachmentFigure);
+ attachment.getBlob = async () => buildBlob("b");
+ const attachmentSaved = new LoadResults([]);
+ attachmentSaved.addAttachmentRow({ attachmentId: attachment.attachmentId } as never, "any");
+ await act(async () => {
+ await parent.handleEvent("entitiesReloaded", { loadResults: attachmentSaved });
+ });
+ await vi.waitFor(() => expect(attachmentView.state.doc.toString()).toBe("b"));
+ });
+
it("loads the note as saved elsewhere, unless it has unsaved changes", async () => {
const { figure } = await mount(buildCodeNote("saved"), buildEditor(), {
content: "stale",
@@ -187,7 +220,6 @@ function buildEditor(overrides: Partial<ContentEditor> = {}): ContentEditor {
getUnsavedContent: () => undefined,
scheduleSave: vi.fn(),
release: vi.fn(),
- componentId: "host",
...overrides
};
}
@@ -210,3 +242,27 @@ async function findView(figure: HTMLElement) {
if (!view) throw new Error("CodeMirror did not mount.");
return view as InstanceType<typeof EditorView>;
}
+
+function buildBlob(content: string) {
+ return new FBlob({
+ blobId: `blob-${content}`,
+ content,
+ contentLength: content.length,
+ dateModified: "",
+ utcDateModified: ""
+ });
+}
+
+function buildAttachment(title: string) {
+ return new FAttachment(froca, {
+ attachmentId: `att-${title}`,
+ ownerId: "owner",
+ role: "file",
+ mime: "text/plain",
+ title,
+ dateModified: "",
+ utcDateModified: "",
+ utcDateScheduledForErasureSince: "",
+ contentLength: 0
+ } as never);
+}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
index 104f3d7c86..82f85e1750 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
@@ -6,7 +6,7 @@ import { useEffect, useRef, useState } from "preact/hooks";
import type FAttachment from "../../../entities/fattachment";
import FNote from "../../../entities/fnote";
import { type ContentEditor, renderCodePreview } from "../../../services/content_renderer";
-import { useNoteBlob, useNoteProperty } from "../../react/hooks";
+import { useNoteBlob, useNoteProperty, useTriliumEvent } from "../../react/hooks";
import {
EditableEmbedContent, useEditableEmbed, useEmbedPreview
} from "../text/editable_embed";
@@ -37,11 +37,12 @@ export default function CodeEmbed({
const { isEditing } = useEditableEmbed(rootRef, { editor, note, focusTarget: ".cm-content" });
const [ content, setContent ] = useState(initialContent);
const mime = useNoteProperty(note, "mime") ?? initialMime;
- useChangesFromElsewhere(note, editor, setContent);
+ useSavedContent(entity, editor, setContent);
const shownPreview = useEmbedPreview(
preview,
`${mime}\n${content}`,
- () => renderCodePreview(content, mime)
+ () => renderCodePreview(content, mime),
+ isEditing
);
return (
@@ -63,19 +64,29 @@ export default function CodeEmbed({
}
/**
- * Shows the content that another component saves to `note`. Unsaved changes made in the embed
- * are kept, and replace that content when they save.
+ * Shows the content of `entity` each time it saves, also when another embed of it saved it.
+ * Unsaved changes made in the embed are kept, and replace that content when they save.
*/
-function useChangesFromElsewhere(
- note: FNote | null,
+function useSavedContent(
+ entity: FNote | FAttachment,
editor: ContentEditor,
setContent: (content: string) => void
) {
- const blob = useNoteBlob(note, editor.componentId);
+ const noteBlob = useNoteBlob(entity instanceof FNote ? entity : null);
+ const [ attachmentContent, setAttachmentContent ] = useState<string>();
+ const content = entity instanceof FNote ? noteBlob?.content : attachmentContent;
+
+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
+ if (entity instanceof FNote) return;
+ const rows = loadResults.getAttachmentRows();
+ if (rows.some((row) => row.attachmentId === entity.attachmentId)) {
+ void entity.getBlob().then((blob) => setAttachmentContent(blob?.content));
+ }
+ });
useEffect(() => {
- if (blob && editor.getUnsavedContent() === undefined) {
- setContent(blob.content);
+ if (content !== undefined && editor.getUnsavedContent() === undefined) {
+ setContent(content);
}
- }, [ blob ]);
+ }, [ content ]);
}
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx
index 20871f9a36..950ca83ba1 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx
@@ -92,4 +92,22 @@ describe("CKEditorWithWatchdog", () => {
await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledTimes(2));
expect(mocks.destroy).toHaveBeenCalledTimes(1);
});
+
+ it("destroys its editor when it goes away", async () => {
+ const props = {
+ contentLanguage: null,
+ watchdogRef: createRef<EditorWatchdog>(),
+ onChange: vi.fn(),
+ editorApi: createRef<CKEditorApi>(),
+ templates: []
+ };
+ await act(async () => {
+ render(<CKEditorWithWatchdog {...props} />, host);
+ });
+ await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());
+
+ await act(async () => render(null, host));
+ await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalledOnce());
+ expect(props.watchdogRef.current).toBeNull();
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 44f1bdfc73..f7e6b7f5b2 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -352,6 +352,20 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
aiEnabled, llmProviders
]);
+ // Destroys the editor when the component goes away, after a build still in progress.
+ useEffect(() => () => {
+ buildQueueRef.current = buildQueueRef.current
+ .then(async () => {
+ const watchdog = watchdogRef.current;
+ watchdogRef.current = null;
+ externalWatchdogRef.current = null;
+ await watchdog?.destroy();
+ })
+ .catch((e) => {
+ console.warn("Watchdog destroy failed", e);
+ });
+ }, []);
+
// Push snippet ("template") definitions into the live editor instead of rebuilding it. The premium
// Template plugin read its definitions once at init; TriliumSnippets keeps them in a live
// collection, so add/remove/rename/re-icon all apply in place.
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
index 0397aa11f1..bb3037488a 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
@@ -45,13 +45,21 @@ afterEach(() => {
for (const figure of figures) {
const box = figure.querySelector(".include-note-content");
if (box) act(() => render(null, box));
- figure.remove();
+ figure.parentElement?.remove();
}
figures.length = 0;
(appContext as unknown as { tabManager: unknown }).tabManager = undefined;
});
describe("TextEmbed", () => {
+ it("uses the floating toolbar inside an editor that has one", async () => {
+ const { figure } = await mount(buildTextNote("floating"), buildEditor(), { isEditable: true });
+ await vi.waitFor(() => expect(editorProps).toHaveBeenCalled(), { timeout: 5000 });
+ const props = editorProps.mock.calls[0][0] as TypeWidgetProps;
+ expect(props.viewScope?.floatingToolbar).toBe(true);
+ expect(figure.isConnected).toBe(true);
+ });
+
it("shows the preview, and offers the Editable toggle only where it can edit", async () => {
const preview = buildPreview("Hello");
const { figure } = await mount(buildTextNote("hello"), buildEditor(), { preview });
@@ -65,7 +73,7 @@ describe("TextEmbed", () => {
it("edits in a note context of its own, and saves before the editor goes away", async () => {
const note = buildTextNote("edited");
- const { figure } = await mount(note, buildEditor(), { isEditable: true });
+ const { figure } = await mount(note, buildEditor(), { isEditable: true, hasFixedToolbar: true });
// The editor module loads on demand, which takes a while under a busy test run.
await vi.waitFor(() => expect(editorProps).toHaveBeenCalled(), { timeout: 5000 });
@@ -74,7 +82,7 @@ describe("TextEmbed", () => {
expect(props.note).toBe(note);
expect(props.ntxId).toMatch(/^_embed_/);
expect(props.noteContext?.ntxId).toBe(props.ntxId);
- // The formatting toolbar of the note hosts the buttons of the editor.
+ // Inside an editor with a fixed toolbar, that toolbar shows the buttons of this editor.
expect(props.viewScope).toMatchObject({ viewMode: "default", floatingToolbar: false });
expect(props.isNested).toBe(true);
// The plugins of the editor find their host from its DOM.
@@ -103,6 +111,8 @@ describe("TextEmbed", () => {
interface MountOptions {
preview?: HTMLElement;
isEditable?: boolean;
+ /** Whether the editor around the embed has a fixed toolbar, rather than a floating one. */
+ hasFixedToolbar?: boolean;
}
/** Renders `TextEmbed` in the markup of an embed, as the host does. */
@@ -121,7 +131,13 @@ async function mount(note: FNote, editor: ContentEditor | undefined, options: Mo
const box = wrapper.querySelector(".include-note-content");
if (!box) throw new Error("Expected the content box.");
figure.append(wrapper);
- document.body.append(figure);
+ // The editable root of the text editor that shows the embed.
+ const hostRoot = document.createElement("div");
+ hostRoot.className = "ck-editor__editable";
+ const toolbar = options.hasFixedToolbar ? { element: document.createElement("div") } : undefined;
+ Object.assign(hostRoot, { ckeditorInstance: { ui: { view: { toolbar } } } });
+ hostRoot.append(figure);
+ document.body.append(hostRoot);
figures.push(figure);
const content = (await note.getBlob())?.content ?? "";
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
index 68680c1441..0ffff70c30 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
@@ -4,7 +4,9 @@ import { useRef } from "preact/hooks";
import type FNote from "../../../entities/fnote";
import type { ContentEditor } from "../../../services/content_renderer";
import { useNoteBlob } from "../../react/hooks";
-import { EditableEmbedContent, useEditableEmbed, useEmbedPreview } from "./editable_embed";
+import {
+ EditableEmbedContent, hasFixedToolbarAround, useEditableEmbed, useEmbedPreview
+} from "./editable_embed";
const TextEmbedEditor = lazy(() => import("./TextEmbedEditor"));
@@ -34,7 +36,8 @@ export default function TextEmbed({
focusTarget: ".ck-editor__editable"
});
const blob = useNoteBlob(note);
- const shownPreview = useEmbedPreview(preview, blob?.content ?? content, renderPreview);
+ const shownPreview =
+ useEmbedPreview(preview, blob?.content ?? content, renderPreview, isEditing);
return (
<EditableEmbedContent
@@ -43,7 +46,10 @@ export default function TextEmbed({
isEditing={isEditing}
preview={shownPreview}
>
- <TextEmbedEditor note={note} />
+ <TextEmbedEditor
+ note={note}
+ hasFixedToolbar={isEditing && hasFixedToolbarAround(rootRef.current)}
+ />
</EditableEmbedContent>
);
}
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
index 4e43be4794..727f8af1dd 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
@@ -13,15 +13,22 @@ import { useLegacyComponentElement, useNoteContext } from "../../react/hooks";
import EditableText from "./EditableText";
import { NestedEmbedContext, useEmbedBadgeSlot } from "./editable_embed";
+interface TextEmbedEditorProps {
+ note: FNote;
+ /** Whether the editor around the embed has a fixed toolbar, rather than a floating one. */
+ hasFixedToolbar: boolean;
+}
+
/**
* 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 }: { note: FNote }) {
+export default function TextEmbedEditor({ note, hasFixedToolbar }: TextEmbedEditorProps) {
const [ ntxId ] = useState(() => `_embed_${randomString(10)}`);
- // The formatting toolbar of the note shows the buttons of this editor while it has the focus.
+ // Inside an editor with a fixed toolbar, that toolbar shows the buttons of this editor while
+ // it has the focus.
const { noteContext, component } =
- useEmbeddedNoteContext(note, ntxId, { floatingToolbar: false });
+ useEmbeddedNoteContext(note, ntxId, { floatingToolbar: !hasFixedToolbar });
// A layout cleanup runs while the editor is still mounted, so it saves what is left.
useLayoutEffect(() => () => {
diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts
index 3671d654d3..da4f53504b 100644
--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts
@@ -210,7 +210,6 @@ describe("useNoteEditor", () => {
await act(() => {
render(h(ParentComponent.Provider, { value: component }, h(Probe, {})), container);
});
- expect(editor?.componentId).toBe(component.componentId);
editor?.scheduleSave(code, () => "first");
await act(async () => {
diff --git a/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx
index 3bf55e9e54..20b2ceacf4 100644
--- a/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsx
@@ -113,6 +113,29 @@ describe("useEmbedEditors", () => {
});
describe("useEmbedPreview", () => {
+ it("renders no preview while paused, and the latest one once resumed", async () => {
+ const initial = document.createElement("pre");
+ const rendered = document.createElement("pre");
+ const renderPreview = vi.fn(async () => rendered);
+ let preview: HTMLElement | undefined;
+ function Probe({ previewKey, isPaused }: { previewKey: string; isPaused: boolean }) {
+ preview = useEmbedPreview(initial, previewKey, renderPreview, isPaused);
+ return null;
+ }
+
+ const container = document.createElement("div");
+ await act(async () => render(<Probe previewKey="a" isPaused />, container));
+ await act(async () => render(<Probe previewKey="b" isPaused />, container));
+ await act(async () => render(<Probe previewKey="c" isPaused />, container));
+ expect(renderPreview).not.toHaveBeenCalled();
+ expect(preview).toBe(initial);
+
+ await act(async () => render(<Probe previewKey="c" isPaused={false} />, container));
+ await vi.waitFor(() => expect(preview).toBe(rendered));
+ expect(renderPreview).toHaveBeenCalledOnce();
+ act(() => render(null, container));
+ });
+
it("keeps the first preview for its key, and renders one for any other key", async () => {
const initial = document.createElement("pre");
const rendered = document.createElement("pre");
diff --git a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
index ffc2689f07..0499ca7144 100644
--- a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
@@ -90,17 +90,23 @@ export function EditableEmbedContent({
/**
* The preview of the content of an embed: `initial` while `key` has its first value, otherwise
* what `render` returns for the current key. The previous preview stays until the next is ready.
+ * While `isPaused`, as while the content is edited, no preview renders.
*/
export function useEmbedPreview(
initial: HTMLElement,
key: string,
- render: () => Promise<HTMLElement>
+ render: () => Promise<HTMLElement>,
+ isPaused = false
) {
const [ preview, setPreview ] = useState(initial);
const initialKeyRef = useRef(key);
+ const shownKeyRef = useRef(key);
useEffect(() => {
+ if (isPaused || key === shownKeyRef.current) return;
+
if (key === initialKeyRef.current) {
+ shownKeyRef.current = key;
setPreview(initial);
return;
}
@@ -108,13 +114,14 @@ export function useEmbedPreview(
let isCurrent = true;
render().then((element) => {
if (isCurrent) {
+ shownKeyRef.current = key;
setPreview(element);
}
});
return () => {
isCurrent = false;
};
- }, [ key ]);
+ }, [ key, isPaused ]);
return preview;
}
@@ -180,6 +187,15 @@ export function useEmbedBadgeSlot(rootRef: RefObject<HTMLElement | null>) {
return slot;
}
+/**
+ * Whether the text editor around `element` shows its buttons in a fixed formatting toolbar,
+ * 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;
+}
+
/** The editable root of a text editor, which CKEditor gives a reference to the editor. */
type EditorRootElement = HTMLElement & { ckeditorInstance?: CKTextEditor };
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index 1841a88bb4..b84f398cfa 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -97,7 +97,7 @@ declare global {
* The box size of a new embed of a file being uploaded, from its media type. Hosts without
* embeds leave it out.
*/
- getEmbedBoxSize?(mime: string): string;
+ getEmbedBoxSize?(mime: string, size: number): string;
/**
* Opens the context menu of what `embed` shows, below `anchor`. Hosts without embeds
* leave it out.
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
index 4da297b0bc..824cc2bb8c 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
@@ -146,12 +146,10 @@ describe("FileUploadCommand", () => {
));
});
- it("inserts an embed placeholder per file, in the size the host gives its type", () => {
- installGlobMock({
- getComponentByEl: () => ({
- getEmbedBoxSize: (mime: string) => (mime === "image/png" ? "medium" : "tiny")
- })
- });
+ it("inserts an embed placeholder per file, in the size the host gives its type and size", () => {
+ const getEmbedBoxSize = vi.fn((mime: string, _size: number) =>
+ (mime === "image/png" ? "medium" : "tiny"));
+ installGlobMock({ getComponentByEl: () => ({ getEmbedBoxSize }) });
setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
editor.execute("fileUpload", {
@@ -170,6 +168,7 @@ describe("FileUploadCommand", () => {
"</contentEmbed>" +
"<paragraph>\\[\\]bar</paragraph>$"
));
+ expect(getEmbedBoxSize.mock.calls).toEqual([ [ "text/plain", 1 ], [ "image/png", 1 ] ]);
});
it("sizes the embeds medium for a host that names no size", () => {
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
index d2c6cbf09b..7f26ebfa21 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
@@ -141,5 +141,5 @@ interface EmbedPlaceholderOptions {
/** The box size the host gives an embed of `file`, `medium` when the host does not say. */
function getEmbedBoxSize(editor: Editor, file: File) {
const component = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());
- return component.getEmbedBoxSize?.(file.type) ?? "medium";
+ return component.getEmbedBoxSize?.(file.type, file.size) ?? "medium";
}