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/content embed: tweak the title bar
Adorian Doran1cb814ae775f
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 9e15d4fcec..ee018c10d1 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1191,11 +1191,27 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-ttext-decoration: none;}-/* Expandable include note styles */-.include-note[data-box-size="expandable"] .include-note-title-row {+.include-note[data-box-size="expandable"] > .include-note-wrapper > .include-note-title-row {+ border-start-start-radius: var(--_include-note-top-border-radius, 8px);+ border-start-end-radius: var(--_include-note-top-border-radius, 8px);++ &:hover {+ background: var(--card-background-hover-color);+ }+}++.include-note[data-box-size="expandable"]:not(.ck-widget)+ > .include-note-wrapper > .include-note-title-row {cursor: pointer;}+.include-note[data-box-size="expandable"]:not(:has(> figcaption))+ > .include-note-wrapper:has(> .include-note-body > .include-note-content[hidden])+ > .include-note-title-row {+ border-end-start-radius: var(--_include-note-bottom-border-radius, 8px);+ border-end-end-radius: var(--_include-note-bottom-border-radius, 8px);+}+/* The title inside the expandable row defers its header styling to the row. */.include-note-title-row .include-note-title {display: flex;@@ -1203,9 +1219,12 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-tmargin: 0;padding: 0;border-bottom: none;+ width: max-content;font-weight: inherit;font-size: inherit;- min-width: 0;+}++.include-note-title-row > .include-note-title-label {flex-grow: 1;}@@ -1213,11 +1232,22 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-tflex-shrink: 0;}+/* Browsers drop a click on a disabled button, which then toggles no expandable embed. */+.include-note-title-row > .icon-action.disabled {+ pointer-events: auto;+}+.include-note-title-row > .include-note-badges:empty {display: none;}+.include-note-badges > .excerpt-badge {+ order: 1;+}+.include-note-toggle {+ --icon-button-hover-background: transparent;+transition: transform 0.2s ease;}diff --git a/apps/client/src/widgets/react/ScrollableLabel.spec.tsx b/apps/client/src/widgets/react/ScrollableLabel.spec.tsxindex 6dbbadbc97..11c078f0f9 100644--- a/apps/client/src/widgets/react/ScrollableLabel.spec.tsx+++ b/apps/client/src/widgets/react/ScrollableLabel.spec.tsx@@ -1,4 +1,4 @@-import { render } from "preact";+import { type ComponentChildren, render } from "preact";import { act } from "preact/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";@@ -18,7 +18,9 @@ afterEach(() => {* happy-dom lays nothing out, so the metrics the component reads are given directly. `scrollLeft` is* writable already; the two widths are not, and stand for a line of the given length in a 100px box.*/-function renderLabel(text: string, scrollWidth: number, clientWidth = 100, autoScroll = false) {+function renderLabel(+ text: ComponentChildren, scrollWidth: number, clientWidth = 100, autoScroll = false+) {const mountPoint = document.body.appendChild(document.createElement("div"));container = mountPoint;// Flushed here: the fade attaches its listeners from an effect, which Preact defers past the@@ -50,6 +52,20 @@ async function scrollTo(label: HTMLDivElement, scrollLeft: number) {await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });}+/** Dispatches a pointer event of the primary mouse button at `clientX`. */+function pointer(target: Element, type: string, clientX: number, init: PointerEventInit = {}) {+ target.dispatchEvent(new PointerEvent(type, {+ bubbles: true, pointerId: 1, pointerType: "mouse", button: 0, clientX, ...init+ }));+}++/** Dispatches a cancelable `type` event on `target` and tells whether the label canceled it. */+function isPrevented(target: Element, type: string) {+ const event = new MouseEvent(type, { bubbles: true, cancelable: true });+ target.dispatchEvent(event);+ return event.defaultPrevented;+}+describe("ScrollableLabel", () => {it("fades whichever end the line carries on past, and neither where it fits", async () => {const label = renderLabel("a name far longer than its box", 300);@@ -162,6 +178,78 @@ describe("ScrollableLabel", () => {}});+ it("scrolls with a mouse dragged along it, in place of a native drag or selection", () => {+ const label = renderLabel(<span className="text">a name longer than its box</span>, 300);+ const text = label.querySelector(".text");+ expect(text).not.toBeNull();+ if (!text) return;+ const click = vi.fn();+ label.parentElement?.addEventListener("click", click);++ pointer(text, "pointerdown", 100);+ expect(isPrevented(text, "dragstart")).toBe(true);+ expect(isPrevented(text, "selectstart")).toBe(true);+ pointer(text, "pointermove", 98);+ expect(label.scrollLeft).toBe(0);+ expect(label.hasPointerCapture(1)).toBe(false);++ pointer(text, "pointermove", 40);+ expect(label.scrollLeft).toBe(60);+ expect(label.hasPointerCapture(1)).toBe(true);+ pointer(label, "pointermove", 70);+ expect(label.scrollLeft).toBe(30);+ pointer(label, "pointerup", 70);+ expect(isPrevented(label, "click")).toBe(true);+ expect(click).not.toHaveBeenCalled();++ // A canceled drag stops there.+ pointer(text, "pointerdown", 70);+ pointer(text, "pointermove", 20);+ pointer(text, "pointercancel", 20);+ pointer(text, "pointermove", 0);+ expect(label.scrollLeft).toBe(80);+ expect(isPrevented(text, "click")).toBe(false);++ // A press that stays put is a click.+ pointer(text, "pointerdown", 0);+ pointer(text, "pointerup", 0);+ expect(isPrevented(text, "click")).toBe(false);++ // So is a tap after a drag whose click never came.+ pointer(text, "pointerdown", 20);+ pointer(text, "pointermove", 0);+ pointer(text, "pointerup", 0);+ pointer(text, "pointerdown", 0, { pointerType: "touch" });+ pointer(text, "pointerup", 0, { pointerType: "touch" });+ expect(isPrevented(text, "click")).toBe(false);+ expect(click).toHaveBeenCalledTimes(3);+ expect(label.scrollLeft).toBe(100);+ });++ it("leaves the presses of a touch, another button, or on a label that fits alone", () => {+ const presses: [ number, PointerEventInit ][] = [+ [ 300, { pointerType: "touch" } ],+ [ 300, { button: 1 } ],+ [ 100, {} ]+ ];++ for (const [ scrollWidth, init ] of presses) {+ const label = renderLabel("a name", scrollWidth);+ pointer(label, "pointerdown", 100, init);+ expect(isPrevented(label, "dragstart")).toBe(false);+ pointer(label, "pointermove", 40, init);+ expect(label.scrollLeft).toBe(0);+ pointer(label, "pointerup", 40, init);+ expect(isPrevented(label, "click")).toBe(false);++ const mountPoint = label.parentElement;+ if (mountPoint) {+ act(() => render(null, mountPoint));+ mountPoint.remove();+ }+ }+ });+it("leaves a label that fits alone, fading nothing", async () => {const label = renderLabel("short", 100);diff --git a/apps/client/src/widgets/react/ScrollableLabel.tsx b/apps/client/src/widgets/react/ScrollableLabel.tsxindex 35c9ff0ba3..c57a6e5d02 100644--- a/apps/client/src/widgets/react/ScrollableLabel.tsx+++ b/apps/client/src/widgets/react/ScrollableLabel.tsx@@ -1,7 +1,7 @@import "./ScrollableLabel.css";import clsx from "clsx";-import type { ComponentChildren } from "preact";+import type { ComponentChildren, RefObject } from "preact";import { useCallback, useEffect, useRef } from "preact/hooks";import { useScrollFade } from "./scroll_fade";@@ -9,6 +9,9 @@ import { useScrollFade } from "./scroll_fade";/** How fast a label reads itself out, in pixels a second: walking pace for the eye, not a marquee. */const AUTO_SCROLL_SPEED = 30;+/** How far a pressed mouse moves along the label before it drags the line, in pixels. */+const DRAG_THRESHOLD = 4;+interface ScrollableLabelProps {children?: ComponentChildren;className?: string;@@ -43,6 +46,7 @@ export default function ScrollableLabel({ children, className, autoScroll }: Scrdirection: "horizontal",minOverflow: 1});+ useMouseDragScroll(ref);// Set by the reader's own first scroll, and cleared only by a remount, which is what a new label// is: a walk they interrupted must not start again while the same line is still on screen. A// consumer whose label changes what it names keys it, so the new one arrives with a fresh walk.@@ -117,6 +121,83 @@ export default function ScrollableLabel({ children, className, autoScroll }: Scr);}+/**+ * Scrolls the label in `ref` with a mouse dragged along it, as a swipe does on a touch screen.+ * While the label overflows, a mouse press on it starts no native drag, such as that of a link, and+ * no text selection, and the click that ends a drag is canceled.+ */+function useMouseDragScroll(ref: RefObject<HTMLElement | null>) {+ useEffect(() => {+ const element = ref.current;+ if (!element) return;++ let press: { pointerId: number; x: number; scrollLeft: number; isDragging: boolean }+ | undefined;+ let isClickCanceled = false;++ const onPointerDown = (event: PointerEvent) => {+ isClickCanceled = false;+ press = event.pointerType === "mouse" && event.button === 0+ && element.scrollWidth > element.clientWidth+ ? {+ pointerId: event.pointerId,+ x: event.clientX,+ scrollLeft: element.scrollLeft,+ isDragging: false+ }+ : undefined;+ };+ const onPointerMove = (event: PointerEvent) => {+ if (event.pointerId !== press?.pointerId) return;++ const distance = event.clientX - press.x;+ if (!press.isDragging && Math.abs(distance) >= DRAG_THRESHOLD) {+ press.isDragging = true;+ // Keeps the drag going once the pointer leaves the label.+ element.setPointerCapture(event.pointerId);+ }+ if (press.isDragging) {+ element.scrollLeft = press.scrollLeft - distance;+ }+ };+ const onPointerUp = (event: PointerEvent) => {+ if (event.pointerId !== press?.pointerId) return;++ isClickCanceled = event.type === "pointerup" && press.isDragging;+ press = undefined;+ };+ const preventWhilePressed = (event: Event) => {+ if (press) {+ event.preventDefault();+ }+ };+ const cancelClick = (event: MouseEvent) => {+ if (isClickCanceled) {+ isClickCanceled = false;+ event.preventDefault();+ event.stopPropagation();+ }+ };++ element.addEventListener("pointerdown", onPointerDown);+ element.addEventListener("pointermove", onPointerMove);+ element.addEventListener("pointerup", onPointerUp);+ element.addEventListener("pointercancel", onPointerUp);+ element.addEventListener("dragstart", preventWhilePressed);+ element.addEventListener("selectstart", preventWhilePressed);+ element.addEventListener("click", cancelClick, true);+ return () => {+ element.removeEventListener("pointerdown", onPointerDown);+ element.removeEventListener("pointermove", onPointerMove);+ element.removeEventListener("pointerup", onPointerUp);+ element.removeEventListener("pointercancel", onPointerUp);+ element.removeEventListener("dragstart", preventWhilePressed);+ element.removeEventListener("selectstart", preventWhilePressed);+ element.removeEventListener("click", cancelClick, true);+ };+ }, [ ref ]);+}+/** A line that moves on its own is the thing this setting is there to ask for less of. */function prefersReducedMotion() {return window.matchMedia("(prefers-reduced-motion: reduce)").matches;diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsxindex 0500d470b0..38498ca0c2 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx@@ -206,14 +206,14 @@ function click(target: HTMLElement) {describe("ContentEmbed", () => {it("lays out the title row for each box size", () => {- const plain = [ "title", "badges", "open", "menu" ];- const withFullscreen = [ "title", "badges", "open", "fullscreen", "menu" ];+ const plain = [ "title-label", "badges", "open", "menu" ];+ const withFullscreen = [ "title-label", "badges", "open", "fullscreen", "menu" ];const layouts: [ string | undefined, string[] ][] = [[ undefined, plain ],[ "small", plain ],[ "medium", withFullscreen ],[ "full", withFullscreen ],- [ "expandable", [ "toggle", "title", "badges", "open", "menu" ] ]+ [ "expandable", [ "toggle", "title-label", "badges", "open", "menu" ] ]];for (const [ boxSize, expected ] of layouts) {@@ -224,7 +224,7 @@ describe("ContentEmbed", () => {});it("lays out an excerpt with an edit button in place of fullscreen", () => {- const excerpt = [ "title", "badges", "open", "edit", "menu" ];+ const excerpt = [ "title-label", "badges", "open", "edit", "menu" ];const layouts: [ string, string[] ][] = [[ "small", excerpt ],[ "medium", excerpt ],@@ -240,9 +240,11 @@ describe("ContentEmbed", () => {}});- it("shows its title and content, and swaps them on a new render", () => {+ it("shows its scrollable title and its content, and swaps them on a new render", () => {const titleChildren = () => [- ...container.querySelector("h4.include-note-title")?.childNodes ?? []+ ...container.querySelector(+ ".include-note-title-label.scrollable-label > h4.include-note-title"+ )?.childNodes ?? []];const first = renderBox({ contentType: "pdf" });const box = contentBox();@@ -291,6 +293,39 @@ describe("ContentEmbed", () => {expect(contentBox().hidden).toBe(false);});+ it("toggles an expandable box on a click on its title row, but its buttons and link", () => {+ const titleRow = () => {+ const row = container.querySelector<HTMLElement>(".include-note-title-row");+ const label = row?.querySelector<HTMLElement>(".include-note-title-label");+ const link = label?.querySelector<HTMLElement>("a");+ if (!row || !label || !link) {+ throw new Error("Expected the title row, its label and its link.");+ }+ link.addEventListener("click", (e) => e.preventDefault());+ return { row, label, link };+ };+ renderBox({ boxSize: "expandable" });+ const { row, label, link } = titleRow();++ click(row);+ expect(contentBox().hidden).toBe(false);+ click(label);+ expect(contentBox().hidden).toBe(true);+ for (const target of [ link, button("include-note-open"), button("include-note-menu") ]) {+ click(target);+ expect(contentBox().hidden).toBe(true);+ }+ click(button("include-note-toggle"));+ expect(contentBox().hidden).toBe(false);++ // In an editor, a click on the row selects the embed instead.+ act(() => render(null, container));+ placeInHostEditor();+ renderBox({ boxSize: "expandable" });+ click(titleRow().row);+ expect(contentBox().hidden).toBe(true);+ });+it("opens the note in a new tab, and its context menu, from the title row", () => {renderBox({ notePath: "owner", viewScope: ATTACHMENT_SCOPE });const open = button("include-note-open");@@ -664,8 +699,11 @@ describe("TinyContentEmbed", () => {]);expect(container.querySelector(".include-note-content")).toBeNull();expect(container.querySelector(".include-note-icon")?.className).toContain("bx-file");- expect([ ...container.querySelector("h4.include-note-title")?.childNodes ?? [] ])- .toEqual([ title ]);+ expect([+ ...container.querySelector(+ ".include-note-heading > .scrollable-label > h4.include-note-title"+ )?.childNodes ?? []+ ]).toEqual([ title ]);expect(container.querySelector(".include-note-heading > small.include-note-description")?.textContent).toBe("2 KiB");diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsxindex 1b5d03de3a..d37aaa524c 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx@@ -14,6 +14,7 @@ import { Badge } from "../../react/Badge";import { useFocusWithin } from "../../react/hooks";import Icon from "../../react/Icon";import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";+import ScrollableLabel from "../../react/ScrollableLabel";import {type ContentEmbedEvent, getContentEmbedTools, showContentEmbedFullscreen,useIsContentEmbedEditable, watchContentEmbedTools@@ -91,6 +92,11 @@ export default function ContentEmbed({<><divclassName="include-note-title-row"+ onClick={(e) => {+ if (isExpandable && isTogglingClick(e)) {+ setIsExpanded(!isExpanded);+ }+ }}onContextMenu={(e) => openMenuOnRightClick(e, notePath, viewScope)}>{isExpandable && (@@ -341,6 +347,7 @@ function getFocusTargetAt(content: HTMLElement, x: number, y: number) {return hit?.closest<HTMLElement>(FOCUSABLE_SELECTOR) ?? content;}+/** The title on a single line, which scrolls sideways when it does not fit. */function ContentEmbedTitle({ title }: { title: HTMLElement }) {const titleRef = useRef<HTMLHeadingElement>(null);@@ -348,7 +355,11 @@ function ContentEmbedTitle({ title }: { title: HTMLElement }) {titleRef.current?.replaceChildren(title);}, [ title ]);- return <h4 ref={titleRef} className="include-note-title" />;+ return (+ <ScrollableLabel className="include-note-title-label">+ <h4 ref={titleRef} className="include-note-title" />+ </ScrollableLabel>+ );}function ContentEmbedActionButton({ className, action }: {@@ -459,6 +470,15 @@ function useFullscreenEvents(contentRef: RefObject<HTMLElement | null>) {}, [ contentRef ]);}+/**+ * Whether a click on the title row expands or collapses the embed: one outside its buttons and+ * link, in content that no text editor holds. In an editor, the click selects the embed.+ */+function isTogglingClick(e: MouseEvent) {+ return e.target instanceof Element && !e.target.closest("a, button")+ && e.currentTarget instanceof HTMLElement && !findTextEditorAround(e.currentTarget);+}+/*** 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.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 e98c5801e0..8cd40cd6e9 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@@ -29,7 +29,8 @@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.</li>+ 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>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 88d3b7ff0e..af38de7cbb 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@@ -20,7 +20,7 @@ The box size sets how much of the included note is shown.* _Tiny_ 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 _Tiny_ include appears as a link to the included note.* _Small_ and _Medium_ 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.* _Full_ shows the whole content.-* _Expandable_ shows only the title until its <span class="tn-icon bx bx-chevron-right"></span> arrow is pressed.+* _Expandable_ 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.A new include gets the size that suits what it shows: