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(client): share one hook for a slide between two views
Elian Doranfe385791c095
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex 30faab34c0..d349d4e13d 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -667,12 +667,26 @@ describe("contextMenu", () => {if (!button) throw new Error("expected a back button");press(button);};+ /** How each page is moving, as its slide class names it. */+ const slides = () => [ ...menuElement()?.querySelectorAll(":scope > .tn-menu-page") ?? [] ]+ .map((page) => page.classList.contains("tn-menu-page-entering") ? "entering"+ : page.classList.contains("tn-menu-page-leaving") ? "leaving" : "shown");+ /** Ends every page's slide, as the browser does once the animation has run. */+ const endSlides = () => {+ for (const page of menuElement()?.querySelectorAll(":scope > .tn-menu-page") ?? []) {+ page.dispatchEvent(Object.assign(new Event("animationend", { bubbles: true }),+ { animationName: "tn-slide-in-from-right" }));+ }+ };hover(parent);expect(pages()).toEqual([]);press(parent);await vi.waitFor(() => expect(pages()).toEqual([ [ "Templates", "Meeting" ] ]));+ expect(slides()).toEqual([ "entering" ]);+ endSlides();+ await vi.waitFor(() => expect(slides()).toEqual([ "shown" ]));// Opening runs nothing, and neither unfolds rows in the row nor draws a layer beside it.expect(picked).toEqual([]);expect(parent.querySelector(".dropdown-menu")).toBeNull();@@ -680,11 +694,17 @@ describe("contextMenu", () => {press(row("Meeting"));await vi.waitFor(() => expect(pages()).toEqual([ [ "Templates", "Meeting" ], [ "Meeting", "Weekly" ] ]));+ endSlides();- // Back goes up one level at a time, running nothing and keeping the menu up.+ // Back goes up one level at a time, running nothing and keeping the menu up. The page+ // left is drawn until it has slid out.back();+ await vi.waitFor(() => expect(slides()).toEqual([ "shown", "leaving" ]));+ endSlides();await vi.waitFor(() => expect(pages()).toEqual([ [ "Templates", "Meeting" ] ]));back();+ await vi.waitFor(() => expect(slides()).toEqual([ "leaving" ]));+ endSlides();await vi.waitFor(() => expect(pages()).toEqual([]));expect(picked).toEqual([]);expect(contextMenu.isShown).toBe(true);@@ -1220,6 +1240,8 @@ describe("contextMenu", () => {it("opens a submenu's page on a phone as Right and Enter open one, and goes back on Escape", async () => {layout.onMobile = true;+ // Without slides, a page goes as soon as it closes.+ document.body.classList.add("motion-disabled");try {await openMenu();key("End");@@ -1242,11 +1264,13 @@ describe("contextMenu", () => {await vi.waitFor(() => expect(activeRow()).toBe("Meeting"));} finally {layout.onMobile = false;+ document.body.classList.remove("motion-disabled");}});it("moves the keys onto the page a tap opened, and back to its row from the header", async () => {layout.onMobile = true;+ document.body.classList.add("motion-disabled");try {const picked: string[] = [];await openMenu((title) => picked.push(title));@@ -1276,6 +1300,7 @@ describe("contextMenu", () => {expect(picked).toEqual([ "Paste" ]);} finally {layout.onMobile = false;+ document.body.classList.remove("motion-disabled");}});diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsxindex 3ad6284d10..85a25465ea 100644--- a/apps/client/src/widgets/react/Dropdown.spec.tsx+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx@@ -46,6 +46,7 @@ describe("Dropdown", () => {layout.onMobile = false;layout.narrow = true;layout.onChange.clear();+ document.body.classList.remove("motion-disabled");});/** Renders a `Dropdown`, or a `DropdownPanel` for `panel`. */@@ -437,6 +438,8 @@ describe("Dropdown", () => {render(null, host);layout.onMobile = true;+ // Without slides, a page goes as soon as it closes.+ document.body.classList.add("motion-disabled");const { toggle: phoneToggle } = renderDropdown({}, content);click(phoneToggle);await vi.waitFor(() => expect(submenuRow()).toBeTruthy());diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsxindex 1028106003..3d89f1d0d2 100644--- a/apps/client/src/widgets/react/FormList.tsx+++ b/apps/client/src/widgets/react/FormList.tsx@@ -5,7 +5,7 @@ import type { KeyboardActionNames } from "@triliumnext/commons";import type { Tooltip } from "bootstrap";import clsx from "clsx";import { ComponentChildren, createPortal, type CSSProperties, RefObject } from "preact";-import { useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";+import { useContext, useLayoutEffect, useMemo, useRef } from "preact/hooks";import { t } from "../../services/i18n";import { getActionSync } from "../../services/keyboard_actions";@@ -19,6 +19,7 @@ import { isRightToLeft, MenuContext, type MenuContextValue, MenuFilterContext, Mimport { placeFloating } from "./Popup";import { joinElements } from "./react_utils";import { renderShortcutKbds } from "./shortcut_kbd";+import { type Slide, useSlide } from "./SlidePages";interface FormListOpts {children: ComponentChildren;@@ -405,7 +406,8 @@ function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleCliconst open = openSubmenu?.id === id;const isActive = menu.active?.id === id;const filter = filterable ? { rowId: id, level, text: menu.filter?.rowId === id ? menu.filter.text : "" } : undefined;- const [ pageSlide, settlePage ] = usePageSlide(open);+ // A phone's page that closes keeps being drawn until it has slid out.+ const pageSlide = useSlide(open);/** Runs the row's own action for the keys, with the modifiers of the key that ran it. */function select(e: MouseEvent | KeyboardEvent) {@@ -460,8 +462,8 @@ function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleCli</span>{isMobile()// A phone has no room beside the menu, so a submenu replaces it as a page of its own.- ? (open || pageSlide) && menu.layerHost && createPortal((- <SubmenuPage rowId={id} level={level + 1} title={title} slide={pageSlide} onSlideEnd={settlePage}>+ ? (open || pageSlide.from !== undefined) && menu.layerHost && createPortal((+ <SubmenuPage rowId={id} level={level + 1} title={title} slide={pageSlide}><MenuFilterContext.Provider value={filter}>{children}</MenuFilterContext.Provider></SubmenuPage>), menu.layerHost)@@ -559,22 +561,15 @@ function SubmenuLayer({ level, submenu, pinned, children }: {* A submenu opened on a phone: a page that takes the menu's place, headed by the submenu's title and* a way back. The level it covers stays mounted, as the row that owns this page stands in it.*/-function SubmenuPage({ rowId, level, title, slide, onSlideEnd, children }: {+function SubmenuPage({ rowId, level, title, slide, children }: {rowId: string,level: number,title: ComponentChildren,- slide: PageSlide | undefined,- onSlideEnd(): void,+ /** The slide of whether the page is open: from closed as it arrives, from open as it leaves. */+ slide: Slide<boolean>,children: ComponentChildren}) {const menu = useMenu();- const pageRef = useRef<HTMLDivElement>(null);-- // Without an animation to wait for, as with `motion-disabled`, the slide ends at once.- useLayoutEffect(() => {- const page = pageRef.current;- if (slide && page && !hasAnimation(page)) onSlideEnd();- }, [ slide, onSlideEnd ]);function back() {menu.openSubmenu(level - 1);@@ -584,12 +579,10 @@ function SubmenuPage({ rowId, level, title, slide, onSlideEnd, children }: {return (<MenuLevelContext.Provider value={level}><div- ref={pageRef} role="menu" aria-labelledby={titleId(rowId)}- className={clsx("tn-menu-page", slide && `tn-menu-page-${slide}`)}- onAnimationEnd={(e) => {- // Animations inside the page bubble up here too.- if (e.target === e.currentTarget) onSlideEnd();- }}+ role="menu" aria-labelledby={titleId(rowId)}+ className={clsx("tn-menu-page", slide.from === false && "tn-menu-page-entering",+ slide.from === true && "tn-menu-page-leaving")}+ onAnimationEnd={slide.onAnimationEnd}>{/* As a row's press: the menu keeps focus, and the dropdown does not close on it. */}<div@@ -605,38 +598,6 @@ function SubmenuPage({ rowId, level, title, slide, onSlideEnd, children }: {);}-/** How a phone's submenu page is moving: sliding in over its menu, or back out. */-type PageSlide = "entering" | "leaving";--/**- * The slide of a phone's submenu page that `open` shows or hides. A page that closes keeps being- * drawn until it has slid out, which the page reports with the returned callback.- */-function usePageSlide(open: boolean) {- const slide = useRef<PageSlide | undefined>(undefined);- const wasOpen = useRef(open);- const [ , redraw ] = useState(0);-- // Worked out while rendering, so the first frame of the page already carries its slide.- if (wasOpen.current !== open) {- wasOpen.current = open;- slide.current = open ? "entering" : "leaving";- }-- const settle = useCallback(() => {- if (!slide.current) return;- slide.current = undefined;- redraw((pass) => pass + 1);- }, []);-- return [ slide.current, settle ] as const;-}--function hasAnimation(element: HTMLElement) {- const name = getComputedStyle(element).animationName;- return !!name && name !== "none";-}-/** The id of a row's title, which names the submenu it opens. */function titleId(rowId: string) {return `${rowId}-title`;diff --git a/apps/client/src/widgets/react/SlidePages.spec.tsx b/apps/client/src/widgets/react/SlidePages.spec.tsxindex 961b6ae668..428ae04172 100644--- a/apps/client/src/widgets/react/SlidePages.spec.tsx+++ b/apps/client/src/widgets/react/SlidePages.spec.tsx@@ -29,11 +29,16 @@ function arriving() {/** Ends the animation the way the browser would, which is what tells the component to let go. */async function finishSlide() {- leaving()?.dispatchEvent(new Event("animationend", { bubbles: true }));+ leaving()?.dispatchEvent(slideEnd());// Letting go is the one part that needs a render of its own, which Preact schedules.await new Promise((resolve) => setTimeout(resolve, 0));}+/** The end of a slide, as the browser reports it: named after the keyframes that ran. */+function slideEnd() {+ return Object.assign(new Event("animationend", { bubbles: true }), { animationName: "tn-slide-out-to-left" });+}+afterEach(() => {render(null, container);container.remove();@@ -88,13 +93,28 @@ describe("sliding between pages", () => {// Animation events bubble, and a spinner or a field's own animation ending is not the slide// ending: acting on it would drop the page mid-flight and snap the other into place.- container.querySelector(".page-first")?.dispatchEvent(new Event("animationend", { bubbles: true }));+ container.querySelector(".page-first")?.dispatchEvent(Object.assign(new Event("animationend", { bubbles: true }),+ { animationName: "spin" }));await new Promise((resolve) => setTimeout(resolve, 0));expect(leaving()).toBeTruthy();expect(arriving()?.className).toContain("slide-in-forward");});+ it("switches at once with motion disabled, where no animation would run to end the slide", () => {+ document.body.classList.add("motion-disabled");+ try {+ show("first");+ show("second");++ expect(leaving()).toBeFalsy();+ expect(container.textContent).toBe("second");+ expect(arriving()?.className).toContain("slide-current");+ } finally {+ document.body.classList.remove("motion-disabled");+ }+ });+it("takes only the page leaving out of the flow when the pages keep their place", () => {show("first", { inFlow: true });show("second", { inFlow: true });diff --git a/apps/client/src/widgets/react/SlidePages.tsx b/apps/client/src/widgets/react/SlidePages.tsxindex 8691b3b351..6c08a8c4a5 100644--- a/apps/client/src/widgets/react/SlidePages.tsx+++ b/apps/client/src/widgets/react/SlidePages.tsx@@ -3,7 +3,7 @@ import "./SlidePages.css";import clsx from "clsx";import { ComponentChildren } from "preact";-import { useRef, useState } from "preact/hooks";+import { useCallback, useRef, useState } from "preact/hooks";interface SlidePagesProps<T extends string> {/** The page to show. Changing it slides the one before it out and this one in. */@@ -31,37 +31,15 @@ interface SlidePagesProps<T extends string> {* and going back looks like going back without anything having to remember that it did.*/export default function SlidePages<T extends string>({ current, order, inFlow, className, children }: SlidePagesProps<T>) {- const shown = useRef(current);- const leavingRef = useRef<{ page: T; direction: Direction } | null>(null);- const [ , redraw ] = useState(0);-- // Worked out while rendering the page being arrived at rather than in an effect afterwards: a- // pass that drew the new page before the slide had started would put it in its final place and- // then jump it back to slide in from there.- if (shown.current !== current) {- leavingRef.current = { page: shown.current, direction: directionBetween(order, shown.current, current) };- shown.current = current;- }-- const leaving = leavingRef.current;+ const slide = useSlide(current);+ const leaving = slide.from !== undefined+ ? { page: slide.from, direction: directionBetween(order, slide.from, current) }+ : null;return (<div className={clsx("slide-pages", className, { "slide-pages-in-flow": inFlow })}>{leaving && (- <div- class={`slide-page slide-out-${leaving.direction}`}- onAnimationEnd={(e) => {- // Animation events bubble, so anything inside the page that animates would- // otherwise end the slide early: the page leaving is dropped and the one- // arriving loses its class mid-flight, snapping into place.- if (e.target !== e.currentTarget) {- return;- }-- leavingRef.current = null;- redraw((pass) => pass + 1);- }}- >+ <div class={`slide-page slide-out-${leaving.direction}`} onAnimationEnd={slide.onAnimationEnd}>{children(leaving.page)}</div>)}@@ -74,6 +52,52 @@ export default function SlidePages<T extends string>({ current, order, inFlow, c);}+/** The keyframes of slide_animations.css are named with this, which is how a slide's end is recognized. */+const SLIDE_ANIMATION_PREFIX = "tn-slide-";++export interface Slide<T> {+ /** What `current` replaced, while the slide from it runs, so both can be drawn; `undefined` at rest. */+ from: T | undefined;+ /**+ * Ends the slide at the end of one of slide_animations.css's animations. Other animations that+ * bubble up from inside the views, such as a spinner's, leave it running.+ */+ onAnimationEnd(e: AnimationEvent): void;+ /** Ends the slide at once, as for a view put back without the animation that would end it. */+ settle(): void;+}++/**+ * Keeps the value `current` replaced for as long as the slide between the two runs. A change while+ * `animated` is false, or with `motion-disabled`, where no animation runs to end it, switches at once.+ */+export function useSlide<T>(current: T, animated = true): Slide<T> {+ const shown = useRef(current);+ const from = useRef<T | undefined>(undefined);+ const [ , redraw ] = useState(0);++ // Worked out while rendering the view being arrived at rather than in an effect afterwards: a+ // pass that drew the new view before the slide had started would put it in its final place and+ // then jump it back to slide in from there.+ if (!Object.is(shown.current, current)) {+ const slides = animated && !document.body.classList.contains("motion-disabled");+ from.current = slides ? shown.current : undefined;+ shown.current = current;+ }++ const settle = useCallback(() => {+ if (from.current === undefined) return;+ from.current = undefined;+ redraw((pass) => pass + 1);+ }, []);++ const onAnimationEnd = useCallback((e: AnimationEvent) => {+ if (e.animationName?.startsWith(SLIDE_ANIMATION_PREFIX)) settle();+ }, [ settle ]);++ return { from: from.current, onAnimationEnd, settle };+}+type Direction = "forward" | "backward";/** Which way through `order` the move went. A page that is not in the order counts as forwards. */diff --git a/apps/client/src/widgets/react/master_detail.tsx b/apps/client/src/widgets/react/master_detail.tsxindex dde2cadffb..c4a2c88a41 100644--- a/apps/client/src/widgets/react/master_detail.tsx+++ b/apps/client/src/widgets/react/master_detail.tsx@@ -9,6 +9,7 @@ import utils from "../../services/utils";import ActionButton from "./ActionButton";import { useWindowSize } from "./hooks";import Modal, { ModalProps } from "./Modal";+import { useSlide } from "./SlidePages";/*** The flow a dialog that pairs a list with a detail takes on a screen too narrow to hold both: one at a@@ -22,9 +23,6 @@ import Modal, { ModalProps } from "./Modal";* master-detail flow. */export const MASTER_DETAIL_TABLET_MIN_WIDTH = 768;-/** What the slides of slide_animations.css are named with, which is how a finished one is recognized. */-const SLIDE_ANIMATION_PREFIX = "tn-slide-";-export interface MobileMasterDetail {/** True on narrow mobile viewports where the list and detail collapse into a master-detail flow. */isMasterDetail: boolean;@@ -44,27 +42,27 @@ export interface MobileMasterDetail {*/export function useMobileMasterDetail(modalRef: RefObject<HTMLElement | null>): MobileMasterDetail {const [ mobileView, setMobileView ] = useState<"list" | "page">("list");- // Direction of the in-flight slide between the two views, or null when at rest. While set, both- // panes stay rendered so the outgoing one can slide away as the incoming one slides in.- const [ mobileTransition, setMobileTransition ] = useState<"to-list" | "to-page" | null>(null);const isMobile = utils.isMobile();const { windowWidth } = useWindowSize();const isMasterDetail = isMobile && windowWidth < MASTER_DETAIL_TABLET_MIN_WIDTH;+ /** Whether the next change of view slides: a switch does, a reset does not. */+ const slideNext = useRef(false);+ // Outside the master-detail flow both panes are on show, and there is nothing to slide between.+ const slide = useSlide(mobileView, isMasterDetail && slideNext.current);+ // While set, both panes stay rendered so the outgoing one can slide away as the incoming one slides in.+ const mobileTransition = slide.from === undefined ? null : mobileView === "page" ? "to-page" : "to-list";const switchMobileView = useCallback((view: "list" | "page") => {- if (view === mobileView) return;+ slideNext.current = true;setMobileView(view);- // With animations globally disabled there is no animationend to clear the transition, so- // switch directly. Outside the master-detail flow there is nothing to animate.- if (isMasterDetail && !document.body.classList.contains("motion-disabled")) {- setMobileTransition(view === "page" ? "to-page" : "to-list");- }- }, [ mobileView, isMasterDetail ]);+ }, []);+ const { settle } = slide;const resetMobileView = useCallback((view: "list" | "page") => {+ slideNext.current = false;setMobileView(view);- setMobileTransition(null);- }, []);+ settle();+ }, [ settle ]);// Bootstrap adds its own classes (e.g. `show`) to the modal element at runtime, so the className// prop must stay static; toggle the mobile view classes directly on the element instead.@@ -76,18 +74,14 @@ export function useMobileMasterDetail(modalRef: RefObject<HTMLElement | null>):modalRef.current?.classList.toggle("mobile-transition-to-page", mobileTransition === "to-page");}, [ isMasterDetail, mobileView, mobileTransition ]);- // End the view transition once the slide finishes (animationend bubbles up from the panes).+ // The slide's end bubbles up from the panes.+ const { onAnimationEnd } = slide;useEffect(() => {const modalElement = modalRef.current;if (!modalElement) return;- function onAnimationEnd(e: AnimationEvent) {- if (e.animationName.startsWith(SLIDE_ANIMATION_PREFIX)) {- setMobileTransition(null);- }- }modalElement.addEventListener("animationend", onAnimationEnd);return () => modalElement.removeEventListener("animationend", onAnimationEnd);- }, []);+ }, [ onAnimationEnd ]);return { isMasterDetail, mobileView, switchMobileView, resetMobileView };}