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/canvas: relocate the "Library" and "Search" pane outside of the canvas
Adorian Doran3263d55ef06c
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.cssindex a757b06d46..f297397214 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css@@ -71,20 +71,29 @@opacity: 0;}-/* The properties panel beside the drawing, in the top layer, placed by `useSidePanel()`. */-.canvas-drawing-editor[data-side-panel] {- /* Resets the user agent style of a popover as well as Excalidraw's own placement. */- .Island.App-menu__left[popover] {- position: fixed;- inset: var(--side-panel-top) auto auto var(--side-panel-left);- margin: 0;- border: none;- /* Overrides the height limit that Excalidraw sets inline. */- max-height: var(--side-panel-max-height) !important;- color: inherit;+/* The library and the properties panel beside the drawing, in the top layer, placed by+ `useSidePanels()`. Resets the user agent style of a popover and Excalidraw's own placement. */+.canvas-drawing-editor .excalidraw .Island[data-side-panel][popover] {+ position: fixed;+ inset: var(--side-panel-top) auto auto var(--side-panel-left);+ margin: 0;+ border: none;+ height: var(--side-panel-height, fit-content);+ /* Overrides the height limit that Excalidraw sets inline on the properties panel. */+ max-height: var(--side-panel-max-height) !important;+ color: inherit;++ &.default-sidebar {+ border: 1px solid var(--sidebar-border-color);+ border-radius: var(--border-radius-lg);}}+/* Excalidraw narrows its controls for a docked library, which is beside the drawing instead. */+.canvas-drawing-editor:has(.default-sidebar[data-side-panel]) .layer-ui__wrapper {+ width: 100% !important;+}+/* The tools, undo and redo, and zoom are buttons of the embed's toolbar, which fullscreen hides.`CanvasTools` clicks the hidden undo and redo buttons. */.include-note-content:not(:fullscreen) .canvas-drawing .excalidraw {diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsxindex 9de8e23037..57050b474f 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx@@ -26,7 +26,7 @@ globalThis.ResizeObserver = class {} as unknown as typeof ResizeObserver;const {- default: CanvasDrawing, useIsToolbarOverPanel, useSidePanel+ default: CanvasDrawing, useIsToolbarOverPanel, useSidePanels} = await import("./CanvasDrawing");/** Horizontal edges by class name; happy-dom computes no layout. */@@ -94,19 +94,23 @@ describe("useIsToolbarOverPanel", () => {});});-describe("useSidePanel", () => {+describe("useSidePanels", () => {/** Boxes by class name, in pixels; happy-dom computes no layout. */const rects: Record<string, { left: number; top: number; right: number; bottom: number }> = {};let container: HTMLElement;let showPopover: ReturnType<typeof vi.fn>;- function SidePanelProbe({ isEnabled }: { isEnabled: boolean }) {+ function SidePanelProbe({ isEnabled, hasLibrary }: {+ isEnabled: boolean;+ hasLibrary: boolean;+ }) {const rootRef = useRef<HTMLDivElement>(null);- useSidePanel(rootRef, isEnabled);+ useSidePanels(rootRef, isEnabled);return (<div className="scrolling-container"><div className="include-note-body active"><div ref={rootRef} className="drawing">+ {hasLibrary && <div className="Island sidebar default-sidebar" />}<div className="App-menu__left" /></div></div>@@ -151,13 +155,15 @@ describe("useSidePanel", () => {Reflect.deleteProperty(document, "fullscreenElement");});- async function mount(panelHeight: number) {- await act(async () => render(<SidePanelProbe isEnabled={false} />, container));+ async function mount(panelHeight: number, hasLibrary = false) {+ await act(async () => {+ render(<SidePanelProbe isEnabled={false} hasLibrary={hasLibrary} />, container);+ });const viewport = container.querySelector(".scrolling-container");const body = container.querySelector(".include-note-body");- const root = container.querySelector<HTMLElement>(".drawing");const panel = container.querySelector<HTMLElement>(".App-menu__left");- if (!viewport || !body || !root || !panel) {+ const library = container.querySelector<HTMLElement>(".default-sidebar");+ if (!viewport || !body || !panel) {throw new Error("Expected the probe.");}Object.defineProperties(viewport, {@@ -168,85 +174,113 @@ describe("useSidePanel", () => {offsetWidth: { value: 200 },offsetHeight: { value: panelHeight, configurable: true }});+ if (library) {+ Object.defineProperty(library, "offsetWidth", { value: 200 });+ }- await act(async () => render(<SidePanelProbe isEnabled />, container));- return { viewport, body, root, panel };+ await act(async () => {+ render(<SidePanelProbe isEnabled hasLibrary={hasLibrary} />, container);+ });+ return { viewport, body, panel, library };}- /** The position of the panel beside the drawing, or `false` while it is in the drawing. */- function getPlacement(root: HTMLElement, panel: HTMLElement) {- const isPlaced = root.hasAttribute("data-side-panel");- expect(panel.getAttribute("popover")).toBe(isPlaced ? "manual" : null);+ /** The position of `panel` beside the drawing, or `false` while it is in the drawing. */+ function getPlacement(panel: HTMLElement | null) {+ const isPlaced = !!panel?.hasAttribute("data-side-panel");+ expect(panel?.getAttribute("popover") ?? null).toBe(isPlaced ? "manual" : null);return isPlaced && [ "left", "top", "max-height" ]- .map((name) => root.style.getPropertyValue(`--side-panel-${name}`));+ .map((name) => panel?.style.getPropertyValue(`--side-panel-${name}`));}it("places the panel level with the drawing's top, on its right or else its left", async () => {- const { viewport, root, panel } = await mount(300);- expect(getPlacement(root, panel)).toEqual([ "848px", "200px", "884px" ]);+ const { viewport, panel } = await mount(300);+ expect(getPlacement(panel)).toEqual([ "848px", "200px", "884px" ]);rects.drawing = { left: 340, top: 200, right: 1100, bottom: 520 };viewport.dispatchEvent(new Event("scroll"));- expect(getPlacement(root, panel)).toEqual([ "132px", "200px", "884px" ]);+ expect(getPlacement(panel)).toEqual([ "132px", "200px", "884px" ]);expect(showPopover).toHaveBeenCalledTimes(1);});+ it("places the library first, as tall as the drawing, the panel on a free side", async () => {+ const { viewport, panel, library } = await mount(300, true);+ expect(getPlacement(library)).toEqual([ "848px", "200px", "884px" ]);+ expect(library?.style.getPropertyValue("--side-panel-height")).toBe("320px");+ expect(getPlacement(panel)).toEqual([ "132px", "200px", "884px" ]);+ expect(panel.style.getPropertyValue("--side-panel-height")).toBe("");++ // A drawing of 160px gives the library its least height of 20rem.+ rects.drawing = { left: 340, top: 200, right: 1100, bottom: 360 };+ viewport.dispatchEvent(new Event("scroll"));+ expect(getPlacement(library)).toEqual([ "132px", "200px", "884px" ]);+ expect(library?.style.getPropertyValue("--side-panel-height")).toBe("320px");+ expect(getPlacement(panel)).toBe(false);++ rects.drawing = { left: 340, top: 100, right: 840, bottom: 1100 };+ viewport.dispatchEvent(new Event("scroll"));+ expect(getPlacement(library)).toEqual([ "848px", "8px", "884px" ]);+ expect(library?.style.getPropertyValue("--side-panel-height")).toBe("884px");+ expect(getPlacement(panel)).toEqual([ "132px", "100px", "884px" ]);+ });+it("keeps the panel inside the window while the note scrolls", async () => {- const { viewport, root, panel } = await mount(300);+ const { viewport, panel } = await mount(300);rects.drawing = { left: 340, top: -50, right: 840, bottom: 270 };viewport.dispatchEvent(new Event("scroll"));- expect(getPlacement(root, panel)).toEqual([ "848px", "8px", "884px" ]);+ expect(getPlacement(panel)).toEqual([ "848px", "8px", "884px" ]);rects.drawing = { left: 340, top: 700, right: 840, bottom: 1020 };viewport.dispatchEvent(new Event("scroll"));- expect(getPlacement(root, panel)).toEqual([ "848px", "592px", "884px" ]);+ expect(getPlacement(panel)).toEqual([ "848px", "592px", "884px" ]);Object.defineProperty(panel, "offsetHeight", { value: 1000 });viewport.dispatchEvent(new Event("scroll"));- expect(getPlacement(root, panel)).toEqual([ "848px", "8px", "884px" ]);+ expect(getPlacement(panel)).toEqual([ "848px", "8px", "884px" ]);});it("keeps the panel in the drawing without room beside it or out of view", async () => {- const { viewport, root, panel } = await mount(300);+ const { viewport, panel } = await mount(300);rects.drawing = { left: 100, top: 200, right: 1100, bottom: 520 };viewport.dispatchEvent(new Event("scroll"));- expect(getPlacement(root, panel)).toBe(false);+ expect(getPlacement(panel)).toBe(false);// Inside the window, but scrolled out of the note area.rects.drawing = { left: 340, top: 810, right: 840, bottom: 1130 };viewport.dispatchEvent(new Event("scroll"));- expect(getPlacement(root, panel)).toBe(false);+ expect(getPlacement(panel)).toBe(false);rects.drawing = { left: 340, top: -300, right: 840, bottom: 90 };viewport.dispatchEvent(new Event("scroll"));- expect(getPlacement(root, panel)).toBe(false);+ expect(getPlacement(panel)).toBe(false);rects.drawing = { left: 340, top: 200, right: 840, bottom: 520 };viewport.dispatchEvent(new Event("scroll"));- expect(getPlacement(root, panel)).not.toBe(false);+ expect(getPlacement(panel)).not.toBe(false);expect(showPopover).toHaveBeenCalledTimes(2);- await act(async () => render(<SidePanelProbe isEnabled={false} />, container));- expect(getPlacement(root, panel)).toBe(false);+ await act(async () => {+ render(<SidePanelProbe isEnabled={false} hasLibrary={false} />, container);+ });+ expect(getPlacement(panel)).toBe(false);});it("keeps the panel in the drawing without the focus or in fullscreen", async () => {- const { body, root, panel } = await mount(300);+ const { body, panel } = await mount(300);await act(async () => body.classList.remove("active"));- expect(getPlacement(root, panel)).toBe(false);+ expect(getPlacement(panel)).toBe(false);await act(async () => body.classList.add("active"));- expect(getPlacement(root, panel)).not.toBe(false);+ expect(getPlacement(panel)).not.toBe(false);Object.defineProperty(document, "fullscreenElement", {value: container,configurable: true});document.dispatchEvent(new Event("fullscreenchange"));- expect(getPlacement(root, panel)).toBe(false);+ expect(getPlacement(panel)).toBe(false);});});diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsxindex 9c6c7ff62d..16b74b2b3a 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx@@ -36,7 +36,7 @@ export default function CanvasDrawing({ attachment, editor }: CanvasDrawingProps);const isToolbarOverPanel = useIsToolbarOverPanel(rootRef);useFocusFromEmbedBox(rootRef);- useSidePanel(rootRef, isEditable);+ useSidePanels(rootRef, isEditable);return (<div@@ -139,36 +139,51 @@ export function useIsToolbarOverPanel(rootRef: RefObject<HTMLElement>) {return isOver;}-/** The space between the drawing, the properties panel and the edges of the window, in rem. */+/** The space between the drawing, the panels beside it and the edges of the window, in rem. */const SIDE_PANEL_GAP_REM = 0.5;+/** The least height of a panel as tall as the drawing, in rem. */+const SIDE_PANEL_MIN_HEIGHT_REM = 20;++/** The panels of Excalidraw that go beside the drawing, in the order in which they take a side. */+const SIDE_PANELS = [+ // The item list of the library fills the height it is given and has none of its own.+ { selector: ".default-sidebar", hasDrawingHeight: true },+ { selector: ".App-menu__left", hasDrawingHeight: false }+];++type Side = "left" | "right";/**- * Shows Excalidraw's properties panel beside the drawing while the drawing has the focus, in the- * top layer so that no clip or stacking of the note covers it. Sets `data-side-panel` on the root- * while the panel is there, and its position in `--side-panel-*`.+ * Shows Excalidraw's library and properties panel beside the drawing while the drawing has the+ * focus, in the top layer so that no clip or stacking of the note covers them. A panel there has+ * `data-side-panel`, and its position in `--side-panel-*`.*/-export function useSidePanel(rootRef: RefObject<HTMLElement>, isEnabled: boolean) {+export function useSidePanels(rootRef: RefObject<HTMLElement>, isEnabled: boolean) {useEffect(() => {const root = rootRef.current;const viewport = root?.closest<HTMLElement>(".scrolling-container");const embedBody = root?.closest<HTMLElement>(".include-note-body");if (!root || !viewport || !embedBody || !isEnabled) return;- let panel: HTMLElement | null = null;+ const panels = new Map<string, HTMLElement>();const update = () => {// `ContentEmbed` marks the body active while the drawing has the focus.const isShown = embedBody.classList.contains("active")&& !document.fullscreenElement?.contains(root);- const position = panel && isShown ? getSidePanelPosition(root, viewport, panel) : null;-- root.toggleAttribute("data-side-panel", !!position);- if (position) {- root.style.setProperty("--side-panel-left", `${position.left}px`);- root.style.setProperty("--side-panel-top", `${position.top}px`);- root.style.setProperty("--side-panel-max-height", `${position.maxHeight}px`);+ const layout = isShown ? getSideLayout(root, viewport) : null;+ const takenSides = new Set<Side>();+ for (const { selector, hasDrawingHeight } of SIDE_PANELS) {+ const panel = panels.get(selector);+ if (!panel) continue;++ const position = layout+ && getSidePanelPosition(layout, panel, hasDrawingHeight, takenSides);+ if (position) {+ takenSides.add(position.side);+ }+ placePanel(panel, position || null);}- setTopLayer(panel, !!position);};const resizeObserver = new ResizeObserver(update);@@ -177,22 +192,31 @@ export function useSidePanel(rootRef: RefObject<HTMLElement>, isEnabled: booleanconst activeObserver = new MutationObserver(update);activeObserver.observe(embedBody, { attributes: true, attributeFilter: [ "class" ] });- // The panel mounts when a shape is selected or a tool is picked, and its height follows- // the properties of the selection.- const watchPanel = () => {- const current = root.querySelector<HTMLElement>(".App-menu__left");- if (current === panel) return;-- if (panel) resizeObserver.unobserve(panel);- panel = current;- if (panel) resizeObserver.observe(panel);- update();+ // The panels mount when they open, and the properties panel takes the height of the+ // properties of the selection.+ const watchPanels = () => {+ let isChanged = false;+ for (const { selector } of SIDE_PANELS) {+ const current = root.querySelector<HTMLElement>(selector);+ const previous = panels.get(selector);+ if (current === previous) continue;++ isChanged = true;+ if (previous) resizeObserver.unobserve(previous);+ if (current) {+ panels.set(selector, current);+ resizeObserver.observe(current);+ } else {+ panels.delete(selector);+ }+ }+ if (isChanged) update();};- const mutationObserver = new MutationObserver(watchPanel);+ const mutationObserver = new MutationObserver(watchPanels);mutationObserver.observe(root, { childList: true, subtree: true });viewport.addEventListener("scroll", update, { passive: true });document.addEventListener("fullscreenchange", update);- watchPanel();+ watchPanels();update();return () => {@@ -201,44 +225,88 @@ export function useSidePanel(rootRef: RefObject<HTMLElement>, isEnabled: booleanmutationObserver.disconnect();viewport.removeEventListener("scroll", update);document.removeEventListener("fullscreenchange", update);- root.removeAttribute("data-side-panel");- setTopLayer(panel, false);+ for (const panel of panels.values()) {+ placePanel(panel, null);+ }};}, [ rootRef, isEnabled ]);}-/**- * The position of `panel` beside the drawing `root`: on its right when the window has room there,- * otherwise on its left, level with the top of the drawing and inside the window. `null` when- * neither side has room or the drawing is scrolled out of `viewport`.- */-function getSidePanelPosition(root: HTMLElement, viewport: HTMLElement, panel: HTMLElement) {+interface SideLayout {+ drawing: DOMRect;+ /** The window, which the panels stay inside. */+ area: VisibleArea;+ gap: number;+ /** The least height of a panel as tall as the drawing. */+ minHeight: number;+}++/** The layout of the panels beside `root`, or `null` while it is scrolled out of `viewport`. */+function getSideLayout(root: HTMLElement, viewport: HTMLElement): SideLayout | null {const rem = parseFloat(getComputedStyle(document.documentElement).fontSize);- const gap = SIDE_PANEL_GAP_REM * rem;const drawing = root.getBoundingClientRect();const noteArea = getVisibleArea(viewport);if (drawing.bottom <= noteArea.top || drawing.top >= noteArea.bottom) {return null;}- const area = getWindowArea();- const left = getSidePanelLeft(drawing, area, panel.offsetWidth, gap);- if (left === null) {+ return {+ drawing,+ area: getWindowArea(),+ gap: SIDE_PANEL_GAP_REM * rem,+ minHeight: SIDE_PANEL_MIN_HEIGHT_REM * rem+ };+}++/**+ * The position of `panel` beside the drawing: on its right when the window has room there and+ * no other panel took that side, otherwise on its left, level with the top of the drawing and+ * inside the window. `null` when no free side has room.+ */+function getSidePanelPosition(+ { drawing, area, gap, minHeight }: SideLayout,+ panel: HTMLElement,+ hasDrawingHeight: boolean,+ takenSides: ReadonlySet<Side>+) {+ const placement = getSidePanelLeft(drawing, area, panel.offsetWidth, gap, takenSides);+ if (!placement) {return null;}const maxHeight = area.bottom - area.top - 2 * gap;- const height = Math.min(panel.offsetHeight, maxHeight);+ const contentHeight = hasDrawingHeight+ ? Math.max(drawing.height, minHeight)+ : panel.offsetHeight;+ const height = Math.min(contentHeight, maxHeight);const top = Math.max(area.top + gap, Math.min(drawing.top, area.bottom - gap - height));- return { left, top, maxHeight };+ return { ...placement, top, maxHeight, height: hasDrawingHeight ? height : null };+}++type SidePanelPosition = NonNullable<ReturnType<typeof getSidePanelPosition>>;++/** Moves `panel` to `position` beside the drawing, or back into the drawing for `null`. */+function placePanel(panel: HTMLElement, position: SidePanelPosition | null) {+ panel.toggleAttribute("data-side-panel", !!position);+ if (position) {+ panel.style.setProperty("--side-panel-left", `${position.left}px`);+ panel.style.setProperty("--side-panel-top", `${position.top}px`);+ panel.style.setProperty("--side-panel-max-height", `${position.maxHeight}px`);+ if (position.height === null) {+ panel.style.removeProperty("--side-panel-height");+ } else {+ panel.style.setProperty("--side-panel-height", `${position.height}px`);+ }+ }+ setTopLayer(panel, !!position);}/*** Moves `panel` into the top layer, or back into the drawing. The `popover` attribute is present* exactly while the panel is in the top layer; removing it hides the popover.*/-function setTopLayer(panel: HTMLElement | null, isMoved: boolean) {- if (!panel || isMoved === panel.hasAttribute("popover")) return;+function setTopLayer(panel: HTMLElement, isMoved: boolean) {+ if (isMoved === panel.hasAttribute("popover")) return;if (isMoved) {panel.setAttribute("popover", "manual");@@ -275,15 +343,25 @@ function getWindowArea(): VisibleArea {}/**- * The left edge of a panel `width` wide in the margin right of `drawing`, else in the margin left- * of it, or `null` when neither margin fits the panel with a `gap` on both sides.+ * The side and the left edge of a panel `width` wide in the margin right of `drawing`, else in+ * the margin left of it, or `null` when no side outside `takenSides` fits the panel with a `gap`+ * on both sides.*/-function getSidePanelLeft(drawing: DOMRect, area: VisibleArea, width: number, gap: number) {+function getSidePanelLeft(+ drawing: DOMRect,+ area: VisibleArea,+ width: number,+ gap: number,+ takenSides: ReadonlySet<Side>+): { side: Side; left: number } | null {const rightOfDrawing = drawing.right + gap;- if (rightOfDrawing + width + gap <= area.right) {- return rightOfDrawing;+ if (!takenSides.has("right") && rightOfDrawing + width + gap <= area.right) {+ return { side: "right", left: rightOfDrawing };}const leftOfDrawing = drawing.left - gap - width;- return leftOfDrawing >= area.left + gap ? leftOfDrawing : null;+ if (!takenSides.has("left") && leftOfDrawing >= area.left + gap) {+ return { side: "left", left: leftOfDrawing };+ }+ return null;}