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/include notes: use an invisible backdrop over content to prevent accidental manipulation while the widget is not focused
Adorian Doran166ae6dcc759
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 3811189ab9..9f257a3221 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1433,6 +1433,8 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t}.include-note {+ --ck-color-focus-border: var(--link-color);+margin: 0 0 10px;border-radius: var(--_include-note-top-border-radius, 8px)var(--_include-note-top-border-radius, 8px)@@ -1465,10 +1467,6 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-tmargin-bottom: 3px;}-.ck-widget.include-note {- --ck-color-focus-border: var(--link-color);-}-/* CKEditor counts only non-UIElements as content (see `hasContent` in theengine), so a widget rendered entirely from UIElements — an include note, aMermaid diagram, etc. — looks "empty" to it. When such a widget is the first@@ -1692,7 +1690,13 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t}}+.include-note-body {+ position: relative;+}+.include-note-content {+ /* Keeps the z-indexes inside the content, such as those of map panes, under the backdrop. */+ isolation: isolate;border-top: 2px solid var(--main-background-color);padding: .75rem 1rem;}@@ -1701,8 +1705,26 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-tmargin-bottom: 0;}+/* Takes the wheel and the touch gestures for the page until the content has the focus. */+.include-note-backdrop {+ position: absolute;+ inset: 0;+}++.include-note-content:focus {+ outline: none;+}++/* Outlined as a selected widget in the editor. */+.include-note:has(> .include-note-wrapper > .include-note-body.active) {+ /* The editor shows a selected widget as blurred while the focus is in its content. */+ --ck-color-widget-blurred-border: var(--ck-color-focus-border);++ outline: var(--ck-widget-outline-thickness, 3px) solid var(--ck-color-focus-border);+}+/* Hides what a larger box size drew, until the Tiny row replaces it. */-.include-note[data-box-size="tiny"] > .include-note-wrapper > .include-note-content {+.include-note[data-box-size="tiny"] > .include-note-wrapper > .include-note-body {display: none;}@@ -1711,7 +1733,7 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-tdisplay: none;}- > .include-note-wrapper > .include-note-content:not(:fullscreen) {+ > .include-note-wrapper > .include-note-body > .include-note-content:not(:fullscreen) {border-top: none;border-radius: var(--_include-note-top-border-radius, 8px)var(--_include-note-top-border-radius, 8px) 0 0;diff --git a/apps/client/src/widgets/react/hooks.spec.tsx b/apps/client/src/widgets/react/hooks.spec.tsxindex f1b8914d42..5461ecfc46 100644--- a/apps/client/src/widgets/react/hooks.spec.tsx+++ b/apps/client/src/widgets/react/hooks.spec.tsx@@ -6,7 +6,15 @@ import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { buildNote } from "../../test/easy-froca";-import { type DelayedVisibilityPhase, useDelayedVisibility, useImperativeSearchHighlighlighting, useNoteLabelBoolean, useStaticTooltip, useTooltip } from "./hooks";+import {+ type DelayedVisibilityPhase,+ useDelayedVisibility,+ useFocusWithin,+ useImperativeSearchHighlighlighting,+ useNoteLabelBoolean,+ useStaticTooltip,+ useTooltip+} from "./hooks";/*** mark.js delegating to the real implementation, so marking still works, while recording the calls@@ -119,6 +127,79 @@ describe("useDelayedVisibility", () => {});});+describe("useFocusWithin", () => {+ let container: HTMLElement;+ let isFocusWithin: boolean | undefined;++ function FocusProbe() {+ const ref = useRef<HTMLDivElement>(null);+ isFocusWithin = useFocusWithin(ref);+ return (+ <div ref={ref}>+ <button />+ <iframe />+ </div>+ );+ }++ beforeEach(() => {+ vi.useFakeTimers();+ isFocusWithin = undefined;+ container = document.createElement("div");+ document.body.appendChild(container);+ act(() => render(<FocusProbe />, container));+ });++ afterEach(() => {+ act(() => render(null, container));+ container.remove();+ vi.useRealTimers();+ });++ /** Fires `type` at the window, and runs what the hook defers until the focus settles. */+ async function fireOnWindow(type: "blur" | "focus") {+ await act(async () => {+ window.dispatchEvent(new FocusEvent(type));+ await vi.runAllTimersAsync();+ });+ }++ it("follows the focus into the element and out of it, but not out of the window", async () => {+ const inside = container.querySelector("button");+ const outside = document.createElement("button");+ document.body.appendChild(outside);+ expect(isFocusWithin).toBe(false);++ act(() => inside?.focus());+ expect(isFocusWithin).toBe(true);++ // Switching to another window leaves the document's active element where it was.+ await fireOnWindow("blur");+ expect(isFocusWithin).toBe(true);++ await act(async () => {+ outside.focus();+ await vi.runAllTimersAsync();+ });+ expect(isFocusWithin).toBe(false);+ outside.remove();+ });++ it("counts the focus in a frame inside, which only the window reports", async () => {+ const activeElement = vi.spyOn(document, "activeElement", "get");++ activeElement.mockReturnValue(container.querySelector("iframe"));+ await fireOnWindow("blur");+ expect(isFocusWithin).toBe(true);++ activeElement.mockReturnValue(document.body);+ await fireOnWindow("focus");+ expect(isFocusWithin).toBe(false);++ activeElement.mockRestore();+ });+});+describe("useStaticTooltip", () => {let container: HTMLElement;diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex f38fa4c2df..4ce82392b2 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -1019,6 +1019,43 @@ export function useIsOnScreen(ref: RefObject<Element>, enabled: boolean) {return isOnScreen;}+/**+ * Whether the focus is in the element, including in an `<iframe>` or a `<webview>` inside it,+ * which the document reports as its `activeElement`. Switching to another window keeps the value.+ */+export function useFocusWithin(ref: RefObject<HTMLElement>) {+ const [ isFocusWithin, setIsFocusWithin ] = useState(false);++ useEffect(() => {+ const element = ref.current;+ if (!element) return;++ let timer: number | undefined;+ const update = () => setIsFocusWithin(element.contains(document.activeElement));+ // Reads the focus once it has moved: during `focusout`, the active element is the body.+ const updateLater = () => {+ window.clearTimeout(timer);+ timer = window.setTimeout(update);+ };++ update();+ element.addEventListener("focusin", update);+ element.addEventListener("focusout", updateLater);+ // A frame taking or returning the focus fires no focus event inside the document.+ window.addEventListener("blur", updateLater);+ window.addEventListener("focus", updateLater);+ return () => {+ window.clearTimeout(timer);+ element.removeEventListener("focusin", update);+ element.removeEventListener("focusout", updateLater);+ window.removeEventListener("blur", updateLater);+ window.removeEventListener("focus", updateLater);+ };+ }, [ ref ]);++ return isFocusWithin;+}+/*** `value`, held at true for `ms` after it turns false, for something that leaves the page with an* animation: what draws it keeps drawing it that long, and tells it that it is leaving.diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsxindex 576cef6140..8ada8f5dd6 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx@@ -295,6 +295,29 @@ describe("ContentEmbed", () => {renderBox({ boxSize: "small" });expect(container.querySelector(".include-note-fullscreen-controls")).toBeNull();});++ it("keeps its content behind a backdrop until a click on it focuses the content", async () => {+ renderBox();+ const box = contentBox();+ const isActive = () => box.parentElement?.classList.contains("active");+ const backdrop = () => container.querySelector<HTMLElement>(+ ".include-note-body > .include-note-content + .include-note-backdrop"+ );+ const firstBackdrop = backdrop();+ expect(firstBackdrop).not.toBeNull();+ expect(box.tabIndex).toBe(-1);+ expect(isActive()).toBe(false);+ if (!firstBackdrop) return;++ click(firstBackdrop);+ expect(document.activeElement).toBe(box);+ expect(backdrop()).toBeNull();+ expect(isActive()).toBe(true);++ act(() => box.blur());+ await vi.waitFor(() => expect(backdrop()).not.toBeNull());+ expect(isActive()).toBe(false);+ });});describe("TinyContentEmbed", () => {diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsxindex 1a070045a1..aa5ccde8d0 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx@@ -7,6 +7,7 @@ import content_renderer from "../../../services/content_renderer";import { t } from "../../../services/i18n";import type { ViewScope } from "../../../services/link";import ActionButton from "../../react/ActionButton";+import { useFocusWithin } from "../../react/hooks";import Icon from "../../react/Icon";import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";@@ -47,6 +48,7 @@ export default function ContentEmbed({boxSize, title, content, contentType, notePath, viewScope}: ContentEmbedProps) {const contentRef = useRef<HTMLDivElement>(null);+ const isContentActive = useFocusWithin(contentRef);const [ isExpanded, setIsExpanded ] = useState(false);const isExpandable = boxSize === "expandable";const hasFullscreen = boxSize === "medium" || boxSize === "full";@@ -97,29 +99,38 @@ export default function ContentEmbed({)}<MoreActionsButton notePath={notePath} viewScope={viewScope} /></div>- <div- ref={contentRef}- className={`include-note-content type-${contentType}`}- hidden={isExpandable && !isExpanded}- >- {hasFullscreen && (- <div className="include-note-fullscreen-controls">- <OverlayControlGroup- placement="top-end"- className="include-note-exit-fullscreen"- >- <OverlayControlButton- icon="bx-exit"- text={t("common.exit_fullscreen")}- onClick={(e) => {- e.stopPropagation();- document.exitFullscreen().catch((error: unknown) => {- console.warn("Could not leave fullscreen:", error);- });- }}- />- </OverlayControlGroup>- </div>+ <div className={clsx("include-note-body", isContentActive && "active")}>+ <div+ ref={contentRef}+ className={`include-note-content type-${contentType}`}+ hidden={isExpandable && !isExpanded}+ tabIndex={-1}+ >+ {hasFullscreen && (+ <div className="include-note-fullscreen-controls">+ <OverlayControlGroup+ placement="top-end"+ className="include-note-exit-fullscreen"+ >+ <OverlayControlButton+ icon="bx-exit"+ text={t("common.exit_fullscreen")}+ onClick={(e) => {+ e.stopPropagation();+ document.exitFullscreen().catch((error: unknown) => {+ console.warn("Could not leave fullscreen:", error);+ });+ }}+ />+ </OverlayControlGroup>+ </div>+ )}+ </div>+ {!isContentActive && (+ <div+ className="include-note-backdrop"+ onClick={() => contentRef.current?.focus({ preventScroll: true })}+ />)}</div></>diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.tsindex d3795de8c2..02d15572ac 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts@@ -386,6 +386,40 @@ describe("ContentEmbed", () => {expect(stop).not.toHaveBeenCalled();});+ it("leaves a mousedown in the content alone, and selects the widget on the backdrop", () => {+ const embed = insertContentEmbed(editor, "noteBackdrop", "small");+ editor.model.change((writer) => {+ const paragraph = embed.nextSibling;+ if (!paragraph) {+ throw new Error("Expected a paragraph after the embed.");+ }+ writer.setSelection(paragraph, 0);+ });++ const wrapper = editor.editing.view.getDomRoot()?.querySelector("div.include-note-wrapper");+ expect(wrapper).not.toBeNull();+ if (!wrapper) {+ return;+ }+ wrapper.innerHTML = `<div class="include-note-body">`+ + `<div class="include-note-content"><p>text</p></div>`+ + `<div class="include-note-backdrop"></div></div>`;+ const text = wrapper.querySelector(".include-note-content p");+ const backdrop = wrapper.querySelector(".include-note-backdrop");++ const textEvt = new MouseEvent("mousedown", { bubbles: true, cancelable: true });+ const textStop = vi.spyOn(textEvt, "stopPropagation");+ text?.dispatchEvent(textEvt);+ expect(textEvt.defaultPrevented).toBe(false);+ expect(textStop).not.toHaveBeenCalled();+ expect(editor.model.document.selection.getSelectedElement()).toBeNull();++ const backdropEvt = new MouseEvent("mousedown", { bubbles: true, cancelable: true });+ backdrop?.dispatchEvent(backdropEvt);+ expect(backdropEvt.defaultPrevented).toBe(true);+ expect(editor.model.document.selection.getSelectedElement()).toBe(embed);+ });+it("leaves a mousedown inside an embedded collection untouched so the live widget keeps working", () => {insertContentEmbed(editor, "noteColl", "full");diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex e69c663817..2f2170e516 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -1035,6 +1035,9 @@ function preventCKEditorHandling( domElement: HTMLElement, editor: Editor ) {* caret or their own controls) and, crucially, live embedded widgets: web views and collection views* (geo map, calendar, board, table) whose own drag/click handlers rely on the native event.*+ * Covers all of `.include-note-content` as well: the host covers it with `.include-note-backdrop`+ * until the content has the focus, and a press inside it keeps that focus out of the editor.+ ** The match is bounded to within `boundary` (the widget wrapper) so the editable editor root — an* ancestor with `contenteditable="true"` — is never mistaken for an interactive target.*/@@ -1044,7 +1047,7 @@ function isInteractiveTarget( target: EventTarget | null, boundary: HTMLElement}const match = target.closest(- '.rendered-collection, .note-detail-web-view, ' ++ '.include-note-content, .rendered-collection, .note-detail-web-view, ' +'a, button, input, textarea, select, label, audio, video, ' +'[role="button"], [role="textbox"], [contenteditable]:not([contenteditable="false"])');