Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor/text note transclusion: add support for fixed formatting toolbar
Adorian Doran54732030ded8
diff --git a/apps/client/src/menus/text_editor_context_menu.spec.ts b/apps/client/src/menus/text_editor_context_menu.spec.tsindex 9f3b97281b..ed826f298e 100644--- a/apps/client/src/menus/text_editor_context_menu.spec.ts+++ b/apps/client/src/menus/text_editor_context_menu.spec.ts@@ -119,6 +119,30 @@ describe("getTextEditorAtSelection", () => {expect(await getTextEditorAtSelection()).toBeNull();});+ it("returns the editor of an included note that is edited inside the note", async () => {+ const root = document.createElement("div");+ root.className = "ck-editor__editable";+ const { editor } = fakeEditor({ domRoot: root });+ const nestedEditor = { editing: { view: {} } };+ const nestedRoot = Object.assign(document.createElement("div"), {+ className: "ck-editor__editable",+ ckeditorInstance: nestedEditor+ });+ const caption = document.createElement("div");+ caption.className = "ck-editor__editable ck-editor__nested-editable";+ root.append(nestedRoot, caption);+ const nestedText = nestedRoot.appendChild(document.createTextNode("inside"));+ const nestedCaption = nestedRoot.appendChild(caption.cloneNode());++ setSelection(nestedText);+ expect(await getTextEditorAtSelection()).toBe(nestedEditor);+ setSelection(nestedCaption);+ expect(await getTextEditorAtSelection()).toBe(nestedEditor);+ // The editable caption of a widget belongs to the editor around it.+ setSelection(caption.appendChild(document.createTextNode("caption")));+ expect(await getTextEditorAtSelection()).toBe(editor);+ });+it("returns null for a non-text note, and swallows a failing editor lookup", async () => {setSelection(document.createTextNode("hello"));diff --git a/apps/client/src/menus/text_editor_context_menu.ts b/apps/client/src/menus/text_editor_context_menu.tsindex 445c58004e..cf08e86b26 100644--- a/apps/client/src/menus/text_editor_context_menu.ts+++ b/apps/client/src/menus/text_editor_context_menu.ts@@ -149,7 +149,7 @@ export async function getTextEditorAtSelection(): Promise<CKTextEditor | null> {* the selection in every browser.** Looks up the editor in the split pane that contains `node`, because a right-click does not- * activate that pane.+ * activate that pane. Inside an included note edited in place, the editor of that note answers.*/export async function getTextEditorContaining(node: Node | null | undefined@@ -164,7 +164,7 @@ export async function getTextEditorContaining(const domRoot = editor?.editing.view.getDomRoot();if (editor && domRoot && domRoot.contains(node)) {- return editor;+ return getNestedEditor(node, domRoot) ?? editor;}} catch (error) {// Editor not ready or the request timed out.@@ -174,6 +174,17 @@ export async function getTextEditorContaining(return null;}+/** The editor of an included note edited inside the editable `domRoot`, which contains `node`. */+function getNestedEditor(node: Node, domRoot: HTMLElement) {+ const element = node instanceof Element ? node : node.parentElement;+ const editable = element?.closest<HTMLElement & { ckeditorInstance?: CKTextEditor }>(+ ".ck-editor__editable:not(.ck-editor__nested-editable)"+ );+ return editable && editable !== domRoot && domRoot.contains(editable)+ ? editable.ckeditorInstance ?? null+ : null;+}+/*** Returns the note context whose `ntxId` matches the `data-ntx-id` of the split pane that contains* `node`, or the active note context when `node` is outside every pane, e.g. in a dialog.diff --git a/apps/client/src/services/keyboard_actions.spec.ts b/apps/client/src/services/keyboard_actions.spec.tsindex 1f7d7f016f..fbb53988cb 100644--- a/apps/client/src/services/keyboard_actions.spec.ts+++ b/apps/client/src/services/keyboard_actions.spec.ts@@ -143,6 +143,22 @@ describe("keyboard_actions", () => {spy!.mockRestore();});+ it("setupWindowShortcutsForElement binds the window-scoped shortcuts on an element", async () => {+ const { kb } = await loadModule([+ action({ actionName: "winA", scope: "window", effectiveShortcuts: [ "ctrl+1" ] }),+ action({ actionName: "treeA", scope: "note-tree", effectiveShortcuts: [ "ctrl+9" ] })+ ]);+ vi.mocked(appContext.triggerCommand).mockClear();++ const $el = $("<div></div>");+ const bindings = await kb.default.setupWindowShortcutsForElement($el as any);++ expect(bindings.map((binding) => binding.shortcut)).toEqual([ "ctrl+1" ]);+ expect(bindings[0].element).toBe($el[0]);+ bindings[0].handler(new KeyboardEvent("keydown"));+ expect(appContext.triggerCommand).toHaveBeenCalledWith("winA", { ntxId: "ntx-active" });+ });+it("setupActionsForElement returns [] for an empty jQuery element", async () => {const { kb } = await loadModule([action({ actionName: "a", scope: "text-detail", effectiveShortcuts: ["ctrl+a"] })]);const $empty = $(); // length 0 -> $el[0] undefineddiff --git a/apps/client/src/services/keyboard_actions.ts b/apps/client/src/services/keyboard_actions.tsindex 2025930372..716024049e 100644--- a/apps/client/src/services/keyboard_actions.ts+++ b/apps/client/src/services/keyboard_actions.ts@@ -66,11 +66,36 @@ async function setupWindowShortcuts() {for (const action of actions) {/* v8 ignore next -- effectiveShortcuts is always normalized to an array by the loader (line 13) before this resolves, so the ?? [] fallback is unreachable */for (const shortcut of action.effectiveShortcuts ?? []) {- shortcutService.bindGlobalShortcut(shortcut, () => appContext.triggerCommand(action.actionName, { ntxId: appContext.tabManager.activeNtxId }));+ shortcutService.bindGlobalShortcut(shortcut, () => runWindowAction(action.actionName));}}}+/**+ * Binds the window-scoped actions on `$el` as well, for content that keeps its keys from the+ * document, such as the content of an embed in a text note.+ */+async function setupWindowShortcutsForElement($el: JQuery<HTMLElement>) {+ const bindings: ShortcutBinding[] = [];++ for (const action of await getActionsForScope("window")) {+ for (const shortcut of action.effectiveShortcuts ?? []) {+ const binding = shortcutService.bindElShortcut($el, shortcut, () => {+ runWindowAction(action.actionName);+ });+ if (binding) {+ bindings.push(binding);+ }+ }+ }++ return bindings;+}++function runWindowAction(actionName: ActionKeyboardShortcut["actionName"]) {+ return appContext.triggerCommand(actionName, { ntxId: appContext.tabManager.activeNtxId });+}+async function getAction(actionName: string, silent = false) {await keyboardActionsLoaded;@@ -138,6 +163,7 @@ function updateDisplayedShortcuts($container: JQuery<HTMLElement>) {export default {updateDisplayedShortcuts,setupWindowShortcuts,+ setupWindowShortcutsForElement,setupActionsForElement,getAction,getActions,diff --git a/apps/client/src/widgets/EmbeddedNotePane.tsx b/apps/client/src/widgets/EmbeddedNotePane.tsxindex aa3ada83a9..0c12d8e979 100644--- a/apps/client/src/widgets/EmbeddedNotePane.tsx+++ b/apps/client/src/widgets/EmbeddedNotePane.tsx@@ -42,7 +42,11 @@ import { NoteContextContext, ParentComponent } from "./react/react_utils";* child, so app-wide events travel down into the pane — a component hanging off nothing would never* hear that its note was edited elsewhere.*/-export function useEmbeddedNoteContext(note: FNote | undefined, ntxId: string) {+export function useEmbeddedNoteContext(+ note: FNote | undefined,+ ntxId: string,+ { floatingToolbar = true }: { floatingToolbar?: boolean } = {}+) {const parentComponent = useContext(ParentComponent);const [ noteContext ] = useState(() => new NoteContext(ntxId));const [ component ] = useState(() => new Component());@@ -72,7 +76,7 @@ export function useEmbeddedNoteContext(note: FNote | undefined, ntxId: string) {readOnlyTemporarilyDisabled: !note.hasLabel("readOnly"),// The pane has a third of a note's width, which is not a toolbar's worth: the// editor's own follows the selection instead of standing in a bar (see link.ts).- floatingToolbar: true+ floatingToolbar}});}, [ noteContext, note?.noteId ]);diff --git a/apps/client/src/widgets/ribbon/FormattingToolbar.tsx b/apps/client/src/widgets/ribbon/FormattingToolbar.tsxindex d687c82d46..7bcf443440 100644--- a/apps/client/src/widgets/ribbon/FormattingToolbar.tsx+++ b/apps/client/src/widgets/ribbon/FormattingToolbar.tsx@@ -7,6 +7,7 @@ import NoteContext from "../../components/note_context";import FNote from "../../entities/fnote";import options from "../../services/options";import { useActiveNoteContext, useNoteProperty, useTriliumEvent, useTriliumEvents, useTriliumOption } from "../react/hooks";+import { useNestedEditor } from "../type_widgets/text/editable_embed";import { TabConfiguration, TabContext } from "./ribbon-interface";/**@@ -22,18 +23,23 @@ import { TabConfiguration, TabContext } from "./ribbon-interface";export default function FormattingToolbar({ hidden, ntxId }: TabContext) {const containerRef = useRef<HTMLDivElement>(null);const [ textNoteEditorType ] = useTriliumOption("textNoteEditorType");+ const [ noteToolbar, setNoteToolbar ] = useState<HTMLElement | null>();+ const nestedEditor = useNestedEditor(ntxId);+ const toolbar = nestedEditor?.ui.view.toolbar?.element ?? noteToolbar;// Attach the toolbar from the CKEditor.useTriliumEvent("textEditorRefreshed", ({ ntxId: eventNtxId, editor }) => {- if (eventNtxId !== ntxId || !containerRef.current) return;- const toolbar = editor.ui.view.toolbar?.element;+ if (eventNtxId !== ntxId) return;+ setNoteToolbar(editor.ui.view.toolbar?.element);+ });+ useEffect(() => {if (toolbar) {- containerRef.current.replaceChildren(toolbar);+ containerRef.current?.replaceChildren(toolbar);} else {- containerRef.current.replaceChildren();+ containerRef.current?.replaceChildren();}- });+ }, [ toolbar ]);return (textNoteEditorType === "ckeditor-classic" &&<div@@ -57,15 +63,17 @@ export function FixedFormattingToolbar() {const noteType = useNoteProperty(note, "type");const renderState = useRenderState(noteContext, note);const [ toolbarToRender, setToolbarToRender ] = useState<HTMLElement | null | undefined>();+ const nestedEditor = useNestedEditor(ntxId);+ const shownToolbar = nestedEditor?.ui.view.toolbar?.element ?? toolbarToRender;// Keyboard shortcut.const lastFocusedElement = useRef<Element>(null);useTriliumEvent("toggleRibbonTabClassicEditor", () => {- if (!toolbarToRender) return;- if (!toolbarToRender.contains(document.activeElement)) {+ if (!shownToolbar) return;+ if (!shownToolbar.contains(document.activeElement)) {// Focus to the fixed formatting toolbar.lastFocusedElement.current = document.activeElement;- toolbarToRender.querySelector<HTMLButtonElement>(".ck-toolbar__items button")?.focus();+ shownToolbar.querySelector<HTMLButtonElement>(".ck-toolbar__items button")?.focus();} else {// Focus back to the last selection.(lastFocusedElement.current as HTMLElement)?.focus();@@ -102,12 +110,12 @@ export function FixedFormattingToolbar() {// Render the toolbar.useEffect(() => {- if (toolbarToRender) {- containerRef.current?.replaceChildren(toolbarToRender);+ if (shownToolbar) {+ containerRef.current?.replaceChildren(shownToolbar);} else {containerRef.current?.replaceChildren();}- }, [ toolbarToRender ]);+ }, [ shownToolbar ]);return (<divdiff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsxindex b1e8464b67..1b3bc251fb 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx@@ -8,13 +8,17 @@ const {triggerCommand,openContextMenu,getOriginBelow,- disposeInteractiveContent+ disposeInteractiveContent,+ setupWindowShortcutsForElement,+ removeIndividualBinding} = vi.hoisted(() => ({openTabWithNoteWithHoisting: vi.fn(),triggerCommand: vi.fn(),openContextMenu: vi.fn(),getOriginBelow: vi.fn((anchor: Element) => ({ below: anchor })),- disposeInteractiveContent: vi.fn()+ disposeInteractiveContent: vi.fn(),+ setupWindowShortcutsForElement: vi.fn(async (_$el: JQuery<HTMLElement>) => [ { shortcut: "ctrl+j" } ]),+ removeIndividualBinding: vi.fn()}));vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));@@ -25,6 +29,13 @@ vi.mock("../../../menus/link_context_menu", () => ({default: { openContextMenu, getOriginBelow }}));vi.mock("../../../services/content_renderer", () => ({ default: { disposeInteractiveContent } }));+vi.mock("../../../services/keyboard_actions", () => ({+ default: { setupWindowShortcutsForElement }+}));+vi.mock("../../../services/shortcuts", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ removeIndividualBinding+}));import ContentEmbed, {getNoteActions,@@ -410,6 +421,18 @@ describe("ContentEmbed", () => {expect(isActive()).toBe(true);});+ it("runs the window shortcuts from its content, whose keys the editor keeps to itself", async () => {+ renderBox();+ const box = contentBox();+ expect(setupWindowShortcutsForElement).toHaveBeenCalledOnce();+ expect(setupWindowShortcutsForElement.mock.calls[0][0][0]).toBe(box);++ await act(async () => render(null, container));+ await vi.waitFor(() => {+ expect(removeIndividualBinding).toHaveBeenCalledWith({ shortcut: "ctrl+j" });+ });+ });+it("lets a drag reach its content, with the backdrop back once the drag leaves or ends", () => {renderBox();const box = contentBox();diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsxindex e78b463ea8..587e7ef38c 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx@@ -5,8 +5,10 @@ import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";import linkContextMenu from "../../../menus/link_context_menu";import content_renderer from "../../../services/content_renderer";+import keyboard_actions from "../../../services/keyboard_actions";import { t } from "../../../services/i18n";import type { ViewScope } from "../../../services/link";+import { removeIndividualBinding } from "../../../services/shortcuts";import ActionButton from "../../react/ActionButton";import { useFocusWithin } from "../../react/hooks";import Icon from "../../react/Icon";@@ -56,6 +58,7 @@ export default function ContentEmbed({const isContentActive = useFocusWithin(contentRef);const isDraggedOver = useIsDraggedOver(bodyRef);useFullscreenEvents(contentRef);+ useWindowShortcuts(contentRef);const [ isExpanded, setIsExpanded ] = useState(false);const isExpandable = boxSize === "expandable";const hasFullscreen = boxSize === "medium" || boxSize === "full";@@ -255,6 +258,26 @@ function ContentEmbedActionButton({ className, action }: {* Opens the menu of the embed for a right click on its title row. The title link is left to the* handler of every link, which opens the same menu, or a quick edit with Ctrl.*/+/**+ * Runs the window shortcuts, such as switching tabs, from inside the content. The text editor+ * keeps the keys pressed in an embed from the document, where these shortcuts listen.+ */+function useWindowShortcuts(contentRef: RefObject<HTMLElement | null>) {+ useEffect(() => {+ const content = contentRef.current;+ if (!content) return;++ const bindings = keyboard_actions.setupWindowShortcutsForElement($(content));+ return () => {+ void bindings.then((bound) => {+ for (const binding of bound) {+ removeIndividualBinding(binding);+ }+ });+ };+ }, [ contentRef ]);+}+/*** Whether something is dragged over the body of the embed, which then lets the drag reach the* content under the backdrop, such as the editor of an included note.diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsxindex 0a2455a529..c303795e4a 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx@@ -69,12 +69,13 @@ describe("TextEmbed", () => {// The editor module loads on demand, which takes a while under a busy test run.await vi.waitFor(() => expect(editorProps).toHaveBeenCalled(), { timeout: 5000 });- // Mounted once the note context holds the note, with the floating toolbar from the start.+ // Mounted once the note context holds the note, with its view scope from the start.const props = editorProps.mock.calls[0][0] as TypeWidgetProps & { isNested: boolean };expect(props.note).toBe(note);expect(props.ntxId).toMatch(/^_embed_/);expect(props.noteContext?.ntxId).toBe(props.ntxId);- expect(props.viewScope?.floatingToolbar).toBe(true);+ // The formatting toolbar of the note hosts the buttons of the editor.+ expect(props.viewScope).toMatchObject({ viewMode: "default", floatingToolbar: false });expect(props.isNested).toBe(true);// The plugins of the editor find their host from its DOM.const stub = figure.querySelector<HTMLElement>(".editable-text-stub");diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsxindex e29a6960ec..f6f7400a65 100644--- a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx@@ -17,7 +17,9 @@ import { NestedEmbedContext } from "./editable_embed";*/export default function TextEmbedEditor({ note }: { note: FNote }) {const [ ntxId ] = useState(() => `_embed_${randomString(10)}`);- const { noteContext, component } = useEmbeddedNoteContext(note, ntxId);+ // The formatting toolbar of the note shows the buttons of this editor while it has the focus.+ const { noteContext, component } =+ useEmbeddedNoteContext(note, ntxId, { floatingToolbar: false });// 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/editable_embed.spec.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.spec.tsxindex ae21cd7c95..3bf55e9e54 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@@ -9,7 +9,7 @@ import { buildNote } from "../../../test/easy-froca";import { type ContentEmbedToolProvider, getContentEmbedTools } from "./content_embed_tools";import {type EditableEmbedOptions, NestedEmbedContext, useEditableEmbed, useEmbedEditors,- useEmbedPreview+ useEmbedPreview, useNestedEditor} from "./editable_embed";const figures: HTMLElement[] = [];@@ -139,6 +139,55 @@ describe("useEmbedPreview", () => {});});+describe("useNestedEditor", () => {+ it("follows the focus between the editor of a note and an editor nested in it", () => {+ const split = buildEditable({ ntxId: "ntx1" });+ const host = buildEditable({ parent: split, editor: buildFakeEditor() });+ const nestedEditor = buildFakeEditor();+ const nested = buildEditable({ parent: host, editor: nestedEditor });+ const caption = buildEditable({ parent: nested, isNestedEditable: true });+ const otherSplit = buildEditable({ ntxId: "ntx2" });+ const otherNested = buildEditable({+ parent: buildEditable({ parent: otherSplit, editor: buildFakeEditor() }),+ editor: buildFakeEditor()+ });+ const button = document.body.appendChild(document.createElement("button"));+ document.body.append(split, otherSplit);++ let editor: unknown;+ function Probe() {+ editor = useNestedEditor("ntx1");+ return null;+ }+ const container = document.createElement("div");+ act(() => render(<Probe />, container));+ expect(editor).toBeNull();++ act(() => nested.focus());+ expect(editor).toBe(nestedEditor);+ // The focus moves to a toolbar, or into a caption of the nested editor.+ act(() => button.focus());+ act(() => caption.focus());+ expect(editor).toBe(nestedEditor);+ // Another split has its own toolbar.+ act(() => otherNested.focus());+ expect(editor).toBe(nestedEditor);++ act(() => host.focus());+ expect(editor).toBeNull();++ act(() => nested.focus());+ expect(editor).toBe(nestedEditor);+ act(() => nestedEditor.fire("destroy"));+ expect(editor).toBeNull();++ act(() => render(null, container));+ split.remove();+ otherSplit.remove();+ button.remove();+ });+});+interface ProbeState {canEdit: boolean;isEditing: boolean;@@ -185,3 +234,40 @@ function buildEditor(canEdit = true): ContentEditor {release: vi.fn()};}++interface EditableOptions {+ parent?: HTMLElement;+ ntxId?: string;+ editor?: object;+ isNestedEditable?: boolean;+}++/** An element with the classes of a text editor's editable, focusable, or a split with `ntxId`. */+function buildEditable({ parent, ntxId, editor, isNestedEditable }: EditableOptions) {+ const element = document.createElement("div");+ element.tabIndex = -1;+ if (ntxId) {+ element.dataset.ntxId = ntxId;+ } else {+ element.className = isNestedEditable+ ? "ck-editor__editable ck-editor__nested-editable"+ : "ck-editor__editable";+ }+ Object.assign(element, { ckeditorInstance: editor });+ parent?.append(element);+ return element;+}++/** An editor that fires its events to the listeners added with `on()`. */+function buildFakeEditor() {+ const listeners = new Map<string, Set<() => void>>();+ return {+ on: (name: string, listener: () => void) => {+ listeners.set(name, (listeners.get(name) ?? new Set()).add(listener));+ },+ off: (name: string, listener: () => void) => listeners.get(name)?.delete(listener),+ fire: (name: string) => {+ for (const listener of listeners.get(name) ?? []) listener();+ }+ };+}diff --git a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx b/apps/client/src/widgets/type_widgets/text/editable_embed.tsxindex 609bacd158..c23488f8b4 100644--- a/apps/client/src/widgets/type_widgets/text/editable_embed.tsx+++ b/apps/client/src/widgets/type_widgets/text/editable_embed.tsx@@ -1,3 +1,4 @@+import type { CKTextEditor } 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";@@ -118,6 +119,55 @@ export function useEmbedPreview(return preview;}+/**+ * The text editor nested in the split of `ntxId`, such as the editor of an included note, while it+ * holds the focus, for the formatting toolbar to show its buttons. `null` once the editor of the+ * note takes the focus, or the nested editor goes away. Focus elsewhere, such as in the toolbar,+ * changes nothing.+ */+export function useNestedEditor(ntxId: string | null | undefined) {+ const [ editor, setEditor ] = useState<CKTextEditor | null>(null);++ useEffect(() => {+ setEditor(null);+ if (!ntxId) return;++ let stopWatching: (() => void) | undefined;+ const onFocusIn = (event: FocusEvent) => {+ const editable = event.target instanceof Element+ ? event.target.closest<EditorRootElement>(EDITOR_ROOT_SELECTOR)+ : null;+ if (editable?.closest<HTMLElement>("[data-ntx-id]")?.dataset.ntxId !== ntxId) return;++ stopWatching?.();+ stopWatching = undefined;+ const focused = editable.ckeditorInstance;+ if (!focused || !editable.parentElement?.closest(EDITOR_ROOT_SELECTOR)) {+ setEditor(null);+ return;+ }++ const release = () => setEditor(null);+ focused.on("destroy", release);+ stopWatching = () => focused.off("destroy", release);+ setEditor(focused);+ };++ document.addEventListener("focusin", onFocusIn);+ return () => {+ document.removeEventListener("focusin", onFocusIn);+ stopWatching?.();+ };+ }, [ ntxId ]);++ return editor;+}++/** The editable root of a text editor, which CKEditor gives a reference to the editor. */+type EditorRootElement = HTMLElement & { ckeditorInstance?: CKTextEditor };++const EDITOR_ROOT_SELECTOR = ".ck-editor__editable:not(.ck-editor__nested-editable)";+const EDITABLE_FLAG_TOOLS: ContentEmbedToolProvider = {hasEditableFlag: true,getTools: () => [],diff --git a/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx b/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsxindex 64e5dd5e07..0dbdbdfd82 100644--- a/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx+++ b/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx@@ -6,6 +6,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { isIOS } from "../../../services/utils";import { useIsNoteReadOnly, useNoteContext, useNoteProperty, useTriliumEvent } from "../../react/hooks";+import { useNestedEditor } from "./editable_embed";interface MobileEditorToolbarProps {inPopupEditor?: boolean;@@ -24,24 +25,36 @@ export default function MobileEditorToolbar({ inPopupEditor }: MobileEditorToolbconst { isReadOnly } = useIsNoteReadOnly(note, noteContext);const shouldDisplay = noteType === "text" && isReadOnly === false;const [ dropdownActive, setDropdownActive ] = useState(false);+ const [ noteEditor, setNoteEditor ] = useState<CKTextEditor>();+ const nestedEditor = useNestedEditor(ntxId);+ const editor = nestedEditor?.ui.view.toolbar ? nestedEditor : noteEditor;usePositioningOniOS(!inPopupEditor, containerRef);// Attach the toolbar from the CKEditor.useTriliumEvent("textEditorRefreshed", ({ ntxId: eventNtxId, editor }) => {- if (eventNtxId !== ntxId || !containerRef.current) return;- const toolbar = editor.ui.view.toolbar?.element;+ if (eventNtxId !== ntxId) return;if (!inPopupEditor) {repositionDropdowns(editor);}+ setNoteEditor(editor);+ });++ useEffect(() => {+ if (nestedEditor && !inPopupEditor) {+ repositionDropdowns(nestedEditor);+ }+ }, [ nestedEditor, inPopupEditor ]);+ useEffect(() => {+ const toolbar = editor?.ui.view.toolbar?.element;if (toolbar) {- containerRef.current.replaceChildren(toolbar);+ containerRef.current?.replaceChildren(toolbar);} else {- containerRef.current.replaceChildren();+ containerRef.current?.replaceChildren();}- });+ }, [ editor ]);// Observe when a dropdown is expanded to apply a style that allows the dropdown to be visible, since we can't have the element both visible and the toolbar scrollable.useEffect(() => {@@ -100,12 +113,18 @@ function usePositioningOniOS(enabled: boolean, wrapperRef: RefObject<HTMLDivElem}, [ enabled, adjustPosition ]);}+/** The editors whose toolbar dropdowns open upwards already. */+const repositionedEditors = new WeakSet<CKTextEditor>();+/*** Reposition all dropdowns to point upwards instead of downwards.* See https://ckeditor.com/docs/ckeditor5/latest/examples/framework/bottom-toolbar-editor.html for more info.* @param editor*/function repositionDropdowns(editor: CKTextEditor) {+ if (repositionedEditors.has(editor)) return;+ repositionedEditors.add(editor);+const toolbarView = (editor as ClassicEditor).ui.view.toolbar;for (const item of toolbarView.items) {if (!("panelView" in item)) continue;diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.htmlindex ece296835f..e167311d81 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Include Note.html@@ -169,9 +169,8 @@<li>To edit, select the include and turn on the <span class="tn-icon bx bx-edit-alt"></span> <em>Editable</em> buttonat 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>A text note is edited with the floating toolbar, which appears over the- selected text, whichever toolbar the other text notes use. The notes it- includes in turn stay read-only.</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,diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.mdindex a50fc77e3f..91d36b3636 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@@ -107,7 +107,7 @@ In a _Small_ or _Medium_ box, the image is scaled down to fit the height of theAn 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.-* A text note is edited with the floating toolbar, which appears over the selected text, whichever toolbar the other text notes use. The notes it includes in turn stay read-only.+* 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.* Editing is not available in a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), for an included note marked `#readOnly`, or for an attachment of another note.