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
refactor(popover): place the calendar's popovers with Floating UI instead of Popper
Elian Doranfb847132c320
diff --git a/apps/client/src/widgets/collections/calendar/EventPopover.css b/apps/client/src/widgets/collections/calendar/EventPopover.cssindex 512668e655..d0e2836b4e 100644--- a/apps/client/src/widgets/collections/calendar/EventPopover.css+++ b/apps/client/src/widgets/collections/calendar/EventPopover.css@@ -1,7 +1,6 @@.calendar-event-popover {- /* Held to the window: Popper shifts a card too wide for the room into the viewport rather than- narrowing it, so an unclamped width would hang off the edge.- Must agree with `MAX_ANCHOR_WIDTH` in selection.ts. */+ /* `Popover` shifts a card wider than the free space back into the viewport without narrowing+ it, so the width is clamped here. Must agree with `MAX_ANCHOR_WIDTH` in selection.ts. */width: min(480px, calc(100vw - 4rem));/* As tall as the event needs; what it holds scrolls within it (see the body below). */max-height: min(640px, 85vh);diff --git a/apps/client/src/widgets/collections/calendar/selection.ts b/apps/client/src/widgets/collections/calendar/selection.tsindex 1a035b86eb..4f354614f9 100644--- a/apps/client/src/widgets/collections/calendar/selection.ts+++ b/apps/client/src/widgets/collections/calendar/selection.ts@@ -37,10 +37,8 @@ export type CalendarSelection =* length of a week — or a range dragged across one — is drawn as a piece as wide as the grid, and* the far edge of that is nowhere near the press that opened the popover: the card lands at the* other end of the month, which is how a popover comes to appear over the note tree. Where the grid- * is as wide as the window, it lands nowhere at all — neither side has the room for a card, and- * Popper keeps a popover within the viewport only along the axis it was placed on (the vertical- * one, for a card standing to the left or the right; see Popover), so the card is put outside the- * screen entirely and only its shadow is ever seen.+ * is as wide as the window, neither side has room for the card, so `Popover` shifts it into the+ * viewport on top of the event.** So a piece wider than the card that stands beside it is narrowed to the press within it: the* popover appears where the eye already is, with the grid's own room on either side of it. Wherediff --git a/apps/client/src/widgets/react/Popover.css b/apps/client/src/widgets/react/Popover.cssindex b4f84a9ee8..57edfdde65 100644--- a/apps/client/src/widgets/react/Popover.css+++ b/apps/client/src/widgets/react/Popover.css@@ -12,8 +12,6 @@/* Above the note split's own layers; menus and dialogs stand higher still. */z-index: 998;- /* Popper writes this too, but gives it back as it is destroyed; without it here the panel- falls into the page's flow for a frame on the way back from being maximized. */position: fixed;display: flex;flex-direction: column;@@ -26,10 +24,16 @@backdrop-filter: var(--dropdown-backdrop-filter, blur(10px));}-/* The card let go of its anchor and grown to the window (see `maximized` in Popover.tsx). Popper- takes the placement attribute off as it is destroyed, so its absence is what says the inline- placement has been given back and the stylesheet may place the card itself. */-.tn-popover.maximized:not([data-popper-placement]) {+/* Hidden until `placeFloating()` sets its position. */+.tn-popover:not(.maximized) {+ top: 0;+ left: 0;+ visibility: hidden;+}++/* A maximized card (see `maximized` in Popover.tsx). `Popover` removes `data-placement` together+ with the inline position, so these rules apply only once both are gone. */+.tn-popover.maximized:not([data-placement]) {position: fixed;inset-block: 5vh;inset-inline: 0;@@ -64,8 +68,9 @@}/*- * The arrow: which side the popover is on says where it stands, and Popper slides it along that- * side to sit over the anchor (see the arrow modifier in Popover.tsx).+ * The arrow. `data-placement` gives the side of the anchor the card is on; these rules put the+ * arrow on the facing edge, and `placeFloating()` sets its offset along that edge so it points at+ * the anchor (see the `arrow` option in Popover.tsx).** A window onto the square rather than the square itself. The panel's own background is* translucent (see `--menu-background-color`), so the half of the diamond that would lie inside the@@ -99,62 +104,61 @@* outward side it is measured.*/-/* stylelint-disable property-layout-mappings -- The sides here are physical because Popper's- placements are: `data-popper-placement="right"` says the panel stands to the right of its anchor- whatever the text direction, so its arrow belongs on the panel's physical left edge. A- right-to-left app asks Popper for the other placement (see the callers) rather than having these- flipped underneath it, and `inset-inline-start` would do exactly that — putting the arrow on the- side the panel is anchored against. */-.tn-popover[data-popper-placement^="right"] > .tn-popover-arrow {+/* stylelint-disable property-layout-mappings -- The sides here are physical because Floating UI's+ placements are: `data-placement="right"` means the card is right of its anchor in either text+ direction, so the arrow goes on the card's physical left edge. The callers request the mirrored+ placement in a right-to-left layout; `inset-inline-start` would flip the arrow a second time,+ onto the wrong edge. */+.tn-popover[data-placement^="right"] > .tn-popover-arrow {top: 0;left: calc(-1 * var(--tn-popover-arrow-depth));width: calc(var(--tn-popover-arrow-depth) + 1px);height: var(--tn-popover-arrow-base);}-.tn-popover[data-popper-placement^="right"] > .tn-popover-arrow::before {+.tn-popover[data-placement^="right"] > .tn-popover-arrow::before {left: calc(var(--tn-popover-arrow-depth) - var(--tn-popover-arrow-square) / 2);top: calc((var(--tn-popover-arrow-base) - var(--tn-popover-arrow-square)) / 2);border-left-color: var(--dropdown-border-color);border-bottom-color: var(--dropdown-border-color);}-.tn-popover[data-popper-placement^="left"] > .tn-popover-arrow {+.tn-popover[data-placement^="left"] > .tn-popover-arrow {top: 0;right: calc(-1 * var(--tn-popover-arrow-depth));width: calc(var(--tn-popover-arrow-depth) + 1px);height: var(--tn-popover-arrow-base);}-.tn-popover[data-popper-placement^="left"] > .tn-popover-arrow::before {+.tn-popover[data-placement^="left"] > .tn-popover-arrow::before {right: calc(var(--tn-popover-arrow-depth) - var(--tn-popover-arrow-square) / 2);top: calc((var(--tn-popover-arrow-base) - var(--tn-popover-arrow-square)) / 2);border-top-color: var(--dropdown-border-color);border-right-color: var(--dropdown-border-color);}-.tn-popover[data-popper-placement^="bottom"] > .tn-popover-arrow {+.tn-popover[data-placement^="bottom"] > .tn-popover-arrow {left: 0;top: calc(-1 * var(--tn-popover-arrow-depth));height: calc(var(--tn-popover-arrow-depth) + 1px);width: var(--tn-popover-arrow-base);}-.tn-popover[data-popper-placement^="bottom"] > .tn-popover-arrow::before {+.tn-popover[data-placement^="bottom"] > .tn-popover-arrow::before {top: calc(var(--tn-popover-arrow-depth) - var(--tn-popover-arrow-square) / 2);left: calc((var(--tn-popover-arrow-base) - var(--tn-popover-arrow-square)) / 2);border-top-color: var(--dropdown-border-color);border-left-color: var(--dropdown-border-color);}-.tn-popover[data-popper-placement^="top"] > .tn-popover-arrow {+.tn-popover[data-placement^="top"] > .tn-popover-arrow {left: 0;bottom: calc(-1 * var(--tn-popover-arrow-depth));height: calc(var(--tn-popover-arrow-depth) + 1px);width: var(--tn-popover-arrow-base);}-.tn-popover[data-popper-placement^="top"] > .tn-popover-arrow::before {+.tn-popover[data-placement^="top"] > .tn-popover-arrow::before {bottom: calc(var(--tn-popover-arrow-depth) - var(--tn-popover-arrow-square) / 2);left: calc((var(--tn-popover-arrow-base) - var(--tn-popover-arrow-square)) / 2);border-bottom-color: var(--dropdown-border-color);diff --git a/apps/client/src/widgets/react/Popover.maximized.spec.tsx b/apps/client/src/widgets/react/Popover.maximized.spec.tsxindex aabab9faf4..89f242bdfc 100644--- a/apps/client/src/widgets/react/Popover.maximized.spec.tsx+++ b/apps/client/src/widgets/react/Popover.maximized.spec.tsx@@ -1,6 +1,6 @@import { render } from "preact";import { act } from "preact/test-utils";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import Popover from "./Popover";@@ -26,11 +26,7 @@ describe("Popover, maximized", () => {const anchorRect = () => new DOMRect(100, 100, 50, 20);- /**- * Drawn, and then given the turn of the loop Popper places a card in: `createPopper` schedules- * its first placement rather than doing it there and then, so the attribute that says where the- * card ended up is not on it until the microtasks have run out.- */+ /** Renders the popover and runs its effects. `placeFloating()` resolves later. */async function mount(maximized: boolean) {await act(async () => {render(@@ -62,20 +58,22 @@ describe("Popover, maximized", () => {it("lets go of the anchor as it grows, and takes hold again as it comes down", async () => {await mount(false);- // Popper places the card and says where it ended up; the styling of a grown card waits on- // that attribute being gone (see the `.maximized` rules in Popover.css).- expect(popover()?.getAttribute("data-popper-placement")).toBeTruthy();+ // A placed card has `data-placement`; the `.maximized` rules in Popover.css apply only+ // without it.+ await vi.waitFor(() => expect(popover()?.getAttribute("data-placement")).toBeTruthy());+ expect(popover()?.style.left).not.toBe("");await mount(true);expect(popover()?.classList.contains("maximized")).toBe(true);- // Given back as the popper is destroyed, along with the inline placement it wrote — which- // is what leaves the stylesheet free to put the card where it likes.- expect(popover()?.hasAttribute("data-popper-placement")).toBe(false);- expect(popover()?.style.transform).toBe("");+ // Removed together with the inline position, so only the stylesheet positions the card.+ expect(popover()?.hasAttribute("data-placement")).toBe(false);+ expect(popover()?.style.left).toBe("");+ expect(popover()?.style.top).toBe("");+ expect(popover()?.style.visibility).toBe("");await mount(false);expect(popover()?.classList.contains("maximized")).toBe(false);- expect(popover()?.getAttribute("data-popper-placement")).toBeTruthy();+ await vi.waitFor(() => expect(popover()?.getAttribute("data-placement")).toBeTruthy());});it("dims the page only while it is grown", async () => {diff --git a/apps/client/src/widgets/react/Popover.tsx b/apps/client/src/widgets/react/Popover.tsxindex 6ad7f70f58..d1624a9b3c 100644--- a/apps/client/src/widgets/react/Popover.tsx+++ b/apps/client/src/widgets/react/Popover.tsx@@ -1,13 +1,13 @@import "./Popover.css";-import { createPopper, Instance, Placement, VirtualElement } from "@popperjs/core";+import { autoUpdate, type Placement, type VirtualElement } from "@floating-ui/dom";import clsx from "clsx";import { ComponentChildren } from "preact";import { createPortal } from "preact/compat";-import { useCallback, useEffect, useRef } from "preact/hooks";+import { useEffect, useRef } from "preact/hooks";import { FLOATING_LAYER_SELECTOR, isWithinFloatingLayer } from "./floating_layers";-import { useResizeObserver } from "./hooks";+import { placeFloating } from "./Popup";export interface PopoverProps {/**@@ -20,9 +20,9 @@ export interface PopoverProps {/** Which side of the anchor to stand on, flipped away from the viewport's edges as needed. */placement?: Placement;/**- * Repositions when it changes. Popper watches scrolling and resizing on its own, but cannot- * know the anchor moved for a reason of the caller's — the popover switching to stand for- * something else, say — which is what this says.+ * Places the popover again when it changes. `autoUpdate()` handles scrolling and resizing;+ * this covers an anchor that moves for another reason, such as the popover switching to a+ * different event.*/updateKey?: unknown;className?: string;@@ -45,8 +45,8 @@ export interface PopoverProps {* A state of this popover and not a surface of its own, which is the whole of the point: what* the card holds — a note's editor, mid-edit — stays mounted across the change, where a dialog* raised in its place would tear it down and build it again with whatever was typed still- * unsaved. Popper is not merely stopped but taken down, its `applyStyles` giving back the- * inline placement it wrote (see the effect below) so the stylesheet has the field to itself.+ * unsaved. While maximized, the popover stops placing itself and removes its inline position+ * and `data-placement` (see the effect below), so only the stylesheet positions it.*/maximized?: boolean;children: ComponentChildren;@@ -56,65 +56,67 @@ export interface PopoverProps {* A small surface anchored beside something — a dragged-out calendar range, a clicked chip —* rather than docked at an edge or centred as a dialog. Portaled to the body, so no scroll* container clips it and no containment root flattens its frosting (see the Dropdown notes in- * CLAUDE.md); positioned by Popper, which also keeps it in place while ancestors scroll.+ * CLAUDE.md). `placeFloating()` positions it, and `autoUpdate()` places it again as ancestors+ * scroll.*/export default function Popover({ getAnchorRect, placement, updateKey, className, keepOpenSelector, onDismiss, maximized, children }: PopoverProps) {const elRef = useRef<HTMLDivElement>(null);const arrowRef = useRef<HTMLDivElement>(null);- const popperRef = useRef<Instance>();+ const updateRef = useRef<() => void>();- // Held in a ref so the popper built once keeps asking the newest question — rebuilding it on- // every render would reset the positioning mid-interaction.+ // In a ref, so the placement set up once reads the latest `getAnchorRect`. Setting it up again+ // on every render would reset the position mid-interaction.const getRectRef = useRef(getAnchorRect);getRectRef.current = getAnchorRect;useEffect(() => {const el = elRef.current;- // A maximized card is placed by the stylesheet rather than beside anything, so it is given- // no popper at all. Tearing down the one it had is what hands its placement back: Popper's- // `applyStyles` remembers the inline styles it found and restores them as it is destroyed,- // which the cleanup below runs on the way into this state.+ // The stylesheet positions a maximized card. The cleanup below removes the inline position+ // and `data-placement` as the card is maximized.if (!el || maximized) return;const anchor: VirtualElement = { getBoundingClientRect: () => getRectRef.current() };- const popper = createPopper(anchor, el, {+ const options = {placement: placement ?? "right-start",- // Fixed, as the element stands in the body rather than beside its anchor.- strategy: "fixed",- modifiers: [- // Room for the arrow to stand in, and a little air past its tip.- { name: "offset", options: { offset: [ 0, 10 ] } },- // Held within the viewport on both axes. Popper keeps a popover inside it along the- // axis it was placed on and no further — a card standing to the left or the right- // is kept from running off the top and the bottom, and is left wherever the sides- // put it however far outside the window that is. An anchor with the room for a card- // on neither side (a calendar chip as wide as the grid, say) has no side to be- // placed on, so without this the card is put off the screen entirely and only its- // shadow is ever seen. Placement is still the first say — this is what is left when- // no placement fits.- { name: "preventOverflow", options: { padding: 8, altAxis: true } },- // Kept clear of the panel's rounded corners, where an arrow would grow out of thin- // air; an anchor so near a corner that it cannot be pointed at squarely gets the- // arrow as close as the padding allows.- { name: "arrow", options: { element: arrowRef.current, padding: 10 } }- ]+ // The arrow's depth, plus a small gap past its tip.+ offset: 10,+ // Keeps the card in the viewport on both axes. With no room on either side of the+ // anchor, as for a calendar chip as wide as the grid, the card is shifted over the+ // anchor instead of off the screen.+ shiftAcross: true,+ // Keeps the arrow off the card's rounded corners. Near a corner of the anchor, the arrow+ // stops at the padding instead of pointing at it squarely.+ arrow: arrowRef.current ? { element: arrowRef.current, padding: 10 } : undefined+ };+ let released = false;+ const release = () => {+ el.style.removeProperty("left");+ el.style.removeProperty("top");+ el.style.removeProperty("visibility");+ delete el.dataset.placement;+ };+ // `placeFloating()` resolves later, by which time the card can have been maximized.+ const update = () => void placeFloating(el, anchor, options).then((placed) => {+ if (released) release();+ else el.dataset.placement = placed;});- popperRef.current = popper;+ updateRef.current = update;+ // Places the card again when an ancestor scrolls, the viewport resizes, or the card's+ // size changes, as it does when a note's editor or its promoted attributes load.+ const stopUpdating = autoUpdate(anchor, el, update);return () => {- popperRef.current = undefined;- popper.destroy();+ released = true;+ updateRef.current = undefined;+ stopUpdating();+ release();};}, [ placement, maximized ]);useEffect(() => {- void popperRef.current?.update();+ updateRef.current?.();}, [ updateKey ]);- // Placed again whenever what is placed changes size: what a popover holds arrives after it does- // — a note's editor mounting, its promoted attributes filling in — and Popper measures it once.- useResizeObserver(elRef, useCallback(() => void popperRef.current?.update(), []));-useEffect(() => {if (!onDismiss) return;@@ -145,10 +147,9 @@ export default function Popover({ getAnchorRect, placement, updateKey, className{maximized && <div className="tn-popover-backdrop" />}<div ref={elRef} className={clsx("tn-popover", maximized && "maximized", className)}>- {/* What the popover is pointing at, drawn by Popper against whichever side it ended- up on (see the placements in Popover.css). First in the panel so its static- position is the panel's own corner, which is what Popper's offset is reckoned- from. */}+ {/* Points at the anchor from the side the card is on (see the placements in+ Popover.css). First in the card, so its static position is the card's corner,+ which `placeFloating()` measures the arrow's offset from. */}<div ref={arrowRef} className="tn-popover-arrow" />{children}</div>diff --git a/apps/client/src/widgets/react/Popup.spec.tsx b/apps/client/src/widgets/react/Popup.spec.tsxindex 3935ae06d6..f111453a21 100644--- a/apps/client/src/widgets/react/Popup.spec.tsx+++ b/apps/client/src/widgets/react/Popup.spec.tsx@@ -1,7 +1,7 @@import { render } from "preact";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import Popup, { type PopupProps } from "./Popup";+import Popup, { placeFloating, type PopupProps } from "./Popup";describe("Popup", () => {const host = document.createElement("div");@@ -57,6 +57,32 @@ describe("Popup", () => {expect(popup.style.top).toBe("82px");});+ it("offsets an arrow along the edge facing the anchor, clear of the corners", async () => {+ const card = document.createElement("div");+ const pointer = document.createElement("div");+ Object.defineProperty(pointer, "offsetWidth", { value: 12 });+ Object.defineProperty(pointer, "offsetHeight", { value: 12 });+ card.append(pointer);+ document.body.append(card);+ const arrow = { element: pointer, padding: 10 };++ // Right of the anchor: the arrow's offset is along the card's left edge, and the+ // stylesheet sets the other axis.+ anchorAt(100, 350);+ expect(await placeFloating(card, anchor, { placement: "right-start", offset: 10, arrow })).toBe("right-start");+ expect(card.style.left).toBe("190px");+ const top = parseFloat(pointer.style.top);+ expect(top).toBeGreaterThanOrEqual(10);+ expect(top).toBeLessThanOrEqual(100 - 12 - 10);+ expect(pointer.style.left).toBe("");++ // Below the anchor: along the top edge, and the stylesheet sets the other axis.+ expect(await placeFloating(card, anchor, { placement: "bottom-start", offset: 10, arrow })).toBe("bottom-start");+ expect(pointer.style.left).not.toBe("");+ expect(pointer.style.top).toBe("");+ card.remove();+ });+it("flips above its anchor where there is no room below, and caps its height to the room it has", async () => {anchorAt(100, 740);const popup = await open();diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsxindex 938b0676c2..781d169cad 100644--- a/apps/client/src/widgets/react/Popup.tsx+++ b/apps/client/src/widgets/react/Popup.tsx@@ -1,6 +1,6 @@import "./Popup.css";-import { autoUpdate, computePosition, flip, hide, offset, type OffsetOptions, type Placement, type ReferenceElement, shift, size } from "@floating-ui/dom";+import { arrow, autoUpdate, computePosition, flip, hide, offset, type OffsetOptions, type Placement, type ReferenceElement, shift, size } from "@floating-ui/dom";import clsx from "clsx";import { type ComponentChildren, createContext, type HTMLAttributes, type Ref } from "preact";import { createPortal } from "preact/compat";@@ -222,6 +222,11 @@ export interface FloatingPlacement {capHeight?: boolean;/** Hides it while its anchor is scrolled out of view, as a submenu whose row scrolled away. */hideWithAnchor?: boolean;+ /**+ * An arrow element inside it. Its offset along the edge facing the anchor is set to point at+ * the anchor, at least `padding` pixels from the corners.+ */+ arrow?: { element: HTMLElement, padding?: number };}/**@@ -230,7 +235,7 @@ export interface FloatingPlacement {* near the viewport's edge. It stays hidden until placed, so it never paints at a stale position.* Resolves to the placement it took.*/-export async function placeFloating(element: HTMLElement, anchor: ReferenceElement, { placement, offset: gap, shiftAcross, capHeight, hideWithAnchor }: FloatingPlacement) {+export async function placeFloating(element: HTMLElement, anchor: ReferenceElement, { placement, offset: gap, shiftAcross, capHeight, hideWithAnchor, arrow: pointer }: FloatingPlacement) {const { x, y, placement: placed, middlewareData } = await computePosition(anchor, element, {strategy: "fixed",placement,@@ -238,6 +243,7 @@ export async function placeFloating(element: HTMLElement, anchor: ReferenceElemegap !== undefined && offset(gap),flip({ fallbackPlacements: mirroredPlacements(placement), padding: VIEWPORT_PADDING }),shift({ crossAxis: !!shiftAcross, padding: VIEWPORT_PADDING }),+ pointer && arrow({ element: pointer.element, padding: pointer.padding }),capHeight && size({padding: VIEWPORT_PADDING,apply({ availableHeight }) {@@ -251,6 +257,12 @@ export async function placeFloating(element: HTMLElement, anchor: ReferenceElemeelement.style.left = `${x}px`;element.style.top = `${y}px`;element.style.visibility = middlewareData.hide?.referenceHidden ? "hidden" : "visible";+ if (pointer) {+ // Only the offset along the facing edge; the stylesheet sets the other axis.+ const { x: arrowX, y: arrowY } = middlewareData.arrow ?? {};+ pointer.element.style.left = arrowX !== undefined ? `${arrowX}px` : "";+ pointer.element.style.top = arrowY !== undefined ? `${arrowY}px` : "";+ }return placed;}