Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: add support for editable code embeds

Adorian Doran1f97b829c427
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index ea1631bbc5..6c99c2ab35 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -109,6 +109,10 @@ const chatPreviewComponent = vi.fn((props: any): VNode<any> =>
h("span", { class: "mock-chat-marker" }, `messages:${props.messages.length}`));
vi.mock("../widgets/type_widgets/llm_chat/ChatPreview", () => ({ default: chatPreviewComponent }));
+const codeEmbedComponent = vi.fn((_props: any): VNode<any> =>
+ h("span", { class: "mock-code-embed-marker" }));
+vi.mock("../widgets/type_widgets/code/CodeEmbed", () => ({ default: codeEmbedComponent }));
+
// `addHook` is a no-op here: sanitize_content.ts registers a DOMPurify hook at
// module load (pulled in transitively), which would otherwise throw against this mock.
vi.mock("dompurify", () => ({ default: { sanitize: (s: string) => s, addHook: () => {} } }));
@@ -191,8 +195,10 @@ describe("getEmbedBoxSize", () => {
expect([
buildNote({ title: "Script", type: "code", mime: "text/javascript" }),
protectedCode,
- buildAttachment({ role: "file", mime: "application/json" })
- ].map(getEmbedBoxSize)).toEqual([ "full", "full", "full" ]);
+ buildAttachment({ role: "file", mime: "application/json" }),
+ buildAttachment({ role: "file", mime: "text/x-python" }),
+ buildAttachment({ role: "file", mime: "application/javascript" })
+ ].map(getEmbedBoxSize)).toEqual(Array(5).fill("full"));
expect(touchProtectedSession).not.toHaveBeenCalled();
expect([
@@ -211,9 +217,11 @@ describe("getEmbedBoxSize", () => {
it("sizes an upload by its media type, as the attachment it becomes", () => {
expect([
"application/zip", "", "audio/mpeg", "application/json", "application/pdf",
- "image/png", "video/mp4", "application/vnd.excalidraw+json"
+ "image/png", "video/mp4", "application/vnd.excalidraw+json", "text/plain",
+ "application/x-sql", "text/rtf"
].map(getUploadBoxSize)).toEqual([
- "tiny", "tiny", "small", "full", "medium", "medium", "medium", "medium"
+ "tiny", "tiny", "small", "full", "medium", "medium", "medium", "medium", "full",
+ "full", "medium"
]);
});
});
@@ -224,12 +232,14 @@ describe("hasRenderedPreview", () => {
buildAttachment({ role: "file", mime: "application/vnd.excalidraw+json" }),
buildAttachment({ role: "importSource", mime: "application/json" }),
buildAttachment({ role: "file", mime: "application/pdf" }),
+ buildAttachment({ role: "file", mime: "text/plain" }),
+ buildAttachment({ role: "importSource", mime: "text/html" }),
buildNote({ title: "Site", type: "webView", "#webViewSrc": "https://example.com" })
- ].map(hasRenderedPreview)).toEqual([ true, true, true, true ]);
+ ].map(hasRenderedPreview)).toEqual(Array(6).fill(true));
expect([
- buildAttachment({ role: "file", mime: "text/plain" }),
buildAttachment({ role: "file", mime: "application/zip" }),
+ buildNote({ title: "Notes", type: "file", mime: "text/plain" }),
buildNote({ title: "Blank page", type: "webView" })
].map(hasRenderedPreview)).toEqual([ false, false, false ]);
});
@@ -322,6 +332,93 @@ describe("getRenderedContent code rendering", () => {
});
});
+describe("getRenderedContent editable code", () => {
+ function buildEditor() {
+ return {
+ canEdit: vi.fn(() => true),
+ getUnsavedContent: vi.fn((): string | undefined => undefined),
+ scheduleSave: vi.fn(),
+ release: vi.fn(),
+ componentId: "host"
+ };
+ }
+
+ it("renders an attached code file as code", async () => {
+ const att = buildAttachment({ role: "file", mime: "text/x-python" });
+ att.getBlob = (async () => ({ content: "print(1)" })) as any;
+
+ const { type, $renderedContent } = await getRenderedContent(att);
+ expect(type).toBe("code");
+ expect($renderedContent.find("pre > code").text()).toBe("print(1)");
+ });
+
+ it("mounts CodeEmbed for an interactive code note, saved by `noteEditor`", async () => {
+ const note = buildNote({
+ title: "Script", type: "code", mime: "text/javascript", content: "saved"
+ });
+ const noteEditor = buildEditor();
+ noteEditor.getUnsavedContent.mockReturnValue("unsaved");
+
+ const { type, $renderedContent } = await getRenderedContent(note, {
+ interactive: true,
+ noteEditor
+ });
+
+ expect(type).toBe("code");
+ const $mount = $renderedContent.find(".code-embed[data-interactive-mount]");
+ expect($mount.find(".mock-code-embed-marker").length).toBe(1);
+ const props = codeEmbedComponent.mock.calls[0][0];
+ expect(props.entity).toBe(note);
+ expect(props.content).toBe("unsaved");
+ expect(props.preview.textContent).toBe("unsaved");
+
+ const getContent = () => "edited";
+ 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);
+ expect(noteEditor.release).toHaveBeenCalledWith(note.noteId);
+ });
+
+ it("mounts CodeEmbed for an interactive code file, saved by `attachmentEditor`", async () => {
+ const att = buildAttachment({ role: "file", mime: "application/json" });
+ att.getBlob = (async () => ({ content: "{}" })) as any;
+ const attachmentEditor = buildEditor();
+
+ await getRenderedContent(att, { interactive: true, attachmentEditor });
+
+ const props = codeEmbedComponent.mock.calls[0][0];
+ expect(props.entity).toBe(att);
+ expect(props.content).toBe("{}");
+ props.editor.scheduleSave(() => "[]");
+ props.editor.release();
+ expect(attachmentEditor.getUnsavedContent).toHaveBeenCalledWith(att.attachmentId);
+ expect(attachmentEditor.scheduleSave).toHaveBeenCalledWith(att, expect.any(Function));
+ expect(attachmentEditor.release).toHaveBeenCalledWith(att.attachmentId);
+ });
+
+ it("keeps the static preview without an editor, or outside an embed", async () => {
+ const note = buildNote({
+ title: "Script", type: "code", mime: "text/javascript", content: "x"
+ });
+ const att = buildAttachment({ role: "file", mime: "text/plain" });
+ att.getBlob = (async () => ({ content: "y" })) as any;
+
+ const results = await Promise.all([
+ getRenderedContent(note, { interactive: true, attachmentEditor: buildEditor() }),
+ getRenderedContent(att, { interactive: true, noteEditor: buildEditor() }),
+ getRenderedContent(note, { noteEditor: buildEditor() })
+ ]);
+
+ expect(results.map(({ $renderedContent }) => $renderedContent.find("pre > code").text()))
+ .toEqual([ "x", "y", "x" ]);
+ expect(codeEmbedComponent).not.toHaveBeenCalled();
+ });
+});
+
describe("getRenderedContent image rendering", () => {
it("renders an FNote image with an api/images url", async () => {
const note = buildNote({ title: "Pic", type: "image" });
@@ -970,8 +1067,11 @@ describe("getRenderingType detection", () => {
});
it("renders an importSource attachment like a file", async () => {
- const att = buildAttachment({ role: "importSource", mime: "text/html" });
- expect((await getRenderedContent(att)).type).toBe("file");
+ const html = buildAttachment({ role: "importSource", mime: "text/html" });
+ html.getBlob = (async () => ({ content: "<p></p>" })) as any;
+ const zip = buildAttachment({ role: "importSource", mime: "application/zip" });
+ expect((await getRenderedContent(html)).type).toBe("code");
+ expect((await getRenderedContent(zip)).type).toBe("file");
});
it("returns the raw role of an attachment with no branch, drawn as an icon", async () => {
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 0bbea011b6..3746ee7c28 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -89,6 +89,11 @@ export interface RenderOptions {
* Without it, that content is read-only.
*/
attachmentEditor?: AttachmentEditor;
+ /**
+ * Saves the changes that interactive content makes to the note it shows, such as a code note.
+ * Without it, that content is read-only.
+ */
+ noteEditor?: NoteEditor;
}
/** Saves the changes that rendered content makes to attachments of the note that shows it. */
@@ -103,8 +108,27 @@ export interface AttachmentEditor {
release(attachmentId: string): void;
}
+/** Saves the changes that rendered content makes to the notes it shows. */
+export interface NoteEditor {
+ /** Whether the rendered content can change `note`. */
+ canEdit(note: FNote): boolean;
+ /** The content of the note that is not saved yet, or `undefined`. */
+ getUnsavedContent(noteId: string): string | undefined;
+ /** Schedules a save of `note`. The save reads the content from `getContent`. */
+ 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 media types of attached files, besides `text/*` and JSON, that show as code. */
+const ATTACHED_CODE_MIME_TYPES = new Set([
+ "application/javascript", "application/x-javascript", "application/x-sql"
+]);
+
/**
* The content types that an interactive `getRenderedContent()` previews; it shows any other as an
* icon, or as the actions of a file. Keep in step with the branches there.
@@ -140,7 +164,7 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo
} else if (type === "markdown") {
await renderMarkdown(entity, $renderedContent, options);
} else if (type === "code") {
- await renderCode(entity, $renderedContent);
+ await renderCode(entity, $renderedContent, options);
} else if (type === "iconPack" && !options.tooltip && entity instanceof FNote) {
await renderIconPack(entity, $renderedContent, options);
} else if (type === "canvasDrawing") {
@@ -272,13 +296,36 @@ async function renderIconPack(note: FNote, $renderedContent: JQuery<HTMLElement>
}
/**
- * Renders a code note, by displaying its content and applying syntax highlighting based on the selected MIME type.
+ * Renders a code note or file, by displaying its content and applying syntax highlighting based on
+ * the selected MIME type. Interactive content that an editor can save mounts `CodeEmbed`, which
+ * edits the content with CodeMirror while the Editable toggle of its embed is on.
*/
-async function renderCode(note: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>) {
- const blob = await note.getBlob();
+async function renderCode(
+ entity: FNote | FAttachment,
+ $renderedContent: JQuery<HTMLElement>,
+ options: RenderOptions
+) {
+ const editor = options.interactive ? getContentEditor(entity, options) : undefined;
+ const content = editor?.getUnsavedContent() ?? (await entity.getBlob())?.content ?? "";
+ const preview = await renderCodePreview(content, entity.mime);
+
+ if (!editor) {
+ $renderedContent.append(preview);
+ return;
+ }
- let content = blob?.content || "";
- if (note.mime === "application/json") {
+ const { default: CodeEmbed } = await import("../widgets/type_widgets/code/CodeEmbed");
+ const $container = $('<div class="code-embed">');
+ const container = $container.get(0);
+ if (container) {
+ await mountInteractiveWidget(h(CodeEmbed, { entity, editor, content, preview }), container);
+ }
+ $renderedContent.append($container);
+}
+
+/** The highlighted content of a code note or file, with JSON indented. */
+export async function renderCodePreview(content: string, mime: string) {
+ if (mime === "application/json") {
try {
content = JSON.stringify(JSON.parse(content), null, 4);
} catch (e) {
@@ -288,8 +335,45 @@ async function renderCode(note: FNote | FAttachment, $renderedContent: JQuery<HT
const $codeBlock = $("<code>");
$codeBlock.text(content);
- $renderedContent.append($("<pre>").append($codeBlock));
- await applySingleBlockSyntaxHighlight($codeBlock, normalizeMimeTypeForCKEditor(note.mime));
+ const $pre = $("<pre>").append($codeBlock);
+ await applySingleBlockSyntaxHighlight($codeBlock, normalizeMimeTypeForCKEditor(mime));
+ return $pre[0];
+}
+
+/** Saves the changes that rendered content makes to one note or attachment. */
+export interface ContentEditor {
+ /** Whether the rendered content can change the note or attachment. */
+ canEdit(): boolean;
+ getUnsavedContent(): string | undefined;
+ scheduleSave(getContent: () => string): void;
+ release(): void;
+ /** The component that saves the changes, for a note. */
+ componentId?: string;
+}
+
+/** The editor of `options` that saves the changes to `entity`, or `undefined`. */
+function getContentEditor(
+ entity: FNote | FAttachment,
+ options: RenderOptions
+): ContentEditor | undefined {
+ if (entity instanceof FAttachment) {
+ const editor = options.attachmentEditor;
+ return editor && {
+ canEdit: () => editor.canEdit(entity),
+ getUnsavedContent: () => editor.getUnsavedContent(entity.attachmentId),
+ scheduleSave: (getContent) => editor.scheduleSave(entity, getContent),
+ release: () => editor.release(entity.attachmentId)
+ };
+ }
+
+ const editor = options.noteEditor;
+ return editor && {
+ canEdit: () => editor.canEdit(entity),
+ getUnsavedContent: () => editor.getUnsavedContent(entity.noteId),
+ scheduleSave: (getContent) => editor.scheduleSave(entity, getContent),
+ release: () => editor.release(entity.noteId),
+ componentId: editor.componentId
+ };
}
async function renderImage(entity: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>, options: RenderOptions = {}) {
@@ -777,7 +861,7 @@ 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" : getFileContentType("file", mime);
+ const type = isAcceptedImageMime(mime) ? "image" : getAttachedFileContentType(mime);
return getBoxSize(type, PREVIEWED_TYPES.has(type));
}
@@ -820,7 +904,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 getFileContentType("file", entity.mime);
+ return getAttachedFileContentType(entity.mime);
}
// A link preview's "favicon" is a picture like any other as far as showing it goes; the
// role only says where it came from. Without this it would fall through to the unknown
@@ -828,7 +912,17 @@ function getContentType(entity: FNote | FAttachment) {
if (isImageAttachmentRole(entity.role)) {
return "image";
}
- return getFileContentType(entity.role, entity.mime);
+ return entity.role === "file"
+ ? getAttachedFileContentType(entity.mime)
+ : 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) {
+ const type = getFileContentType("file", mime);
+ return type === "file" && (mime.startsWith("text/") || ATTACHED_CODE_MIME_TYPES.has(mime))
+ ? "code"
+ : type;
}
/** Narrows a file, or a `viewConfig` attachment, to the kind of file its media type names. */
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.css b/apps/client/src/widgets/type_widgets/code/CodeEmbed.css
new file mode 100644
index 0000000000..99b32c8a69
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.css
@@ -0,0 +1,5 @@
+.include-note-content .code-embed-content {
+ pre.code-embed-editor {
+ padding: 0;
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
new file mode 100644
index 0000000000..f287acc37b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
@@ -0,0 +1,172 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type FNote from "../../../entities/fnote";
+import type { ContentEditor } from "../../../services/content_renderer";
+import options from "../../../services/options";
+import { buildNote } from "../../../test/easy-froca";
+import { ParentComponent } from "../../react/react_utils";
+import { getContentEmbedTools } from "../text/content_embed_tools";
+import CodeEmbed from "./CodeEmbed";
+
+vi.mock("../../../services/content_renderer", () => ({
+ renderCodePreview: async (content: string) => buildPreview(content)
+}));
+
+// `CodeEditor` reads the theme as a string.
+options.set("codeNoteTheme", "");
+
+const parent = { registerHandler() {}, removeHandler() {}, componentId: "embed-test" } as any;
+const figures: HTMLElement[] = [];
+
+afterEach(() => {
+ for (const figure of figures) {
+ const box = figure.querySelector(".include-note-content");
+ if (box) act(() => render(null, box));
+ figure.remove();
+ }
+ figures.length = 0;
+});
+
+describe("CodeEmbed", () => {
+ it("shows the preview, and offers the Editable toggle only where it can edit", async () => {
+ const note = buildCodeNote("print(1)");
+ const preview = buildPreview("print(1)");
+ const { figure } = await mount(note, buildEditor(), { preview });
+ expect(figure.querySelector(".code-embed-preview")?.firstChild).toBe(preview);
+ expect(getContentEmbedTools(figure)?.hasEditableFlag).toBe(true);
+
+ const { figure: locked } = await mount(note, buildEditor({ canEdit: () => false }));
+ expect(getContentEmbedTools(locked)).toBeNull();
+
+ const readOnly = buildNote({
+ title: "Fixed", type: "code", mime: "text/x-python", content: "", "#readOnly": ""
+ });
+ const { figure: fixed } = await mount(readOnly, buildEditor());
+ expect(getContentEmbedTools(fixed)).toBeNull();
+ });
+
+ it("edits with CodeMirror while the toggle is on, and saves only the changes", async () => {
+ const editor = buildEditor();
+ const { figure } = await mount(buildCodeNote("print(1)"), editor, { isEditable: true });
+
+ const view = await findView(figure);
+ expect(view.state.doc.toString()).toBe("print(1)");
+ expect(figure.querySelector(".code-embed-preview")).toBeNull();
+ expect(editor.scheduleSave).not.toHaveBeenCalled();
+
+ act(() => view.dispatch({ changes: { from: 0, insert: "# " } }));
+ expect(editor.scheduleSave).toHaveBeenCalledOnce();
+ const getContent = vi.mocked(editor.scheduleSave).mock.calls[0][0];
+ expect(getContent()).toBe("# print(1)");
+ });
+
+ it("releases the editor and previews the edited content once the toggle goes off", async () => {
+ const editor = buildEditor();
+ const { figure } = await mount(buildCodeNote("a"), editor, { isEditable: true });
+ const view = await findView(figure);
+ act(() => view.dispatch({ changes: { from: 1, insert: "b" } }));
+
+ await act(async () => {
+ delete figure.dataset.editable;
+ await Promise.resolve();
+ });
+
+ expect(editor.release).toHaveBeenCalledOnce();
+ await vi.waitFor(() => {
+ expect(figure.querySelector(".code-embed-preview")?.textContent).toBe("ab");
+ });
+ expect(figure.querySelector(".cm-editor")).toBeNull();
+ });
+
+ it("loads the note as saved elsewhere, unless it has unsaved changes", async () => {
+ const { figure } = await mount(buildCodeNote("saved"), buildEditor(), {
+ content: "stale",
+ isEditable: true
+ });
+ const view = await findView(figure);
+ await vi.waitFor(() => expect(view.state.doc.toString()).toBe("saved"));
+
+ const { figure: changed } = await mount(
+ buildCodeNote("saved"),
+ buildEditor({ getUnsavedContent: () => "unsaved" }),
+ { content: "unsaved", isEditable: true }
+ );
+ const changedView = await findView(changed);
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ expect(changedView.state.doc.toString()).toBe("unsaved");
+ });
+});
+
+interface MountOptions {
+ content?: string;
+ preview?: HTMLElement;
+ isEditable?: boolean;
+}
+
+/** Renders `CodeEmbed` in the markup of an embed, as the host does. */
+async function mount(note: FNote, editor: ContentEditor, options: MountOptions = {}) {
+ const content = options.content ?? "";
+ const figure = document.createElement("figure");
+ figure.className = "include-note";
+ if (options.isEditable) {
+ figure.dataset.editable = "true";
+ }
+ const box = document.createElement("div");
+ box.className = "include-note-content";
+ figure.append(box);
+ document.body.append(figure);
+ figures.push(figure);
+
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={parent}>
+ <CodeEmbed
+ entity={note}
+ editor={editor}
+ content={options.content ?? (await note.getBlob())?.content ?? content}
+ preview={options.preview ?? buildPreview(content)}
+ />
+ </ParentComponent.Provider>,
+ box
+ );
+ });
+ return { figure };
+}
+
+function buildCodeNote(content: string) {
+ return buildNote({ title: "Script", type: "code", mime: "text/x-python", content });
+}
+
+function buildEditor(overrides: Partial<ContentEditor> = {}): ContentEditor {
+ return {
+ canEdit: () => true,
+ getUnsavedContent: () => undefined,
+ scheduleSave: vi.fn(),
+ release: vi.fn(),
+ componentId: "host",
+ ...overrides
+ };
+}
+
+function buildPreview(content: string) {
+ const pre = document.createElement("pre");
+ pre.textContent = content;
+ return pre;
+}
+
+/** The CodeMirror view in `figure`, once the editor module has loaded. */
+async function findView(figure: HTMLElement) {
+ const { EditorView } = await import("@codemirror/view");
+ let view: InstanceType<typeof EditorView> | null = null;
+ await vi.waitFor(() => {
+ const dom = figure.querySelector(".cm-editor");
+ view = dom instanceof HTMLElement ? EditorView.findFromDOM(dom) : null;
+ expect(view).not.toBeNull();
+ }, { timeout: 5000 });
+ if (!view) throw new Error("CodeMirror did not mount.");
+ return view as InstanceType<typeof EditorView>;
+}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
new file mode 100644
index 0000000000..0452600644
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
@@ -0,0 +1,150 @@
+import "./CodeEmbed.css";
+
+import type { RefObject } from "preact";
+import { lazy, Suspense } from "preact/compat";
+import { useEffect, useLayoutEffect, 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 options from "../../../services/options";
+import { useNoteBlob, useNoteLabelBoolean, useNoteProperty } from "../../react/hooks";
+import {
+ type ContentEmbedToolProvider, registerContentEmbedTools, useIsContentEmbedEditable
+} from "../text/content_embed_tools";
+
+const CodeEmbedEditor = lazy(() => import("./CodeEmbedEditor"));
+
+interface CodeEmbedProps {
+ entity: FNote | FAttachment;
+ /** Saves the changes to `entity`. */
+ editor: ContentEditor;
+ /** The content shown first. */
+ content: string;
+ /** The highlighted `content`. */
+ preview: HTMLElement;
+}
+
+/**
+ * A code note or a code file in an embed, shown highlighted, and edited with CodeMirror while the
+ * Editable toggle of its embed is on.
+ */
+export default function CodeEmbed({
+ entity, editor, content: initialContent, preview
+}: CodeEmbedProps) {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const note = entity instanceof FNote ? entity : null;
+ const [ isNoteReadOnly ] = useNoteLabelBoolean(note, "readOnly");
+ const canEdit = editor.canEdit() && !isNoteReadOnly && !options.is("databaseReadonly");
+ const isEmbedEditable = useIsContentEmbedEditable(rootRef);
+ const isEditing = canEdit && isEmbedEditable;
+ const [ content, setContent ] = useState(initialContent);
+ const mime = useNoteProperty(note, "mime") ?? entity.mime;
+ useEditableFlag(rootRef, canEdit);
+ useChangesFromElsewhere(note, editor, setContent);
+ useFocusFromEmbedBox(rootRef, isEditing);
+
+ const isInitial = content === initialContent && mime === entity.mime;
+ const previewView = (
+ <CodePreview
+ content={content}
+ mime={mime}
+ initialPreview={isInitial ? preview : undefined}
+ />
+ );
+
+ return (
+ <div ref={rootRef} className="code-embed-content">
+ {isEditing ? (
+ <Suspense fallback={previewView}>
+ <CodeEmbedEditor
+ note={note}
+ editor={editor}
+ content={content}
+ mime={mime}
+ onClose={setContent}
+ />
+ </Suspense>
+ ) : previewView}
+ </div>
+ );
+}
+
+interface CodePreviewProps {
+ content: string;
+ mime: string;
+ /** The highlighted `content`, when it is rendered already. */
+ initialPreview?: HTMLElement;
+}
+
+/** The highlighted content. */
+function CodePreview({ content, mime, initialPreview }: CodePreviewProps) {
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ useLayoutEffect(() => {
+ if (initialPreview) {
+ containerRef.current?.replaceChildren(initialPreview);
+ return;
+ }
+
+ let isCurrent = true;
+ renderCodePreview(content, mime).then((preview) => {
+ if (isCurrent) {
+ containerRef.current?.replaceChildren(preview);
+ }
+ });
+ return () => {
+ isCurrent = false;
+ };
+ }, [ content, mime, initialPreview ]);
+
+ return <div ref={containerRef} className="code-embed-preview" />;
+}
+
+/** Gives the embed that contains `rootRef` its Editable toggle while `canEdit`. */
+function useEditableFlag(rootRef: RefObject<HTMLElement | null>, canEdit: boolean) {
+ useEffect(() => {
+ const root = rootRef.current;
+ if (!root || !canEdit) return;
+
+ return registerContentEmbedTools(root, EDITABLE_FLAG_PROVIDER);
+ }, [ rootRef, canEdit ]);
+}
+
+const EDITABLE_FLAG_PROVIDER: ContentEmbedToolProvider = {
+ hasEditableFlag: true,
+ getTools: () => [],
+ execute: () => {},
+ subscribe: () => () => {}
+};
+
+/**
+ * Shows the content that another component saves to `note`. Unsaved changes made in the embed
+ * are kept, and replace that content when they save.
+ */
+function useChangesFromElsewhere(
+ note: FNote | null,
+ editor: ContentEditor,
+ setContent: (content: string) => void
+) {
+ const blob = useNoteBlob(note, editor.componentId);
+
+ useEffect(() => {
+ if (blob && editor.getUnsavedContent() === undefined) {
+ setContent(blob.content);
+ }
+ }, [ blob ]);
+}
+
+/** Moves the focus into CodeMirror when the embed box around it takes the focus. */
+function useFocusFromEmbedBox(rootRef: RefObject<HTMLElement | null>, isEditing: boolean) {
+ useEffect(() => {
+ const root = rootRef.current;
+ const box = root?.closest<HTMLElement>(".include-note-content");
+ if (!root || !box || !isEditing) return;
+
+ const forwardFocus = () => root.querySelector<HTMLElement>(".cm-content")?.focus();
+ box.addEventListener("focus", forwardFocus);
+ return () => box.removeEventListener("focus", forwardFocus);
+ }, [ rootRef, isEditing ]);
+}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
new file mode 100644
index 0000000000..e587778f6d
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
@@ -0,0 +1,69 @@
+import type VanillaCodeMirror from "@triliumnext/codemirror";
+import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
+
+import type FNote from "../../../entities/fnote";
+import type { ContentEditor } from "../../../services/content_renderer";
+import {
+ useNoteLabelInt, useNoteLabelOptionalBool, useTriliumOptionBool
+} from "../../react/hooks";
+import { CodeEditor } from "./Code";
+
+export interface CodeEmbedEditorProps {
+ note: FNote | null;
+ editor: ContentEditor;
+ content: string;
+ mime: string;
+ /** Receives the edited content when the editor goes away. */
+ onClose: (content: string) => void;
+}
+
+/** CodeMirror over the content of a code embed, which `editor` saves as it changes. */
+export default function CodeEmbedEditor({
+ note, editor, content, mime, onClose
+}: CodeEmbedEditorProps) {
+ const viewRef = useRef<VanillaCodeMirror>(null);
+ const isLoadingRef = useRef(false);
+ const [ vimKeymapEnabled ] = useTriliumOptionBool("vimKeymapEnabled");
+ const [ noteTabWidth ] = useNoteLabelInt(note, "tabWidth");
+ const [ noteUseTabs ] = useNoteLabelOptionalBool(note, "indentWithTabs");
+ const [ noteWrapLines ] = useNoteLabelOptionalBool(note, "wrapLines");
+
+ // Runs after the effects of `CodeMirror`, which empties the document as it mounts.
+ useEffect(() => {
+ const view = viewRef.current;
+ if (!view || view.getText() === content) return;
+
+ // Loading changes the document as well, which must not schedule a save.
+ isLoadingRef.current = true;
+ view.setText(content);
+ isLoadingRef.current = false;
+ view.clearHistory();
+ }, [ content ]);
+
+ // A layout cleanup runs during the unmount, before CodeMirror is destroyed.
+ useLayoutEffect(() => () => {
+ const text = viewRef.current?.getText();
+ editor.release();
+ if (text !== undefined) {
+ onClose(text);
+ }
+ }, [ editor, onClose ]);
+
+ return (
+ <CodeEditor
+ ntxId={null}
+ editorRef={viewRef}
+ className="code-embed-editor"
+ mime={mime}
+ vimKeybindings={vimKeymapEnabled}
+ onContentChanged={() => {
+ if (!isLoadingRef.current) {
+ editor.scheduleSave(() => viewRef.current?.getText() ?? "");
+ }
+ }}
+ {...(noteTabWidth != null && { indentSize: noteTabWidth })}
+ {...(noteUseTabs != null && { useTabs: noteUseTabs })}
+ {...(noteWrapLines != null && { lineWrapping: noteWrapLines })}
+ />
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 5ebca5f7a9..04d7368c37 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -30,7 +30,7 @@ import { useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useSe
import IconPicker from "../../react/IconPicker";
import { setEditorNoteId } from "../../react/NoteStore";
import { TypeWidgetProps } from "../type_widget";
-import AttachmentSaves from "./attachment_saves";
+import AttachmentSaves, { useNoteEditor } from "./attachment_saves";
import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditorWithWatchdog";
import { getContentEmbedTools } from "./content_embed_tools";
import getTemplates, { updateTemplateCache } from "./snippets.js";
@@ -77,6 +77,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
const initialized = useRef(deferred<void>());
const [ attachmentSaves ] = useState(() =>
new AttachmentSaves(() => spacedUpdate.scheduleUpdate()));
+ const noteEditor = useNoteEditor(noteContext);
const spacedUpdate = useEditorSpacedUpdate({
note,
noteContext,
@@ -201,7 +202,9 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
editorApi: editorApiRef.current,
});
},
- loadEmbeddedNote,
+ loadEmbeddedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string) {
+ return loadEmbeddedNote(noteId, $el, boxSize, { noteEditor });
+ },
loadEmbeddedAttachment(attachmentId: string, $el: JQuery<HTMLElement>, boxSize?: string) {
const isFocused = focusedAttachmentIdRef.current === attachmentId;
if (isFocused) {
@@ -298,7 +301,7 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
useTriliumEvent("refreshEmbeddedNote", ({ noteId }) => {
if (!containerRef.current) return;
- refreshEmbeddedNote(containerRef.current, noteId);
+ refreshEmbeddedNote(containerRef.current, noteId, { noteEditor });
});
useEffect(() => () => stopWatchingEmbedsRef.current?.(), []);
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 157db4cfab..613c9b6cd6 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
@@ -6,13 +6,14 @@ import Component from "../../../components/component";
import type NoteContext from "../../../components/note_context";
import type FAttachment from "../../../entities/fattachment";
import type FNote from "../../../entities/fnote";
-import type { AttachmentEditor } from "../../../services/content_renderer";
+import type { AttachmentEditor, NoteEditor } from "../../../services/content_renderer";
import { ParentComponent } from "../../react/react_utils";
-import AttachmentSaves, { useAttachmentEditor } from "./attachment_saves";
+import AttachmentSaves, { NoteSaves, useAttachmentEditor, useNoteEditor } from "./attachment_saves";
const serverPost = vi.hoisted(() => vi.fn(async () => undefined));
+const serverPut = vi.hoisted(() => vi.fn(async () => undefined));
vi.mock("../../../services/server", () => ({
- default: { get: async () => [], post: serverPost }
+ default: { get: async () => [], post: serverPost, put: serverPut }
}));
const drawing = {
@@ -154,3 +155,77 @@ describe("useAttachmentEditor", () => {
expect(serverPost).toHaveBeenLastCalledWith(...savedRequest("second"));
});
});
+
+describe("NoteSaves", () => {
+ function buildCodeNote(noteId: string, overrides: Partial<FNote> = {}) {
+ return { noteId, type: "code", isContentAvailable: () => true, ...overrides } as FNote;
+ }
+
+ it("edits code notes whose content is available", () => {
+ const saves = new NoteSaves(vi.fn(), "host");
+
+ expect(saves.canEdit(buildCodeNote("code1"))).toBe(true);
+ expect(saves.canEdit(buildCodeNote("text1", { type: "text" }))).toBe(false);
+ expect(saves.canEdit(buildCodeNote("locked", { isContentAvailable: () => false })))
+ .toBe(false);
+ });
+
+ it("collects each note with its content, and keeps a change made while a save runs", () => {
+ const scheduleUpdate = vi.fn();
+ const saves = new NoteSaves(scheduleUpdate, "host");
+ const first = buildCodeNote("code1");
+ const second = buildCodeNote("code2");
+
+ saves.scheduleSave(first, () => "one");
+ saves.scheduleSave(second, () => "two");
+ const sent = saves.collect();
+ expect(sent).toStrictEqual([
+ { note: first, content: "one" },
+ { note: second, content: "two" }
+ ]);
+ expect(scheduleUpdate).toHaveBeenCalledTimes(2);
+
+ saves.scheduleSave(first, () => "changed meanwhile");
+ saves.markSaved(sent);
+ expect(saves.getUnsavedContent("code1")).toBe("changed meanwhile");
+ expect(saves.getUnsavedContent("code2")).toBeUndefined();
+ });
+});
+
+describe("useNoteEditor", () => {
+ const code = { noteId: "code1", type: "code", isProtected: false } as FNote;
+ const noteContext = { ntxId: "ntx1", setContextData: vi.fn() } as unknown as NoteContext;
+
+ let component: Component;
+ let editor: NoteEditor | undefined;
+ function Probe() {
+ editor = useNoteEditor(noteContext);
+ return null;
+ }
+
+ it("saves each note on its own, before the note switches and once it goes away", async () => {
+ component = new Component();
+ const container = document.createElement("div");
+ await act(() => {
+ render(h(ParentComponent.Provider, { value: component }, h(Probe, {})), container);
+ });
+ expect(editor?.componentId).toBe(component.componentId);
+
+ editor?.scheduleSave(code, () => "first");
+ await act(async () => {
+ await component.handleEvent("beforeNoteSwitch", { noteContext } as never);
+ });
+ expect(serverPut).toHaveBeenCalledExactlyOnceWith(
+ "notes/code1/data", { content: "first" }, component.componentId);
+ expect(editor?.getUnsavedContent("code1")).toBeUndefined();
+ expect(noteContext.setContextData)
+ .toHaveBeenLastCalledWith("saveState", { state: "saved" });
+
+ editor?.scheduleSave(code, () => "second");
+ editor?.release("code1");
+ await act(() => render(null, container));
+ expect(serverPut).toHaveBeenCalledTimes(2);
+ expect(serverPut).toHaveBeenLastCalledWith(
+ "notes/code1/data", { content: "second" }, component.componentId);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
index 906dbf864e..2a64f9817f 100644
--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
@@ -3,7 +3,7 @@ import { useCallback, useContext, useEffect, useRef, useState } from "preact/hoo
import type NoteContext from "../../../components/note_context";
import type FAttachment from "../../../entities/fattachment";
import type FNote from "../../../entities/fnote";
-import type { AttachmentEditor } from "../../../services/content_renderer";
+import type { AttachmentEditor, NoteEditor } from "../../../services/content_renderer";
import protected_session_holder from "../../../services/protected_session_holder";
import server from "../../../services/server";
import SpacedUpdate from "../../../services/spaced_update";
@@ -12,8 +12,13 @@ import { ParentComponent } from "../../react/react_utils";
type SavedAttachments = NonNullable<SavedData["attachments"]>;
-interface PendingSave {
- attachment: FAttachment;
+interface SavedNote {
+ note: FNote;
+ content: string;
+}
+
+interface PendingSave<T> {
+ entity: T;
/** Reads the content from the mounted editor. */
getContent?: () => string;
/** The content read when the editor went away. */
@@ -22,17 +27,73 @@ interface PendingSave {
revision: number;
}
+/**
+ * The content changes that wait for a save, by the ID of the note or attachment they change.
+ * `T` is the changed entity, and `I` the item that `collectItems()` builds for each change.
+ */
+abstract class PendingSaves<T, I extends object> {
+ protected pending = new Map<string, PendingSave<T>>();
+ private sentRevisions = new WeakMap<I[], Map<string, number>>();
+
+ getUnsavedContent(id: string) {
+ const save = this.pending.get(id);
+ return save ? readContent(save) : undefined;
+ }
+
+ release(id: string) {
+ const save = this.pending.get(id);
+ if (save?.getContent) {
+ save.content = save.getContent();
+ save.getContent = undefined;
+ }
+ }
+
+ /** Drops the changes that `items`, as returned by `collectItems()`, saved. */
+ markSaved(items: I[] | undefined) {
+ const revisions = items && this.sentRevisions.get(items);
+ if (!revisions) {
+ return;
+ }
+
+ for (const [ id, revision ] of revisions) {
+ if (this.pending.get(id)?.revision === revision) {
+ this.pending.delete(id);
+ }
+ }
+ }
+
+ protected schedule(id: string, entity: T, getContent: () => string) {
+ const revision = (this.pending.get(id)?.revision ?? 0) + 1;
+ this.pending.set(id, { entity, getContent, revision });
+ }
+
+ /** One item for each change, with the content read at the time of the call. */
+ protected collectItems(toItem: (id: string, entity: T, content: string) => I) {
+ const items: I[] = [];
+ const revisions = new Map<string, number>();
+ for (const [ id, save ] of this.pending) {
+ items.push(toItem(id, save.entity, readContent(save)));
+ revisions.set(id, save.revision);
+ }
+
+ this.sentRevisions.set(items, revisions);
+ return items;
+ }
+}
+
/**
* The attachment changes that content, such as a canvas drawing, makes. A text note saves them
* together with its own content, and `useAttachmentEditor()` saves them on their own.
*/
-export default class AttachmentSaves implements AttachmentEditor {
+export default class AttachmentSaves
+ extends PendingSaves<FAttachment, SavedAttachments[number]>
+ implements AttachmentEditor {
private noteId: string | undefined;
- private pending = new Map<string, PendingSave>();
- private sentRevisions = new WeakMap<SavedAttachments, Map<string, number>>();
/** @param scheduleUpdate schedules a save of the text note. */
- constructor(private scheduleUpdate: () => void) {}
+ constructor(private scheduleUpdate: () => void) {
+ super();
+ }
/** Sets the note whose attachments can change, and drops the changes to any other note. */
setNoteId(noteId: string | undefined) {
@@ -46,51 +107,47 @@ export default class AttachmentSaves implements AttachmentEditor {
return !!this.noteId && attachment.ownerId === this.noteId;
}
- getUnsavedContent(attachmentId: string) {
- const save = this.pending.get(attachmentId);
- return save ? readContent(save) : undefined;
- }
-
scheduleSave(attachment: FAttachment, getContent: () => string) {
- const revision = (this.pending.get(attachment.attachmentId)?.revision ?? 0) + 1;
- this.pending.set(attachment.attachmentId, { attachment, getContent, revision });
+ this.schedule(attachment.attachmentId, attachment, getContent);
this.scheduleUpdate();
}
- release(attachmentId: string) {
- const save = this.pending.get(attachmentId);
- if (save?.getContent) {
- save.content = save.getContent();
- save.getContent = undefined;
- }
- }
-
/** The attachments to save with the note, read at the time of the call. */
collect(): SavedAttachments {
- const attachments: SavedAttachments = [];
- const revisions = new Map<string, number>();
- for (const [ attachmentId, save ] of this.pending) {
- const { role, mime, title } = save.attachment;
- attachments.push({ attachmentId, role, mime, title, content: readContent(save) });
- revisions.set(attachmentId, save.revision);
- }
+ return this.collectItems((attachmentId, { role, mime, title }, content) => (
+ { attachmentId, role, mime, title, content }
+ ));
+ }
+}
- this.sentRevisions.set(attachments, revisions);
- return attachments;
+/**
+ * The changes that content embedded in a text note, such as a code note, makes to the notes it
+ * shows. `useNoteEditor()` saves them.
+ */
+export class NoteSaves extends PendingSaves<FNote, SavedNote> implements NoteEditor {
+ /**
+ * @param scheduleUpdate schedules a save.
+ * @param componentId the component that saves the changes.
+ */
+ constructor(
+ private scheduleUpdate: () => void,
+ readonly componentId: string | undefined
+ ) {
+ super();
}
- /** Drops the changes that `attachments`, as returned by `collect()`, saved. */
- markSaved(attachments: SavedAttachments | undefined) {
- const revisions = attachments && this.sentRevisions.get(attachments);
- if (!revisions) {
- return;
- }
+ canEdit(note: FNote) {
+ return note.type === "code" && note.isContentAvailable();
+ }
- for (const [ attachmentId, revision ] of revisions) {
- if (this.pending.get(attachmentId)?.revision === revision) {
- this.pending.delete(attachmentId);
- }
- }
+ scheduleSave(note: FNote, getContent: () => string) {
+ this.schedule(note.noteId, note, getContent);
+ this.scheduleUpdate();
+ }
+
+ /** The notes to save, read at the time of the call. */
+ collect() {
+ return this.collectItems((_noteId, note, content) => ({ note, content }));
}
}
@@ -137,17 +194,55 @@ export function useAttachmentEditor(
});
useSaveBeforeLeaving(spacedUpdate, noteContext);
+ useSaveOnUnmount(spacedUpdate);
+
+ return saves;
+}
+
+/**
+ * Saves the changes that content embedded in the note of `noteContext`, such as a code note,
+ * makes to the notes it shows. Each note saves with a request of its own.
+ */
+export function useNoteEditor(noteContext: NoteContext | null | undefined): NoteEditor {
+ const parentComponent = useContext(ParentComponent);
+ const [ saves ] = useState(() => new NoteSaves(
+ () => spacedUpdate.scheduleUpdate(),
+ parentComponent?.componentId
+ ));
+ const noteContextRef = useRef(noteContext);
+ noteContextRef.current = noteContext;
+
+ const [ spacedUpdate ] = useState(() => new SpacedUpdate<SavedNote[]>(
+ {
+ key: null,
+ prepare: () => saves.collect(),
+ commit: async (notes) => {
+ for (const { note, content } of notes) {
+ protected_session_holder.touchProtectedSessionIfNecessary(note);
+ await server.put(`notes/${note.noteId}/data`, { content }, saves.componentId);
+ }
+ saves.markSaved(notes);
+ }
+ },
+ undefined,
+ (state) => noteContextRef.current?.setContextData("saveState", { state })
+ ));
+
+ useSaveBeforeLeaving(spacedUpdate, noteContext);
+ useSaveOnUnmount(spacedUpdate);
- // Saves what is left once the content goes away.
+ return saves;
+}
+
+/** Saves what is left once the content goes away. */
+function useSaveOnUnmount<T>(spacedUpdate: SpacedUpdate<T>) {
useEffect(() => () => {
spacedUpdate.updateNowIfNecessary().catch(() => {
// Failures are logged by `SpacedUpdate` and retried.
});
}, [ spacedUpdate ]);
-
- return saves;
}
-function readContent(save: PendingSave) {
+function readContent<T>(save: PendingSave<T>) {
return save.getContent ? save.getContent() : save.content ?? "";
}
diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.ts
index a4d44880c2..4f714a5e41 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.ts
@@ -4,7 +4,9 @@ import { h, type JSX } from "preact";
import appContext from "../../../components/app_context";
import linkContextMenu from "../../../menus/link_context_menu";
-import content_renderer, { type AttachmentEditor } from "../../../services/content_renderer";
+import content_renderer, {
+ type AttachmentEditor, type NoteEditor
+} from "../../../services/content_renderer";
import { getEmbedCaption } from "../../../services/content_renderer_text";
import froca from "../../../services/froca";
import link, { ViewScope } from "../../../services/link";
@@ -12,11 +14,21 @@ import utils from "../../../services/utils";
import { watchContentEmbedTools } from "./content_embed_tools";
import ContentEmbed, { getNoteActions, TinyContentEmbed } from "./ContentEmbed";
+interface EmbeddedNoteOptions {
+ /** Saves the changes that the content makes to the note, such as a code note. */
+ noteEditor?: NoteEditor;
+}
+
/**
* Fills an embed box with a note. Without a box size of its own, the box takes the one of its
* embed.
*/
-export async function loadEmbeddedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string) {
+export async function loadEmbeddedNote(
+ noteId: string,
+ $el: JQuery<HTMLElement>,
+ boxSize?: string,
+ { noteEditor }: EmbeddedNoteOptions = {}
+) {
const note = await froca.getNote(noteId);
if (!note) return;
@@ -47,7 +59,8 @@ export async function loadEmbeddedNote(noteId: string, $el: JQuery<HTMLElement>,
const { $renderedContent, type } = await content_renderer.getRenderedContent(note, {
interactive: true,
embedsAsReferenceLinks: true,
- mediaEnvironment: "embedded"
+ mediaEnvironment: "embedded",
+ noteEditor
});
const box = h(ContentEmbed, {
@@ -224,10 +237,14 @@ function disposeRemoved(records: MutationRecord[]) {
}
}
-export function refreshEmbeddedNote(container: HTMLDivElement, noteId: string) {
+export function refreshEmbeddedNote(
+ container: HTMLDivElement,
+ noteId: string,
+ options?: EmbeddedNoteOptions
+) {
const embeddedNotes = container.querySelectorAll(`.include-note[data-note-id="${noteId}"]`);
for (const embeddedNote of embeddedNotes) {
- loadEmbeddedNote(noteId, $(embeddedNote as HTMLElement));
+ loadEmbeddedNote(noteId, $(embeddedNote as HTMLElement), undefined, options);
}
}
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
index 320b29ee67..82cdf6b9bb 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html
@@ -66,7 +66,10 @@
<h2>Embedding an attachment</h2>
<p>An attachment can be shown in the text instead of linked, the way&nbsp;<a
class="reference-link" href="#root/_help_nBAXQFj20hS1">Include Note</a>&nbsp;shows
- a note: a picture is displayed, and a PDF, a video or a document is previewed.</p>
+ a note: a picture is displayed, a PDF, a video or a document is previewed,
+ and a code or text file is shown with syntax highlighting. An embedded
+ code file can also be edited in place (see <em>Included code</em> in <a class="reference-link"
+ href="#root/_help_nBAXQFj20hS1">Include Note</a>).</p>
<ul>
<li>To attach files and embed them straight away, select <em>Attach and embed file</em> from
the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> <em>Attach file</em> button.
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.html
index e6a93c7228..608bc13f56 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
@@ -33,7 +33,7 @@
<li><em>Tiny</em> for a note or an attachment that has no preview, such as
a relation map or an archive.</li>
<li><em>Small</em> for audio.</li>
- <li><em>Full</em> for a code note.</li>
+ <li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment.</li>
<li><em>Medium</em> for anything else.</li>
</ul>
<p>The dialog that includes a note selects that size once the note is picked,
@@ -100,9 +100,9 @@
<p>In a note being edited, the menu also has the commands of the include's
toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>,
each checked while it is in effect, and <em>Convert to link</em> at the end.
- A drawing canvas also has <em>Editable</em>, above <em>Size</em>. For an
- embedded attachment they follow its first group of actions; for an included
- note they end the menu.</p>
+ A drawing canvas, an included code note and an embedded code file also
+ have <em>Editable</em>, above <em>Size</em>. For an embedded attachment they
+ follow its first group of actions; for an included note they end the menu.</p>
<p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen,
press the <span class="tn-icon bx bx-fullscreen"></span> <em>Fullscreen</em> button
at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> <em>Exit fullscreen</em> in
@@ -159,6 +159,25 @@
</ul>
<p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fit
the height of the box. In fullscreen, it fits the screen.</p>
+<h2>Included code</h2>
+<p>An included code note, or an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment,
+ is shown with syntax highlighting. It can also be edited in place, in the
+ same code editor as a <a class="reference-link" href="#root/_help_6f9hih2hXXZk">Code</a> note.</p>
+<ul>
+ <li>To edit the code, select the include and turn on the <span class="tn-icon bx bx-edit-alt"></span> <em>Editable</em> button
+ at the start of its toolbar, or check <em>Editable</em> in its <span class="tn-icon cke cke-three-vertical-dots"></span> <em>More actions</em> menu.
+ The highlighted code is replaced by the code editor, which follows the
+ theme, indentation and line wrapping settings of code notes. Turn <em>Editable</em> off
+ to return to the highlighted view.</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>A new include starts with <em>Editable</em> off.</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 attachment
+ of another note.</li>
+ <li>A change saved elsewhere, for example in the note's own tab, is shown
+ in the include unless the include has changes of its own still being saved.</li>
+</ul>
<h2>Drawing canvases</h2>
<p>A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-link"
href="#root/_help_grjYqerjn243">Canvas</a> note, drawn directly in the text
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
index e1e742e3dd..f4f61ab04c 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md
@@ -37,7 +37,7 @@ Links follow changes to their attachment: renaming it updates the title they sho
## Embedding an attachment
-An attachment can be shown in the text instead of linked, the way <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a> shows a note: a picture is displayed, and a PDF, a video or a document is previewed.
+An attachment can be shown in the text instead of linked, the way <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a> shows a note: a picture is displayed, a PDF, a video or a document is previewed, and a code or text file is shown with syntax highlighting. An embedded code file can also be edited in place (see _Included code_ in <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a>).
* To attach files and embed them straight away, select _Attach and embed file_ from the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. Each file gets an embed of its own, which shows the file name while the file uploads.
* To embed an attachment that is already linked, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu.
diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
index 6930fd61e3..5762837445 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
@@ -24,7 +24,7 @@ A new include gets the size that suits what it shows:
* _Tiny_ for a note or an attachment that has no preview, such as a relation map or an archive.
* _Small_ for audio.
-* _Full_ for a code note.
+* _Full_ for a code note or a code file, such as a `.js`, `.py` or `.txt` attachment.
* _Medium_ for anything else.
The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the _Box size_ menu in its toolbar, or the _Size_ submenu of its _More actions_ menu.
@@ -64,7 +64,7 @@ To open an included note in a new tab, press the <span class="tn-icon bx bx-link
The <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.
-In a note being edited, the menu also has the commands of the include's toolbar: the _Size_ submenu, _Show title_ and _Show caption_, each checked while it is in effect, and _Convert to link_ at the end. A drawing canvas also has _Editable_, above _Size_. For an embedded attachment they follow its first group of actions; for an included note they end the menu.
+In a note being edited, the menu also has the commands of the include's toolbar: the _Size_ submenu, _Show title_ and _Show caption_, each checked while it is in effect, and _Convert to link_ at the end. A drawing canvas, an included code note and an embedded code file also have _Editable_, above _Size_. For an embedded attachment they follow its first group of actions; for an included note they end the menu.
To show an include of size _Medium_ or _Full_ on the whole screen, press the <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_ button at the end of its title. To return, press <span class="tn-icon bx bx-exit"></span> _Exit fullscreen_ in the top-right corner, or <kbd>Esc</kbd>.
@@ -102,6 +102,16 @@ An included image, whether an image note or an image attachment, is shown in the
In a _Small_ or _Medium_ box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.
+## Included code
+
+An included code note, or an embedded code file such as a `.js`, `.py` or `.txt` attachment, is shown with syntax highlighting. It can also be edited in place, in the same code editor as a <a class="reference-link" href="../Code.md">Code</a> note.
+
+* To edit the code, select the include and turn on the <span class="tn-icon bx bx-edit-alt"></span> _Editable_ button at the start of its toolbar, or check _Editable_ in its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu. The highlighted code is replaced by the code editor, which follows the theme, indentation and line wrapping settings of code notes. Turn _Editable_ off to return to the highlighted view.
+* The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.
+* A new include starts with _Editable_ off.
+* 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.
+* A change saved elsewhere, for example in the note's own tab, is shown in the include unless the include has changes of its own still being saved.
+
## Drawing canvases
A drawing canvas is an Excalidraw canvas, like the one of a <a class="reference-link" href="../Canvas.md">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a `Canvas.excalidraw` [attachment](../../Basic%20Concepts%20and%20Features/Notes/Attachments.md) of the text note and is saved together with the text.