Skip to content

Build your personal knowledge base with Trilium Notes

feat(options): fold the color scheme choice into a dropdown on mobile

Elian Doran1bff2272cc52
diff --git a/apps/client/src/widgets/react/SegmentedChoice.spec.tsx b/apps/client/src/widgets/react/SegmentedChoice.spec.tsx
index da9df79f14..8640541dea 100644
--- a/apps/client/src/widgets/react/SegmentedChoice.spec.tsx
+++ b/apps/client/src/widgets/react/SegmentedChoice.spec.tsx
@@ -1,12 +1,44 @@
+import $ from "jquery";
import { render } from "preact";
+import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+// The collapsed rendering is chosen at render time, so the screen has to be answerable per test.
+// Hoisted alongside the mock: `ActionButton` reads `isMobile()` as its module loads, which happens
+// while the mock factory is still being resolved.
+const isMobileMock = vi.hoisted(() => vi.fn(() => false));
+vi.mock("../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../services/utils")>()),
+ isMobile: () => isMobileMock()
+}));
+
+// Bootstrap places the menu against a real layout, which happy-dom has none of; what the collapsed
+// choice decides is which lines exist, which is marked, and what a press reports.
+vi.mock("bootstrap", () => ({
+ Dropdown: { getOrCreateInstance: () => ({ show() {}, hide() {}, update() {}, dispose() {} }) },
+ Tooltip: class { static getInstance() { return null; } }
+}));
+vi.mock("./hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./hooks")>()),
+ useStaticTooltip: vi.fn(),
+ useTooltip: () => ({ showTooltip: vi.fn(), hideTooltip: vi.fn() })
+}));
+
import SegmentedChoice from "./SegmentedChoice";
+// happy-dom has no ResizeObserver; the dropdown only needs observe/disconnect to exist.
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+globalThis.ResizeObserver = globalThis.ResizeObserver ?? (ResizeObserverStub as unknown as typeof ResizeObserver);
+
describe("SegmentedChoice", () => {
let container: HTMLDivElement;
beforeEach(() => {
+ isMobileMock.mockReturnValue(false);
container = document.createElement("div");
document.body.appendChild(container);
});
@@ -56,4 +88,85 @@ describe("SegmentedChoice", () => {
container.querySelectorAll("button")[1].click();
expect(onChange).toHaveBeenCalledWith("system");
});
+
+ it("turns every option off together", () => {
+ const onChange = vi.fn();
+ render(<SegmentedChoice options={options()} currentValue="user" onChange={onChange} disabled />, container);
+
+ const buttons = [ ...container.querySelectorAll("button") ];
+ expect(buttons.map((button) => button.disabled)).toStrictEqual([ true, true ]);
+ buttons[1].click();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ describe("collapsed onto a narrow screen", () => {
+ const iconOptions = [
+ { value: "light" as const, label: "Light", icon: "bx-sun" },
+ { value: "dark" as const, label: "Dark", icon: "bx-moon" }
+ ];
+
+ it("keeps its buttons where the caller has not asked for the fold", () => {
+ isMobileMock.mockReturnValue(true);
+ renderOpened(<SegmentedChoice options={options()} currentValue="user" onChange={() => {}} />);
+
+ expect(container.querySelectorAll(".dropdown-item")).toHaveLength(0);
+ expect(container.querySelectorAll("button")).toHaveLength(2);
+ });
+
+ it("shows the options as a menu labelled with the current one, and reports the line pressed", () => {
+ isMobileMock.mockReturnValue(true);
+ const onChange = vi.fn();
+ renderOpened(<SegmentedChoice options={iconOptions} currentValue="dark" onChange={onChange} collapseOnMobile />);
+
+ // One toggle rather than a segment each, wearing the current option's own name and icon.
+ const toggle = container.querySelector("button");
+ expect(toggle?.textContent).toContain("Dark");
+ expect(toggle?.querySelector(".bx-moon")).not.toBeNull();
+
+ const items = [ ...container.querySelectorAll(".dropdown-item") ];
+ expect(items.map((item) => item.textContent?.trim())).toStrictEqual([ "Light", "Dark" ]);
+ // The options carry icons, so the current one is highlighted rather than having its icon
+ // replaced by a check mark.
+ expect(items[1].className).toContain("active");
+ expect(items[1].querySelector(".bx-moon")).not.toBeNull();
+
+ act(() => (items[0] as HTMLElement).click());
+ expect(onChange).toHaveBeenCalledExactlyOnceWith("light");
+ });
+
+ it("names an icon-only option by its title, and marks the current one where there are no icons", () => {
+ isMobileMock.mockReturnValue(true);
+ renderOpened(
+ <SegmentedChoice
+ options={[ { value: "square" as const, icon: "bx-square", title: "Square" }, { value: "round" as const, label: "Round" } ]}
+ currentValue="square"
+ onChange={() => {}}
+ collapseOnMobile
+ />);
+ expect([ ...container.querySelectorAll(".dropdown-item") ].map((item) => item.textContent?.trim()))
+ .toStrictEqual([ "Square", "Round" ]);
+
+ renderOpened(<SegmentedChoice options={options()} currentValue="system" onChange={() => {}} collapseOnMobile />);
+ const items = [ ...container.querySelectorAll(".dropdown-item") ];
+ expect(items[1].querySelector(".bx-check")).not.toBeNull();
+ });
+
+ it("shows a count beside the name rather than as a badge, the menu line having room for it", () => {
+ isMobileMock.mockReturnValue(true);
+ renderOpened(<SegmentedChoice options={options({ count: 3 })} currentValue="user" onChange={() => {}} collapseOnMobile />);
+
+ const items = [ ...container.querySelectorAll(".dropdown-item") ];
+ expect(items.map((item) => item.querySelector("small")?.textContent)).toStrictEqual([ "3", "7" ]);
+ expect(container.querySelectorAll(".tn-segmented-choice-count")).toHaveLength(0);
+ });
+ });
+
+ /** The menu only renders its items once Bootstrap reports it open, which nothing does here. */
+ function renderOpened(vnode: preact.ComponentChild) {
+ act(() => render(vnode, container));
+ const dropdown = container.querySelector(".dropdown");
+ act(() => {
+ if (dropdown) $(dropdown).trigger("show.bs.dropdown");
+ });
+ }
});
diff --git a/apps/client/src/widgets/react/SegmentedChoice.tsx b/apps/client/src/widgets/react/SegmentedChoice.tsx
index b9e7890226..b8c084f9bb 100644
--- a/apps/client/src/widgets/react/SegmentedChoice.tsx
+++ b/apps/client/src/widgets/react/SegmentedChoice.tsx
@@ -2,8 +2,10 @@ import "./SegmentedChoice.css";
import clsx from "clsx";
+import { isMobile } from "../../services/utils";
import SimpleBadge from "./Badge";
import Button, { ButtonGroup } from "./Button";
+import FormDropdownList from "./FormDropdownList";
export interface SegmentedChoiceOption<T extends string> {
value: T;
@@ -34,13 +36,30 @@ interface SegmentedChoiceProps<T extends string> {
currentValue: string;
onChange: (newValue: T) => void;
className?: string;
+ /** Turns the whole choice off, showing it as it stands but taking no press. */
+ disabled?: boolean;
+ /**
+ * Fold the group into a dropdown on a mobile screen, where a row of named options runs out of
+ * width and either wraps or pushes the row it sits in out of shape.
+ *
+ * Opt-in rather than automatic: a group of two or three icons is compact enough to keep its
+ * segments anywhere, and hiding those behind a menu costs a press for nothing.
+ */
+ collapseOnMobile?: boolean;
}
/**
* A row of buttons acting as one exclusive choice, the current one highlighted — for switching
* between a few named views or sections where a dropdown would hide the alternatives.
+ *
+ * Where there is no room for the row — a mobile screen, with {@link SegmentedChoiceProps.collapseOnMobile}
+ * set — the same choice is shown as a dropdown instead.
*/
-export default function SegmentedChoice<T extends string>({ options, currentValue, onChange, className }: SegmentedChoiceProps<T>) {
+export default function SegmentedChoice<T extends string>({ options, currentValue, onChange, className, disabled, collapseOnMobile }: SegmentedChoiceProps<T>) {
+ if (collapseOnMobile && isMobile()) {
+ return <CollapsedChoice options={options} currentValue={currentValue} onChange={onChange} className={className} disabled={disabled} />;
+ }
+
return (
<ButtonGroup size="sm" className={clsx("tn-segmented-choice", className)}>
{options.map(({ value, label, icon, title, count }) => (
@@ -60,6 +79,7 @@ export default function SegmentedChoice<T extends string>({ options, currentValu
icon={icon}
title={title}
size="small"
+ disabled={disabled}
className={clsx(currentValue === value && "active")}
onClick={() => onChange(value)}
/>
@@ -67,3 +87,38 @@ export default function SegmentedChoice<T extends string>({ options, currentValu
</ButtonGroup>
);
}
+
+/**
+ * The narrow rendering of a {@link SegmentedChoice}: the same options as one dropdown, labelled with
+ * whichever is current.
+ */
+function CollapsedChoice<T extends string>({ options, currentValue, onChange, className, disabled }: Omit<SegmentedChoiceProps<T>, "collapseOnMobile">) {
+ // An icon per line, or a check mark against the current one — a list mixing the two would show the
+ // current option's icon replaced by the mark, which reads as the option having changed.
+ const hasIcons = options.some(({ icon }) => icon);
+ const values = options.map(({ value, label, icon, title, count }) => ({
+ value,
+ // An option that shows as an icon alone still needs its name once it is a line of text.
+ label: label ?? title ?? value,
+ icon: icon ? `bx ${icon}` : undefined,
+ // A menu line has the width for the count beside the name, so it goes there as a plain suffix
+ // rather than as the badge that keeps it legible against a button's own fill.
+ count: count !== undefined ? String(count) : undefined
+ }));
+
+ return (
+ <FormDropdownList
+ className={className}
+ values={values}
+ keyProperty="value"
+ titleProperty="label"
+ titleSuffixProperty="count"
+ iconProperty={hasIcons ? "icon" : undefined}
+ currentValue={currentValue}
+ onChange={(newValue) => onChange(newValue as T)}
+ disabled={disabled}
+ // A handful of options, so the menu never scrolls — see the prop's own note.
+ noDropdownListStyle
+ />
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.tsx b/apps/client/src/widgets/type_widgets/options/appearance.tsx
index 2d94e4870b..34e2af3a1a 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.tsx
+++ b/apps/client/src/widgets/type_widgets/options/appearance.tsx
@@ -11,13 +11,14 @@ import { t } from "../../../services/i18n";
import server from "../../../services/server";
import { isElectron, isMobile, reloadFrontendApp, restartDesktopApp } from "../../../services/utils";
import { VerticalLayoutIcon } from "../../buttons/global_menu";
-import Button, { ButtonGroup } from "../../react/Button";
+import Button from "../../react/Button";
import Dropdown from "../../react/Dropdown";
import FormList, { FormListHeader, FormListItem } from "../../react/FormList";
import { FormTextBoxWithUnit } from "../../react/FormTextBox";
import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
import Icon from "../../react/Icon";
import Modal from "../../react/Modal";
+import SegmentedChoice, { SegmentedChoiceOption } from "../../react/SegmentedChoice";
import Slider from "../../react/Slider";
import OptionsPageHeader from "./components/OptionsPageHeader";
import OptionsRow, { OptionsRowWithToggle } from "./components/OptionsRow";
@@ -57,10 +58,10 @@ const THEME_FAMILIES: ThemeFamily[] = [
}
];
-const COLOR_SCHEMES: { key: ColorScheme; label: string; icon: string }[] = [
- { key: "system", label: t("theme.color_scheme_system"), icon: "bx bx-brightness-half" },
- { key: "light", label: t("theme.color_scheme_light"), icon: "bx bx-sun" },
- { key: "dark", label: t("theme.color_scheme_dark"), icon: "bx bx-moon" }
+const COLOR_SCHEMES: SegmentedChoiceOption<ColorScheme>[] = [
+ { value: "system", label: t("theme.color_scheme_system"), icon: "bx-brightness-half" },
+ { value: "light", label: t("theme.color_scheme_light"), icon: "bx-sun" },
+ { value: "dark", label: t("theme.color_scheme_dark"), icon: "bx-moon" }
];
function resolveTheme(themeVal: string | null): { family: ThemeFamily | null; scheme: ColorScheme; isCustom: boolean } {
@@ -212,19 +213,15 @@ function UserInterface() {
</Dropdown>
</OptionsRow>
<OptionsRow name="color-scheme" label={t("theme.color_scheme")} description={isCustom ? t("theme.color_scheme_custom_disabled") : undefined}>
- <ButtonGroup>
- {COLOR_SCHEMES.map(cs => (
- <button
- key={cs.key}
- type="button"
- className={`btn btn-sm btn-secondary ${resolved.scheme === cs.key && !isCustom ? "active" : ""}`}
- disabled={isCustom}
- onClick={() => setColorScheme(cs.key)}
- >
- <Icon icon={cs.icon} /> {cs.label}
- </button>
- ))}
- </ButtonGroup>
+ <SegmentedChoice
+ options={COLOR_SCHEMES}
+ // A custom theme brings its own colours, so the group highlights nothing rather
+ // than naming a scheme it is not following.
+ currentValue={isCustom ? "" : resolved.scheme}
+ onChange={setColorScheme}
+ disabled={isCustom}
+ collapseOnMobile
+ />
</OptionsRow>
{!isMobile() && <>
<OptionsRow name="layout-style" label={t("settings_appearance.ui_layout_style")}>
diff --git a/apps/client/src/widgets/type_widgets/options/components/ThemeModeSelector.tsx b/apps/client/src/widgets/type_widgets/options/components/ThemeModeSelector.tsx
index e04172f051..6dce02d0d3 100644
--- a/apps/client/src/widgets/type_widgets/options/components/ThemeModeSelector.tsx
+++ b/apps/client/src/widgets/type_widgets/options/components/ThemeModeSelector.tsx
@@ -1,32 +1,28 @@
import { t } from "../../../../services/i18n";
-import { ButtonGroup } from "../../../react/Button";
-import Icon from "../../../react/Icon";
+import SegmentedChoice, { SegmentedChoiceOption } from "../../../react/SegmentedChoice";
import OptionsRow from "./OptionsRow";
+type ThemeMode = "app" | "fixed";
+
interface ThemeModeSelectorProps {
matchesApp: boolean;
onMatchesAppChange: (value: boolean) => void;
}
export default function ThemeModeSelector({ matchesApp, onMatchesAppChange }: ThemeModeSelectorProps) {
+ const modes: SegmentedChoiceOption<ThemeMode>[] = [
+ { value: "app", label: t("code_theme.match_app_appearance"), icon: "bx-brightness-half" },
+ { value: "fixed", label: t("code_theme.always_use_one_theme"), icon: "bx-pin" }
+ ];
+
return (
<OptionsRow name="theme-mode" label={t("code_theme.theme_mode")}>
- <ButtonGroup>
- <button
- type="button"
- className={`btn btn-sm btn-secondary ${matchesApp ? "active" : ""}`}
- onClick={() => onMatchesAppChange(true)}
- >
- <Icon icon="bx bx-brightness-half" />{" "}{t("code_theme.match_app_appearance")}
- </button>
- <button
- type="button"
- className={`btn btn-sm btn-secondary ${!matchesApp ? "active" : ""}`}
- onClick={() => onMatchesAppChange(false)}
- >
- <Icon icon="bx bx-pin" />{" "}{t("code_theme.always_use_one_theme")}
- </button>
- </ButtonGroup>
+ <SegmentedChoice
+ options={modes}
+ currentValue={matchesApp ? "app" : "fixed"}
+ onChange={(mode) => onMatchesAppChange(mode === "app")}
+ collapseOnMobile
+ />
</OptionsRow>
);
}