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
feat(mind-map): let a node wear a Trilium icon
Elian Doranb491aed50acf
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 101ed508c4..2b12429b75 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3531,6 +3531,9 @@"font-size-medium": "M","font-size-large": "L","font-size-extra-large": "XL",+ "icon": "Icon",+ "choose-icon": "Choose an icon",+ "clear-icon": "Remove the icon","tags": "Tags","tags-placeholder": "Type a tag and press Enter","tags-differ": "The selected nodes don't carry the same tags, so these can only be read.",diff --git a/apps/client/src/widgets/note_icon.css b/apps/client/src/widgets/note_icon.cssindex 47babf8457..70bf867d75 100644--- a/apps/client/src/widgets/note_icon.css+++ b/apps/client/src/widgets/note_icon.css@@ -39,55 +39,6 @@ body > div.note-icon-widget > .dropdown-menu {padding: 10px 15px 10px 15px !important;}-.note-icon-widget .filter-row {- padding: 10px;- display: flex;- align-items: center;- gap: 1em;-}--.note-icon-widget .filter-row span {- display: block;- font-weight: bold;-}--.note-icon-widget .icon-list {- height: 500px;- overflow: auto;-}--.note-icon-widget .icon-list span {- display: inline-block;- padding: 10px;- cursor: pointer;- border: 1px solid transparent;- font-size: 180%;-}--.note-icon-widget .icon-list span:hover {- border: 1px solid var(--main-border-color);-}--.note-icon-widget .icon-list span.bx-empty {- width: unset;-}--.note-icon-widget .icon-list span.bx-empty::before {- display: inline-block;- content: "";- border: 1px dashed var(--muted-text-color);- width: 1em;- height: 1em;-}--.note-icon-widget {- .no-results {- padding: 20px;- text-align: center;- color: var(--muted-text-color);- }-}-body.experimental-feature-new-layout {.note-icon-widget button.note-icon {--input-focus-outline-color: var(--note-icon-hover-background-color);diff --git a/apps/client/src/widgets/note_icon.tsx b/apps/client/src/widgets/note_icon.tsxindex f70b1b07fc..5749a1f534 100644--- a/apps/client/src/widgets/note_icon.tsx+++ b/apps/client/src/widgets/note_icon.tsx@@ -1,36 +1,19 @@import "./note_icon.css";-import { IconRegistry } from "@triliumnext/commons";import { Dropdown as BootstrapDropdown } from "bootstrap";-import clsx from "clsx";import { t } from "i18next";-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";+import { useEffect, useRef, useState } from "preact/hooks";import FNote from "../entities/fnote";import attributes from "../services/attributes";-import server from "../services/server";-import { isDesktop, isMobile } from "../services/utils";+import { isMobile } from "../services/utils";import ActionButton from "./react/ActionButton";import Dropdown from "./react/Dropdown";-import { FormDropdownDivider, FormListItem } from "./react/FormList";-import FormTextBox from "./react/FormTextBox";-import { useNoteContext, useNoteLabel, useStaticTooltip, useWindowSize } from "./react/hooks";+import { useNoteContext, useNoteLabel, useWindowSize } from "./react/hooks";+import IconPicker, { ICON_SIZE } from "./react/IconPicker";import Modal from "./react/Modal";-const ICON_SIZE = isMobile() ? 56 : 48;--interface IconToCountCache {- iconClassToCountMap: Record<string, number>;-}--let iconToCountCache!: Promise<IconToCountCache> | null;--type IconWithName = (IconRegistry["sources"][number]["icons"][number] & { iconPack: string });-export default function NoteIcon() {const { note, viewScope } = useNoteContext();const [ icon, setIcon ] = useState<string | null | undefined>();@@ -64,11 +47,38 @@ export default function NoteIcon() {hideToggleArrowdisabled={isDisabled}>- { note && <NoteIconList note={note} onHide={() => dropdownRef?.current?.hide()} columnCount={12} /> }+ { 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) => {+ const attributeToSet = note.hasOwnedLabel("workspace") ? "workspaceIconClass" : "iconClass";+ attributes.setLabel(note.noteId, attributeToSet, iconClass);+ onHide();+ }}+ // 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);+ }+ onHide();+ } : undefined}+ />+ );+}+function MobileNoteIconSwitcher({ note, icon, disabled }: {note: FNote | null | undefined;icon: string | null | undefined;@@ -95,278 +105,13 @@ function MobileNoteIconSwitcher({ note, icon, disabled }: {className="icon-switcher note-icon-widget"scrollable>- {note && <NoteIconList note={note} onHide={() => setModalShown(false)} columnCount={Math.max(1, Math.floor(windowWidth / ICON_SIZE))} />}+ {note && <NoteIconPicker note={note} onHide={() => setModalShown(false)} columnCount={Math.max(1, Math.floor(windowWidth / ICON_SIZE))} />}</Modal>), document.body)}</div>);}-function NoteIconList({ note, onHide, columnCount }: {- note: FNote;- onHide: () => void;- columnCount: number;-}) {- const iconListRef = useRef<HTMLDivElement>(null);- const [ search, setSearch ] = useState<string>();- const [ filterByPrefix, setFilterByPrefix ] = useState<string | null>(null);- useStaticTooltip(iconListRef, {- selector: "span",- customClass: "pre-wrap-text",- animation: false,- title() { return this.getAttribute("title") || ""; },- });-- const allIcons = useAllIcons();- const filteredIcons = useFilteredIcons(allIcons, search, filterByPrefix);-- return (- <>- <FilterRow- note={note}- filterByPrefix={filterByPrefix}- search={search}- setSearch={setSearch}- setFilterByPrefix={setFilterByPrefix}- filteredIcons={filteredIcons}- onHide={onHide}- />-- <div- class="icon-list"- ref={iconListRef}- style={{- width: (columnCount * ICON_SIZE + 10),- }}- onClick={(e) => {- // Make sure we are not clicking on something else than a button.- const clickedTarget = e.target as HTMLElement;- if (!clickedTarget.classList.contains("tn-icon")) return;-- const iconClass = Array.from(clickedTarget.classList.values()).filter(c => c !== "tn-icon").join(" ");- if (note) {- const attributeToSet = note.hasOwnedLabel("workspace") ? "workspaceIconClass" : "iconClass";- attributes.setLabel(note.noteId, attributeToSet, iconClass);- }- onHide();- }}- >- {filteredIcons.length ? (- <Grid- columnCount={columnCount}- columnWidth={ICON_SIZE}- rowCount={Math.ceil(filteredIcons.length / columnCount)}- rowHeight={ICON_SIZE}- cellComponent={IconItemCell}- cellProps={{- filteredIcons,- columnCount- }}- />- ) : (- <div class="no-results">{t("note_icon.no_results")}</div>- )}- </div>- </>- );-}--function FilterRow({ note, filterByPrefix, search, setSearch, setFilterByPrefix, filteredIcons, onHide }: {- note: FNote;- filterByPrefix: string | null;- search: string | undefined;- setSearch: (value: string | undefined) => void;- setFilterByPrefix: (value: string | null) => void;- filteredIcons: IconWithName[];- onHide: () => void;-}) {- const searchBoxRef = useRef<HTMLInputElement>(null);- const hasCustomIcon = getIconLabels(note).length > 0;-- function resetToDefaultIcon() {- if (!note) return;- for (const label of getIconLabels(note)) {- attributes.removeAttributeById(note.noteId, label.attributeId);- }- onHide();- }-- return (- <div class="filter-row">- <span>{t("note_icon.search")}</span>- <FormTextBox- inputRef={searchBoxRef}- type="text"- name="icon-search"- placeholder={ filterByPrefix- ? t("note_icon.search_placeholder_filtered", {- number: filteredIcons.length ?? 0,- name: glob.iconRegistry.sources.find(s => s.prefix === filterByPrefix)?.name ?? ""- })- : t("note_icon.search_placeholder", { number: filteredIcons.length ?? 0, count: glob.iconRegistry.sources.length })}- currentValue={search} onChange={setSearch}- autoFocus- />-- {isDesktop()- ? <>- {hasCustomIcon && (- <div style={{ textAlign: "center" }}>- <ActionButton- icon="bx bx-reset"- text={t("note_icon.reset-default")}- onClick={resetToDefaultIcon}- />- </div>- )}-- {<Dropdown- buttonClassName="bx bx-filter-alt"- hideToggleArrow- noSelectButtonStyle- noDropdownListStyle- iconAction- title={t("note_icon.filter")}- >- <IconFilterContent filterByPrefix={filterByPrefix} setFilterByPrefix={setFilterByPrefix} />- </Dropdown>}- </> : (- <Dropdown- buttonClassName="bx bx-dots-vertical-rounded"- hideToggleArrow- noSelectButtonStyle- noDropdownListStyle- iconAction- dropdownContainerClassName="mobile-bottom-menu"- >- {hasCustomIcon && <>- <FormListItem- icon="bx bx-reset"- onClick={resetToDefaultIcon}- disabled={!hasCustomIcon}- >{t("note_icon.reset-default")}</FormListItem>- <FormDropdownDivider />- </>}-- <IconFilterContent filterByPrefix={filterByPrefix} setFilterByPrefix={setFilterByPrefix} />- </Dropdown>- )}- </div>- );-}--function IconItemCell({ rowIndex, columnIndex, style, filteredIcons, columnCount }: CellComponentProps<{- filteredIcons: IconWithName[];- columnCount: number;-}>) {- const iconIndex = rowIndex * columnCount + columnIndex;- const iconData = filteredIcons[iconIndex] as IconWithName | undefined;- if (!iconData) return <></> as React.ReactElement;-- const { id, terms, iconPack } = iconData;- return (- <span- key={id}- class={clsx(id, "tn-icon")}- title={t("note_icon.icon_tooltip", { name: terms?.[0] ?? id, iconPack })}- style={style as CSSProperties}- />- ) as React.ReactElement;-}--function IconFilterContent({ filterByPrefix, setFilterByPrefix }: {- filterByPrefix: string | null;- setFilterByPrefix: (value: string | null) => void;-}) {- return (- <>- <FormListItem- checked={filterByPrefix === null}- onClick={() => setFilterByPrefix(null)}- >{t("note_icon.filter-none")}</FormListItem>- <FormListItem- checked={filterByPrefix === "bx"}- onClick={() => setFilterByPrefix("bx")}- >{t("note_icon.filter-default")}</FormListItem>- {glob.iconRegistry.sources.length > 1 && <FormDropdownDivider />}-- {glob.iconRegistry.sources.map(({ prefix, name, icon }) => (- prefix !== "bx" && <FormListItem- key={prefix}- onClick={() => setFilterByPrefix(prefix)}- icon={icon}- checked={filterByPrefix === prefix}- >{name}</FormListItem>- ))}- </>- );-}--function useAllIcons() {- const [ allIcons, setAllIcons ] = useState<IconWithName[]>();-- useEffect(() => {- getIconToCountMap().then((iconsToCount) => {- const allIcons = [- ...glob.iconRegistry.sources.flatMap(s => s.icons.map((i) => ({- ...i,- iconPack: s.name,- })))- ];-- // Sort by count.- if (iconsToCount) {- allIcons.sort((a, b) => {- const countA = iconsToCount[a.id ?? ""] || 0;- const countB = iconsToCount[b.id ?? ""] || 0;-- return countB - countA;- });- }-- setAllIcons(allIcons);- });- }, []);-- return allIcons;-}--function useFilteredIcons(allIcons: IconWithName[] | undefined, search: string | undefined, filterByPrefix: string | null) {- // Filter by text and/or icon pack.- const filteredIcons = useMemo(() => {- let icons: IconWithName[] = allIcons ?? [];- const processedSearch = search?.trim()?.toLowerCase();- if (processedSearch || filterByPrefix !== null) {- icons = icons.filter((icon) => {- if (filterByPrefix) {- if (!icon.id?.startsWith(`${filterByPrefix} `)) {- return false;- }- }-- if (processedSearch) {- if (!icon.terms?.some((t) => t.includes(processedSearch))) {- return false;- }- }-- return true;- });- }- return icons;- }, [ allIcons, search, filterByPrefix ]);- return filteredIcons;-}--async function getIconToCountMap() {- if (!iconToCountCache) {- iconToCountCache = server.get<IconToCountCache>("other/icon-usage");- setTimeout(() => (iconToCountCache = null), 20000); // invalidate cache after 20 seconds- }-- return (await iconToCountCache).iconClassToCountMap;-}-function getIconLabels(note: FNote) {if (!note) {return [];diff --git a/apps/client/src/widgets/react/IconPicker.css b/apps/client/src/widgets/react/IconPicker.cssnew file mode 100644index 0000000000..cb54c1389b--- /dev/null+++ b/apps/client/src/widgets/react/IconPicker.css@@ -0,0 +1,51 @@+/*+ * The picker's own dressing. Written under the class the picker brings rather than the note icon+ * widget's, which it used to live inside; the themes still reach the grid through the legacy class+ * the picker also carries.+ */+.icon-picker .filter-row {+ padding: 10px;+ display: flex;+ align-items: center;+ gap: 1em;+}++.icon-picker .filter-row span {+ display: block;+ font-weight: bold;+}++.icon-picker .icon-list {+ height: 500px;+ overflow: auto;+}++.icon-picker .icon-list span {+ display: inline-block;+ padding: 10px;+ cursor: pointer;+ border: 1px solid transparent;+ font-size: 180%;+}++.icon-picker .icon-list span:hover {+ border: 1px solid var(--main-border-color);+}++.icon-picker .icon-list span.bx-empty {+ width: unset;+}++.icon-picker .icon-list span.bx-empty::before {+ display: inline-block;+ content: "";+ border: 1px dashed var(--muted-text-color);+ width: 1em;+ height: 1em;+}++.icon-picker .no-results {+ padding: 20px;+ text-align: center;+ color: var(--muted-text-color);+}diff --git a/apps/client/src/widgets/react/IconPicker.tsx b/apps/client/src/widgets/react/IconPicker.tsxnew file mode 100644index 0000000000..042d0ac889--- /dev/null+++ b/apps/client/src/widgets/react/IconPicker.tsx@@ -0,0 +1,297 @@+import "./IconPicker.css";++import { IconRegistry } from "@triliumnext/commons";+import clsx from "clsx";+import { CSSProperties } from "preact";+import { useEffect, useMemo, useRef, useState } from "preact/hooks";+import type React from "react";+import { CellComponentProps, Grid } from "react-window";++import { t } from "../../services/i18n";+import server from "../../services/server";+import { isDesktop, isMobile } from "../../services/utils";+import ActionButton from "./ActionButton";+import Dropdown from "./Dropdown";+import { FormDropdownDivider, FormListItem } from "./FormList";+import FormTextBox from "./FormTextBox";+import { useStaticTooltip } from "./hooks";++/** 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;++interface IconPickerProps {+ /** Receives the class of the icon picked, e.g. `bx bx-star`. */+ onSelect(iconClass: string): void;+ /**+ * Offered as the way back to no icon of one's own. Left out, the picker only picks — there is+ * nothing to go back to.+ */+ onReset?: () => void;+ /** What going back means, in the host's own words. Left out, it resets "to the default icon". */+ resetText?: string;+ /** How many icons stand side by side; the host decides from the room it can give the grid. */+ columnCount: number;+}++/**+ * The picker an icon is chosen through: every icon of every installed pack, searchable by name and+ * narrowable to one pack, the ones already used across the note tree leading.+ *+ * It only reports what was picked — what that means is the host's own business, whether it is the+ * icon of a note or of something else entirely.+ */+export default function IconPicker({ onSelect, onReset, resetText, columnCount }: IconPickerProps) {+ const iconListRef = useRef<HTMLDivElement>(null);+ const [ search, setSearch ] = useState<string>();+ const [ filterByPrefix, setFilterByPrefix ] = useState<string | null>(null);+ useStaticTooltip(iconListRef, {+ selector: "span",+ customClass: "pre-wrap-text",+ animation: false,+ title() { return this.getAttribute("title") || ""; },+ });++ const allIcons = useAllIcons();+ const filteredIcons = useFilteredIcons(allIcons, search, filterByPrefix);++ return (+ // The legacy class is kept alongside the picker's own: the themes dress the icon grid+ // through it, having known the picker only as a part of the note icon widget.+ <div className="icon-picker note-icon-widget">+ <FilterRow+ filterByPrefix={filterByPrefix}+ search={search}+ setSearch={setSearch}+ setFilterByPrefix={setFilterByPrefix}+ filteredIcons={filteredIcons}+ onReset={onReset}+ resetText={resetText}+ />++ <div+ class="icon-list"+ ref={iconListRef}+ style={{+ width: (columnCount * ICON_SIZE + 10),+ }}+ onClick={(e) => {+ // Make sure we are not clicking on something else than a button.+ const clickedTarget = e.target as HTMLElement;+ if (!clickedTarget.classList.contains("tn-icon")) return;++ onSelect(Array.from(clickedTarget.classList.values()).filter(c => c !== "tn-icon").join(" "));+ }}+ >+ {filteredIcons.length ? (+ <Grid+ columnCount={columnCount}+ columnWidth={ICON_SIZE}+ rowCount={Math.ceil(filteredIcons.length / columnCount)}+ rowHeight={ICON_SIZE}+ cellComponent={IconItemCell}+ cellProps={{+ filteredIcons,+ columnCount+ }}+ />+ ) : (+ <div class="no-results">{t("note_icon.no_results")}</div>+ )}+ </div>+ </div>+ );+}++type IconWithName = (IconRegistry["sources"][number]["icons"][number] & { iconPack: string });++interface IconToCountCache {+ iconClassToCountMap: Record<string, number>;+}++let iconToCountCache!: Promise<IconToCountCache> | null;++function FilterRow({ filterByPrefix, search, setSearch, setFilterByPrefix, filteredIcons, onReset, resetText }: {+ filterByPrefix: string | null;+ search: string | undefined;+ setSearch: (value: string | undefined) => void;+ setFilterByPrefix: (value: string | null) => void;+ filteredIcons: IconWithName[];+ onReset?: () => void;+ resetText?: string;+}) {+ const searchBoxRef = useRef<HTMLInputElement>(null);++ return (+ <div class="filter-row">+ <span>{t("note_icon.search")}</span>+ <FormTextBox+ inputRef={searchBoxRef}+ type="text"+ name="icon-search"+ placeholder={ filterByPrefix+ ? t("note_icon.search_placeholder_filtered", {+ number: filteredIcons.length ?? 0,+ name: glob.iconRegistry.sources.find(s => s.prefix === filterByPrefix)?.name ?? ""+ })+ : t("note_icon.search_placeholder", { number: filteredIcons.length ?? 0, count: glob.iconRegistry.sources.length })}+ currentValue={search} onChange={setSearch}+ autoFocus+ />++ {isDesktop()+ ? <>+ {onReset && (+ <div style={{ textAlign: "center" }}>+ <ActionButton+ icon="bx bx-reset"+ text={resetText ?? t("note_icon.reset-default")}+ onClick={onReset}+ />+ </div>+ )}++ {<Dropdown+ buttonClassName="bx bx-filter-alt"+ hideToggleArrow+ noSelectButtonStyle+ noDropdownListStyle+ iconAction+ title={t("note_icon.filter")}+ >+ <IconFilterContent filterByPrefix={filterByPrefix} setFilterByPrefix={setFilterByPrefix} />+ </Dropdown>}+ </> : (+ <Dropdown+ buttonClassName="bx bx-dots-vertical-rounded"+ hideToggleArrow+ noSelectButtonStyle+ noDropdownListStyle+ iconAction+ dropdownContainerClassName="mobile-bottom-menu"+ >+ {onReset && <>+ <FormListItem+ icon="bx bx-reset"+ onClick={onReset}+ >{resetText ?? t("note_icon.reset-default")}</FormListItem>+ <FormDropdownDivider />+ </>}++ <IconFilterContent filterByPrefix={filterByPrefix} setFilterByPrefix={setFilterByPrefix} />+ </Dropdown>+ )}+ </div>+ );+}++function IconItemCell({ rowIndex, columnIndex, style, filteredIcons, columnCount }: CellComponentProps<{+ filteredIcons: IconWithName[];+ columnCount: number;+}>) {+ const iconIndex = rowIndex * columnCount + columnIndex;+ const iconData = filteredIcons[iconIndex] as IconWithName | undefined;+ if (!iconData) return <></> as React.ReactElement;++ const { id, terms, iconPack } = iconData;+ return (+ <span+ key={id}+ class={clsx(id, "tn-icon")}+ title={t("note_icon.icon_tooltip", { name: terms?.[0] ?? id, iconPack })}+ style={style as CSSProperties}+ />+ ) as React.ReactElement;+}++function IconFilterContent({ filterByPrefix, setFilterByPrefix }: {+ filterByPrefix: string | null;+ setFilterByPrefix: (value: string | null) => void;+}) {+ return (+ <>+ <FormListItem+ checked={filterByPrefix === null}+ onClick={() => setFilterByPrefix(null)}+ >{t("note_icon.filter-none")}</FormListItem>+ <FormListItem+ checked={filterByPrefix === "bx"}+ onClick={() => setFilterByPrefix("bx")}+ >{t("note_icon.filter-default")}</FormListItem>+ {glob.iconRegistry.sources.length > 1 && <FormDropdownDivider />}++ {glob.iconRegistry.sources.map(({ prefix, name, icon }) => (+ prefix !== "bx" && <FormListItem+ key={prefix}+ onClick={() => setFilterByPrefix(prefix)}+ icon={icon}+ checked={filterByPrefix === prefix}+ >{name}</FormListItem>+ ))}+ </>+ );+}++function useAllIcons() {+ const [ allIcons, setAllIcons ] = useState<IconWithName[]>();++ useEffect(() => {+ getIconToCountMap().then((iconsToCount) => {+ const allIcons = [+ ...glob.iconRegistry.sources.flatMap(s => s.icons.map((i) => ({+ ...i,+ iconPack: s.name,+ })))+ ];++ // Sort by count.+ if (iconsToCount) {+ allIcons.sort((a, b) => {+ const countA = iconsToCount[a.id ?? ""] || 0;+ const countB = iconsToCount[b.id ?? ""] || 0;++ return countB - countA;+ });+ }++ setAllIcons(allIcons);+ });+ }, []);++ return allIcons;+}++function useFilteredIcons(allIcons: IconWithName[] | undefined, search: string | undefined, filterByPrefix: string | null) {+ // Filter by text and/or icon pack.+ const filteredIcons = useMemo(() => {+ let icons: IconWithName[] = allIcons ?? [];+ const processedSearch = search?.trim()?.toLowerCase();+ if (processedSearch || filterByPrefix !== null) {+ icons = icons.filter((icon) => {+ if (filterByPrefix) {+ if (!icon.id?.startsWith(`${filterByPrefix} `)) {+ return false;+ }+ }++ if (processedSearch) {+ if (!icon.terms?.some((t) => t.includes(processedSearch))) {+ return false;+ }+ }++ return true;+ });+ }+ return icons;+ }, [ allIcons, search, filterByPrefix ]);+ return filteredIcons;+}++async function getIconToCountMap() {+ if (!iconToCountCache) {+ iconToCountCache = server.get<IconToCountCache>("other/icon-usage");+ setTimeout(() => (iconToCountCache = null), 20000); // invalidate cache after 20 seconds+ }++ return (await iconToCountCache).iconClassToCountMap;+}diff --git a/apps/client/src/widgets/type_widgets/MindMap.tsx b/apps/client/src/widgets/type_widgets/MindMap.tsxindex eeec05751c..52433d03b7 100644--- a/apps/client/src/widgets/type_widgets/MindMap.tsx+++ b/apps/client/src/widgets/type_widgets/MindMap.tsx@@ -15,6 +15,7 @@ import utils from "../../services/utils";import { useColorScheme, useEditorSpacedUpdate, useEffectiveReadOnly, useSyncedRef, useTriliumEvent, useTriliumEvents, useTriliumOption } from "../react/hooks";import { refToJQuerySelector } from "../react/react_utils";import { renderMindMapPreviewSvg } from "./helpers/mind_map_export";+import { renderIconClasses } from "./helpers/mind_map_icons";import MindMapNodePanel from "./MindMapNodePanel";import { TypeWidgetProps } from "./type_widget";@@ -274,6 +275,20 @@ function MindElixir({ children, containerRef: externalContainerRef, containerPro};}, [ onChange ]);+ // Node icons are rendered as text by Mind Elixir, while ours are icon classes, so they are+ // dressed again after every layout — which is what follows any change to a node.+ useEffect(() => {+ const mind = apiRef.current;+ if (!mind) return;++ const renderIcons = () => renderIconClasses(mind.nodes);++ renderIcons();+ mind.bus.addListener("linkDiv", renderIcons);++ return () => mind.bus.removeListener("linkDiv", renderIcons);+ }, [ instanceVersion ]);+// Selection listener. The events only carry the nodes that were added to or removed from the// selection, so the full selection is read back from the instance instead.useEffect(() => {diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css b/apps/client/src/widgets/type_widgets/MindMapNodePanel.cssindex 814e6c1523..ba18e95e4a 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.css@@ -33,6 +33,12 @@opacity: .75;}+/* The icon stands at the size it will read at on a node, rather than the size a note wears. */+.mind-map-node-panel .mind-map-node-icon {+ --note-icon-size: 20px;+ --note-icon-container-padding-size: 4px;+}+/* The sizes share the width of the panel evenly, rather than each taking its label's width. */.mind-map-node-panel .btn-group {width: 100%;diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsxindex 06df12186b..ab13dd08ca 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx@@ -26,7 +26,8 @@ const SIZE = 0;const TEXT = 1;const BACKGROUND = 2;const BRANCH = 3;-const TAGS = 4;+const ICON = 4;+const TAGS = 5;function section(container: HTMLElement, index: number) {const sections = container.querySelectorAll<HTMLElement>(".mind-map-node-panel-section");@@ -230,6 +231,20 @@ describe("MindMapNodePanel", () => {expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { branchColor: NODE_COLORS[1] });});+ it("shows the icon the selection wears, and none where they disagree", () => {+ const iconButton = (nodes: NodeObj[]) =>+ renderInto(<MindMapNodePanel mind={buildMind(nodes).mind} nodes={nodes} />)+ .querySelector(`.mind-map-node-panel-section:nth-child(${ICON + 1}) button`);++ expect(iconButton([buildNode({ icons: ["bx bx-star"] })])?.className).toContain("bx bx-star");+ // Nothing of its own, and a selection that disagrees, both read as no icon.+ expect(iconButton([buildNode()])?.className).toContain("bx bx-empty");+ expect(iconButton([+ buildNode({ id: "a", icons: ["bx bx-star"] }),+ buildNode({ id: "b", icons: ["bx bx-cube"] })+ ])?.className).toContain("bx bx-empty");+ });+it("edits the tags of a single node, keeping the styling of the ones that stay", () => {const styled = { text: "urgent", style: { color: "red" } };const nodes = [buildNode({ tags: [styled, "later"] })];diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsxindex d5589f7ac6..26dbc831b2 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx@@ -1,11 +1,15 @@import "./MindMapNodePanel.css";+import { Dropdown as BootstrapDropdown } from "bootstrap";import type { MindElixirInstance, NodeObj, TagObj } from "mind-elixir";import { ComponentChildren } from "preact";+import { useRef, useState } from "preact/hooks";import { t } from "../../services/i18n";import ValuesInput from "../attribute_widgets/values_input";import ColorPicker, { DEFAULT_COLOR_PALETTE } from "../react/ColorPicker";+import Dropdown from "../react/Dropdown";+import IconPicker from "../react/IconPicker";import SegmentedChoice from "../react/SegmentedChoice";/**@@ -36,6 +40,7 @@ export default function MindMapNodePanel({ mind, nodes }: MindMapNodePanelProps)const textColor = getCommonValue(nodes, (node) => node.style?.color);const backgroundColor = getCommonValue(nodes, (node) => node.style?.background);const branchColor = getCommonValue(nodes, (node) => node.branchColor);+ const icon = getCommonValue(nodes, (node) => node.icons?.[0]);const tags = gatherTags(nodes);/**@@ -90,6 +95,16 @@ export default function MindMapNodePanel({ mind, nodes }: MindMapNodePanelProps)/></PanelSection>+ <PanelSection label={t("mind-map.icon")}>+ <NodeIcon+ currentValue={icon !== MIXED ? icon : null}+ // A node takes one icon, like a note does, so what is picked replaces what was+ // there rather than joining it.+ onSelect={(iconClass) => patchSelectedNodes({ icons: [ iconClass ] })}+ onClear={() => patchSelectedNodes({ icons: [] })}+ />+ </PanelSection>+<PanelSectionlabel={t("mind-map.tags")}title={tags.readOnly ? t("mind-map.tags-differ") : undefined}@@ -172,6 +187,55 @@ function toPickerValue(value: string | null | typeof MIXED) {};}+/**+ * The icon a node wears, 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.+ */+function NodeIcon({ currentValue, onSelect, onClear }: {+ currentValue: string | null;+ onSelect(iconClass: string): void;+ onClear(): 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 ${currentValue ?? "bx bx-empty"}`}+ title={t("mind-map.choose-icon")}+ 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={currentValue ? () => {+ onClear();+ dropdownRef.current?.hide();+ } : undefined}+ />+ )}+ </Dropdown>+ );+}+function PanelSection({ label, title, children }: { label: string, title?: string, children: ComponentChildren }) {return (<div className="mind-map-node-panel-section" title={title}>diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_icons.spec.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_icons.spec.tsnew file mode 100644index 0000000000..2a778c46d4--- /dev/null+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_icons.spec.ts@@ -0,0 +1,65 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { renderIconClasses } from "./mind_map_icons";++const uncheckedWindow = window as unknown as { glob: { iconRegistry?: unknown } };++/** Renders what Mind Elixir makes of a node's icons: the text it was given, one span each. */+function buildNode(...icons: string[]) {+ const container = document.createElement("div");+ container.innerHTML = `<me-tpc><span class="icons">${icons.map((icon) => `<span>${icon}</span>`).join("")}</span></me-tpc>`;+ return container;+}++describe("renderIconClasses", () => {+ beforeEach(() => {+ uncheckedWindow.glob.iconRegistry = { sources: [ { prefix: "bx" }, { prefix: "mdi" } ] };+ });++ afterEach(() => {+ delete uncheckedWindow.glob.iconRegistry;+ });++ it("dresses a Trilium icon class, whichever pack it belongs to", () => {+ const container = buildNode("bx bx-star", "mdi mdi-cube");++ renderIconClasses(container);++ const [ boxicon, mdi ] = container.querySelectorAll(".icons > span");+ expect(boxicon.className).toBe("bx bx-star");+ expect(boxicon.textContent).toBe("");+ expect(mdi.className).toBe("mdi mdi-cube");+ });++ it("leaves alone whatever is not one, so that a map made elsewhere keeps its icons", () => {+ // An emoji is an icon in its own right; a pack that is not installed names nothing that+ // could be drawn; and a sentence is a sentence.+ const container = buildNode("⭐", "phosphor ph-cube", "bx");++ renderIconClasses(container);++ expect([ ...container.querySelectorAll(".icons > span") ].map((icon) => [ icon.className, icon.textContent ]))+ .toEqual([ [ "", "⭐" ], [ "", "phosphor ph-cube" ], [ "", "bx" ] ]);+ });++ it("can be run again over what it has already dressed", () => {+ // It runs after every layout, and a layout does not always rebuild the node.+ const container = buildNode("bx bx-star");++ renderIconClasses(container);+ renderIconClasses(container);++ const icon = container.querySelector(".icons > span");+ expect(icon?.className).toBe("bx bx-star");+ expect(icon?.textContent).toBe("");+ });++ it("holds off until the icon packs are known", () => {+ delete uncheckedWindow.glob.iconRegistry;+ const container = buildNode("bx bx-star");++ renderIconClasses(container);++ expect(container.querySelector(".icons > span")?.textContent).toBe("bx bx-star");+ });+});diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_icons.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_icons.tsnew file mode 100644index 0000000000..d9c25a6e31--- /dev/null+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_icons.ts@@ -0,0 +1,30 @@+/**+ * Dresses the node icons a map carries as Trilium icon classes.+ *+ * Mind Elixir renders an icon as text — its topic renderer escapes what it is given and drops it+ * into a `<span>` — so a class such as `bx bx-star` arrives as those very words. Putting the class+ * onto the span the text landed in and emptying it leaves the icon pack's own CSS to draw it, the+ * same way an icon is drawn anywhere else in Trilium.+ *+ * Called for the whole map after every layout, which is what follows any change to a node.+ *+ * @param container the element holding the rendered nodes.+ */+export function renderIconClasses(container: HTMLElement) {+ for (const iconEl of container.querySelectorAll<HTMLElement>(".icons > span")) {+ const iconClass = iconEl.textContent?.trim() ?? "";+ if (!isIconClass(iconClass)) continue;++ iconEl.className = iconClass;+ iconEl.textContent = "";+ }+}++/**+ * Tells a Trilium icon class from an icon that came from elsewhere — a map made in another tool+ * carries emoji, which are icons in their own right and are left as they are.+ */+function isIconClass(text: string) {+ const [ prefix, name, ...rest ] = text.split(" ");+ return !rest.length && !!name && (glob.iconRegistry?.sources ?? []).some((source) => source.prefix === prefix);+}