Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/content embed: allow the caret to move between editable content embeds and the host text notes

Adorian Dorandeb33b8e6c8a
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
index f135308f2c..96535757d8 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
@@ -53,6 +53,7 @@ export default function CodeEmbed({
rootRef={rootRef}
className="code-embed-content"
isEditing={isEditing}
+ hasCaretNavigation
preview={shownPreview}
>
<CodeEmbedEditor
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
index e587778f6d..7d1221ac26 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
@@ -6,6 +6,7 @@ import type { ContentEditor } from "../../../services/content_renderer";
import {
useNoteLabelInt, useNoteLabelOptionalBool, useTriliumOptionBool
} from "../../react/hooks";
+import { useEmbedCaretNavigation } from "../text/editable_embed";
import { CodeEditor } from "./Code";
export interface CodeEmbedEditorProps {
@@ -27,6 +28,7 @@ export default function CodeEmbedEditor({
const [ noteTabWidth ] = useNoteLabelInt(note, "tabWidth");
const [ noteUseTabs ] = useNoteLabelOptionalBool(note, "indentWithTabs");
const [ noteWrapLines ] = useNoteLabelOptionalBool(note, "wrapLines");
+ useEmbedCaretNavigation(() => viewRef.current);
// Runs after the effects of `CodeMirror`, which empties the document as it mounts.
useEffect(() => {
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index c77f8fea3c..404399f16a 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -41,7 +41,7 @@ import { convertImageToDrawing } from "../canvas/image_to_drawing";
import { TypeWidgetProps } from "../type_widget";
import AttachmentSaves, { useNoteEditor } from "./attachment_saves";
import CKEditor, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditor";
-import { getContentEmbedTools } from "./content_embed_tools";
+import { enterContentEmbed, getContentEmbedTools } from "./content_embed_tools";
import { useEmbedEditors } from "./editable_embed";
import getTemplates, { updateTemplateCache } from "./snippets.js";
import linkEmbedService from "../../../services/link_embed";
@@ -319,6 +319,7 @@ export default function EditableText({
copyBlockReference: () => copyReference(),
copyTabReference: () => void copyReference(copyTabReference),
getContentEmbedTools,
+ enterContentEmbed,
// Link preview functionality. The insert flow itself lives in the editor (a balloon form),
// so the host only has to supply the metadata and the rendering.
async fetchLinkMetadata(url: string) {
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
index d0d9ebe7da..c964159df8 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.tsx
@@ -55,6 +55,7 @@ export default function TextEmbed({
rootRef={rootRef}
className="text-embed-content"
isEditing={isEditing}
+ hasCaretNavigation
preview={shownPreview}
>
<TextEmbedEditor
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
index c3d666eed5..c0198d2081 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
@@ -12,7 +12,9 @@ import {
import { SaveStatusBadge } from "../../layout/NoteBadges";
import { useLegacyComponentElement, useNoteContext } from "../../react/hooks";
import EditableText, { getBlockData } from "./EditableText";
-import { findTextEditorIn, NestedEmbedContext, useEmbedBadgeSlot } from "./editable_embed";
+import {
+ findTextEditorIn, NestedEmbedContext, useEmbedBadgeSlot, useEmbedCaretNavigation
+} from "./editable_embed";
import { getClosingSave, trackClosingSave } from "./TextEmbed";
interface TextEmbedEditorProps {
@@ -50,6 +52,9 @@ export default function TextEmbedEditor({
floatingToolbar: !hasFixedToolbar,
skipRecentNotes: true
});
+ useEmbedCaretNavigation(() => (
+ findTextEditorIn(rootRef.current)?.plugins.get("ContentEmbedCaret")
+ ));
// 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/content_embed_tools.ts b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts
index c493aea5d9..27d3562891 100644
--- a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts
+++ b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts
@@ -1,3 +1,4 @@
+import type { EmbedEdge } from "@triliumnext/ckeditor5";
import type { RefObject } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
@@ -53,8 +54,15 @@ export interface ContentEmbedToolProvider {
*/
export type ContentEmbedEvent = "fullscreenChangeStart" | "enterFullscreen" | "leaveFullscreen";
+/** The editor in an embed, as the caret of the text editor around the embed enters it. */
+export interface EmbedCaretTarget {
+ /** Focuses the editor with the caret at `edge` of its content, and returns whether it did. */
+ enter(edge: EmbedEdge): boolean;
+}
+
const providers = new Map<HTMLElement, ContentEmbedToolProvider>();
const watchers = new Set<{ container: HTMLElement; callback: () => void }>();
+const caretTargets = new Map<HTMLElement, EmbedCaretTarget>();
/**
* Adds the buttons of `provider` to the toolbar of the embed that contains `element`, until the
@@ -95,6 +103,30 @@ export function getContentEmbedTools(embed: HTMLElement) {
return null;
}
+/**
+ * Lets the caret of the text editor around the embed that contains `element` enter `target`, until
+ * the returned function is called.
+ */
+export function registerEmbedCaretTarget(element: HTMLElement, target: EmbedCaretTarget) {
+ caretTargets.set(element, target);
+ return () => {
+ caretTargets.delete(element);
+ };
+}
+
+/**
+ * Focuses the editor that `embed` shows, with the caret at `edge` of its content. Returns `false`
+ * when `embed` shows no editor that takes the caret.
+ */
+export function enterContentEmbed(embed: HTMLElement, edge: EmbedEdge) {
+ for (const [ element, target ] of caretTargets) {
+ if (embed.contains(element)) {
+ return target.enter(edge);
+ }
+ }
+ return false;
+}
+
function notifyWatchers(element: HTMLElement) {
for (const { container, callback } of watchers) {
if (container.contains(element)) {
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 20b2ceacf4..de99e3d47e 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
@@ -1,4 +1,5 @@
-import { render } from "preact";
+import type { EmbedEdge } from "@triliumnext/ckeditor5";
+import { createRef, render } from "preact";
import { useRef } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -6,10 +7,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { ContentEditor } from "../../../services/content_renderer";
import options from "../../../services/options";
import { buildNote } from "../../../test/easy-froca";
-import { type ContentEmbedToolProvider, getContentEmbedTools } from "./content_embed_tools";
import {
- type EditableEmbedOptions, NestedEmbedContext, useEditableEmbed, useEmbedEditors,
- useEmbedPreview, useNestedEditor
+ type ContentEmbedToolProvider, enterContentEmbed, getContentEmbedTools
+} from "./content_embed_tools";
+import {
+ EditableEmbedContent, type EditableEmbedOptions, type EmbeddedCaretEditor, NestedEmbedContext,
+ useEditableEmbed, useEmbedCaretNavigation, useEmbedEditors, useEmbedPreview, useNestedEditor
} from "./editable_embed";
const figures: HTMLElement[] = [];
@@ -211,11 +214,134 @@ describe("useNestedEditor", () => {
});
});
+describe("useEmbedCaretNavigation", () => {
+ it("lets the caret enter an editor with caret navigation, unless its content is hidden", () => {
+ const editor = buildCaretEditor(null);
+ const { figure, unmount } = mountCaretProbe(editor);
+
+ expect(enterContentEmbed(figure, "end")).toBe(true);
+ expect(editor.focusAt).toHaveBeenCalledExactlyOnceWith("end");
+
+ figure.hidden = true;
+ expect(enterContentEmbed(figure, "start")).toBe(false);
+ figure.hidden = false;
+
+ unmount();
+ expect(enterContentEmbed(figure, "start")).toBe(false);
+ expect(editor.focusAt).toHaveBeenCalledOnce();
+
+ const notReady = mountCaretProbe(null);
+ expect(enterContentEmbed(notReady.figure, "start")).toBe(false);
+ notReady.unmount();
+ });
+
+ it("leaves through the text editor around the embed, at the edge the editor reports", () => {
+ const editor = buildCaretEditor("end");
+ const { figure, leaveEmbed, pressKey, unmount } = mountCaretProbe(editor);
+ const onKeyDown = vi.fn();
+ figure.addEventListener("keydown", onKeyDown);
+
+ expect(pressKey()).toBe(true);
+ expect(leaveEmbed).toHaveBeenCalledExactlyOnceWith(
+ figure.querySelector(".caret-content"), "end"
+ );
+ expect(onKeyDown).not.toHaveBeenCalled();
+
+ leaveEmbed.mockReturnValue(false);
+ expect(pressKey()).toBe(false);
+ editor.getEdgeLeftBy.mockReturnValue(null);
+ expect(pressKey()).toBe(false);
+ expect(leaveEmbed).toHaveBeenCalledTimes(2);
+ expect(onKeyDown).toHaveBeenCalledTimes(2);
+ unmount();
+
+ const outside = mountCaretProbe(buildCaretEditor("end"), { hasHost: false });
+ expect(outside.pressKey()).toBe(false);
+ outside.unmount();
+ });
+
+ it("does nothing in an embed without caret navigation", () => {
+ const editor = buildCaretEditor("end");
+ const { figure, pressKey, unmount } =
+ mountCaretProbe(editor, { hasCaretNavigation: false });
+
+ expect(enterContentEmbed(figure, "start")).toBe(false);
+ expect(pressKey()).toBe(false);
+ expect(editor.getEdgeLeftBy).not.toHaveBeenCalled();
+ unmount();
+ });
+});
+
interface ProbeState {
canEdit: boolean;
isEditing: boolean;
}
+interface CaretProbeOptions {
+ hasCaretNavigation?: boolean;
+ /** Whether a text editor with the `ContentEmbedCaret` plugin is around the embed. */
+ hasHost?: boolean;
+}
+
+/**
+ * Renders an editor that uses `useEmbedCaretNavigation()` in an embed, as the content of an
+ * `EditableEmbedContent` in the editable of a text editor.
+ */
+function mountCaretProbe(
+ editor: EmbeddedCaretEditor | null,
+ { hasCaretNavigation = true, hasHost = true }: CaretProbeOptions = {}
+) {
+ const leaveEmbed = vi.fn((_element: HTMLElement, _edge: string) => true);
+ const host = buildEditable({
+ editor: { plugins: { has: () => hasHost, get: () => ({ leaveEmbed }) } }
+ });
+ const figure = document.createElement("figure");
+ figure.className = "include-note";
+ host.append(figure);
+ document.body.append(host);
+
+ function Probe() {
+ useEmbedCaretNavigation(() => editor);
+ return <div className="caret-editor" tabIndex={-1} />;
+ }
+ act(() => render(
+ <EditableEmbedContent
+ rootRef={createRef()}
+ className="caret-content"
+ isEditing
+ hasCaretNavigation={hasCaretNavigation}
+ preview={document.createElement("div")}
+ >
+ <Probe />
+ </EditableEmbedContent>,
+ figure
+ ));
+
+ return {
+ figure,
+ leaveEmbed,
+ /** Presses an arrow key in the editor, and returns whether a listener prevented it. */
+ pressKey() {
+ const event = new KeyboardEvent("keydown", {
+ key: "ArrowDown", bubbles: true, cancelable: true
+ });
+ figure.querySelector(".caret-editor")?.dispatchEvent(event);
+ return event.defaultPrevented;
+ },
+ unmount() {
+ act(() => render(null, figure));
+ host.remove();
+ }
+ };
+}
+
+function buildCaretEditor(edge: EmbedEdge | null) {
+ return {
+ focusAt: vi.fn(),
+ getEdgeLeftBy: vi.fn((_event: KeyboardEvent): EmbedEdge | null => edge)
+ };
+}
+
/** Renders a component that uses `useEditableEmbed()`, in the markup of an embed. */
async function mountProbe(
embedOptions: EditableEmbedOptions,
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 44504aa844..d2243b6c55 100644
--- a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx
@@ -1,4 +1,4 @@
-import type { CKTextEditor } from "@triliumnext/ckeditor5";
+import type { CKTextEditor, EmbedEdge } from "@triliumnext/ckeditor5";
import { type ComponentChildren, createContext, type RefObject } from "preact";
import { Suspense } from "preact/compat";
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
@@ -8,7 +8,8 @@ import type { ContentEditor } from "../../../services/content_renderer";
import options from "../../../services/options";
import { useNoteLabelBoolean } from "../../react/hooks";
import {
- type ContentEmbedToolProvider, registerContentEmbedTools, useIsContentEmbedEditable
+ type ContentEmbedToolProvider, registerContentEmbedTools, registerEmbedCaretTarget,
+ useIsContentEmbedEditable
} from "./content_embed_tools";
/**
@@ -68,6 +69,11 @@ interface EditableEmbedContentProps {
rootRef: RefObject<HTMLDivElement | null>;
className: string;
isEditing: boolean;
+ /**
+ * Whether the arrow keys move the caret between the editor and the text editor around the
+ * embed. The editor opts in with `useEmbedCaretNavigation()`.
+ */
+ hasCaretNavigation?: boolean;
/** The rendered content, shown while the content is not edited. */
preview: HTMLElement;
/** The editor, loaded on demand, which replaces the preview while `isEditing`. */
@@ -76,17 +82,78 @@ interface EditableEmbedContentProps {
/** The content of an embed: its preview, replaced by its editor while it is edited. */
export function EditableEmbedContent({
- rootRef, className, isEditing, preview, children
+ rootRef, className, isEditing, hasCaretNavigation, preview, children
}: EditableEmbedContentProps) {
const previewView = <EmbedPreview element={preview} />;
return (
<div ref={rootRef} className={className}>
- {isEditing ? <Suspense fallback={previewView}>{children}</Suspense> : previewView}
+ {isEditing ? (
+ <CaretNavigationContext.Provider value={hasCaretNavigation ? rootRef : null}>
+ <Suspense fallback={previewView}>{children}</Suspense>
+ </CaretNavigationContext.Provider>
+ ) : previewView}
</div>
);
}
+/**
+ * An editor in an embed that the caret enters from the text editor around the embed, and leaves,
+ * with the arrow keys. The `ContentEmbedCaret` plugin of a text editor and `CodeMirror` are ones.
+ */
+export interface EmbeddedCaretEditor {
+ /** Focuses the editor with the caret at `edge` of its content. */
+ focusAt(edge: EmbedEdge): void;
+ /**
+ * The edge of the content that the arrow key of `event` moves the caret past, or `null` for
+ * any other key and while the caret stays in the content.
+ */
+ getEdgeLeftBy(event: KeyboardEvent): EmbedEdge | null;
+}
+
+/**
+ * Lets the arrow keys move the caret between `getEditor()`, the editor of an embed, and the text
+ * editor around the embed, while its `EditableEmbedContent` has `hasCaretNavigation`.
+ * `getEditor()` returns `null` while the editor is not ready.
+ */
+export function useEmbedCaretNavigation(
+ getEditor: () => EmbeddedCaretEditor | null | undefined
+) {
+ const rootRef = useContext(CaretNavigationContext);
+ const getEditorRef = useRef(getEditor);
+ getEditorRef.current = getEditor;
+
+ useEffect(() => {
+ const root = rootRef?.current;
+ if (!root) return;
+
+ // The capture phase runs before the editor handles the key.
+ const onKeyDown = (event: KeyboardEvent) => {
+ const edge = getEditorRef.current()?.getEdgeLeftBy(event);
+ if (edge && leaveContentEmbed(root, edge)) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ };
+ root.addEventListener("keydown", onKeyDown, { capture: true });
+ const unregister = registerEmbedCaretTarget(root, {
+ enter(edge) {
+ const editor = getEditorRef.current();
+ // A collapsed Expandable embed hides its content, so the caret steps over it.
+ if (!editor || root.closest("[hidden]")) return false;
+
+ editor.focusAt(edge);
+ return true;
+ }
+ });
+
+ return () => {
+ root.removeEventListener("keydown", onKeyDown, { capture: true });
+ unregister();
+ };
+ }, [ rootRef ]);
+}
+
/**
* 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.
@@ -211,6 +278,9 @@ type EditorRootElement = HTMLElement & { ckeditorInstance?: CKTextEditor };
const EDITOR_ROOT_SELECTOR = ".ck-editor__editable:not(.ck-editor__nested-editable)";
+/** The content box of an embed whose editor has caret navigation, or `null`. */
+const CaretNavigationContext = createContext<RefObject<HTMLElement | null> | null>(null);
+
const EDITABLE_FLAG_TOOLS: ContentEmbedToolProvider = {
hasEditableFlag: true,
getTools: () => [],
@@ -218,6 +288,16 @@ const EDITABLE_FLAG_TOOLS: ContentEmbedToolProvider = {
subscribe: () => () => {}
};
+/**
+ * Puts the caret of the text editor around `element` beside its embed, past `edge`. Returns
+ * `false` when `element` is in no embed of a text editor.
+ */
+function leaveContentEmbed(element: HTMLElement, edge: EmbedEdge) {
+ const editor = findTextEditorAround(element);
+ return !!editor?.plugins.has("ContentEmbedCaret")
+ && editor.plugins.get("ContentEmbedCaret").leaveEmbed(element, edge);
+}
+
function EmbedPreview({ element }: { element: HTMLElement }) {
const containerRef = useRef<HTMLDivElement>(null);
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index 6a4c01d697..5a96e60c0c 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -134,7 +134,7 @@
"_help_0Ofbk1aSuVRu": "<figure class=\"image image-style-align-right image_resized\" style=\"width:50.47%;\"><img style=\"aspect-ratio:880/553;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Images/Image%20references_image.png\" width=\"880\" height=\"553\"></figure><p>Image references are an easy way to embed the preview of another note type into a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note.</p><h2>Supported note types</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a></li><li><a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a></li><li><a class=\"reference-link\" href=\"#root/_help_gBbsAeiuUxI5\">Mind Map</a></li></ul><h2>Steps</h2><ol><li>Go to one of the supported notes (listed above) and look for the&nbsp;<span class=\"tn-icon bx bx-copy\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>&nbsp;area.</li><li>Go to a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note and use the Paste function to insert the reference to that note.</li></ol><h2>Interaction</h2><ul><li>Double-clicking an image reference from a text note will automatically open the target note.</li><li>Clicking an image reference while <kbd>Ctrl</kbd> is pressed will open the target note in a new tab.</li><li>Modifying the target note should also update the image reference. If that doesn't happen, consider&nbsp;<a class=\"reference-link\" href=\"#root/_help_s8alTXmpFR61\">Refreshing the application</a>.</li></ul>",
"_help_VRoP0g1uHHc2": "<figure class=\"image image-style-align-center image_resized\" style=\"width:76.29%;\"><img style=\"aspect-ratio:1479/865;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/In-editor%20AI%20assistant_image.png\" width=\"1479\" height=\"865\"></figure><p>The AI assistant works on the text you are already writing: select a passage and have it rewritten, translated or turned into a table, or ask for new content at the cursor. Unlike the <a href=\"#root/_help_LrKznOtw9cQD\">AI chat</a>, it does not open a conversation window, the result is previewed in place and only enters the note when you accept it.</p><h2>Requirements</h2><p>The assistant is only available once at least one provider is configured in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, with at least one model selected for it. Until then the toolbar entry is not shown at all.</p><h2>Accessing the AI assistant</h2><p>To access the AI assistant:</p><ul><li>Look for the&nbsp;<span class=\"tn-icon cke cke-trilium-ai\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. Press the button itself to enter the <em>Ask AI</em> mode or press the arrow key next to it to access the quick commands and the model selection.</li><li>Look for <em>AI assistant</em> or any of the <em>AI</em>-prefixed quick commands in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</li><li>Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd>.</li><li>Select a text and choose the <em>AI assistant</em> option in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_jcQVxzYybYgz\">Note contextual menu</a>.</li></ul><h2>What the assistant works on</h2><figure class=\"table\"><table><thead><tr><th>Situation</th><th>What is sent</th></tr></thead><tbody><tr><td>Text is selected</td><td>The selection.</td></tr><tr><td>Nothing is selected, and you pick a quick action</td><td>The paragraph the cursor is in.</td></tr><tr><td>Nothing is selected, and you type your own prompt</td><td>Nothing, the response is new content written at the cursor.</td></tr></tbody></table></figure><p>In all cases the assistant also sends the text before and after the target, so that the model can tell what it is writing into: asked to <em>Continue writing</em> or to summarize, a model that can only see the selected words is guessing at the document around them. This surrounding text is context only, it is never rewritten.</p><aside class=\"admonition important\"><p>That means a single run sends more than the passage you highlighted. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_cRRrdZjgyhNc\">Privacy</a>&nbsp;for exactly what leaves your machine.</p></aside><h2>Quick actions</h2><p>The arrow beside the toolbar button opens a menu of ready-made instructions, grouped by what they do.</p><ul><li>The <em>Reformat</em> actions produce real Trilium content rather than plain text: <em>Diagram</em> inserts a Mermaid diagram, <em>Callout</em> an admonition, and <em>Collapsible</em> a collapsible block.</li><li>The <em>Translate</em> group lists the <a href=\"#root/_help_veGu4faJErEM\">content languages</a> you have enabled, or a predefined list if no content languages are set. It can be filled from within the editor, the last entry of the submenu opens the language configuration directly.</li></ul><p>Actions that need something to work on are greyed out when there is nothing to work on (for example an empty paragraph with no selection).</p><h2>Asking for something specific</h2><p>Choosing <em>Ask AI…</em> (<span class=\"tn-icon bx bx-message-square-dots\"></span>) opens a prompt where you can describe the change in your own words, for example: \"make this less formal\", \"add a row for 2024\", \"write an intro paragraph for this section\". Press <kbd>Enter</kbd> or the <span class=\"tn-icon cke cke-arrow-up\"></span> send button to run it.</p><p>Once a response arrives you can keep going in the same prompt, and the assistant treats it as a conversation rather than as a fresh request: after <em>Translate this to German</em>, asking for <em>make it shorter</em> shortens the German, not the original.</p><h2>Reviewing the result</h2><p>The response streams in as it is generated, and can be interrupted at any point by pressing the <em>Stop</em> (<span class=\"tn-icon cke cke-stop\"></span>) button; whatever arrived before that stays usable.</p><p>Nothing is written into the note until you say so. The review offers:</p><ul><li><em>Result</em>, which displays the response as it will be inserted.</li><li><em>Changes</em>, which displays an inline diff against the original, with insertions and deletions marked. When the model rewrote the passage rather than editing it, the review opens on <em>Result</em> instead: a diff of two texts with little in common is harder to read than the answer itself.</li><li><em>Try again</em> (<span class=\"tn-icon cke cke-refresh\"></span>), to re-run the same instruction.</li><li><em>Replace</em>, which substitutes the original passage</li><li><em>Insert below</em>, which keeps the original and adds the response after it.</li></ul><p>Trilium also reports the model that produced it, the tokens consumed and, for providers that report it, the price.</p><p>If you ask for a correction and there is nothing to correct, the assistant will indicate it instead of showing a blank diff.</p><h2>Choosing the model</h2><p>The bottom of the quick actions menu shows which model the assistant runs on, and lets you pick another from the models you selected in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, grouped by provider.</p><p>The model can also be changed while asking for something specific, or after the assistant has generated its response (i.e. if the response needs a better model).</p><p>This choice is separate from the model used by the chat, and is remembered across notes and devices. Left unset, the assistant follows the first configured provider.</p>",
"_help_mVEYwt20exhO": "<p><em>Quick actions</em> are a feature of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a>&nbsp;for&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes which automatically triggers an LLM suggestion based on a defined prompt. The built-in quick actions come with a predefined prompt, but it is also possible to define your own quick actions.</p><h2>Creating a custom quick action</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right-click the note where you want to place the quick action.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>AI Quick Action</em>. The entry appears only when AI is enabled.</li></ol><p>Afterwards, simply type in the content of the note the desired prompt. The text can be formatted in the same manner as a normal text note and it will be passed to the LLM as Markdown.</p><p>The title of the note will become the title of the quick action.</p><p>Of note:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;notes work too.</li><li>An empty note is ignored.</li><li><a class=\"reference-link\" href=\"#root/_help_MKmLg5x6xkor\">Archived Notes</a>&nbsp;are also excluded.</li></ul><h2>Using a quick action</h2><p>Once a quick action is defined, the action will appear under the <em>Quick Actions</em> dropdown in a group called <em>Custom</em>.</p>",
- "_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts &amp; \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> 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.</p><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, an included text or 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. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;(e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a>&nbsp;provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></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>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. A code note or file is shown with syntax highlighting until then.</p><ul><li>To edit, 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. Turn <em>Editable</em> off to return to the preview.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</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 note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",
+ "_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts &amp; \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> 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.</p><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, an included text or 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. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;(e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a>&nbsp;provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></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>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. A code note or file is shown with syntax highlighting until then.</p><ul><li>To edit, 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. Turn <em>Editable</em> off to return to the preview.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</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 note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",
"_help_CohkqWQC1iBv": "<p>Press the&nbsp;<span class=\"tn-icon cke cke-plus\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;to reveal special inserable items and blocks such as symbols, Math expressions and separators.</p><h2>Bookmarks</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a>&nbsp;section.</p><h2>Emoji</h2><figure class=\"image image-style-align-right image_resized\" style=\"width:42.4%;\"><img style=\"aspect-ratio:366/410;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_plus.png\" width=\"366\" height=\"410\"></figure><p>This feature allows inserting Unicode emoji characters. Simply select a category and a desired emoji to insert it.</p><p>Emojis can also be searched by their English name and the skin tone can be selected via a combo box to the right.</p><p>There is also the possibility of inserting emojis directly by typing <code>:</code> followed by a name of an emoji, triggering the display of a list of emojis. Simply use the arrow keys to select one and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to insert it.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_plus.png\" width=\"272\" height=\"187\"><h2>Symbols</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:346/322;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_image.png\" width=\"346\" height=\"322\"></figure><p>Pressing the&nbsp;<span class=\"tn-icon cke cke-special-characters\"></span> button will reveal a popup window displaying a list of characters that are generally more difficult to insert directly from the keyboard, such as a subset of emojis, quotation characters, etc.</p><p>Interaction:</p><ul><li>Click on a character to insert it at the current cursor position.</li><li>The window can be dragged around by the top bar where the title is, to avoid it getting in the way of the text.</li><li>Click on the <em>Category</em> selector to filter the characters.</li></ul><h2>Multicolumn layout</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a>&nbsp;page.</p><h2>Math equations</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a>&nbsp;page.</p><h2>Drawing canvas</h2><p>Choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em> to draw on an Excalidraw canvas inside the text. See <em>Drawing canvases</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><h2>Mermaid diagram</h2><p>Press the&nbsp;<span class=\"tn-icon cke cke-trilium-mermaid-insert\"></span> button to create an inline Mermaid diagram.</p><p>This feature is quite similar to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>&nbsp;note types and is meant as an alternative to it for simple diagrams. For more complex diagrams, use the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>&nbsp;feature for a dedicated Mermaid note.</p><figure class=\"image\"><img style=\"aspect-ratio:1174/358;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Insert%20buttons_image.png\" width=\"1174\" height=\"358\"></figure><h2>Horizontal ruler</h2><p>This feature will display a horizontal line, generally useful to separate different sections of the text. To do so, press the&nbsp;<span class=\"tn-icon cke cke-horizontal-line\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_image.png\" width=\"502\" height=\"95\"><p>Alternatively, it's possible to insert a horizontal ruler by typing <code>---</code>.</p><h2>Page break</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:371/79;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Insert%20buttons_image.png\" width=\"371\" height=\"79\"></figure><p>Page breaks provide a way to force the next paragraph or block (table, image, etc.) to be displayed onto the next page when printing (either to a real printer to <a href=\"#root/_help_NRnIZmSMc5sj\">when exporting to PDF</a>).</p><p>Page breaks are marked in the editor with the words <em>Page break</em>, but they will not actually be shown when printed.</p><ul><li>To insert a page break, press the&nbsp;<span class=\"tn-icon cke cke-page-break\"></span> in the formatting toolbar.</li><li>To insert many page breaks at once, insert a page break first, click on it and press <kbd>Ctrl</kbd>+<kbd>C</kbd>. Then use <kbd>Ctrl</kbd>+<kbd>V</kbd>, to paste as many times as needed.</li></ul><h2>Date and time</h2><p>The <span class=\"tn-icon cke cke-trilium-date-time\"></span> button inserts the current date and time at the cursor, replacing the selected text if there is any. The inserted text takes the formatting of the text around it, so a date inserted inside bold text is bold too.</p><ul><li>To insert the date in the default format, press the button itself or press <kbd>Alt</kbd>+<kbd>T</kbd>.</li><li>To insert it in another format, press the arrow next to the button and pick a format from the list. Each entry shows the current date and time in that format: the default one, the date or the time alone, the date written out, and ISO 8601.</li><li>The same formats are offered by the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>: type <code>/date</code>, <code>/time</code>, <code>/now</code> or <code>/today</code>. The <em>Insert date/time</em> entry uses the default format, and shows what it inserts underneath; the other entries show their output in the title.</li></ul><p>The default format can be changed in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em>, using <a href=\"https://day.js.org/docs/en/display/format\">Day.js format tokens</a> (for example <code>DD.MM.YYYY HH:mm</code>).</p><h2>Icons</h2><p>Icons just like the ones for the <a href=\"#root/_help_p9kXRFAkwN4o\">note icon</a> can be inserted in text. For more information see&nbsp;<a class=\"reference-link\" href=\"#root/_help_hD8GawVuazff\">Icons</a>.</p>",
"_help_hD8GawVuazff": "<p>Icons just like the <a href=\"#root/_help_hD8GawVuazff\">note icons</a> can be inserted in the content of a note, including from any other <a href=\"#root/_help_gOKqSJgXLcIj\">custom icon packs</a>.</p><h2>Features</h2><ul><li>The icon can be formatted through the<a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a>&nbsp;tools of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:<ul><li>Foreground/icon color</li><li>Background color/highlight</li><li>Font size</li></ul></li><li>Custom&nbsp;<a class=\"reference-link\" href=\"#root/_help_gOKqSJgXLcIj\">Icon Packs</a>&nbsp;are also supported.<ul><li>For emojis, prefer the Emoji functionality from&nbsp;<a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</li></ul></li><li>When an icon is clicked a floating toolbar appears with the following functions:<ul><li><span class=\"tn-icon bx bx-sticker\"></span>&nbsp;which changes the icon.</li><li><span class=\"tn-icon bx bx-reflect-horizontal\"></span>&nbsp;which applies transforms: rotate (90 / 180 / 270) and flip horizontal/vertical. Only one transform can be used per icon.</li></ul></li></ul><h2>Usage</h2><ul><li>The in-app help/user guide makes use of these icons in order to illustrate buttons in the UI.</li><li>The&nbsp;<a class=\"reference-link\" href=\"#root/_help_GnhlmrATVqcH\">Microsoft OneNote</a>&nbsp;importer also makes use of them for the&nbsp;<a class=\"reference-link\" href=\"#root/_help_LpvyEIBIAAj7\">Tags</a>.</li></ul><h2>Inserting an icon</h2><p>There are two ways to insert an icon:</p><ul><li>Via the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;look for the&nbsp;<span class=\"tn-icon bx bx-plus\"></span> icon and then the&nbsp;<span class=\"tn-icon bx bx-sticker\"></span> icon.</li><li>Via&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>, type <code>/icon</code>.</li></ul><p>An icon picker will appear, search for an icon and click it to insert it in the document.</p><h2>Finding notes by their icons</h2><p>An icon can be <a href=\"#root/_help_eIg8jdvaoNNd\">searched</a>. A note containing a&nbsp;<span class=\"tn-icon bx bx-star\"></span> icon can be found by searching for <code>star</code>, or its <code>iconClass</code> (<code>bx-star</code>).</p><p>To find the name of the icon, hover the mouse over an icon while in the icon picker.</p><h2>Markdown rendering</h2><p>When exporting to&nbsp;<a class=\"reference-link\" href=\"#root/_help_Oau6X9rCuegd\">Markdown</a>, the item will render as raw HTML representation of the icon as is used by Trilium:</p><pre><code class=\"language-text-html\">&lt;span class=\"tn-icon bx bx-star\"&gt;&lt;/span&gt;</code></pre>",
"_help_oiVPnW8QfnvS": "<h2>Trilium-specific shortcuts</h2><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Bring up inline formatting toolbar (arrow keys ←,→ to navigate, Enter to apply)</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Bring up block formatting toolbar</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">external link</a></td><td>Ctrl+K</td><td>⌘+K</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">internal (note) link</a></td><td>Ctrl+L</td><td>⌘+L</td></tr><tr><td>Inserts current date and time at caret position</td><td>Alt+T</td><td>⌥+T</td></tr><tr><td>Increase paragraph indentation</td><td>Tab</td><td>⇥</td></tr><tr><td>Decrease paragraph indentation</td><td>Shift + Tab</td><td>⇧ + ⇥</td></tr><tr><td>Mark selected text as <a href=\"#root/_help_UYuUB1ZekNQU\">keyboard shortcut</a></td><td>Ctrl + Alt + K</td><td>⌘+ ⌥+ K</td></tr><tr><td>Insert&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a></td><td>Ctrl + M</td><td>⌘+ M</td></tr><tr><td>Move blocks (lists, paragraphs, etc.) up</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↑</td><td>⌥+↑</td><td></td></tr><tr><td>Move blocks (lists, paragraphs, etc.) down</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↓</td><td>⌥+↓</td><td></td></tr><tr><td>Move the selected content to another column of a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current column of a multicolumn layout</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a column after or before the current one in a multicolumn layout</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr><tr><td>Move the selected content to another tab in <a class=\"reference-link\" href=\"#root/_help_EK2ckIZ74tbT\">Content tabs</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current tab of a tabs block</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a tab after or before the current one in a tabs block</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr></tbody></table></figure><h2>Common shortcuts</h2><aside class=\"admonition tip\"><p>This section of keyboard shortcuts presents a subset of the keyboard shortcuts as supported by the editor technology we are using,&nbsp;<a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>. The shortcuts were taken from the <a href=\"https://ckeditor.com/docs/ckeditor5/latest/features/accessibility.html#keyboard-shortcuts\">official documentation</a>. Note that not all the shortcuts in the original documentation are applicable (due to using a different configuration).</p></aside><h3>Content editing</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a hard break (a new paragraph)</td><td>Enter</td><td></td></tr><tr><td>Insert a soft break (a <code>&lt;br&gt;</code> element)</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Copy selected content</td><td>Ctrl+C</td><td>⌘C</td></tr><tr><td>Paste content</td><td>Ctrl+V</td><td>⌘V</td></tr><tr><td>Paste content as plain text</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Undo</td><td>Ctrl+Z</td><td>⌘Z</td></tr><tr><td>Redo</td><td>Ctrl+Y, Ctrl+Shift+Z</td><td>⌘Y, ⌘⇧Z</td></tr><tr><td>Bold text</td><td>Ctrl+B</td><td>⌘B</td></tr><tr><td>Change text case</td><td>Shift+F3</td><td>⇧F3 (may require Fn)</td></tr><tr><td>Create link</td><td>Ctrl+K</td><td>⌘K</td></tr><tr><td>Move out of a link</td><td>←←, →→</td><td></td></tr><tr><td>Move out of an inline code style</td><td>←←, →→</td><td></td></tr><tr><td>Select all</td><td>Ctrl+A</td><td>⌘A</td></tr><tr><td>Find in the document</td><td>Ctrl+F</td><td>⌘F</td></tr><tr><td>Copy text formatting</td><td>Ctrl+Shift+C</td><td>⌘⇧C</td></tr><tr><td>Paste text formatting</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Italic text</td><td>Ctrl+I</td><td>⌘I</td></tr><tr><td>Strikethrough text</td><td>Ctrl+Shift+X</td><td>⌘⇧X</td></tr><tr><td>Underline text</td><td>Ctrl+U</td><td>⌘U</td></tr><tr><td>Revert autoformatting action</td><td>Backspace</td><td></td></tr></tbody></table></figure><h3>Interacting with blocks</h3><p>Blocks are images, tables, blockquotes, annotations.</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a new paragraph directly after a widget</td><td>Enter</td><td></td></tr><tr><td>Insert a new paragraph directly before a widget</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Move the caret to allow typing directly before a widget</td><td>↑, ←</td><td></td></tr><tr><td>Move the caret to allow typing directly after a widget</td><td>↓, →</td><td></td></tr><tr><td>After entering a nested editable, move the selection to the closest ancestor widget. For example: move from an image caption to the whole image widget.</td><td>Tab then Esc</td><td></td></tr></tbody></table></figure><p>Specifically for lists:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Increase list item indent</td><td>⇥</td><td></td></tr><tr><td>Decrease list item indent</td><td>Shift+⇥</td><td>⇧⇥</td></tr></tbody></table></figure><p>In tables:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Move the selection to the next cell</td><td>⇥</td><td></td></tr><tr><td>Move the selection to the previous cell</td><td>Shift+⇥</td><td>⇧⇥</td></tr><tr><td>Insert a new table row (when in the last cell of a table)</td><td>⇥</td><td></td></tr><tr><td>Navigate through the table</td><td>↑, →, ↓, ←</td><td></td></tr></tbody></table></figure><h3>General UI shortcuts</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Close contextual balloons, dropdowns, and dialogs</td><td>Esc</td><td></td></tr><tr><td>Open the accessibility help dialog</td><td>Alt+0</td><td>⌥0</td></tr><tr><td>Move focus between form fields (inputs, buttons, etc.)</td><td>⇥, Shift+⇥</td><td>⇥, ⇧⇥</td></tr><tr><td>Move focus to the toolbar, navigate between toolbars</td><td>Alt+F10</td><td>⌥F10 (may require Fn)</td></tr><tr><td>Navigate through the toolbar or menu bar</td><td>↑, →, ↓, ←</td><td></td></tr><tr><td>Navigate to the next focusable field or an element outside the editor</td><td>Tab, Shift+Tab</td><td></td></tr><tr><td>Execute the currently focused button. Executing buttons that interact with the editor content moves the focus back to the content.</td><td>Enter, Space</td><td></td></tr><tr><td>Move focus in and out of an active dialog window</td><td>Ctrl+F6</td><td>⌘F6 (may require Fn)</td></tr></tbody></table></figure>",
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 af38de7cbb..d53b4fc0c7 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
@@ -109,6 +109,7 @@ In a _Small_ or _Medium_ box, the image is scaled down to fit the height of the
An included text note, an included code note and an embedded code file such as a `.js`, `.py` or `.txt` attachment can be edited without leaving the note that includes them. A code note or file is shown with syntax highlighting until then.
* To edit, 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. Turn _Editable_ off to return to the preview.
+* While _Editable_ is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed _Expandable_ include is skipped.
* While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.
* Code is edited in the same code editor as a <a class="reference-link" href="../Code.md">Code</a> note, with its theme, indentation and line wrapping settings.
* The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.
diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.ts
index c0c26524bb..eac6355c6f 100644
--- a/packages/ckeditor5/src/augmentation.ts
+++ b/packages/ckeditor5/src/augmentation.ts
@@ -140,6 +140,11 @@ declare global {
* without embeds leave it out.
*/
getContentEmbedTools?(embed: HTMLElement): ContentEmbedToolProvider | null;
+ /**
+ * Focuses the editor that `embed` shows, with the caret at `edge` of its content, and
+ * returns whether it did. Hosts without embeds leave it out.
+ */
+ enterContentEmbed?(embed: HTMLElement, edge: "start" | "end"): boolean;
/**
* Gives the focus to what the embed of the attachment shows, once it renders. Hosts
* without embeds leave it out.
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 66aabfefeb..37cc94ebd5 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -19,6 +19,7 @@ export type { ImageEditingSourceConfig } from "./plugins/image_editing_source.js
export type { FileUploadData, FileUploadEvent } from "./plugins/file_upload/fileuploadediting.js";
export type { PasteTarget } from "./plugins/cuttonote.js";
export type { ContentEmbedState } from "./plugins/content_embed/content_embed.js";
+export type { EmbedEdge } from "./plugins/content_embed/content_embed_caret.js";
export type { AttachmentLinkChange } from "./plugins/referencelink.js";
export type { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.js";
export type { default as TriliumSlashCommands, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem } from "./plugins/mention/slash_commands.js";
@@ -36,6 +37,7 @@ export * from "./utils.js";
import "./plugins/file_upload/uploadfileplugin.js";
import "./plugins/block_reference/block_reference.js";
import "./plugins/content_embed/content_embed.js";
+import "./plugins/content_embed/content_embed_caret.js";
import "./plugins/math/math.js";
import "./plugins/tabs/tabs.js";
import "./plugins/multicolumn/multicolumn.js";
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index e9e9db320a..fa3c2ccf36 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -62,6 +62,7 @@ import AdmonitionToolbar from "./plugins/admonition/admonition_toolbar.js";
import ContentEmbedBoxSizeDropdown
from "./plugins/content_embed/content_embed_box_size_dropdown.js";
import ContentEmbedToolbar from "./plugins/content_embed/content_embed_toolbar.js";
+import ContentEmbedCaret from "./plugins/content_embed/content_embed_caret.js";
import LinkEmbedToolbar from "./plugins/link_embed/link_embed_toolbar.js";
import TodoListMultistate from "./plugins/todo_list_multistate/todo_list_multistate.js";
import TodoListUncheckOnEnter from "./plugins/todo_list_uncheck_on_enter.js";
@@ -111,6 +112,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
AdmonitionToolbar,
ContentEmbedBoxSizeDropdown,
ContentEmbedToolbar,
+ ContentEmbedCaret,
LinkEmbedToolbar,
TodoListMultistate,
CollapsibleListItems,
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
index 4589a5ebe8..9931adcaff 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
@@ -925,7 +925,7 @@ function getSelectedContentEmbed( editor: Editor ) {
}
/** The embed whose rendering contains `domElement`, or `null`. */
-function getContentEmbedAt( editor: Editor, domElement: Element ) {
+export function getContentEmbedAt( editor: Editor, domElement: Element ) {
const embedElement = domElement.closest<HTMLElement>( '.include-note' );
const viewElement = embedElement
&& editor.editing.view.domConverter.mapDomToView( embedElement );
@@ -936,7 +936,9 @@ function getContentEmbedAt( editor: Editor, domElement: Element ) {
return editor.editing.mapper.toModelElement( viewElement ) ?? null;
}
-function isContentEmbed( node: ModelNode | ModelDocumentFragment | null ): node is ModelElement {
+export function isContentEmbed(
+ node: ModelNode | ModelDocumentFragment | null
+): node is ModelElement {
return !!node?.is( 'element', 'contentEmbed' );
}
@@ -964,7 +966,7 @@ function isEmbedConvertibleToLink( editor: Editor, embed: ModelElement ) {
}
/** The caption of `embed`, or `null`. */
-function getCaption( embed: ModelElement ) {
+export function getCaption( embed: ModelElement ) {
return Array.from( embed.getChildren() )
.find( ( child ): child is ModelElement => child.is( 'element', 'caption' ) ) ?? null;
}
@@ -1083,7 +1085,10 @@ function openContentEmbedMenu( editor: Editor, anchor: HTMLElement | null ) {
}
/** The rendered `<figure>` of `embed`, or `null`. */
-function getContentEmbedDom( editor: Editor, embed: ModelElement | null ): HTMLElement | null {
+export function getContentEmbedDom(
+ editor: Editor,
+ embed: ModelElement | null
+): HTMLElement | null {
const viewElement = embed && editor.editing.mapper.toViewElement( embed );
const domElement = viewElement && editor.editing.view.domConverter.mapViewToDom( viewElement );
return domElement instanceof HTMLElement ? domElement : null;
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.spec.ts
new file mode 100644
index 0000000000..b32cdd8b57
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.spec.ts
@@ -0,0 +1,418 @@
+import {
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ _WIDGET_TYPE_AROUND_SELECTION_ATTRIBUTE as TYPE_AROUND_ATTRIBUTE,
+ type ClassicEditor,
+ Essentials,
+ HorizontalLine,
+ Paragraph,
+ Table,
+ Widget
+} from "ckeditor5";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor, destroyTrackedEditors, pressKey } from "../../../test/editor-kit.js";
+import { installGlobMock } from "../../../test/globals-test-kit.js";
+import ContentEmbed from "./content_embed.js";
+import ContentEmbedCaret from "./content_embed_caret.js";
+
+const EMBED = "<contentEmbed boxSize=\"medium\" noteId=\"n1\"></contentEmbed>";
+const CAPTIONED_EMBED = "<contentEmbed boxSize=\"medium\" noteId=\"n1\">"
+ + "<caption>Caption</caption></contentEmbed>";
+const CAPTIONED_EMBED_AT_START = "<contentEmbed boxSize=\"medium\" noteId=\"n1\">"
+ + "<caption>[]Caption</caption></contentEmbed>";
+const AB = "<paragraph>ab</paragraph>";
+const CD = "<paragraph>cd</paragraph>";
+const HR = "<horizontalLine></horizontalLine>";
+const TEXT_PLUGINS = [
+ Essentials, Paragraph, Widget, HorizontalLine, ContentEmbed, ContentEmbedCaret
+];
+
+describe("ContentEmbedCaret entering an embed", () => {
+ let editor: ClassicEditor;
+ let enterContentEmbed: ReturnType<typeof vi.fn<(embed: HTMLElement, edge: string) => boolean>>;
+
+ beforeEach(async () => {
+ enterContentEmbed = vi.fn(() => true);
+ installGlobMock({
+ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn(), enterContentEmbed })
+ });
+ editor = await createTestEditor(TEXT_PLUGINS);
+ });
+
+ it("enters the embed beside the caret with Left and Right", () => {
+ setModelData(editor.model, `<paragraph>ab[]</paragraph>${EMBED}<paragraph>cd</paragraph>`);
+ expect(pressKey(editor, "ArrowRight")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "start");
+
+ setModelData(editor.model, `<paragraph>ab</paragraph>${EMBED}<paragraph>[]cd</paragraph>`);
+ expect(pressKey(editor, "ArrowLeft")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "end");
+
+ enterContentEmbed.mockClear();
+ setModelData(editor.model, `<paragraph>a[]b</paragraph>${EMBED}`);
+ expect(pressKey(editor, "ArrowRight")).toBe(false);
+ expect(pressKey(editor, "Enter")).toBe(false);
+ expect(enterContentEmbed).not.toHaveBeenCalled();
+ });
+
+ it("enters with Up and Down only from the line next to the embed", () => {
+ setModelData(editor.model, `<paragraph>a<softBreak></softBreak>b[]c</paragraph>${EMBED}`);
+ expect(pressKey(editor, "ArrowDown")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "start");
+
+ setModelData(editor.model, `${EMBED}<paragraph>a[]b<softBreak></softBreak>c</paragraph>`);
+ expect(pressKey(editor, "ArrowUp")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "end");
+
+ enterContentEmbed.mockClear();
+ setModelData(editor.model, `<paragraph>a[]b<softBreak></softBreak>c</paragraph>${EMBED}`);
+ expect(pressKey(editor, "ArrowDown")).toBe(false);
+ setModelData(editor.model, `${EMBED}<paragraph>a<softBreak></softBreak>b[]c</paragraph>`);
+ expect(pressKey(editor, "ArrowUp")).toBe(false);
+ setModelData(editor.model, `<paragraph>ab[]</paragraph><paragraph>cd</paragraph>${EMBED}`);
+ expect(pressKey(editor, "ArrowDown")).toBe(false);
+ setModelData(editor.model, `<paragraph>ab[]</paragraph>${HR}${EMBED}`);
+ expect(pressKey(editor, "ArrowDown")).toBe(false);
+ expect(enterContentEmbed).not.toHaveBeenCalled();
+ });
+
+ it("enters from the fake caret beside a selected embed, and forward from the embed", () => {
+ setModelData(editor.model, `<paragraph>ab</paragraph>[${EMBED}]<paragraph>cd</paragraph>`);
+ setTypeAround(editor, "before");
+ expect(pressKey(editor, "ArrowDown")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "start");
+
+ setTypeAround(editor, "after");
+ expect(pressKey(editor, "ArrowLeft")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "end");
+
+ setTypeAround(editor, null);
+ expect(pressKey(editor, "ArrowRight")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "start");
+
+ enterContentEmbed.mockClear();
+ expect(pressKey(editor, "ArrowUp")).toBe(false);
+ setTypeAround(editor, "after");
+ expect(pressKey(editor, "ArrowDown")).toBe(false);
+ setModelData(editor.model, "<paragraph>ab</paragraph>[<horizontalLine></horizontalLine>]");
+ expect(pressKey(editor, "ArrowDown")).toBe(false);
+ expect(enterContentEmbed).not.toHaveBeenCalled();
+ });
+
+ it("enters an embed with a caption from below only through its caption", () => {
+ setModelData(editor.model, `<paragraph>ab</paragraph>${CAPTIONED_EMBED_AT_START}`);
+ expect(pressKey(editor, "ArrowLeft")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "end");
+ expect(pressKey(editor, "ArrowUp")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenCalledTimes(2);
+
+ enterContentEmbed.mockClear();
+ setModelData(editor.model, AB + CAPTIONED_EMBED_AT_START.replace("[]C", "C[]"));
+ expect(pressKey(editor, "ArrowLeft")).toBe(false);
+ expect(pressKey(editor, "ArrowDown")).toBe(false);
+ setModelData(editor.model, `${CAPTIONED_EMBED}<paragraph>[]cd</paragraph>`);
+ expect(pressKey(editor, "ArrowLeft")).toBe(false);
+ expect(pressKey(editor, "ArrowUp")).toBe(false);
+ setModelData(editor.model, `<paragraph>ab</paragraph>[${CAPTIONED_EMBED}]`);
+ setTypeAround(editor, "after");
+ expect(pressKey(editor, "ArrowUp")).toBe(false);
+ expect(enterContentEmbed).not.toHaveBeenCalled();
+
+ setModelData(editor.model, `<paragraph>ab[]</paragraph>${CAPTIONED_EMBED}`);
+ expect(pressKey(editor, "ArrowDown")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "start");
+ });
+
+ it("enters from the caption while the caption has the focus", () => {
+ setModelData(editor.model, AB + CAPTIONED_EMBED_AT_START);
+ expect(pressFocusedKey(editor, "ArrowLeft")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(editor), "end");
+ });
+
+ it("leaves the key to the editor when the embed takes no caret", () => {
+ enterContentEmbed.mockReturnValue(false);
+ setModelData(editor.model, `<paragraph>ab[]</paragraph>${EMBED}`);
+ expect(pressKey(editor, "ArrowRight")).toBe(false);
+ expect(enterContentEmbed).toHaveBeenCalledOnce();
+
+ installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
+ expect(pressKey(editor, "ArrowRight")).toBe(false);
+ });
+
+ it("ignores modified keys, a read-only editor and a selection of text", () => {
+ setModelData(editor.model, `<paragraph>ab[]</paragraph>${EMBED}`);
+ for (const modifier of [ "shiftKey", "ctrlKey", "altKey", "metaKey", "isComposing" ]) {
+ expect(pressKey(editor, "ArrowRight", { [modifier]: true })).toBe(false);
+ }
+
+ editor.enableReadOnlyMode("spec");
+ expect(pressKey(editor, "ArrowRight")).toBe(false);
+ editor.disableReadOnlyMode("spec");
+
+ setModelData(editor.model, `<paragraph>[ab]</paragraph>${EMBED}`);
+ expect(pressKey(editor, "ArrowRight")).toBe(false);
+ expect(enterContentEmbed).not.toHaveBeenCalled();
+
+ setModelData(editor.model, `<paragraph>ab[]</paragraph>${EMBED}`);
+ expect(pressKey(editor, "ArrowRight")).toBe(true);
+ });
+
+ it("leaves the keys of the editor in the embed alone", () => {
+ setModelData(editor.model, `<paragraph>ab</paragraph>[${EMBED}]`);
+ const nestedRoot = document.createElement("div");
+ nestedRoot.tabIndex = -1;
+ getEmbedContent(editor).append(nestedRoot);
+
+ const event = new KeyboardEvent("keydown", {
+ key: "ArrowDown", bubbles: true, cancelable: true
+ });
+ nestedRoot.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(false);
+ expect(enterContentEmbed).not.toHaveBeenCalled();
+ expect(pressKey(editor, "ArrowDown")).toBe(true);
+ });
+
+ it("follows the screen in right-to-left content", async () => {
+ const rtlEditor = await createTestEditor(TEXT_PLUGINS, { language: { content: "ar" } });
+ setModelData(rtlEditor.model, `<paragraph>ab[]</paragraph>${EMBED}`);
+ expect(pressKey(rtlEditor, "ArrowRight")).toBe(false);
+ expect(pressKey(rtlEditor, "ArrowLeft")).toBe(true);
+ expect(enterContentEmbed).toHaveBeenLastCalledWith(getEmbedDom(rtlEditor), "start");
+ });
+});
+
+describe("ContentEmbedCaret leaving an embed", () => {
+ let editor: ClassicEditor;
+ let plugin: ContentEmbedCaret;
+
+ beforeEach(async () => {
+ installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
+ editor = await createTestEditor(TEXT_PLUGINS);
+ plugin = editor.plugins.get(ContentEmbedCaret);
+ });
+
+ // Destroying a focused editor with an embed selected reads the `glob` mock, which the global
+ // cleanups remove first.
+ afterEach(() => destroyTrackedEditors());
+
+ it("focuses the editor with the caret in the text beside the embed", () => {
+ setModelData(editor.model, `<paragraph>ab</paragraph>${EMBED}<paragraph>cd</paragraph>`);
+ expect(plugin.leaveEmbed(getEmbedContent(editor), "end")).toBe(true);
+ expect(getModelData(editor.model)).toBe(`${AB}${EMBED}<paragraph>[]cd</paragraph>`);
+ expect(editor.editing.view.document.isFocused).toBe(true);
+
+ expect(plugin.leaveEmbed(getEmbedContent(editor), "start")).toBe(true);
+ expect(getModelData(editor.model)).toBe(`<paragraph>ab[]</paragraph>${EMBED}${CD}`);
+ });
+
+ it("shows the fake caret beside an embed with no text beside it", () => {
+ setModelData(editor.model, AB + EMBED + HR);
+ expect(plugin.leaveEmbed(getEmbedContent(editor), "end")).toBe(true);
+ expect(editor.model.document.selection.getSelectedElement()?.name).toBe("contentEmbed");
+ expect(editor.model.document.selection.getAttribute(TYPE_AROUND_ATTRIBUTE)).toBe("after");
+
+ setModelData(editor.model, `${EMBED}<paragraph>ab</paragraph>`);
+ expect(plugin.leaveEmbed(getEmbedContent(editor), "start")).toBe(true);
+ expect(editor.model.document.selection.getSelectedElement()?.name).toBe("contentEmbed");
+ expect(editor.model.document.selection.getAttribute(TYPE_AROUND_ATTRIBUTE)).toBe("before");
+ });
+
+ it("puts the caret in the caption below the content", () => {
+ setModelData(editor.model, AB + CAPTIONED_EMBED + CD);
+ expect(plugin.leaveEmbed(getEmbedContent(editor), "end")).toBe(true);
+ expect(getModelData(editor.model)).toBe(
+ AB + CAPTIONED_EMBED.replace(">Caption", ">[]Caption") + CD
+ );
+
+ expect(plugin.leaveEmbed(getEmbedContent(editor), "start")).toBe(true);
+ expect(getModelData(editor.model))
+ .toBe(`<paragraph>ab[]</paragraph>${CAPTIONED_EMBED}${CD}`);
+ });
+
+ it("returns false for an element outside its embeds", () => {
+ setModelData(editor.model, `<paragraph>[]ab</paragraph>${EMBED}`);
+ expect(plugin.leaveEmbed(document.body, "end")).toBe(false);
+ expect(getModelData(editor.model)).toBe(`<paragraph>[]ab</paragraph>${EMBED}`);
+ });
+});
+
+describe("ContentEmbedCaret as the editor of an embed", () => {
+ let editor: ClassicEditor;
+ let plugin: ContentEmbedCaret;
+
+ beforeEach(async () => {
+ installGlobMock({ getComponentByEl: () => ({ loadEmbeddedNote: vi.fn() }) });
+ editor = await createTestEditor(TEXT_PLUGINS);
+ plugin = editor.plugins.get(ContentEmbedCaret);
+ });
+
+ /** The edge that `plugin` reports for `key` pressed in the editing root. */
+ function getEdge(key: string, init: KeyboardEventInit = {}) {
+ const root = getDomRoot(editor);
+ let edge: string | null | undefined;
+ root.addEventListener("keydown", (event) => {
+ edge = plugin.getEdgeLeftBy(event);
+ }, { once: true });
+ root.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, ...init }));
+ return edge;
+ }
+
+ it("focuses the editor with the caret at either edge of its content", () => {
+ editor.setData("<p>ab</p><p>cd</p>");
+ plugin.focusAt("start");
+ expect(getModelData(editor.model)).toBe(`<paragraph>[]ab</paragraph>${CD}`);
+ expect(editor.editing.view.document.isFocused).toBe(true);
+
+ plugin.focusAt("end");
+ expect(getModelData(editor.model)).toBe(`${AB}<paragraph>cd[]</paragraph>`);
+ });
+
+ it("shows the fake caret outside an object at the edge it focuses", () => {
+ editor.setData("<hr><p>ab</p><hr>");
+ plugin.focusAt("start");
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(
+ HR + AB + HR
+ );
+ expect(editor.model.document.selection.getSelectedElement()?.index).toBe(0);
+ expect(editor.model.document.selection.getAttribute(TYPE_AROUND_ATTRIBUTE)).toBe("before");
+
+ plugin.focusAt("end");
+ expect(editor.model.document.selection.getSelectedElement()?.index).toBe(2);
+ expect(editor.model.document.selection.getAttribute(TYPE_AROUND_ATTRIBUTE)).toBe("after");
+ });
+
+ it("leaves by Left and Right at the edges of the content", () => {
+ setModelData(editor.model, "<paragraph>[]ab</paragraph><paragraph>cd</paragraph>");
+ expect(getEdge("ArrowLeft")).toBe("start");
+ expect(getEdge("ArrowRight")).toBe(null);
+ setModelData(editor.model, "<paragraph>ab</paragraph><paragraph>c[]d</paragraph>");
+ expect(getEdge("ArrowRight")).toBe(null);
+ setModelData(editor.model, "<paragraph>ab</paragraph><paragraph>cd[]</paragraph>");
+ expect(getEdge("ArrowRight")).toBe("end");
+ expect(getEdge("ArrowLeft")).toBe(null);
+ expect(getEdge("Enter")).toBe(null);
+ });
+
+ it("leaves by Up and Down from the first and the last line", () => {
+ setModelData(editor.model, "<paragraph>a[]b<softBreak></softBreak>cd</paragraph>");
+ expect(getEdge("ArrowUp")).toBe("start");
+ expect(getEdge("ArrowDown")).toBe(null);
+ setModelData(editor.model, "<paragraph>ab<softBreak></softBreak>c[]d</paragraph>");
+ expect(getEdge("ArrowUp")).toBe(null);
+ expect(getEdge("ArrowDown")).toBe("end");
+ setModelData(editor.model, "<paragraph>a[]b</paragraph><paragraph>cd</paragraph>");
+ expect(getEdge("ArrowDown")).toBe(null);
+ setModelData(editor.model, "<paragraph>ab[]</paragraph><horizontalLine></horizontalLine>");
+ expect(getEdge("ArrowDown")).toBe(null);
+ });
+
+ it("measures the lines of a wrapped paragraph", () => {
+ getDomRoot(editor).style.width = "120px";
+ const text = "one two three four five six seven eight nine ten";
+ editor.setData(`<p>${text}</p>`);
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+ if (!paragraph) {
+ throw new Error("Expected a paragraph.");
+ }
+
+ editor.model.change((writer) => writer.setSelection(paragraph, 1));
+ expect(getEdge("ArrowUp")).toBe("start");
+ expect(getEdge("ArrowDown")).toBe(null);
+ editor.model.change((writer) => writer.setSelection(paragraph, text.length - 1));
+ expect(getEdge("ArrowUp")).toBe(null);
+ expect(getEdge("ArrowDown")).toBe("end");
+ });
+
+ it("leaves from the last row of a table that has the focus", async () => {
+ const tableEditor = await createTestEditor([ ...TEXT_PLUGINS, Table ]);
+ const tablePlugin = tableEditor.plugins.get(ContentEmbedCaret);
+ tableEditor.setData("<p>ab</p><table><tr><td>cd</td><td>ef</td></tr></table>");
+ const cell = tableEditor.model.document.getRoot()?.getNodeByPath([ 1, 0, 1, 0 ]);
+ if (!cell) {
+ throw new Error("Expected a paragraph in the last cell.");
+ }
+ tableEditor.model.change((writer) => writer.setSelection(cell, 1));
+
+ let edge: string | null = null;
+ const onKeyDown = (event: KeyboardEvent) => {
+ edge = tablePlugin.getEdgeLeftBy(event);
+ };
+ document.addEventListener("keydown", onKeyDown, { capture: true });
+ pressFocusedKey(tableEditor, "ArrowDown");
+ document.removeEventListener("keydown", onKeyDown, { capture: true });
+ expect(edge).toBe("end");
+ });
+
+ it("leaves from a selected object at the edge, unless the fake caret is inside", () => {
+ setModelData(editor.model, "<paragraph>ab</paragraph>[<horizontalLine></horizontalLine>]");
+ expect(getEdge("ArrowDown")).toBe("end");
+ expect(getEdge("ArrowUp")).toBe(null);
+ setTypeAround(editor, "after");
+ expect(getEdge("ArrowRight")).toBe("end");
+ setTypeAround(editor, "before");
+ expect(getEdge("ArrowDown")).toBe(null);
+ setModelData(editor.model, "[<horizontalLine></horizontalLine>]<paragraph>ab</paragraph>");
+ expect(getEdge("ArrowDown")).toBe(null);
+ expect(getEdge("ArrowLeft")).toBe("start");
+ });
+
+ it("ignores modified keys, a selection of text and keys from other elements", () => {
+ setModelData(editor.model, "<paragraph>ab[]</paragraph>");
+ expect(getEdge("ArrowRight", { shiftKey: true })).toBe(null);
+ const undispatched = new KeyboardEvent("keydown", { key: "ArrowRight" });
+ expect(plugin.getEdgeLeftBy(undispatched)).toBe(null);
+ setModelData(editor.model, "<paragraph>[ab]</paragraph>");
+ expect(getEdge("ArrowRight")).toBe(null);
+ });
+});
+
+/**
+ * Focuses `editor` and presses `key` in the element that takes the focus, such as a caption or a
+ * table cell, and returns whether a listener prevented it.
+ */
+function pressFocusedKey(editor: ClassicEditor, key: string) {
+ editor.editing.view.focus();
+ const target = document.activeElement;
+ if (!(target instanceof HTMLElement) || !getDomRoot(editor).contains(target)) {
+ throw new Error("Expected the focus in the editor.");
+ }
+ const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });
+ target.dispatchEvent(event);
+ return event.defaultPrevented;
+}
+
+function setTypeAround(editor: ClassicEditor, side: "before" | "after" | null) {
+ editor.model.change((writer) => {
+ if (side) {
+ writer.setSelectionAttribute(TYPE_AROUND_ATTRIBUTE, side);
+ } else {
+ writer.removeSelectionAttribute(TYPE_AROUND_ATTRIBUTE);
+ }
+ });
+}
+
+function getDomRoot(editor: ClassicEditor) {
+ const root = editor.editing.view.getDomRoot();
+ if (!root) {
+ throw new Error("Expected the editing root.");
+ }
+ return root;
+}
+
+function getEmbedDom(editor: ClassicEditor) {
+ const embed = getDomRoot(editor).querySelector<HTMLElement>("figure.include-note");
+ if (!embed) {
+ throw new Error("Expected a rendered embed.");
+ }
+ return embed;
+}
+
+/** An element in the content of the rendered embed, as the editor of the embed is. */
+function getEmbedContent(editor: ClassicEditor) {
+ const wrapper = getEmbedDom(editor).querySelector<HTMLElement>(".include-note-wrapper");
+ if (!wrapper) {
+ throw new Error("Expected the wrapper of the embed.");
+ }
+ return wrapper;
+}
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.ts
new file mode 100644
index 0000000000..ef6036c00c
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_caret.ts
@@ -0,0 +1,352 @@
+import {
+ _WIDGET_TYPE_AROUND_SELECTION_ATTRIBUTE as TYPE_AROUND_ATTRIBUTE,
+ type Editor,
+ type Model,
+ type ModelElement,
+ type ModelPosition,
+ type ModelRange,
+ Plugin,
+ Rect
+} from "ckeditor5";
+
+import { addEditingKeydownCapture } from "../move_block_updown.js";
+import {
+ getCaption, getContentEmbedAt, getContentEmbedDom, isContentEmbed
+} from "./content_embed.js";
+
+/** An end of the content of an embed, where the caret enters or leaves it. */
+export type EmbedEdge = "start" | "end";
+
+/**
+ * Moves the caret between the text and the editors in embeds with the arrow keys.
+ *
+ * When an arrow key reaches an embed, the host focuses the editor of the embed at its near edge,
+ * through `enterContentEmbed()`. In the editor of an embed, `focusAt()` and `getEdgeLeftBy()`
+ * do the same for its own content, and `leaveEmbed()` of the editor around it takes the caret back.
+ */
+export default class ContentEmbedCaret extends Plugin {
+ static get pluginName() {
+ return "ContentEmbedCaret" as const;
+ }
+
+ init() {
+ // The capture phase runs before the arrow keys of `Widget` and `WidgetTypeAround`. It also
+ // receives the keys pressed inside an embed, such as in its editor, which are skipped.
+ addEditingKeydownCapture(this, (event) => {
+ const move = getArrowMove(event, this.isRtl());
+ if (!move || this.editor.isReadOnly || !isFromEditable(this.editor, event)) {
+ return;
+ }
+
+ const embed = this.getEmbedAhead(move);
+ if (embed && this.enterEmbed(embed, move.isForward ? "start" : "end")) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ });
+ }
+
+ /**
+ * Focuses this editor with the caret beside the embed that contains `domElement`, past its
+ * `edge`. Returns `false` when `domElement` is not in an embed of this editor.
+ */
+ leaveEmbed(domElement: Element, edge: EmbedEdge): boolean {
+ const editor = this.editor;
+ const embed = getContentEmbedAt(editor, domElement);
+ if (!embed) {
+ return false;
+ }
+
+ const model = editor.model;
+ const isForward = edge === "end";
+ editor.editing.view.focus();
+ model.change((writer) => {
+ const caption = isForward ? getCaption(embed) : null;
+ const outside = isForward
+ ? writer.createPositionAfter(embed)
+ : writer.createPositionBefore(embed);
+ const direction = isForward ? "forward" : "backward";
+ const range = caption
+ ? writer.createRange(writer.createPositionAt(caption, 0))
+ : model.schema.getNearestSelectionRange(outside, direction);
+
+ if (range?.isCollapsed) {
+ writer.setSelection(range);
+ return;
+ }
+ // Without text beside the embed, the fake caret of `WidgetTypeAround` shows there.
+ writer.setSelection(embed, "on");
+ writer.setSelectionAttribute(TYPE_AROUND_ATTRIBUTE, isForward ? "after" : "before");
+ });
+ editor.editing.view.scrollToTheSelection();
+ return true;
+ }
+
+ /** Focuses this editor with the caret at `edge` of its content. */
+ focusAt(edge: EmbedEdge) {
+ const editor = this.editor;
+ const model = editor.model;
+ const root = model.document.getRoot();
+ const isStart = edge === "start";
+ const range = root && model.schema.getNearestSelectionRange(
+ model.createPositionAt(root, isStart ? 0 : "end"),
+ isStart ? "forward" : "backward"
+ );
+
+ if (range) {
+ model.change((writer) => {
+ writer.setSelection(range);
+ // An object at the edge gets the fake caret on its outer side.
+ if (!range.isCollapsed) {
+ const side = isStart ? "before" : "after";
+ writer.setSelectionAttribute(TYPE_AROUND_ATTRIBUTE, side);
+ }
+ });
+ }
+ editor.editing.view.focus();
+ editor.editing.view.scrollToTheSelection();
+ }
+
+ /**
+ * The edge of the content that the arrow key of `event`, pressed in this editor, moves the
+ * caret past, or `null` while the caret stays in the content.
+ */
+ getEdgeLeftBy(event: KeyboardEvent): EmbedEdge | null {
+ const editor = this.editor;
+ const move = getArrowMove(event, this.isRtl());
+ if (!move || !isFromEditable(editor, event)) {
+ return null;
+ }
+
+ const model = editor.model;
+ const selection = model.document.selection;
+ const { isForward } = move;
+ const edge = isForward ? "end" : "start";
+ const selected = selection.getSelectedElement();
+ if (selected) {
+ // An object at the edge, unless the fake caret shows on its inner side.
+ const outside = isForward
+ ? model.createPositionAfter(selected)
+ : model.createPositionBefore(selected);
+ const isInnerSide = selection.getAttribute(TYPE_AROUND_ATTRIBUTE)
+ === (isForward ? "before" : "after");
+ return !isInnerSide && isAtRootEdge(model, outside, isForward) ? edge : null;
+ }
+
+ const focus = selection.focus;
+ if (!selection.isCollapsed || !focus) {
+ return null;
+ }
+ if (isAtRootEdge(model, focus, isForward)) {
+ return edge;
+ }
+ return move.isVertical && this.isOnEdgeLine(focus, isForward) ? edge : null;
+ }
+
+ /** The embed that `move` takes the caret into from the selection, or `null`. */
+ private getEmbedAhead({ isForward, isVertical }: ArrowMove): ModelElement | null {
+ const editor = this.editor;
+ const model = editor.model;
+ const selection = model.document.selection;
+
+ // From the fake caret beside the embed, or forward from the selected embed. Going back,
+ // the caption comes first.
+ const selected = selection.getSelectedElement();
+ if (selected) {
+ const side = selection.getAttribute(TYPE_AROUND_ATTRIBUTE);
+ const isEntered = isForward
+ ? side !== "after"
+ : side === "after" && !getCaption(selected);
+ return isContentEmbed(selected) && isEntered ? selected : null;
+ }
+
+ const focus = selection.focus;
+ if (!selection.isCollapsed || !focus) {
+ return null;
+ }
+
+ // From the start of the caption below the content.
+ const block = focus.parent;
+ if (block.is("element", "caption") && isContentEmbed(block.parent)) {
+ const line = model.createRange(model.createPositionAt(block, 0), focus);
+ const isAtStart = isVertical ? isSingleLineRange(editor, line) : focus.isAtStart;
+ return !isForward && isAtStart ? block.parent : null;
+ }
+
+ const embed = isVertical
+ ? getEmbedBelowLine(editor, focus, isForward)
+ : getEmbedNextTo(model, isForward);
+ return embed && (isForward || !getCaption(embed)) ? embed : null;
+ }
+
+ /** Has the host focus the editor in `embed` at `edge`. Returns whether it did. */
+ private enterEmbed(embed: ModelElement, edge: EmbedEdge) {
+ const editor = this.editor;
+ const domElement = getContentEmbedDom(editor, embed);
+ const component = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());
+ return !!domElement && !!component?.enterContentEmbed?.(domElement, edge);
+ }
+
+ /**
+ * Whether `position` is on the first line of the content, or on the last one when going
+ * forward.
+ */
+ private isOnEdgeLine(position: ModelPosition, isForward: boolean) {
+ const model = this.editor.model;
+ const topBlock = position.getAncestors()[1];
+ if (!topBlock?.is("element")
+ || (isForward ? topBlock.nextSibling : topBlock.previousSibling)) {
+ return false;
+ }
+
+ const edgeRange = model.schema.getNearestSelectionRange(
+ model.createPositionAt(topBlock, isForward ? "end" : 0),
+ isForward ? "backward" : "forward"
+ );
+ if (!edgeRange?.isCollapsed) {
+ return false;
+ }
+ const range = isForward
+ ? model.createRange(position, edgeRange.start)
+ : model.createRange(edgeRange.start, position);
+ return isSingleLineRange(this.editor, range);
+ }
+
+ private isRtl() {
+ return this.editor.locale.contentLanguageDirection === "rtl";
+ }
+}
+
+interface ArrowMove {
+ isForward: boolean;
+ isVertical: boolean;
+}
+
+/**
+ * The move of an arrow key pressed without modifiers, or `null`. Left and Right follow the
+ * screen, so in right-to-left content Left moves forward.
+ */
+function getArrowMove(event: KeyboardEvent, isRtl: boolean): ArrowMove | null {
+ if (event.shiftKey || event.ctrlKey || event.altKey || event.metaKey || event.isComposing) {
+ return null;
+ }
+
+ switch (event.key) {
+ case "ArrowUp":
+ return { isForward: false, isVertical: true };
+ case "ArrowDown":
+ return { isForward: true, isVertical: true };
+ case "ArrowLeft":
+ return { isForward: isRtl, isVertical: false };
+ case "ArrowRight":
+ return { isForward: !isRtl, isVertical: false };
+ default:
+ return null;
+ }
+}
+
+/**
+ * Whether `event` comes from an editable of `editor`, such as its root, a caption or a table cell,
+ * rather than from the content of an embed, which the wrapper of the embed marks with
+ * `data-cke-ignore-events`.
+ */
+function isFromEditable(editor: Editor, event: Event) {
+ const root = editor.editing.view.getDomRoot();
+ const target = event.target instanceof Element ? event.target : null;
+ const embedWrapper = target?.closest("[data-cke-ignore-events]");
+ return !!root && !!target && root.contains(target)
+ && !(embedWrapper && root.contains(embedWrapper));
+}
+
+/** The embed right beside the collapsed selection, in the direction of the move, or `null`. */
+function getEmbedNextTo(model: Model, isForward: boolean) {
+ const selection = model.document.selection;
+ const probe = model.createSelection(selection);
+ model.modifySelection(probe, { direction: isForward ? "forward" : "backward" });
+ const node = (isForward ? probe.focus?.nodeBefore : probe.focus?.nodeAfter) ?? null;
+ return !probe.isEqual(selection) && isContentEmbed(node) ? node : null;
+}
+
+/**
+ * The embed that follows the block of `position`, or precedes it going back, while `position`
+ * is on the last line of that block, or on its first line. `null` otherwise.
+ */
+function getEmbedBelowLine(editor: Editor, position: ModelPosition, isForward: boolean) {
+ const model = editor.model;
+ const schema = model.schema;
+ const enteringType = isForward ? "elementStart" : "elementEnd";
+ const walker = model.createRangeIn(position.root).getWalker({
+ startPosition: position,
+ direction: isForward ? "forward" : "backward"
+ });
+
+ // The first block or limit element that the walk enters, as `Widget` finds it.
+ let embed: ModelElement | null = null;
+ for (const { item, type } of walker) {
+ if (!item.is("element")) {
+ continue;
+ }
+ if (schema.isLimit(item) && !schema.isInline(item)) {
+ embed = type === enteringType && isContentEmbed(item) ? item : null;
+ break;
+ }
+ if (type === enteringType && schema.isBlock(item)) {
+ break;
+ }
+ }
+
+ const block = position.parent;
+ const line = isForward
+ ? model.createRange(position, model.createPositionAt(block, "end"))
+ : model.createRange(model.createPositionAt(block, 0), position);
+ return embed && isSingleLineRange(editor, line) ? embed : null;
+}
+
+/**
+ * Whether no position for the caret, and no object, lies between `position` and the edge of its
+ * root, in the direction of the move.
+ */
+function isAtRootEdge(model: Model, position: ModelPosition, isForward: boolean) {
+ const schema = model.schema;
+ const rootRange = model.createRangeIn(position.root);
+ const range = isForward
+ ? model.createRange(position, rootRange.end)
+ : model.createRange(rootRange.start, position);
+ const enteringType = isForward ? "elementStart" : "elementEnd";
+
+ for (const { item, type, nextPosition } of range.getWalker({
+ direction: isForward ? "forward" : "backward"
+ })) {
+ if (schema.checkChild(nextPosition, "$text")
+ || (type === enteringType && schema.isObject(item))) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/** Whether the rendering of `range` fits on one line, as `Widget` measures it. */
+function isSingleLineRange(editor: Editor, range: ModelRange) {
+ const viewRange = editor.editing.mapper.toViewRange(range);
+ const domRange = editor.editing.view.domConverter.viewRangeToDom(viewRange);
+
+ // A rectangle that starts below the bottom of the ones before it is on a new line. An empty
+ // rectangle, as of an empty text node, has no position.
+ let bottom: number | null = null;
+ for (const rect of Rect.getDomRangeRects(domRange)) {
+ if (rect.width === 0 && rect.height === 0) {
+ continue;
+ }
+ if (bottom !== null && Math.round(rect.top) >= bottom) {
+ return false;
+ }
+ bottom = Math.max(bottom ?? 0, Math.round(rect.bottom));
+ }
+ return true;
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [ContentEmbedCaret.pluginName]: ContentEmbedCaret;
+ }
+}
diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.ts
index 5b0eb9dcec..04d2458ae3 100644
--- a/packages/codemirror/src/index.spec.ts
+++ b/packages/codemirror/src/index.spec.ts
@@ -366,6 +366,49 @@ describe("CodeMirror", () => {
editor.insertBlankLineAtTop();
expect(editor.getText()).toBe("");
});
+
+ it("focuses the editor at either end of the document", () => {
+ editor = build();
+ editor.setText("line one\nline two");
+
+ editor.focusAt("end");
+ expect(editor.state.selection.main.head).toBe(editor.state.doc.length);
+ expect(document.activeElement).toBe(editor.contentDOM);
+ editor.focusAt("start");
+ expect(editor.state.selection.main.head).toBe(0);
+ });
+
+ it("tells the end of the document that an arrow key moves the cursor past", () => {
+ const instance = build();
+ editor = instance;
+ instance.setText("ab\ncd");
+ const getEdge = (head: number, key: string, init: KeyboardEventInit = {}) => {
+ instance.dispatch({ selection: EditorSelection.cursor(head) });
+ return instance.getEdgeLeftBy(createKeydown(key, instance.contentDOM, init));
+ };
+
+ expect(getEdge(0, "ArrowLeft")).toBe("start");
+ expect(getEdge(1, "ArrowLeft")).toBe(null);
+ expect(getEdge(5, "ArrowRight")).toBe("end");
+ expect(getEdge(4, "ArrowRight")).toBe(null);
+ expect(getEdge(1, "ArrowUp")).toBe("start");
+ expect(getEdge(4, "ArrowUp")).toBe(null);
+ expect(getEdge(4, "ArrowDown")).toBe("end");
+ expect(getEdge(1, "ArrowDown")).toBe(null);
+ expect(getEdge(0, "Enter")).toBe(null);
+ for (const modifier of [ "shiftKey", "ctrlKey", "altKey", "metaKey", "isComposing" ]) {
+ expect(getEdge(0, "ArrowLeft", { [modifier]: true })).toBe(null);
+ }
+ expect(instance.getEdgeLeftBy(createKeydown("ArrowLeft", document.body))).toBe(null);
+
+ const arrowLeft = createKeydown("ArrowLeft", instance.contentDOM);
+ instance.dispatch({ selection: EditorSelection.range(0, 1) });
+ expect(instance.getEdgeLeftBy(arrowLeft)).toBe(null);
+ instance.setNamedExtension("multi", EditorState.allowMultipleSelections.of(true));
+ const cursors = [ EditorSelection.cursor(0), EditorSelection.cursor(5) ];
+ instance.dispatch({ selection: EditorSelection.create(cursors) });
+ expect(instance.getEdgeLeftBy(arrowLeft)).toBe(null);
+ });
});
describe("find and replace", () => {
@@ -537,3 +580,10 @@ function build(config: Partial<EditorConfig> = {}): CodeMirror {
document.body.appendChild(parent);
return new CodeMirror({ parent, ...config });
}
+
+/** A keydown of `key` from `target`, which the editor does not handle, as it is not dispatched. */
+function createKeydown(key: string, target: EventTarget, init: KeyboardEventInit = {}) {
+ const event = new KeyboardEvent("keydown", { key, ...init });
+ Object.defineProperty(event, "target", { value: target });
+ return event;
+}
diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.ts
index a20873eff5..e83e0d3557 100644
--- a/packages/codemirror/src/index.ts
+++ b/packages/codemirror/src/index.ts
@@ -80,6 +80,9 @@ export interface EditorConfig {
onContentChanged?: ContentChangedListener;
}
+/** An end of the document, where the cursor enters or leaves the editor. */
+export type DocumentEdge = "start" | "end";
+
function buildIndentUnit(indentSize: number, useTabs: boolean) {
return useTabs ? "\t" : " ".repeat(indentSize);
}
@@ -319,6 +322,41 @@ export default class CodeMirror extends EditorView {
});
}
+ /** Focuses the editor with the cursor at the start or the end of the document. */
+ focusAt(edge: DocumentEdge) {
+ const position = edge === "start" ? 0 : this.state.doc.length;
+ this.dispatch({ selection: EditorSelection.cursor(position), scrollIntoView: true });
+ this.focus();
+ }
+
+ /**
+ * The edge of the document that the arrow key of `event`, pressed without modifiers, moves
+ * the cursor past, or `null` for any other key and while the cursor stays in the document.
+ */
+ getEdgeLeftBy(event: KeyboardEvent): DocumentEdge | null {
+ const { ranges, main } = this.state.selection;
+ const hasModifier = event.shiftKey || event.ctrlKey || event.altKey || event.metaKey;
+ if (event.target !== this.contentDOM || hasModifier || event.isComposing
+ || ranges.length > 1 || !main.empty) {
+ return null;
+ }
+
+ const length = this.state.doc.length;
+ switch (event.key) {
+ case "ArrowLeft":
+ return main.head === 0 ? "start" : null;
+ case "ArrowRight":
+ return main.head === length ? "end" : null;
+ // The line boundary is the start or end of the visual line, wrapped lines included.
+ case "ArrowUp":
+ return this.moveToLineBoundary(main, false).head === 0 ? "start" : null;
+ case "ArrowDown":
+ return this.moveToLineBoundary(main, true).head === length ? "end" : null;
+ default:
+ return null;
+ }
+ }
+
/**
* Inserts a blank line at the very top of the document and places the cursor on it — the code-note
* analog of the Notion-like behavior when pressing Enter in the note title. If the first line is