Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: allow changing the card icon without opening the note

Adorian Doran64d7fbd18a23
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 65fc4add3e..3ed0bc3cb7 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -463,6 +463,14 @@ body > .tn-dropdown-portal > .dropdown-menu {
--bs-dropdown-zindex: 1200;
}
+/* Under the menu above, which is what it is drawn for; stated beside it so the two stay in step. */
+body > .tn-dropdown-portal > .tn-dropdown-backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 1199;
+ background: rgba(0, 0, 0, 0.1);
+}
+
body.desktop .dropdown-menu,
body.desktop .tabulator-popup-container,
:root .excalidraw .dropdown-menu .dropdown-menu-container,
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 40f7225a14..2881e618b1 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3372,7 +3372,7 @@
"unarchive-note": "Unarchive note",
"status-header": "Status",
"duplicate-item": "Duplicate",
- "edit-title": "Edit title",
+ "edit-title": "Edit title & icon",
"insert-above": "Insert new above",
"insert-below": "Insert new below",
"move-to-top": "Move to top",
@@ -3426,6 +3426,7 @@
"move-column-first": "As the first column",
"move-column-after": "After {{column}}",
"change-column-icon": "Change column icon",
+ "change-note-icon": "Change icon",
"column-menu": "Column menu",
"column-already-exists": "This column already exists on the board.",
"column-definition-save-error": "The columns were saved on the board, but could not be saved to the status attribute.",
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index f3216634fe..fcc1dd9408 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -170,7 +170,9 @@ export default class BoardApi {
* board lands at the bottom. The top is created before the column's own first card: all
* columns share one list of children, so the board's first child is not this column's.
*/
- async createNewItem(column: string, title: string, placement: CardPlacement = "bottom") {
+ async createNewItem(
+ column: string, title: string, placement: CardPlacement = "bottom", icon?: string
+ ) {
const first = placement === "top"
? this.byColumn?.get(column)?.[0]?.branch.branchId
: undefined;
@@ -180,7 +182,17 @@ export default class BoardApi {
activate: false,
title,
isProtected: this.parentNote.isProtected,
- attributes: this.groupingFor(column),
+ attributes: [
+ ...this.groupingFor(column),
+ ...(icon
+ ? [ {
+ type: "label" as const,
+ name: "iconClass",
+ value: icon,
+ isInheritable: false
+ } ]
+ : [])
+ ],
...(first ? { target: "before", targetBranchId: first } : {})
});
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index d16ce3db4d..aceb979d60 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -12,7 +12,7 @@ import { t } from "../../../services/i18n";
import UserAttributesDisplay from "../../attribute_widgets/UserAttributesList";
import { FLIP_SETTLE_MS } from "../../react/flip";
import {
- useNoteColorClass, useNoteIcon, useNoteLabelBoolean, useTriliumEvent
+ useNoteColorClass, useNoteIcon, useNoteLabel, useNoteLabelBoolean, useTriliumEvent
} from "../../react/hooks";
function Card({
@@ -60,6 +60,7 @@ function Card({
const editorRef = useRef<HTMLInputElement>(null);
const cardRef = useRef<HTMLDivElement>(null);
const [ isArchived ] = useNoteLabelBoolean(note, "archived");
+ const [ iconClass, setIconClass ] = useNoteLabel(note, "iconClass");
// The card stays the one just made until another is, so what has already been shown is
// remembered here rather than played again by every redraw of the column.
const [ isRevealed, setIsRevealed ] = useState(false);
@@ -191,6 +192,11 @@ function Card({
}}
dismiss={() => api.dismissEditingTitle()}
mode="multiline"
+ icon={{
+ current: icon ?? "",
+ onSelect: setIconClass,
+ onReset: iconClass ? () => setIconClass(null) : undefined
+ }}
/>
)}
</div>
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index a971a1cc18..a5d9a5ee86 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -27,6 +27,9 @@ import { useScrollFade } from "../../react/scroll_fade";
*/
const FOOTER_QUIET_MS = 5000;
+/** What a card is drawn with until an icon is picked for it, which is what a text note carries. */
+const DEFAULT_CARD_ICON = "bx bx-note";
+
/** How long an open takes. Matches `--board-expand-duration` in the board's own rules. */
const EXPAND_MS = 200;
import NoteLink from "../../react/NoteLink";
@@ -517,6 +520,8 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreat
// What the editor opens with: empty to begin with, then whatever was typed into it and left
// unsaved, so that reaching for something else and coming back does not cost the title.
const [ initialTitle, setInitialTitle ] = useState("");
+ // Kept between cards, unlike the title: a run of cards is often a run of the same kind of card.
+ const [ icon, setIcon ] = useState(DEFAULT_CARD_ICON);
const open = useCallback((title: string) => {
setInitialTitle(title);
@@ -571,7 +576,8 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreat
save={async (title, atStart) => {
onCreating();
onCreated(await api.createNewItem(
- column, title, atStart ? "top" : "bottom"));
+ column, title, atStart ? "top" : "bottom",
+ icon !== DEFAULT_CARD_ICON ? icon : undefined));
}}
dismiss={() => setIsCreating(false)}
mode="multiline" isNewItem
@@ -584,6 +590,13 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreat
}}
submitTitle={t("board_view.create-new-note")}
openPlacements={openCreateCardMenu}
+ icon={{
+ current: icon,
+ onSelect: setIcon,
+ onReset: icon !== DEFAULT_CARD_ICON
+ ? () => setIcon(DEFAULT_CARD_ICON)
+ : undefined
+ }}
/>
)}
</div>
diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.css
index 56bc258619..23e16836ea 100644
--- a/apps/client/src/widgets/collections/board/index.css
+++ b/apps/client/src/widgets/collections/board/index.css
@@ -517,8 +517,8 @@ body.mobile .board-view-container .board-add-column {
resize: none;
}
-/* The field and the button that submits it, which stands over the field's own end. */
-.board-view-container .title-editor-with-submit {
+/* The field with what stands over it: the icon at its leading edge, the submit at its trailing. */
+.board-view-container .title-editor-field {
display: flex;
flex-grow: 1;
position: relative;
@@ -534,7 +534,7 @@ body.mobile .board-view-container .board-add-column {
* rather than `em`: a custom property is worked out where it is used, and this button's font is
* itself derived from the size below.
*/
-.board-view-container .title-editor-with-submit .title-editor-submit {
+.board-view-container .title-editor-field .title-editor-submit {
--icon-button-size: 1.6rem;
--icon-button-icon-ratio: 0.72;
@@ -556,10 +556,52 @@ body.mobile .board-view-container .board-add-column {
}
}
-/* Room for the button, so a long title runs up to it rather than under it. Stated after the rule
+/*
+ * The icon the card carries, which opens the picker. Flat and the size of the icon a card is drawn
+ * with, rather than the button a note header stands on: it is part of the line being typed.
+ *
+ * Three sizes, and the icon stays where it is through all of them: `--note-icon-size` is the glyph,
+ * `--note-icon-container-padding-size` the ring it lights up under the pointer, which grows
+ * outwards from the glyph, and `--title-editor-icon-inset` where the glyph stands from the field's
+ * leading edge.
+ *
+ * Down the field it is held against the first line: the field's own top padding and half a line
+ * down, less half the icon's box. That is the middle of a field of one line, and the first line of
+ * a taller one. Written in `em` on this element rather than on the field: a custom property is
+ * worked out where it is used, and both sit in the card's own font.
+ */
+.board-view-container .title-editor-field .title-editor-icon {
+ --note-icon-size: 15px;
+ --note-icon-container-padding-size: 4px;
+ --title-editor-icon-inset: 0.42rem;
+ /* No disc behind it, and the colour the line itself is written in: it stands in the text being
+ typed, not on a note's own header. */
+ --note-icon-custom-background-color: transparent;
+ --note-icon-color: var(--main-text-color);
+ /* What every other icon button in the page lights up with under the pointer. */
+ --note-icon-hover-custom-background-color: var(--icon-button-hover-background);
+ --title-editor-icon-box: calc(
+ var(--note-icon-size) + 2 * var(--note-icon-container-padding-size));
+
+ position: absolute;
+ inset-inline-start: calc(
+ var(--title-editor-icon-inset) - var(--note-icon-container-padding-size));
+ inset-block-start: calc(
+ var(--card-padding) + (var(--card-line-height) * 1em - var(--title-editor-icon-box)) / 2);
+ z-index: 1;
+}
+
+/* Room for the icon, so a long title runs up to it rather than under it. Stated after the rules
above, whose shorthand padding would otherwise take this back. */
-.board-view-container .title-editor-with-submit textarea.form-control,
-.board-view-container .title-editor-with-submit input.form-control {
+.board-view-container .title-editor-field textarea.form-control,
+.board-view-container .title-editor-field input.form-control {
+ padding-inline-start: 1.9em;
+}
+
+/* And for the button, wherever there is one to make room for. Kept whether or not it is drawn just
+ now, or the text would shift as the field is typed into and emptied again. */
+.board-view-container .title-editor-field.with-submit textarea.form-control,
+.board-view-container .title-editor-field.with-submit input.form-control {
padding-inline-end: 2.2em;
}
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index 5a02676e27..cc4fa48431 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -15,6 +15,7 @@ import server from "../../../services/server";
import toast from "../../../services/toast";
import FBranch from "../../../entities/fbranch";
import froca from "../../../services/froca";
+import attributes from "../../../services/attributes";
import { executeBulkActions } from "../../../services/bulk_action";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
@@ -35,6 +36,31 @@ vi.mock("../../../services/i18n", () => ({
translationsInitializedPromise: $.Deferred().resolve()
}));
+// The picker is a Bootstrap dropdown portalled to the page, which happy-dom does not open. What the
+// board answers for is the icon it shows and what it does with a pick, so the button stands in for
+// the picker and hands one over when it is pressed.
+vi.mock("../../react/IconPicker", () => ({
+ IconPickerButton: ({ className, icon, onSelect, onOpened, onClosed }: {
+ className?: string, icon: string, onSelect: (picked: string) => void,
+ onOpened?: () => void, onClosed?: () => void
+ }) => (
+ <span className={className}>
+ <button className={icon} onClick={() => {
+ onOpened?.();
+ onSelect(PICKED_ICON);
+ onClosed?.();
+ }} />
+ {/* The picker opening and closing on their own, for what the editor does in between.
+ Not buttons: a host counting the buttons its picker draws would count these too. */}
+ <span className="picker-open" onClick={() => onOpened?.()} />
+ <span className="picker-close" onClick={() => onClosed?.()} />
+ </span>
+ )
+}));
+
+/** What the picker hands over when it is pressed under test. */
+const PICKED_ICON = "bx bx-star";
+
vi.mock("../../../services/bulk_action", () => ({
executeBulkActions: vi.fn(async (
noteIds: string[],
@@ -1420,7 +1446,7 @@ describe("Board column rename", () => {
await flush();
});
- expect(created).toHaveBeenCalledWith("Doing", "First", "bottom");
+ expect(created).toHaveBeenCalledWith("Doing", "First", "bottom", undefined);
expect(slot?.querySelector("textarea")).toBe(editor);
expect(editor.value).toBe("");
expect(document.activeElement).toBe(editor);
@@ -1433,7 +1459,7 @@ describe("Board column rename", () => {
});
expect(created).toHaveBeenCalledTimes(2);
- expect(created).toHaveBeenLastCalledWith("Doing", "Second", "bottom");
+ expect(created).toHaveBeenLastCalledWith("Doing", "Second", "bottom", undefined);
});
/**
@@ -2016,12 +2042,147 @@ describe("Board column rename", () => {
await flush();
});
- expect(created).toHaveBeenCalledWith("Doing", "From the button", "bottom");
+ expect(created).toHaveBeenCalledWith("Doing", "From the button", "bottom", undefined);
expect(editor.value).toBe("");
expect(slot?.querySelector("textarea")).toBe(editor);
expect(document.activeElement).toBe(editor);
});
+ /**
+ * The icon stands inside the field, at its head, and is what the card is made with. It is kept
+ * between cards, unlike the title: a run of cards is often a run of the same kind of card.
+ */
+ it("makes a card with the icon picked in the editor, and keeps it for the next", async () => {
+ const { container } = await setup();
+ const created = vi.spyOn(BoardApi.prototype, "createNewItem")
+ .mockResolvedValue(undefined);
+ created.mockClear();
+ const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]
+ .querySelector<HTMLElement>(".board-new-item");
+
+ await act(async () => {
+ slot?.click();
+ await flush();
+ });
+
+ const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");
+ const picker = slot?.querySelector<HTMLElement>(".title-editor-icon");
+ if (!editor || !picker) throw new Error("expected the editor and its icon");
+
+ // What a text note is drawn with, until something else is picked.
+ expect(picker.querySelector("button")?.className).toContain("bx bx-note");
+
+ await pickIcon(slot);
+ expect(slot?.querySelector(".title-editor-icon button")?.className)
+ .toContain(PICKED_ICON);
+
+ await type(editor, "Starred");
+ await act(async () => {
+ editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ await flush();
+ });
+
+ expect(created).toHaveBeenCalledWith("Doing", "Starred", "bottom", PICKED_ICON);
+ // The title goes, the icon stays.
+ expect(editor.value).toBe("");
+ expect(slot?.querySelector(".title-editor-icon button")?.className)
+ .toContain(PICKED_ICON);
+ });
+
+ /**
+ * The picker takes focus with it, and losing focus is what closes the editor: it would take the
+ * picker down with itself the moment it was opened.
+ */
+ it("stays open while the icon picker has the focus", async () => {
+ const { container } = await setup();
+ const created = vi.spyOn(BoardApi.prototype, "createNewItem")
+ .mockResolvedValue(undefined);
+ // The spy outlives the test that made it, and with it what it was called with there.
+ created.mockClear();
+ const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]
+ .querySelector<HTMLElement>(".board-new-item");
+
+ await act(async () => {
+ slot?.click();
+ await flush();
+ });
+
+ const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");
+ if (!editor) throw new Error("expected the new-item editor to be open");
+ await type(editor, "Still here");
+
+ await act(async () => {
+ slot?.querySelector<HTMLElement>(".picker-open")?.click();
+ editor.dispatchEvent(new FocusEvent("blur"));
+ editor.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
+ await flush();
+ });
+
+ expect(slot?.querySelector("textarea")).toBe(editor);
+ expect(editor.value).toBe("Still here");
+ expect(created).not.toHaveBeenCalled();
+
+ // The blur that would have ended the edit is spent, so the field is focused again.
+ await act(async () => {
+ slot?.querySelector<HTMLElement>(".picker-close")?.click();
+ await flush();
+ });
+ expect(document.activeElement).toBe(editor);
+ });
+
+ /** Renaming a card makes nothing, so the button that creates is not offered beside it. */
+ it("offers no create button while a card's title is edited", async () => {
+ const { container } = await setup();
+ const card = container.querySelectorAll<HTMLElement>(".board-column")[1]
+ .querySelector<HTMLElement>(".board-note");
+ if (!card) throw new Error("expected a card");
+
+ await act(async () => {
+ card.dispatchEvent(new KeyboardEvent("keydown", { key: "F2", bubbles: true }));
+ await flush();
+ });
+
+ const editor = card.querySelector<HTMLTextAreaElement>("textarea");
+ if (!editor) throw new Error("expected the title editor");
+
+ await type(editor, "Renamed");
+ expect(card.querySelector(".title-editor-submit")).toBeNull();
+ // The icon is offered all the same, which is what the editor is dressed for.
+ expect(card.querySelector(".title-editor-icon")).toBeTruthy();
+ });
+
+ /** The same picker on a card being renamed, which writes the icon onto the card itself. */
+ it("writes the icon picked while a card's title is edited", async () => {
+ const { container } = await setup();
+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ const card = container.querySelectorAll<HTMLElement>(".board-column")[1]
+ .querySelector<HTMLElement>(".board-note");
+ const noteId = card?.getAttribute("data-note-id");
+ if (!card || !noteId) throw new Error("expected a card");
+
+ await act(async () => {
+ card.dispatchEvent(new KeyboardEvent("keydown", { key: "F2", bubbles: true }));
+ await flush();
+ });
+ expect(card.querySelector("textarea")).toBeTruthy();
+
+ await pickIcon(card);
+
+ expect(setLabel).toHaveBeenCalledWith(noteId, "iconClass", PICKED_ICON);
+ setLabel.mockRestore();
+ });
+
+ /** Takes an icon from the picker standing in the given editor. */
+ async function pickIcon(host: HTMLElement | null | undefined) {
+ const button = host?.querySelector<HTMLElement>(".title-editor-icon button");
+ if (!button) throw new Error("expected an icon beside the field");
+
+ await act(async () => {
+ button.click();
+ await flush();
+ });
+ }
+
/**
* Cards are made at the end of a column, and at its head for the reader adding what comes next
* rather than what comes last. Both ends are reached from the field: Enter for the end, and
@@ -2050,7 +2211,7 @@ describe("Board column rename", () => {
await flush();
});
- expect(created).toHaveBeenCalledWith("Doing", "On top", "top");
+ expect(created).toHaveBeenCalledWith("Doing", "On top", "top", undefined);
// The field is emptied for the next one, as it is for a card made at the end.
expect(editor.value).toBe("");
});
@@ -2094,7 +2255,7 @@ describe("Board column rename", () => {
entries[0]?.handler?.({} as never, {} as never);
await flush();
});
- expect(created).toHaveBeenCalledWith("Doing", "Either end", "top");
+ expect(created).toHaveBeenCalledWith("Doing", "Either end", "top", undefined);
expect(editor.value).toBe("");
show.mockRestore();
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index ff3c2501be..570ef13c74 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -29,6 +29,7 @@ import NoteAutocomplete from "../../react/NoteAutocomplete";
import ShortcutHintButton from "../../shortcut_hints/shortcut_hint_button";
import { onWheelHorizontalScroll } from "../../widget_utils";
import ActionButton from "../../react/ActionButton";
+import { IconPickerButton } from "../../react/IconPicker";
import { useDragPan } from "../../react/drag_pan";
import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";
import { ViewModeProps } from "../interface";
@@ -850,7 +851,7 @@ function AddNewColumn({ api, isInRelationMode, columnCount, onCreated }: {
export function TitleEditor({
currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true,
- saveAndContinue = false, returnFocusTo, abandon, whenEmpty, submitTitle, openPlacements
+ saveAndContinue = false, returnFocusTo, abandon, whenEmpty, submitTitle, openPlacements, icon
}: {
currentValue?: string;
placeholder?: string;
@@ -874,6 +875,12 @@ export function TitleEditor({
whenEmpty?: { title: string, onClick?: () => void };
/** Names what the button creates, shown in its tooltip. */
submitTitle?: string;
+ /**
+ * The icon shown inside the field, at the leading edge, which opens the picker when pressed.
+ * The caller answers for what a pick does: a card carries it as `iconClass`, and the editor a
+ * card is made in keeps it for the next card.
+ */
+ icon?: { current: string, onSelect: (icon: string) => void, onReset?: () => void };
/**
* Opens the menu naming which end to create at, for a `save` that reads `atStart`. Passing it
* is what gives the button both ends: a right click or a hold opens the menu, Shift+Enter
@@ -902,6 +909,15 @@ export function TitleEditor({
const focusElRef = useRef<Element>(null);
const dismissOnNextRefreshRef = useRef(false);
const shouldDismiss = useRef(false);
+ /**
+ * Whether the icon picker is open, during which the editor stays where it is.
+ *
+ * The picker takes focus with it, and losing focus is what closes this editor: it would take
+ * the picker down with itself. Held in a ref rather than in state because the blur arrives
+ * before the render a state change would schedule. Focus goes back to the field as the picker
+ * closes, the blur that would have ended the edit being spent.
+ */
+ const isPickingIcon = useRef(false);
const held = useRef<number>();
/** Where on the screen the finger went down, against which a scroll is told from a hold. */
const heldFrom = useRef<{ x: number, y: number }>();
@@ -1040,6 +1056,10 @@ export function TitleEditor({
}
const onBlur = (newValue: string) => {
+ if (isPickingIcon.current) {
+ return;
+ }
+
if (saveAndContinue) {
abandon?.(newValue);
dismiss();
@@ -1079,19 +1099,20 @@ export function TitleEditor({
/>
);
- if (!saveAndContinue) {
+ if (!saveAndContinue && !icon) {
return field;
}
// A placement applies only to the button that creates. With nothing typed there is nothing
// to create, so the button stands for whatever the caller offers instead, or for nothing.
+ // An editor that saves once, a card being renamed above all, makes nothing and offers none.
const offersPlacement = !!openPlacements && !isEmpty;
const madeBy = submitTitle ?? t("board_view.add-new-item");
const offered = isEmpty
? whenEmpty && {
icon: "bx bx-folder-open", title: whenEmpty.title, onClick: whenEmpty.onClick
}
- : {
+ : saveAndContinue && {
icon: "bx bx-plus-circle",
title: offersPlacement
? `<span class="action">${escapeHtml(madeBy)}</span>`
@@ -1101,7 +1122,29 @@ export function TitleEditor({
};
return (
- <div className="title-editor-with-submit">
+ <div className={clsx("title-editor-field", { "with-submit": saveAndContinue })}>
+ {/* The press that opens the picker must not take focus out of the field: the
+ blur arrives before the picker reports itself open, and losing focus is what
+ closes the editor. */}
+ {icon && (
+ <span onMouseDown={(e) => e.preventDefault()}>
+ <IconPickerButton
+ className="title-editor-icon"
+ icon={icon.current}
+ title={t("board_view.change-note-icon")}
+ onSelect={icon.onSelect}
+ onReset={icon.onReset}
+ // A grid of a thousand icons and a search field is a task of its own,
+ // so the board behind it is dimmed rather than left looking pressable.
+ backdrop
+ onOpened={() => { isPickingIcon.current = true; }}
+ onClosed={() => {
+ isPickingIcon.current = false;
+ inputRef.current?.focus();
+ }}
+ />
+ </span>
+ )}
{field}
{/* The press must not take focus out of the field first: losing it is what closes
the editor, and it would be gone before the click arrived. */}
diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsx
index 61eef3dda0..bf5735a863 100644
--- a/apps/client/src/widgets/react/Dropdown.spec.tsx
+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx
@@ -150,6 +150,49 @@ describe("Dropdown", () => {
expect(document.body.querySelector(":scope > .my-scope")).toBeNull();
});
+ /**
+ * A menu that is a task of its own dims the page behind it. The cover is drawn inside the same
+ * portal, before the menu, so what covers what is document order rather than two z-index scales
+ * meeting; and only while the menu is actually open, an armed but closed one covering nothing.
+ */
+ it("draws a backdrop under a portaled menu while it is open", () => {
+ const el = renderInto(
+ <Dropdown portalToBody backdrop className="my-scope">
+ <li>entry</li>
+ </Dropdown>
+ );
+
+ fire(getToggle(), "pointerdown");
+ expect(document.body.querySelector(":scope > .my-scope > .tn-dropdown-backdrop")).toBeNull();
+
+ const dropdownEl = el.querySelector(".dropdown");
+ void act(() => {
+ $(dropdownEl as HTMLElement).trigger("show.bs.dropdown");
+ });
+
+ const wrapper = document.body.querySelector<HTMLElement>(":scope > .my-scope");
+ const drawn = [ ...(wrapper?.children ?? []) ].map(child => child.className.split(" ")[0]);
+ expect(drawn).toEqual([ "tn-dropdown-backdrop", "dropdown-menu" ]);
+
+ void act(() => {
+ $(dropdownEl as HTMLElement).trigger("hide.bs.dropdown");
+ });
+ expect(document.body.querySelector(":scope > .my-scope")).toBeNull();
+ });
+
+ it("leaves a menu without the prop undimmed", () => {
+ const el = renderInto(
+ <Dropdown portalToBody className="my-scope"><li>entry</li></Dropdown>
+ );
+
+ fire(getToggle(), "pointerdown");
+ void act(() => {
+ $(el.querySelector(".dropdown") as HTMLElement).trigger("show.bs.dropdown");
+ });
+
+ expect(document.body.querySelector(":scope > .my-scope > .tn-dropdown-backdrop")).toBeNull();
+ });
+
it("leaves a mobileBottomSheet menu alone on a desktop layout", () => {
const el = renderInto(<Dropdown mobileBottomSheet forceShown>item</Dropdown>);
diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsx
index 2fb7cd720e..4a4c884a21 100644
--- a/apps/client/src/widgets/react/Dropdown.tsx
+++ b/apps/client/src/widgets/react/Dropdown.tsx
@@ -69,9 +69,19 @@ export interface DropdownProps extends Pick<HTMLProps<HTMLDivElement>, "id" | "c
* above the whole modal, would otherwise dim the menu through.
*/
mobileBottomSheet?: boolean;
+ /**
+ * Dim the page behind the menu on any screen, for a menu that is a task of its own rather than
+ * a list of actions: the icon picker, which holds a search field and a grid of a thousand
+ * icons.
+ *
+ * Drawn inside the same portal as the menu, immediately before it, so what covers what is a
+ * matter of document order and one z-index rather than of two scales meeting. Needs
+ * {@link portalToBody} for that, and does nothing without it.
+ */
+ backdrop?: boolean;
}
-export default function Dropdown({ id, className, buttonClassName, isStatic, children, title, text, dropdownContainerStyle, dropdownContainerClassName, dropdownContainerRef: externalContainerRef, hideToggleArrow, iconAction, disabled, noSelectButtonStyle, noDropdownListStyle, forceShown, onShown: externalOnShown, onHidden: externalOnHidden, dropdownOptions, buttonProps, dropdownRef, titlePosition, titleOptions, mobileBackdrop: mobileBackdropProp, portalToBody: portalToBodyProp, mobileBottomSheet }: DropdownProps) {
+export default function Dropdown({ id, className, buttonClassName, isStatic, children, title, text, dropdownContainerStyle, dropdownContainerClassName, dropdownContainerRef: externalContainerRef, hideToggleArrow, iconAction, disabled, noSelectButtonStyle, noDropdownListStyle, forceShown, onShown: externalOnShown, onHidden: externalOnHidden, dropdownOptions, buttonProps, dropdownRef, titlePosition, titleOptions, mobileBackdrop: mobileBackdropProp, portalToBody: portalToBodyProp, mobileBottomSheet, backdrop }: DropdownProps) {
// The sheet is three things at once — placed by the app's own rule, dimming what is behind it,
// and lifted out of whatever opened it — so it is asked for as one thing and unpacked here.
const bottomSheet = !!mobileBottomSheet && isMobile();
@@ -260,7 +270,12 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
// `tn-dropdown-portal` beside it carries the z-index a menu needs out here (style.css).
// Only mount it while needed (see `menuMounted`) so closed pickers don't each leave an
// empty menu wrapper in the body.
- ? (menuMounted && createPortal(<div class={`tn-dropdown-portal ${className ?? ""}`}>{menu}</div>, document.body))
+ ? (menuMounted && createPortal((
+ <div class={`tn-dropdown-portal ${className ?? ""}`}>
+ {backdrop && shown && <div class="tn-dropdown-backdrop" />}
+ {menu}
+ </div>
+ ), document.body))
: menu}
</div>
);
diff --git a/apps/client/src/widgets/react/IconPicker.tsx b/apps/client/src/widgets/react/IconPicker.tsx
index d2daee66bb..fe91f91879 100644
--- a/apps/client/src/widgets/react/IconPicker.tsx
+++ b/apps/client/src/widgets/react/IconPicker.tsx
@@ -117,6 +117,17 @@ interface IconPickerButtonProps extends Pick<IconPickerProps, "onSelect" | "onRe
/** The host's own class, for a host that dresses the button or the widget around it. */
className?: string;
disabled?: boolean;
+ /**
+ * Said as the picker opens and closes, for a host that has to hold something open while the
+ * reader is in it: the picker takes focus with it, and an editor that closes on losing focus
+ * would take the picker down with itself.
+ */
+ onOpened?: () => void;
+ onClosed?: () => void;
+ /** Dim the page behind the picker, for a host that would rather it were answered before
+ * anything else. Has no effect on a phone, where the picker is a dialog with a backdrop of its
+ * own. */
+ backdrop?: boolean;
}
/**
@@ -136,7 +147,9 @@ export function IconPickerButton({ className, ...props }: IconPickerButtonProps)
}
/** The picker under the button, as a desktop shows it. */
-function IconPickerDropdownButton({ icon, title, className, disabled, onSelect, onReset, resetText }: IconPickerButtonProps) {
+function IconPickerDropdownButton({
+ icon, title, className, disabled, onSelect, onReset, resetText, onOpened, onClosed, backdrop
+}: IconPickerButtonProps) {
const dropdownRef = useRef<BootstrapDropdown>(null);
const [ pickerShown, setPickerShown ] = useState(false);
@@ -155,9 +168,16 @@ function IconPickerDropdownButton({ icon, title, className, disabled, onSelect,
// 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
+ backdrop={backdrop}
hideToggleArrow
- onShown={() => setPickerShown(true)}
- onHidden={() => setPickerShown(false)}
+ onShown={() => {
+ setPickerShown(true);
+ onOpened?.();
+ }}
+ onHidden={() => {
+ setPickerShown(false);
+ onClosed?.();
+ }}
>
{/* 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. */}
@@ -180,7 +200,9 @@ function IconPickerDropdownButton({ icon, title, className, disabled, onSelect,
}
/** The picker on a screen of its own, as a phone shows it. */
-function IconPickerModalButton({ icon, title, className, disabled, onSelect, onReset, resetText }: IconPickerButtonProps) {
+function IconPickerModalButton({
+ icon, title, className, disabled, onSelect, onReset, resetText, onOpened, onClosed
+}: IconPickerButtonProps) {
const [ modalShown, setModalShown ] = useState(false);
const { windowWidth } = useWindowSize();
@@ -190,7 +212,10 @@ function IconPickerModalButton({ icon, title, className, disabled, onSelect, onR
className="note-icon"
icon={icon}
text={title}
- onClick={() => setModalShown(true)}
+ onClick={() => {
+ setModalShown(true);
+ onOpened?.();
+ }}
disabled={disabled}
/>
@@ -200,7 +225,11 @@ function IconPickerModalButton({ icon, title, className, disabled, onSelect, onR
<Modal
title={title}
size="xl"
- show={modalShown} onHidden={() => setModalShown(false)}
+ show={modalShown}
+ onHidden={() => {
+ setModalShown(false);
+ onClosed?.();
+ }}
className="icon-switcher note-icon-widget"
scrollable
stackable