Skip to content

Build your personal knowledge base with Trilium Notes

feat(calendar): fold the view switcher into a menu where it does not fit

Elian Dorande50bfbbb424
diff --git a/apps/client/src/widgets/collections/calendar/index.css b/apps/client/src/widgets/collections/calendar/index.css
index a0c39433d0..78332ccf73 100644
--- a/apps/client/src/widgets/collections/calendar/index.css
+++ b/apps/client/src/widgets/collections/calendar/index.css
@@ -66,6 +66,15 @@
}
}
+ /* The end the view switcher stands at is the one asked to give where the bar is short: it holds
+ a row that folds into a menu when it no longer fits (see CollapseOnOverflow), which is a
+ better answer than either half of what happens otherwise — a flex item keeps its content's
+ width unless told it may not, so the bar would grow past the pane rather than hand the
+ switcher less, and the switcher would never learn that it was short. */
+ .right-container {
+ min-width: 0;
+ }
+
@media (max-width: 991px) {
>div {
justify-content: flex-start;
diff --git a/apps/client/src/widgets/collections/calendar/index.tsx b/apps/client/src/widgets/collections/calendar/index.tsx
index 66edc1db8e..e277137926 100644
--- a/apps/client/src/widgets/collections/calendar/index.tsx
+++ b/apps/client/src/widgets/collections/calendar/index.tsx
@@ -25,6 +25,7 @@ import { isMobile } from "../../../services/utils";
import CollectionProperties from "../../note_bars/CollectionProperties";
import ActionButton from "../../react/ActionButton";
import Button, { ButtonGroup } from "../../react/Button";
+import CollapseOnOverflow from "../../react/CollapseOnOverflow";
import Dropdown from "../../react/Dropdown";
import { FormListItem } from "../../react/FormList";
import { useNoteLabel, useNoteLabelBoolean, useSpacedUpdate, useTriliumEvent, useTriliumOption, useTriliumOptionInt } from "../../react/hooks";
@@ -324,7 +325,7 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarVi
return (plugins &&
<div className="calendar-view" ref={containerRef} tabIndex={100}>
- <CalendarCollectionProperties note={note} calendarRef={calendarRef} />
+ <CalendarCollectionProperties note={note} calendarRef={calendarRef} containerRef={containerRef} />
<Calendar
events={eventBuilder}
calendarRef={calendarRef}
@@ -404,9 +405,10 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarVi
);
}
-function CalendarCollectionProperties({ note, calendarRef }: {
+function CalendarCollectionProperties({ note, calendarRef, containerRef }: {
note: FNote;
calendarRef: RefObject<FullCalendar>;
+ containerRef: RefObject<HTMLDivElement>;
}) {
const { title, viewType: currentViewType } = useOnDatesSet(calendarRef);
const currentViewData = CALENDAR_VIEWS.find(v => calendarRef.current && v.type === currentViewType);
@@ -421,10 +423,12 @@ function CalendarCollectionProperties({ note, calendarRef }: {
<ActionButton icon="bx bx-chevron-right" text={currentViewData?.nextText ?? ""} onClick={() => calendarRef.current?.next()} />
<Button text={t("calendar.today")} onClick={() => calendarRef.current?.today()} />
<PinDateButton note={note} calendarRef={calendarRef} />
- {isMobileLocal && <MobileCalendarViewSwitcher calendarRef={calendarRef} />}
+ {/* On a phone the switcher is a menu whatever the width, and stands with the date
+ rather than on a right-hand end the wrapped bar no longer has. */}
+ {isMobileLocal && <CalendarViewSwitcher calendarRef={calendarRef} containerRef={containerRef} />}
</>}
rightChildren={<>
- {!isMobileLocal && <DesktopCalendarViewSwitcher calendarRef={calendarRef} />}
+ {!isMobileLocal && <CalendarViewSwitcher calendarRef={calendarRef} containerRef={containerRef} />}
</>}
/>
);
@@ -455,42 +459,49 @@ function PinDateButton({ note, calendarRef }: {
);
}
-function DesktopCalendarViewSwitcher({ calendarRef }: { calendarRef: RefObject<FullCalendar> }) {
- const { viewType: currentViewType } = useOnDatesSet(calendarRef);
-
- return (
- <>
- <ButtonGroup>
- {CALENDAR_VIEWS.map(viewData => (
- <Button
- key={viewData.type}
- text={viewData.name}
- className={currentViewType === viewData.type ? "active" : ""}
- onClick={() => calendarRef.current?.changeView(viewData.type)}
- />
- ))}
- </ButtonGroup>
- </>
- );
-}
-
-function MobileCalendarViewSwitcher({ calendarRef }: { calendarRef: RefObject<FullCalendar> }) {
+/**
+ * The choice of view, as a row of buttons where the bar has the width for one and as a menu where it
+ * has not — five names beside the date and its buttons outgrow a split pane long before they outgrow
+ * a screen, which is why the fold is decided by the view's own width rather than by the device.
+ */
+function CalendarViewSwitcher({ calendarRef, containerRef }: {
+ calendarRef: RefObject<FullCalendar>;
+ /** The view's own element, whose width the row of buttons is weighed against. */
+ containerRef: RefObject<HTMLDivElement>;
+}) {
const { viewType: currentViewType } = useOnDatesSet(calendarRef);
const currentViewTypeData = CALENDAR_VIEWS.find(view => view.type === currentViewType);
return (
- <Dropdown
- text={currentViewTypeData?.name}
- >
- {CALENDAR_VIEWS.map(viewData => (
- <FormListItem
- key={viewData.type}
- selected={currentViewType === viewData.type}
- icon={viewData.icon}
- onClick={() => calendarRef.current?.changeView(viewData.type)}
- >{viewData.name}</FormListItem>
- ))}
- </Dropdown>
+ <CollapseOnOverflow container={containerRef} alwaysCollapsed={isMobile()}>
+ {(collapsed) => (collapsed
+ ? (
+ // A handful of views, so the menu never scrolls and can be frosted the way that
+ // survives being opened inside the note's own content (see noDropdownListStyle).
+ <Dropdown text={currentViewTypeData?.name} noDropdownListStyle>
+ {CALENDAR_VIEWS.map(viewData => (
+ <FormListItem
+ key={viewData.type}
+ selected={currentViewType === viewData.type}
+ icon={viewData.icon}
+ onClick={() => calendarRef.current?.changeView(viewData.type)}
+ >{viewData.name}</FormListItem>
+ ))}
+ </Dropdown>
+ )
+ : (
+ <ButtonGroup>
+ {CALENDAR_VIEWS.map(viewData => (
+ <Button
+ key={viewData.type}
+ text={viewData.name}
+ className={currentViewType === viewData.type ? "active" : ""}
+ onClick={() => calendarRef.current?.changeView(viewData.type)}
+ />
+ ))}
+ </ButtonGroup>
+ ))}
+ </CollapseOnOverflow>
);
}
diff --git a/apps/client/src/widgets/react/CollapseOnOverflow.css b/apps/client/src/widgets/react/CollapseOnOverflow.css
new file mode 100644
index 0000000000..604beca7fb
--- /dev/null
+++ b/apps/client/src/widgets/react/CollapseOnOverflow.css
@@ -0,0 +1,22 @@
+/* A control drawn one of two ways — wide, or folded into a menu — by whether the wide one has the
+ room it wants. See CollapseOnOverflow.tsx, which measures the two classes below. */
+.tn-collapse-on-overflow {
+ display: flex;
+ /* Free to be handed less than it asks for: what cannot be squeezed never reports being too wide. */
+ min-width: 0;
+}
+
+/*
+ * While the wide rendering is up it keeps its own width and is cut off rather than squeezed, so that
+ * what it spills is the measure of how much room is missing.
+ *
+ * Left off the folded rendering, which is a dropdown: this would cut its menu off at the control's
+ * own edge.
+ */
+.tn-collapse-on-overflow-wide {
+ overflow: hidden;
+}
+
+.tn-collapse-on-overflow-wide > * {
+ flex-shrink: 0;
+}
diff --git a/apps/client/src/widgets/react/CollapseOnOverflow.spec.tsx b/apps/client/src/widgets/react/CollapseOnOverflow.spec.tsx
new file mode 100644
index 0000000000..5441db41ee
--- /dev/null
+++ b/apps/client/src/widgets/react/CollapseOnOverflow.spec.tsx
@@ -0,0 +1,170 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import CollapseOnOverflow, { nextCollapsedState } from "./CollapseOnOverflow";
+
+describe("nextCollapsedState", () => {
+ /** The folded rendering, which fits wherever it is put and hangs outside nothing. */
+ const fitting = { wantedWidth: 90, givenWidth: 90, spilledWidth: 0 };
+
+ it("folds once the row is handed less than it asked for, and notes the width it was short of", () => {
+ expect(nextCollapsedState({ collapsed: false, expandAt: 0 }, { wantedWidth: 420, givenWidth: 380, spilledWidth: 0, containerWidth: 700 }))
+ .toStrictEqual({ collapsed: true, expandAt: 740 });
+ });
+
+ it("folds on a row that is not squeezed but hangs outside the container instead", () => {
+ // A bar with no room left may hand its parts nothing less and grow past the pane, which is
+ // the same shortage read off the other end.
+ expect(nextCollapsedState({ collapsed: false, expandAt: 0 }, { wantedWidth: 420, givenWidth: 420, spilledWidth: 93, containerWidth: 700 }))
+ .toStrictEqual({ collapsed: true, expandAt: 793 });
+ });
+
+ it("leaves the wide rendering up where it fits, a rounded pixel being no shortage", () => {
+ const fits = { collapsed: false, expandAt: 0 };
+ expect(nextCollapsedState(fits, { wantedWidth: 380, givenWidth: 380, spilledWidth: 0, containerWidth: 700 })).toStrictEqual(fits);
+ // Whole numbers off a fractional layout: a row that fits exactly is as likely to report one
+ // over as one under, and folding on that would fold rows that are perfectly well shown.
+ expect(nextCollapsedState(fits, { wantedWidth: 381, givenWidth: 380, spilledWidth: 1, containerWidth: 700 })).toStrictEqual(fits);
+ });
+
+ it("stays folded until the container has grown by what was missing", () => {
+ const folded = { collapsed: true, expandAt: 740 };
+ // The folded rendering fits wherever it is put, so its own measurement says nothing: what is
+ // waited on is the container.
+ expect(nextCollapsedState(folded, { ...fitting, containerWidth: 739 })).toStrictEqual(folded);
+ expect(nextCollapsedState(folded, { ...fitting, containerWidth: 740 }))
+ .toStrictEqual({ collapsed: false, expandAt: 0 });
+ });
+
+ it("settles rather than flipping, where unfolding shows the mark to have been set short", () => {
+ // The row may be given only its own share of a shortage the whole bar takes part in, so the
+ // mark it sets on folding can be too low. Unfolding at that mark folds straight back — but
+ // with a mark above the width just shown not to work, so the same width cannot flip again.
+ const first = nextCollapsedState({ collapsed: false, expandAt: 0 }, { wantedWidth: 420, givenWidth: 400, spilledWidth: 0, containerWidth: 700 });
+ expect(first).toStrictEqual({ collapsed: true, expandAt: 720 });
+
+ const unfolded = nextCollapsedState(first, { ...fitting, containerWidth: 720 });
+ expect(unfolded.collapsed).toBe(false);
+
+ const refolded = nextCollapsedState(unfolded, { wantedWidth: 420, givenWidth: 410, spilledWidth: 0, containerWidth: 720 });
+ expect(refolded).toStrictEqual({ collapsed: true, expandAt: 730 });
+ expect(nextCollapsedState(refolded, { ...fitting, containerWidth: 720 })).toStrictEqual(refolded);
+ });
+});
+
+describe("CollapseOnOverflow", () => {
+ let root: HTMLDivElement;
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ observers = [];
+ globalThis.ResizeObserver = ResizeObserverStub as unknown as typeof ResizeObserver;
+ root = document.createElement("div");
+ container = document.createElement("div");
+ document.body.append(root, container);
+ });
+
+ afterEach(() => {
+ render(null, root);
+ root.remove();
+ container.remove();
+ });
+
+ it("draws the wide rendering while it fits, and clips it so that what it wants can be read off it", () => {
+ renderChoice();
+
+ const wrapper = root.querySelector(".tn-collapse-on-overflow");
+ expect(wrapper?.textContent).toBe("wide");
+ expect(wrapper?.classList.contains("tn-collapse-on-overflow-wide")).toBe(true);
+ // Watched from both ends: what the control is given comes from the row it is in, and what
+ // that row has to give comes from the container.
+ expect(observers[0]?.observed).toStrictEqual([ wrapper, container ]);
+ });
+
+ it("folds when the wide rendering no longer fits, and lifts the clipping off the menu", () => {
+ renderChoice();
+ resize({ wantedWidth: 420, givenWidth: 380, containerWidth: 700 });
+
+ const wrapper = root.querySelector(".tn-collapse-on-overflow");
+ expect(wrapper?.textContent).toBe("folded");
+ // The folded rendering is a dropdown, whose menu clipping would cut off at the control's edge.
+ expect(wrapper?.classList.contains("tn-collapse-on-overflow-wide")).toBe(false);
+
+ // Held folded at a width the wide rendering has already been shown not to fit, and let back
+ // out once the container has grown by what was missing.
+ resize({ wantedWidth: 90, givenWidth: 90, containerWidth: 700 });
+ expect(root.querySelector(".tn-collapse-on-overflow")?.textContent).toBe("folded");
+ resize({ wantedWidth: 90, givenWidth: 90, containerWidth: 740 });
+ expect(root.querySelector(".tn-collapse-on-overflow")?.textContent).toBe("wide");
+ });
+
+ it("folds a row that its own bar will not squeeze, and so hangs past the container", () => {
+ renderChoice();
+ resize({ wantedWidth: 282, givenWidth: 282, spilledWidth: 93, containerWidth: 700 });
+
+ expect(root.querySelector(".tn-collapse-on-overflow")?.textContent).toBe("folded");
+ });
+
+ it("stays folded without measuring anything where the caller says there is no room at all", () => {
+ renderChoice(true);
+
+ expect(root.querySelector(".tn-collapse-on-overflow")?.textContent).toBe("folded");
+ expect(observers).toHaveLength(0);
+ });
+
+ /** Renders a control naming which of its two renderings is up. */
+ function renderChoice(alwaysCollapsed?: boolean) {
+ act(() => render(
+ <CollapseOnOverflow container={{ current: container }} alwaysCollapsed={alwaysCollapsed}>
+ {(collapsed) => <span>{collapsed ? "folded" : "wide"}</span>}
+ </CollapseOnOverflow>,
+ root));
+ }
+
+ /**
+ * Hands the component a layout, happy-dom measuring everything as nought. The control is laid
+ * against the container's right edge, `spilledWidth` putting it that far past it.
+ */
+ function resize({ wantedWidth, givenWidth, containerWidth, spilledWidth = 0 }: {
+ wantedWidth: number;
+ givenWidth: number;
+ containerWidth: number;
+ spilledWidth?: number;
+ }) {
+ const wrapper = root.querySelector(".tn-collapse-on-overflow") as HTMLElement;
+ stateWidth(wrapper, "scrollWidth", wantedWidth);
+ stateWidth(wrapper, "clientWidth", givenWidth);
+ stateWidth(container, "clientWidth", containerWidth);
+ stateBox(container, 0, containerWidth);
+ stateBox(wrapper, containerWidth + spilledWidth - givenWidth, containerWidth + spilledWidth);
+ act(() => observers.forEach((observer) => observer.callback()));
+ }
+});
+
+function stateWidth(element: HTMLElement, property: "scrollWidth" | "clientWidth", value: number) {
+ Object.defineProperty(element, property, { value, configurable: true });
+}
+
+function stateBox(element: HTMLElement, left: number, right: number) {
+ element.getBoundingClientRect = () => ({ left, right }) as DOMRect;
+}
+
+let observers: ResizeObserverStub[] = [];
+
+/** happy-dom has no ResizeObserver, and lays nothing out for one to report on. */
+class ResizeObserverStub {
+ observed: Element[] = [];
+
+ constructor(readonly callback: () => void) {
+ observers.push(this);
+ }
+
+ observe(element: Element) {
+ this.observed.push(element);
+ }
+
+ unobserve() {}
+
+ disconnect() {}
+}
diff --git a/apps/client/src/widgets/react/CollapseOnOverflow.tsx b/apps/client/src/widgets/react/CollapseOnOverflow.tsx
new file mode 100644
index 0000000000..e0045a64fb
--- /dev/null
+++ b/apps/client/src/widgets/react/CollapseOnOverflow.tsx
@@ -0,0 +1,145 @@
+import "./CollapseOnOverflow.css";
+
+import clsx from "clsx";
+import { ComponentChildren, RefObject } from "preact";
+import { useLayoutEffect, useRef, useState } from "preact/hooks";
+
+interface CollapseOnOverflowProps {
+ /**
+ * The element the control is weighed against — the pane or the bar it sits in, whose width is
+ * decided by something other than which of the two renderings is currently up.
+ *
+ * It cannot be the control's own box: the folded rendering fits wherever it is put, so a control
+ * measuring itself would find room the moment it folded and unfold straight back into the same
+ * shortage.
+ */
+ container: RefObject<HTMLElement | null>;
+ /** Keeps the folded rendering up whatever the width — for a phone, which has room for no other. */
+ alwaysCollapsed?: boolean;
+ className?: string;
+ /** Draws the control, told which of its two renderings is being asked for. */
+ children: (collapsed: boolean) => ComponentChildren;
+}
+
+/**
+ * Shows a control one of two ways — as it stands, or folded into something narrower — by whether the
+ * wide way fits the room it is given.
+ *
+ * For a row of named options that is worth showing whole where there is width for it (a calendar's
+ * views, say) and is better as a menu where there is not: an alternative to hiding it behind a menu
+ * everywhere, or to switching on the screen's own size, which says nothing about the width of the one
+ * pane the control is in.
+ *
+ * A shortage is read either from the width the control is handed or from what it hangs outside the
+ * container by, since a bar out of room may squeeze its parts or may simply grow past the pane. The
+ * first is the tidier of the two and is worth arranging: `min-width: 0` on whatever the control sits
+ * in, a flex item otherwise refusing to go under its content's width.
+ */
+export default function CollapseOnOverflow({ container, alwaysCollapsed, className, children }: CollapseOnOverflowProps) {
+ const ref = useRef<HTMLDivElement>(null);
+ const collapsed = useCollapsed(ref, container, alwaysCollapsed);
+
+ return (
+ <div
+ ref={ref}
+ className={clsx(
+ "tn-collapse-on-overflow",
+ // Stated only while the wide rendering is up: it is measured by what it spills, and the
+ // folded one is a menu that clipping would cut off (see the CSS).
+ !collapsed && "tn-collapse-on-overflow-wide",
+ className
+ )}
+ >
+ {children(collapsed)}
+ </div>
+ );
+}
+
+interface CollapseState {
+ collapsed: boolean;
+ /**
+ * The container width the wide rendering is owed before it is tried again — nought while it is
+ * up, there being nothing to wait for.
+ */
+ expandAt: number;
+}
+
+interface CollapseMeasurement {
+ /** What the wide rendering asks for. */
+ wantedWidth: number;
+ /** What it is given where it stands, which is less than it asked for once the row is squeezed. */
+ givenWidth: number;
+ /**
+ * How far it hangs outside the container, for a row that is not squeezed but spills.
+ *
+ * The other way a shortage shows itself, and the one that shows where a row cannot be squeezed:
+ * a flex item keeps its content's width unless something states otherwise, so a bar with no room
+ * left hands its parts nothing less and grows past the pane instead.
+ */
+ spilledWidth: number;
+ /** The width of the container it is weighed against. */
+ containerWidth: number;
+}
+
+/**
+ * Whether the folded rendering should be up, from a measurement of the wide one.
+ *
+ * Folding is decided by what the wide rendering spills. Unfolding cannot be — the folded one spills
+ * nothing wherever it is put — so the container width at the moment of folding is kept, raised by
+ * what was missing, and the wide rendering is not tried again until the container has grown that far.
+ *
+ * What was missing is the control's own share of the shortage, the row it sits in sharing a shortage
+ * out between everything that can give, so the mark can be set short and unfolding then folds
+ * straight back with a higher one. It settles after a step or two, and each step puts the mark above
+ * a width just shown not to work, so no single width can flip back and forth.
+ */
+export function nextCollapsedState(state: CollapseState, { wantedWidth, givenWidth, spilledWidth, containerWidth }: CollapseMeasurement): CollapseState {
+ if (state.collapsed) {
+ return containerWidth < state.expandAt ? state : { collapsed: false, expandAt: 0 };
+ }
+
+ // A pixel of slack: these widths are whole numbers rounded off a fractional layout, and a row
+ // that fits exactly is as likely to report one over as one under.
+ const missing = Math.max(wantedWidth - givenWidth, spilledWidth);
+ return missing > 1 ? { collapsed: true, expandAt: containerWidth + missing } : state;
+}
+
+/** Watches the control and its container, answering which rendering the width allows for. */
+function useCollapsed(ref: RefObject<HTMLDivElement>, container: RefObject<HTMLElement | null>, alwaysCollapsed?: boolean) {
+ const [ collapsed, setCollapsed ] = useState(false);
+ // Held rather than read from the state: the measuring below happens outside of a render, and what
+ // it decides from is its own last answer along with the width it then found wanting.
+ const stateRef = useRef<CollapseState>({ collapsed: false, expandAt: 0 });
+
+ useLayoutEffect(() => {
+ const element = ref.current;
+ const containerElement = container.current;
+ if (alwaysCollapsed || !element || !containerElement) return;
+
+ const measure = () => {
+ const box = element.getBoundingClientRect();
+ const containerBox = containerElement.getBoundingClientRect();
+ const next = nextCollapsedState(stateRef.current, {
+ wantedWidth: element.scrollWidth,
+ givenWidth: element.clientWidth,
+ // Which edge it hangs past is a matter of the writing direction, so both are asked.
+ spilledWidth: Math.max(0, box.right - containerBox.right, containerBox.left - box.left),
+ containerWidth: containerElement.clientWidth
+ });
+ stateRef.current = next;
+ setCollapsed(next.collapsed);
+ };
+
+ // Measured before the first paint rather than after it, so a control with no room for its
+ // wide rendering is never shown wearing it.
+ measure();
+ // Both are watched: what the control is given comes from the row it is in, and what that row
+ // has to give comes from the container.
+ const resizes = new ResizeObserver(measure);
+ resizes.observe(element);
+ resizes.observe(containerElement);
+ return () => resizes.disconnect();
+ }, [ ref, container, alwaysCollapsed ]);
+
+ return alwaysCollapsed || collapsed;
+}