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
client/collections: create a module for manipulating promoted attributes via a context menu
Adorian Doran9275f89cd633
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 26e7d23f91..bbbeb60d04 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2959,6 +2959,10 @@"reformat_collapsible": "Collapsible","reformat_action_items": "Action items"},+ "attribute_menu": {+ "attributes": "Attributes",+ "not-set": "Not set"+ },"link_context_menu": {"open_note": "Open note","open_note_in_new_tab": "Open note in a new tab",diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsxindex 93a67368d2..fb402c1601 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx@@ -32,6 +32,7 @@ import NoteLink, { NewNoteLink } from "../react/NoteLink.jsx";import { disposeReactWidget, ParentComponent, renderReactWidgetAtElement } from "../react/react_utils.jsx";import OptionsRow, { OptionsRowWithToggle } from "../type_widgets/options/components/OptionsRow.jsx";import { ATTR_HELP, AttrHelpEntry } from "./attr_help.js";+import { DEFINITION_TYPE_ICONS, RELATION_DEFINITION_TYPE } from "./attribute_types.js";import LabelValueInput, { getTypedInputForLabel } from "./label_value_input.js";import ValuesInput from "./values_input.jsx";@@ -824,23 +825,21 @@ const TARGET_NOTE_OPTS = { allowCreatingNotes: true };* The value standing for a definition that points at a note rather than holding a value of its own.* Not a label type: it is what the definition is named after, `relation:foo` rather than `label:foo`.*/-export const RELATION_DEFINITION_TYPE = "relation";-/** Exported so that hosts listing definitions can name their label type as the popup does. */export const LABEL_TYPES = [- { value: "text", title: t("attribute_detail.text"), icon: "bx bx-text" },- { value: "textarea", title: t("attribute_detail.textarea"), icon: "bx bx-align-left" },- { value: "number", title: t("attribute_detail.number"), icon: "bx bx-hash" },- { value: "boolean", title: t("attribute_detail.boolean"), icon: "bx bx-toggle-left" },- { value: "select", title: t("attribute_detail.select_type"), icon: "bx bx-list-ul" },- { value: "date", title: t("attribute_detail.date"), icon: "bx bx-calendar" },- { value: "datetime", title: t("attribute_detail.date_time"), icon: "bx bx-calendar-event" },- { value: "time", title: t("attribute_detail.time"), icon: "bx bx-time" },- { value: "url", title: t("attribute_detail.url"), icon: "bx bx-link" },- { value: "email", title: t("attribute_detail.email"), icon: "bx bx-envelope" },- { value: "phone", title: t("attribute_detail.phone"), icon: "bx bx-phone" },- { value: "color", title: t("attribute_detail.color_type"), icon: "bx bx-palette" }-];+ { value: "text", title: t("attribute_detail.text") },+ { value: "textarea", title: t("attribute_detail.textarea") },+ { value: "number", title: t("attribute_detail.number") },+ { value: "boolean", title: t("attribute_detail.boolean") },+ { value: "select", title: t("attribute_detail.select_type") },+ { value: "date", title: t("attribute_detail.date") },+ { value: "datetime", title: t("attribute_detail.date_time") },+ { value: "time", title: t("attribute_detail.time") },+ { value: "url", title: t("attribute_detail.url") },+ { value: "email", title: t("attribute_detail.email") },+ { value: "phone", title: t("attribute_detail.phone") },+ { value: "color", title: t("attribute_detail.color_type") }+].map((type) => ({ ...type, icon: DEFINITION_TYPE_ICONS[type.value] }));/*** What a definition can set its field up to hold, the note it can point at instead included. The last@@ -854,7 +853,7 @@ export const DEFINITION_TYPES: { value: string; title: string; icon: string; sta{value: RELATION_DEFINITION_TYPE,title: t("attribute_detail.relation_type"),- icon: "bx bx-transfer",+ icon: DEFINITION_TYPE_ICONS[RELATION_DEFINITION_TYPE],startsGroup: true}];diff --git a/apps/client/src/widgets/attribute_widgets/attribute_types.ts b/apps/client/src/widgets/attribute_widgets/attribute_types.tsnew file mode 100644index 0000000000..946102b066--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/attribute_types.ts@@ -0,0 +1,36 @@+import type { PromotedAttribute } from "../collections/promoted_attributes";++/** The kind a definition takes when it points at a note instead of holding a value. */+export const RELATION_DEFINITION_TYPE = "relation";++/**+ * The icon each kind of definition is drawn with, wherever one is listed by its kind: the editor's+ * own type list, a sort menu, a menu that sets values.+ *+ * Data alone, so that a menu naming an icon does not pull in the attribute editor and the widget+ * stack behind it.+ */+export const DEFINITION_TYPE_ICONS: Record<string, string> = {+ text: "bx bx-text",+ textarea: "bx bx-align-left",+ number: "bx bx-hash",+ boolean: "bx bx-toggle-left",+ select: "bx bx-list-ul",+ date: "bx bx-calendar",+ datetime: "bx bx-calendar-event",+ time: "bx bx-time",+ url: "bx bx-link",+ email: "bx bx-envelope",+ phone: "bx bx-phone",+ color: "bx bx-palette",+ [RELATION_DEFINITION_TYPE]: "bx bx-transfer"+};++/** The icon for an attribute's kind: its `labelType`, or the relation icon for a relation. */+export function promotedAttributeIcon(attribute: PromotedAttribute) {+ const kind = attribute.type === "relation"+ ? RELATION_DEFINITION_TYPE+ : attribute.labelType ?? "text";++ return DEFINITION_TYPE_ICONS[kind] ?? DEFINITION_TYPE_ICONS.text;+}diff --git a/apps/client/src/widgets/collections/attribute_menu.css b/apps/client/src/widgets/collections/attribute_menu.cssnew file mode 100644index 0000000000..cbca1c6cb4--- /dev/null+++ b/apps/client/src/widgets/collections/attribute_menu.css@@ -0,0 +1,10 @@+.dropdown-item.attribute-menu-item {+ /* Names come from the user, so a long one is clipped instead of widening the menu. */+ .attribute-menu-name {+ display: block;+ max-width: 300px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+}diff --git a/apps/client/src/widgets/collections/attribute_menu.spec.ts b/apps/client/src/widgets/collections/attribute_menu.spec.tsnew file mode 100644index 0000000000..e97496d2c7--- /dev/null+++ b/apps/client/src/widgets/collections/attribute_menu.spec.ts@@ -0,0 +1,196 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type FNote from "../../entities/fnote";+import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";+import { buildNote } from "../../test/easy-froca";+import { buildAttributeMenuItems } from "./attribute_menu";+import type { PromotedAttribute } from "./promoted_attributes";++// The writes alone, so the rest of the service reads a note the way the application does.+const writes = vi.hoisted(() => ({ setLabelValues: vi.fn() }));+vi.mock("../../services/attributes", async (importOriginal) => ({+ ...await importOriginal<object>(),+ ...writes+}));++// i18next is never initialised under test, so `t` echoes the key it is given.+vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));++beforeEach(() => vi.clearAllMocks());++describe("buildAttributeMenuItems", () => {+ it("lists the flags and states an item shows, in order, under one heading", () => {+ const items = build({ title: "Card" }, [+ attribute({ name: "done", title: "Done", labelType: "boolean" }),+ attribute({ name: "notes", title: "Notes", labelType: "text" }),+ attribute({+ name: "state", title: "State", labelType: "select", selectOptions: [ "A" ]+ }),+ attribute({ name: "owner", title: "Owner", type: "relation" }),+ attribute({ name: "urgent", title: "Urgent", labelType: "boolean", hidden: true })+ ]);++ expect(items[0]).toEqual({ kind: "header", title: "attribute_menu.attributes" });+ expect(titles(items).slice(1)).toEqual([+ `<span class="attribute-menu-name">Done</span>`,+ `<span class="attribute-menu-name">State</span>`+ ]);+ expect(items[1]).toMatchObject({+ uiIcon: "bx bx-toggle-left", className: "attribute-menu-item"+ });+ expect(items[2]).toMatchObject({ uiIcon: "bx bx-list-ul" });+ });++ it("answers with nothing where no attribute can be set from a menu", () => {+ expect(build({ title: "Card" }, [])).toEqual([]);+ expect(build({ title: "Card" }, [+ attribute({ name: "notes", title: "Notes", labelType: "text" }),+ // A select offering nothing would open on "Not set" alone.+ attribute({ name: "state", title: "State", labelType: "select" })+ ])).toEqual([]);+ });++ it("lets the caller name the section", () => {+ const items = build({ title: "Card" }, [+ attribute({ name: "done", title: "Done", labelType: "boolean" })+ ], "Fields");++ expect(items[0]).toEqual({ kind: "header", title: "Fields" });+ });++ describe("a flag", () => {+ const flag = [ attribute({ name: "done", title: "Done", labelType: "boolean" }) ];++ it("is marked while the item carries it, and turned off when picked", () => {+ const note = buildNote({ title: "Card", "#done": "true" });+ const items = buildAttributeMenuItems<string>({ note, attributes: flag });++ expect(items[1]).toMatchObject({ trailingIcon: "bx bx-check" });+ pick(items[1]);+ expect(writes.setLabelValues).toHaveBeenCalledWith(note, "done", [ "false" ]);+ });++ it("is unmarked while the item does not, and turned on when picked", () => {+ const note = buildNote({ title: "Card" });+ const items = buildAttributeMenuItems<string>({ note, attributes: flag });++ expect(items[1]).toMatchObject({ trailingIcon: undefined });+ pick(items[1]);+ expect(writes.setLabelValues).toHaveBeenCalledWith(note, "done", [ "true" ]);+ });++ // The stored values are the checkbox's own, so the entry says what the item draws: a box+ // the user unchecked holds "false", and anything else was never set through the field.+ it("counts every value but true as unset", () => {+ for (const value of [ "false", "", "yes" ]) {+ const note = buildNote({ title: "Card", "#done": value });+ const items = buildAttributeMenuItems<string>({ note, attributes: flag });++ expect(items[1]).toMatchObject({ trailingIcon: undefined });+ }+ });+ });++ describe("a state", () => {+ const state = [ attribute({+ name: "state",+ title: "State",+ labelType: "select",+ selectOptions: [ "To Do", "Doing", "Done" ]+ }) ];++ /** The entries a state's submenu offers, the caller having none of its own to add. */+ function options(note: FNote) {+ const items = buildAttributeMenuItems<string>({ note, attributes: state });+ const entry = items[1];+ if (!entry || !("items" in entry)) throw new Error("expected a submenu");+ return entry.items ?? [];+ }++ it("offers the options as defined, above nothing but Not set, and no icons", () => {+ const items = options(buildNote({ title: "Card" }));++ expect(titles(items)).toEqual([+ `<span class="attribute-menu-name">attribute_menu.not-set</span>`,+ `<span class="attribute-menu-name">To Do</span>`,+ `<span class="attribute-menu-name">Doing</span>`,+ `<span class="attribute-menu-name">Done</span>`+ ]);+ expect(items.every(item => !("uiIcon" in item) || !item.uiIcon)).toBe(true);+ });++ it("marks the option the item holds", () => {+ const items = options(buildNote({ title: "Card", "#state": "Doing" }));++ expect(marked(items)).toEqual([ `<span class="attribute-menu-name">Doing</span>` ]);+ });++ it("marks Not set while the item holds none", () => {+ expect(marked(options(buildNote({ title: "Card" }))))+ .toEqual([ `<span class="attribute-menu-name">attribute_menu.not-set</span>` ]);+ });++ it("marks nothing for a value the definition no longer offers", () => {+ expect(marked(options(buildNote({ title: "Card", "#state": "Parked" })))).toEqual([]);+ });++ it("writes the option picked, and takes the value off for Not set", () => {+ const note = buildNote({ title: "Card", "#state": "Doing" });+ const items = options(note);++ pick(items[2]);+ expect(writes.setLabelValues).toHaveBeenCalledWith(note, "state", [ "Doing" ]);++ pick(items[0]);+ expect(writes.setLabelValues).toHaveBeenCalledWith(note, "state", []);+ });+ });++ it("escapes what a crafted name would plant in the menu", () => {+ const crafted = `<img src=x onerror="alert(1)">`;+ const items = build({ title: "Card" }, [ attribute({+ name: "state", title: crafted, labelType: "select", selectOptions: [ crafted ]+ }) ]);+ const entry = items[1];+ if (!entry || !("items" in entry)) throw new Error("expected a submenu");++ const escaped = "<span class=\"attribute-menu-name\">"+ + "<img src=x onerror="alert(1)"></span>";+ expect(titles(items)[1]).toBe(escaped);+ expect(titles(entry.items ?? [])[1]).toBe(escaped);+ });+});++function build(+ note: { title: string } & Record<string, string>,+ attributes: PromotedAttribute[],+ title?: string+) {+ return buildAttributeMenuItems<string>({ note: buildNote(note), attributes, title });+}++function attribute(fields: Partial<PromotedAttribute> & { name: string }): PromotedAttribute {+ return {+ definitionName: `label:${fields.name}`,+ type: "label",+ title: fields.name,+ hidden: false,+ definitionValue: "",+ isOwned: true,+ isInheritable: true,+ ...fields+ };+}++const titles = (items: MenuItem<string>[]) =>+ items.map(item => (item && "title" in item ? item.title : "separator"));++/** The titles of the entries carrying the mark, which is what says where a value stands. */+const marked = (items: MenuItem<string>[]) => items+ .filter(item => "trailingIcon" in item && item.trailingIcon)+ .map(item => ("title" in item ? item.title : ""));++function pick(item: MenuItem<string> | undefined) {+ if (!item || !("handler" in item)) throw new Error("expected a menu entry");+ item.handler?.(item as MenuCommandItem<string>, {} as never);+}diff --git a/apps/client/src/widgets/collections/attribute_menu.ts b/apps/client/src/widgets/collections/attribute_menu.tsnew file mode 100644index 0000000000..c40ac6ca02--- /dev/null+++ b/apps/client/src/widgets/collections/attribute_menu.ts@@ -0,0 +1,131 @@+import "./attribute_menu.css";++import type FNote from "../../entities/fnote";+import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";+import { setLabelValues } from "../../services/attributes";+import { t } from "../../services/i18n";+import { escapeHtml } from "../../services/utils";+import { promotedAttributeIcon } from "../attribute_widgets/attribute_types";+import type { PromotedAttribute } from "./promoted_attributes";++/** Marks the value an item holds, at the trailing edge as the other menus place it. */+const CHECK = "bx bx-check";++/** What a promoted `boolean` holds when it is set, which is what its checkbox writes. */+const TRUE = "true";+const FALSE = "false";++export interface AttributeMenuOptions {+ /** The item whose values the entries read and write. */+ note: FNote;+ /** The attributes the collection shows on its items, in the order it shows them. */+ attributes: PromotedAttribute[];+ /** What the section is called. "Attributes" unless the caller names it. */+ title?: string;+}++/**+ * Builds the section a collection's item menu uses to set the values shown on an item, so a flag or+ * a state changes without opening the note.+ *+ * Lists the attributes the items draw, in the order they are drawn, and only the two types a menu+ * can hold: `boolean`, which the entry marks and toggles, and `select`, whose options open in a+ * submenu. The other types need a field to type into and stay in the attribute editor.+ *+ * Returns an empty array when no attribute qualifies, so a caller can spread the result without+ * checking for an empty section.+ */+export function buildAttributeMenuItems<T>({+ note, attributes, title+}: AttributeMenuOptions): MenuItem<T>[] {+ const items = attributes.flatMap<MenuItem<T>>((attribute) => {+ if (attribute.hidden || attribute.type !== "label") {+ return [];+ }++ if (attribute.labelType === "boolean") {+ return [ buildBooleanItem<T>(note, attribute) ];+ }++ // A select without options is skipped: its submenu would hold "Not set" alone.+ if (attribute.labelType === "select" && attribute.selectOptions?.length) {+ return [ buildSelectItem<T>(note, attribute, attribute.selectOptions) ];+ }++ return [];+ });++ if (!items.length) {+ return [];+ }++ return [ { kind: "header", title: title ?? t("attribute_menu.attributes") }, ...items ];+}++/**+ * A `boolean`, marked while it is set and toggled when the entry is picked.+ *+ * Read and written as `"true"` and `"false"`, the values the field's own checkbox stores, so the+ * entry says what the item draws. A value stored any other way counts as unset, as it does on the+ * item.+ */+function buildBooleanItem<T>(note: FNote, attribute: PromotedAttribute): MenuCommandItem<T> {+ const isSet = note.getLabelValue(attribute.name) === TRUE;++ return {+ ...attributeEntry<T>(attribute),+ trailingIcon: isSet ? CHECK : undefined,+ handler: () => {+ void setLabelValues(note, attribute.name, [ isSet ? FALSE : TRUE ]);+ }+ };+}++/**+ * A `select`, its options in a submenu in the order the definition lists them, with the value the+ * item holds marked. A value the definition no longer lists marks nothing.+ */+function buildSelectItem<T>(+ note: FNote, attribute: PromotedAttribute, options: string[]+): MenuCommandItem<T> {+ const current = note.getLabelValue(attribute.name);++ return {+ ...attributeEntry<T>(attribute),+ // The options carry no icon: they are the user's own words, and one icon would repeat+ // across every option.+ items: [+ {+ // Boxed like the options: the menu lays a row out as a flex line, so a bare title+ // keeps the space that separates it from the icon and reads as indented.+ title: boxed(t("attribute_menu.not-set")),+ className: "attribute-menu-item",+ trailingIcon: current ? undefined : CHECK,+ handler: () => { void setLabelValues(note, attribute.name, []); }+ },+ ...options.map<MenuItem<T>>((option) => ({+ title: boxed(option),+ className: "attribute-menu-item",+ trailingIcon: option === current ? CHECK : undefined,+ handler: () => { void setLabelValues(note, attribute.name, [ option ]); }+ }))+ ]+ };+}++/** What every entry carries: the attribute's display name, under the icon of its type. */+function attributeEntry<T>(attribute: PromotedAttribute): MenuCommandItem<T> {+ return {+ title: boxed(attribute.title),+ className: "attribute-menu-item",+ uiIcon: promotedAttributeIcon(attribute)+ };+}++/**+ * Boxes a name the user wrote. The menu reads a title as markup, so the name is escaped, and+ * `attribute_menu.css` clips the box rather than letting a long name widen the menu.+ */+function boxed(name: string) {+ return `<span class="attribute-menu-name">${escapeHtml(name)}</span>`;+}diff --git a/apps/client/src/widgets/collections/sort_menu.spec.ts b/apps/client/src/widgets/collections/sort_menu.spec.tsindex 67d8dd41fb..ba6339b4fb 100644--- a/apps/client/src/widgets/collections/sort_menu.spec.ts+++ b/apps/client/src/widgets/collections/sort_menu.spec.ts@@ -4,12 +4,8 @@ import type { MenuItem } from "../../menus/context_menu";import type { PromotedAttribute } from "./promoted_attributes";import { buildSortMenuItems, type SortMenuOptions } from "./sort_menu";-// i18next is never initialised under test, so `t` echoes the key it is given. The promise is what-// the command registry awaits as `PromotedAttributesCard` is pulled in for the attribute icons.-vi.mock("../../services/i18n", () => ({- t: (key: string) => key,- translationsInitializedPromise: Promise.resolve()-}));+// i18next is never initialised under test, so `t` echoes the key it is given.+vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));describe("buildSortMenuItems", () => {it("offers no sorting, the two built-in keys and the direction", () => {diff --git a/apps/client/src/widgets/collections/sort_menu.ts b/apps/client/src/widgets/collections/sort_menu.tsindex 8f3c4c22f1..7e0778daae 100644--- a/apps/client/src/widgets/collections/sort_menu.ts+++ b/apps/client/src/widgets/collections/sort_menu.ts@@ -3,7 +3,7 @@ import "./sort_menu.css";import type { MenuItem } from "../../menus/context_menu";import { t } from "../../services/i18n";import { escapeHtml } from "../../services/utils";-import { promotedAttributeType } from "../react/PromotedAttributesCard";+import { promotedAttributeIcon } from "../attribute_widgets/attribute_types";import type { PromotedAttribute } from "./promoted_attributes";import type { SortKey } from "./sorting";@@ -56,7 +56,7 @@ export function buildSortMenuItems<T>({// clips a long one instead of widening the menu.title: `<span class="sort-menu-name">${escapeHtml(attribute.title)}</span>`,className: "sort-menu-item",- uiIcon: promotedAttributeType(attribute).icon,+ uiIcon: promotedAttributeIcon(attribute),trailingIcon: checkFor(`attr:${attribute.name}`),handler: () => onSelect(`attr:${attribute.name}`)})),diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.tsx b/apps/client/src/widgets/react/PromotedAttributesCard.tsxindex 19e466e819..c4a7b3e964 100644--- a/apps/client/src/widgets/react/PromotedAttributesCard.tsx+++ b/apps/client/src/widgets/react/PromotedAttributesCard.tsx@@ -9,8 +9,9 @@ import attributes, { removeOwnedAttributesByNameOrType } from "../../services/atimport dialog from "../../services/dialog";import { t } from "../../services/i18n";import {- AttributeDetail, type AttributeDetailOpts, DEFINITION_TYPES, RELATION_DEFINITION_TYPE+ AttributeDetail, type AttributeDetailOpts, DEFINITION_TYPES} from "../attribute_widgets/attribute_detail";+import { RELATION_DEFINITION_TYPE } from "../attribute_widgets/attribute_types";import {deleteAttributeInSubtree, type PromotedAttribute, type PromotedAttributeSetting,renameAttributeInSubtree, resolvePromotedAttributes, storedPromotedAttributes@@ -272,7 +273,7 @@ export default function PromotedAttributesCard({}/** The kind entry for an attribute: its `labelType`, or the relation kind for a relation. */-export function promotedAttributeType(attribute: PromotedAttribute) {+function promotedAttributeType(attribute: PromotedAttribute) {const kind = attribute.type === "relation"? RELATION_DEFINITION_TYPE: attribute.labelType ?? "text";diff --git a/apps/client/src/widgets/sidebar/AttributeList.tsx b/apps/client/src/widgets/sidebar/AttributeList.tsxindex 321aac5ebf..959a5c15bb 100644--- a/apps/client/src/widgets/sidebar/AttributeList.tsx+++ b/apps/client/src/widgets/sidebar/AttributeList.tsx@@ -15,7 +15,8 @@ import dialog from "../../services/dialog";import { t } from "../../services/i18n";import server from "../../services/server";import { isMobile } from "../../services/utils";-import { AttributeDetail, AttributeDetailOpts, AttributeForm, AttrType, DEFINITION_TYPES, getAttrType, RELATION_DEFINITION_TYPE } from "../attribute_widgets/attribute_detail";+import { AttributeDetail, AttributeDetailOpts, AttributeForm, AttrType, DEFINITION_TYPES, getAttrType } from "../attribute_widgets/attribute_detail";+import { RELATION_DEFINITION_TYPE } from "../attribute_widgets/attribute_types";import { ColorChip, renderLabelValue } from "../attribute_widgets/label_value_display";import ActionButton from "../react/ActionButton";import { FormListItem } from "../react/FormList";