Skip to content

Build your personal knowledge base with Trilium Notes

refactor(icons): pick an icon the same way wherever one is picked

Elian Doran5c66c75abc20
diff --git a/apps/client/src/widgets/note_icon.tsx b/apps/client/src/widgets/note_icon.tsx
index 5749a1f534..de9b5fd0bc 100644
--- a/apps/client/src/widgets/note_icon.tsx
+++ b/apps/client/src/widgets/note_icon.tsx
@@ -1,25 +1,23 @@
import "./note_icon.css";
-import { Dropdown as BootstrapDropdown } from "bootstrap";
import { t } from "i18next";
-import { createPortal } from "preact/compat";
-import { useEffect, useRef, useState } from "preact/hooks";
+import { useEffect, useState } from "preact/hooks";
import FNote from "../entities/fnote";
import attributes from "../services/attributes";
-import { isMobile } from "../services/utils";
-import ActionButton from "./react/ActionButton";
-import Dropdown from "./react/Dropdown";
-import { useNoteContext, useNoteLabel, useWindowSize } from "./react/hooks";
-import IconPicker, { ICON_SIZE } from "./react/IconPicker";
-import Modal from "./react/Modal";
-
+import { useNoteContext, useNoteLabel } from "./react/hooks";
+import { IconPickerButton } from "./react/IconPicker";
+
+/**
+ * The icon of the note being read, and the way to change it: the shared picking button, made to
+ * write what it gives back onto the note (see {@link IconPickerButton}, which is also what decides
+ * whether the picker hangs under the button or takes a screen of its own).
+ */
export default function NoteIcon() {
const { note, viewScope } = useNoteContext();
const [ icon, setIcon ] = useState<string | null | undefined>();
const [ iconClass ] = useNoteLabel(note, "iconClass");
const [ workspaceIconClass ] = useNoteLabel(note, "workspaceIconClass");
- const dropdownRef = useRef<BootstrapDropdown>(null);
useEffect(() => {
setIcon(note?.getIcon());
@@ -27,95 +25,29 @@ export default function NoteIcon() {
const isDisabled = viewScope?.viewMode !== "default"
|| note?.isMetadataReadOnly;
-
- if (isMobile()) {
- return <MobileNoteIconSwitcher note={note} icon={icon} disabled={isDisabled} />;
- }
+ const iconLabels = note ? getIconLabels(note) : [];
return (
- <Dropdown
- className="note-icon-widget"
+ <IconPickerButton
+ icon={icon ?? "bx bx-empty"}
title={t("note_icon.change_note_icon")}
- dropdownRef={dropdownRef}
- dropdownContainerStyle={{ width: "620px" }}
- dropdownOptions={{ autoClose: "outside" }}
- // The inline title sets `container-type: inline-size`, which makes it a backdrop root and
- // flattens the menu's blur into a flat tint. Portal the menu out of that subtree; it stays
- // wrapped in a `.note-icon-widget` div so the picker's scoped CSS keeps applying.
- portalToBody
- buttonClassName={`note-icon tn-focusable-button ${icon ?? "bx bx-empty"}`}
- hideToggleArrow
disabled={isDisabled}
- >
- { note && <NoteIconPicker note={note} onHide={() => dropdownRef?.current?.hide()} columnCount={12} /> }
- </Dropdown>
- );
-}
-
-/** The shared picker, made to set and clear the icon of a note. */
-function NoteIconPicker({ note, onHide, columnCount }: {
- note: FNote;
- onHide: () => void;
- columnCount: number;
-}) {
- const iconLabels = getIconLabels(note);
-
- return (
- <IconPicker
- columnCount={columnCount}
- onSelect={(iconClass) => {
+ onSelect={(picked) => {
+ if (!note) return;
const attributeToSet = note.hasOwnedLabel("workspace") ? "workspaceIconClass" : "iconClass";
- attributes.setLabel(note.noteId, attributeToSet, iconClass);
- onHide();
+ attributes.setLabel(note.noteId, attributeToSet, picked);
}}
// Nothing to reset while the note wears the icon its type gives it.
onReset={iconLabels.length ? () => {
for (const label of iconLabels) {
- attributes.removeAttributeById(note.noteId, label.attributeId);
+ attributes.removeAttributeById(label.noteId, label.attributeId);
}
- onHide();
} : undefined}
/>
);
}
-function MobileNoteIconSwitcher({ note, icon, disabled }: {
- note: FNote | null | undefined;
- icon: string | null | undefined;
- disabled?: boolean;
-}) {
- const [ modalShown, setModalShown ] = useState(false);
- const { windowWidth } = useWindowSize();
-
- return (
- <div className="note-icon-widget">
- <ActionButton
- className="note-icon"
- icon={icon ?? "bx bx-empty"}
- text={t("note_icon.change_note_icon")}
- onClick={() => setModalShown(true)}
- disabled={disabled}
- />
-
- {createPortal((
- <Modal
- title={t("note_icon.change_note_icon")}
- size="xl"
- show={modalShown} onHidden={() => setModalShown(false)}
- className="icon-switcher note-icon-widget"
- scrollable
- >
- {note && <NoteIconPicker note={note} onHide={() => setModalShown(false)} columnCount={Math.max(1, Math.floor(windowWidth / ICON_SIZE))} />}
- </Modal>
- ), document.body)}
- </div>
- );
-}
-
function getIconLabels(note: FNote) {
- if (!note) {
- return [];
- }
return note.getOwnedLabels()
.filter((label) => ["workspaceIconClass", "iconClass"]
.includes(label.name));
diff --git a/apps/client/src/widgets/react/IconPicker.spec.tsx b/apps/client/src/widgets/react/IconPicker.spec.tsx
new file mode 100644
index 0000000000..0c6bc9df96
--- /dev/null
+++ b/apps/client/src/widgets/react/IconPicker.spec.tsx
@@ -0,0 +1,46 @@
+import { describe, expect, it, vi } from "vitest";
+
+// Hoisted: a module in the import chain reads the device once as it loads (see ActionButton), which
+// happens before a plain `const` here would have been initialized.
+const isMobileMock = vi.hoisted(() => vi.fn(() => false));
+// The button asks the device what it is at render time; mock it so both halves of the split can be
+// rendered here, whichever machine the tests are run on.
+vi.mock("../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../services/utils")>()),
+ isMobile: () => isMobileMock()
+}));
+
+import { renderInto } from "../../test/render";
+import { IconPickerButton } from "./IconPicker";
+
+describe("IconPickerButton", () => {
+ /** Renders the button as the given device would see it. */
+ function renderButton(mobile: boolean) {
+ isMobileMock.mockReturnValue(mobile);
+ return renderInto(
+ <IconPickerButton icon="bx bx-star" title="Change this icon" onSelect={() => {}} />
+ );
+ }
+
+ it("hangs the picker under the button on a desktop, and gives it a screen of its own on a phone", () => {
+ const desktop = renderButton(false);
+
+ // The button stands where it was put; what it opens is a menu, which is neither built nor
+ // handed to the page until it is opened (see `portalToBody`).
+ expect(desktop.querySelector(".note-icon-widget button.note-icon")).toBeTruthy();
+ expect(document.body.querySelector(".modal.icon-switcher")).toBeNull();
+ expect(document.body.querySelector(".dropdown-menu")).toBeNull();
+
+ const mobile = renderButton(true);
+
+ // A menu at the width of the picker is wider than a phone, so what opens there is the modal
+ // the note's own icon is picked through, which the stylesheet gives the whole screen to.
+ expect(mobile.querySelector(".note-icon-widget button.note-icon")).toBeTruthy();
+ expect(document.body.querySelector(".modal.icon-switcher")).toBeTruthy();
+ expect(document.body.querySelector(".dropdown-menu")).toBeNull();
+
+ // On either device the picker itself waits to be asked for: it holds every icon of every
+ // installed pack, which is far more work than a button on screen should be doing.
+ expect(document.body.querySelector(".icon-picker")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/react/IconPicker.tsx b/apps/client/src/widgets/react/IconPicker.tsx
index 042d0ac889..2928c78652 100644
--- a/apps/client/src/widgets/react/IconPicker.tsx
+++ b/apps/client/src/widgets/react/IconPicker.tsx
@@ -1,8 +1,10 @@
import "./IconPicker.css";
import { IconRegistry } from "@triliumnext/commons";
+import { Dropdown as BootstrapDropdown } from "bootstrap";
import clsx from "clsx";
import { CSSProperties } from "preact";
+import { createPortal } from "preact/compat";
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import type React from "react";
import { CellComponentProps, Grid } from "react-window";
@@ -14,7 +16,8 @@ import ActionButton from "./ActionButton";
import Dropdown from "./Dropdown";
import { FormDropdownDivider, FormListItem } from "./FormList";
import FormTextBox from "./FormTextBox";
-import { useStaticTooltip } from "./hooks";
+import { useStaticTooltip, useWindowSize } from "./hooks";
+import Modal from "./Modal";
/** The room one icon takes in the grid, which also decides how many fit across a given width. */
export const ICON_SIZE = isMobile() ? 56 : 48;
@@ -102,6 +105,121 @@ export default function IconPicker({ onSelect, onReset, resetText, columnCount }
);
}
+interface IconPickerButtonProps extends Pick<IconPickerProps, "onSelect" | "onReset" | "resetText"> {
+ /** The class the button wears, which is the icon it stands for, e.g. `bx bx-star`. */
+ icon: string;
+ /** What pressing it is for, worn as its tooltip and as the heading of the modal on a phone. */
+ title: string;
+ /** The host's own class, for a host that dresses the button or the widget around it. */
+ className?: string;
+ disabled?: boolean;
+}
+
+/**
+ * The button an icon is picked through: the picker hangs under it, and what is picked is reported
+ * and the picker put away.
+ *
+ * Where it is put differs with the screen. A desktop gets the menu under the button, at the width
+ * twelve icons and a search field ask for. A phone gets a modal of its own instead: that width is
+ * wider than the screen, and a menu of it — hung off a button that may itself be in the corner of a
+ * panel — leaves the grid mostly off-screen, which is no way to pick from a thousand icons.
+ */
+export function IconPickerButton({ className, ...props }: IconPickerButtonProps) {
+ // A constant of the session rather than of the render, as everywhere else it is branched on.
+ return isMobile()
+ ? <IconPickerModalButton className={className} {...props} />
+ : <IconPickerDropdownButton className={className} {...props} />;
+}
+
+/** The picker under the button, as a desktop shows it. */
+function IconPickerDropdownButton({ icon, title, className, disabled, onSelect, onReset, resetText }: IconPickerButtonProps) {
+ const dropdownRef = useRef<BootstrapDropdown>(null);
+ const [ pickerShown, setPickerShown ] = useState(false);
+
+ return (
+ <Dropdown
+ // The legacy class dresses the menu the picker sits in, which the themes and the
+ // picker's own stylesheet reach through it.
+ className={clsx("note-icon-widget", className)}
+ buttonClassName={`note-icon tn-focusable-button ${icon}`}
+ title={title}
+ disabled={disabled}
+ dropdownRef={dropdownRef}
+ dropdownContainerStyle={{ width: "620px" }}
+ dropdownOptions={{ autoClose: "outside" }}
+ // The menu is wider than some of the places a button stands in, and the inline title
+ // establishes a backdrop root that would flatten its blur into a tint; hand the menu to
+ // the page rather than leaving it to be clipped or dulled.
+ portalToBody
+ hideToggleArrow
+ onShown={() => setPickerShown(true)}
+ onHidden={() => setPickerShown(false)}
+ >
+ {/* Built only once opened: it holds every icon of every installed pack, which is far
+ more work than a button that merely happens to be on screen should be doing. */}
+ {pickerShown && (
+ <IconPicker
+ columnCount={12}
+ resetText={resetText}
+ onSelect={(iconClass) => {
+ onSelect(iconClass);
+ dropdownRef.current?.hide();
+ }}
+ onReset={onReset && (() => {
+ onReset();
+ dropdownRef.current?.hide();
+ })}
+ />
+ )}
+ </Dropdown>
+ );
+}
+
+/** The picker on a screen of its own, as a phone shows it. */
+function IconPickerModalButton({ icon, title, className, disabled, onSelect, onReset, resetText }: IconPickerButtonProps) {
+ const [ modalShown, setModalShown ] = useState(false);
+ const { windowWidth } = useWindowSize();
+
+ return (
+ <div className={clsx("note-icon-widget", className)}>
+ <ActionButton
+ className="note-icon"
+ icon={icon}
+ text={title}
+ onClick={() => setModalShown(true)}
+ disabled={disabled}
+ />
+
+ {/* Out of whatever the button stands in — a panel floating over a note holds its own
+ stacking context, and the modal belongs to the page rather than to it. */}
+ {createPortal((
+ <Modal
+ title={title}
+ size="xl"
+ show={modalShown} onHidden={() => setModalShown(false)}
+ className="icon-switcher note-icon-widget"
+ scrollable
+ >
+ {/* As many icons as the screen has room for, rather than the twelve a menu is
+ built for (see the CSS, which gives the grid the rest of the screen). */}
+ <IconPicker
+ columnCount={Math.max(1, Math.floor(windowWidth / ICON_SIZE))}
+ resetText={resetText}
+ onSelect={(iconClass) => {
+ onSelect(iconClass);
+ setModalShown(false);
+ }}
+ onReset={onReset && (() => {
+ onReset();
+ setModalShown(false);
+ })}
+ />
+ </Modal>
+ ), document.body)}
+ </div>
+ );
+}
+
type IconWithName = (IconRegistry["sources"][number]["icons"][number] & { iconPack: string });
interface IconToCountCache {
diff --git a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.tsx b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.tsx
index 8bd99eddee..269be958e7 100644
--- a/apps/client/src/widgets/type_widgets/mind_map/NodePanel.tsx
+++ b/apps/client/src/widgets/type_widgets/mind_map/NodePanel.tsx
@@ -1,7 +1,6 @@
import "./NodePanel.css";
import { parseMindMapNoteLink } from "@triliumnext/commons";
-import { Dropdown as BootstrapDropdown } from "bootstrap";
import type { MindElixirInstance, NodeObj, TagObj } from "mind-elixir";
import { ComponentChildren } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
@@ -13,11 +12,10 @@ import ValuesInput from "../../attribute_widgets/values_input";
import ActionButton from "../../react/ActionButton";
import Button from "../../react/Button";
import ColorPicker, { DEFAULT_COLOR_PALETTE } from "../../react/ColorPicker";
-import Dropdown from "../../react/Dropdown";
import { FormFileUploadActionButton } from "../../react/FormFileUpload";
import { useNote, useNoteIcon, useNoteTitle } from "../../react/hooks";
import Icon from "../../react/Icon";
-import IconPicker from "../../react/IconPicker";
+import { IconPickerButton } from "../../react/IconPicker";
import SegmentedChoice from "../../react/SegmentedChoice";
import TabStrip, { type TabStripTabDefinition } from "../../react/TabStrip";
import { fitNodeImage, getNodeImageShape, nearestNodeImageWidth, NODE_IMAGE_SHAPES, NODE_IMAGE_WIDTHS, type NodeImage as NodeImageData, type NodeImageShape, shapeNodeImage, uploadNodeImage } from "./images";
@@ -467,10 +465,9 @@ function NodeIcons({ icons, readOnly, onChange }: {
}
/**
- * One icon of a node, chosen through the picker every other icon in Trilium is chosen through.
- *
- * The picker is only built once opened: it holds every icon of every installed pack, which is far
- * more work than a panel that merely happens to be on screen should be doing.
+ * One icon of a node, chosen through the button every other icon in Trilium is chosen through —
+ * the picker under it on a desktop, and on a phone the modal a note's icon is picked in as well
+ * (see {@link IconPickerButton}), rather than a menu wider than the screen hung off a panel.
*/
function NodeIcon({ face, title, disabled, onSelect, onRemove }: {
/** The class the button wears, whether an icon of the node or the invitation to add one. */
@@ -482,42 +479,16 @@ function NodeIcon({ face, title, disabled, onSelect, onRemove }: {
* to remove. */
onRemove?(): void;
}) {
- const dropdownRef = useRef<BootstrapDropdown>(null);
- const [ pickerShown, setPickerShown ] = useState(false);
-
return (
- <Dropdown
- // The legacy class dresses the menu the picker sits in, which the themes and the
- // picker's own stylesheet reach through it.
- className="mind-map-node-icon note-icon-widget"
- buttonClassName={`note-icon tn-focusable-button ${face}`}
+ <IconPickerButton
+ className="mind-map-node-icon"
+ icon={face}
title={title}
disabled={disabled}
- dropdownRef={dropdownRef}
- dropdownContainerStyle={{ width: "620px" }}
- dropdownOptions={{ autoClose: "outside" }}
- // The panel scrolls, and the picker is wider than the panel is; hand the menu to the
- // page instead of leaving it to be clipped.
- portalToBody
- hideToggleArrow
- onShown={() => setPickerShown(true)}
- onHidden={() => setPickerShown(false)}
- >
- {pickerShown && (
- <IconPicker
- columnCount={12}
- resetText={t("mind-map.clear-icon")}
- onSelect={(iconClass) => {
- onSelect(iconClass);
- dropdownRef.current?.hide();
- }}
- onReset={onRemove && (() => {
- onRemove();
- dropdownRef.current?.hide();
- })}
- />
- )}
- </Dropdown>
+ onSelect={onSelect}
+ onReset={onRemove}
+ resetText={t("mind-map.clear-icon")}
+ />
);
}