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/board: allow controlling the visibility and the order of the promoted attributes displayed on the cards
Adorian Doran511affdd4e6b
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e8a6cd08a5..d6f920d27a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1385,6 +1385,10 @@},"promoted_attributes": {"promoted_attributes": "Promoted Attributes",+ "create_attribute": "Create a new attribute",+ "edit_attribute": "Edit this attribute",+ "shown_on_items": "Shown on the items",+ "hidden_from_items": "Hidden from the items","unset-field-placeholder": "not set","url_placeholder": "http://website...","open_external_link": "Open external link",@@ -3445,6 +3449,8 @@"properties-title": "Board properties","card-templates": "Card templates","card-templates-hint": "Choose what note types and note templates you would like to use when creating new board cards.",+ "promoted-attributes": "Promoted attributes",+ "promoted-attributes-hint": "Choose which attributes the cards show, and drag them into the order they appear in.","new-template-name": "New card template","more-templates": "More templates…","card-template": "Select a card template",diff --git a/apps/client/src/widgets/attribute_widgets/UserAttributesList.spec.tsx b/apps/client/src/widgets/attribute_widgets/UserAttributesList.spec.tsxnew file mode 100644index 0000000000..91bb0d0d28--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/UserAttributesList.spec.tsx@@ -0,0 +1,100 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type FNote from "../../entities/fnote";+import UserAttributesDisplay from "./UserAttributesList";++// i18next is never initialised under test, so every label would read as undefined.+vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));++/** A note carrying the given labels, each defined and promoted. */+function noteWith(labels: Record<string, string[]>) {+ return {+ noteId: "card1",+ getAttributeDefinitions: () => Object.keys(labels).map((name) => ({+ name: `label:${name}`,+ getDefinition: () => ({ isPromoted: true, labelType: "text" })+ })),+ getLabels: (name: string) => (labels[name] ?? []).map((value) => ({ value })),+ getRelations: () => []+ } as unknown as FNote;+}++const NOTE = noteWith({ dueDate: [ "2026-01-01" ], owner: [ "Ada" ], stage: [ "Doing" ] });++describe("UserAttributesDisplay", () => {+ let container: HTMLElement;++ beforeEach(() => {+ container = document.body.appendChild(document.createElement("div"));+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ it("draws every defined attribute, in the order the definitions stand in", () => {+ draw();++ expect(values()).toEqual([ "2026-01-01", "Ada", "Doing" ]);+ });++ it("draws only what it is told to, in the order it is given them", () => {+ draw({ shownAttributes: [ "stage", "dueDate" ] });++ expect(values()).toEqual([ "Doing", "2026-01-01" ]);+ });++ it("draws nothing where nothing is to be shown", () => {+ draw({ shownAttributes: [] });++ expect(container.querySelector(".user-attributes")).toBeNull();+ });++ /** The values of one attribute belong together wherever the attribute is placed. */+ it("keeps the values of one attribute together", () => {+ const note = noteWith({ tag: [ "red", "green" ], owner: [ "Ada" ] });++ draw({ note, shownAttributes: [ "owner", "tag" ] });++ expect(values()).toEqual([ "Ada", "red", "green" ]);+ });++ it("leaves out what it is told to ignore, whichever way it is ordered", () => {+ draw({ ignoredAttributes: [ "stage" ], shownAttributes: [ "stage", "owner" ] });++ expect(values()).toEqual([ "Ada" ]);+ });++ /** The reader arranges the attributes while the items are on screen. */+ it("draws them afresh when what is to be shown changes", () => {+ draw({ shownAttributes: [ "owner" ] });+ expect(values()).toEqual([ "Ada" ]);++ draw({ shownAttributes: [ "stage", "owner" ] });++ expect(values()).toEqual([ "Doing", "Ada" ]);+ });++ function draw({ note = NOTE, ignoredAttributes, shownAttributes }: {+ note?: FNote, ignoredAttributes?: string[], shownAttributes?: string[]+ } = {}) {+ act(() => {+ render(+ <UserAttributesDisplay+ note={note}+ ignoredAttributes={ignoredAttributes}+ shownAttributes={shownAttributes}+ />,+ container);+ });+ }++ /** What each attribute reads as, less the name that leads it. */+ function values() {+ return [ ...container.querySelectorAll(".user-attribute") ]+ .map((element) => element.textContent?.split(": ").at(-1));+ }+});diff --git a/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx b/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsxindex d3e2ddcbce..8b6b6c9849 100644--- a/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx+++ b/apps/client/src/widgets/attribute_widgets/UserAttributesList.tsx@@ -2,7 +2,7 @@ import "./UserAttributesList.css";import type { DefinitionObject } from "@triliumnext/commons";import { ComponentChildren, CSSProperties } from "preact";-import { useState } from "preact/hooks";+import { useEffect, useState } from "preact/hooks";import FNote from "../../entities/fnote";import attributes from "../../services/attributes";@@ -15,6 +15,11 @@ import NoteLink from "../react/NoteLink";interface UserAttributesListProps {note: FNote;ignoredAttributes?: string[];+ /**+ * The attributes to draw, by name and in the order they are given. Without it every attribute+ * carrying a definition is drawn, in the order the definitions stand in.+ */+ shownAttributes?: string[];}interface AttributeWithDefinitions {@@ -25,8 +30,10 @@ interface AttributeWithDefinitions {def: DefinitionObject;}-export default function UserAttributesDisplay({ note, ignoredAttributes }: UserAttributesListProps) {- const userAttributes = useNoteAttributesWithDefinitions(note, ignoredAttributes);+export default function UserAttributesDisplay({+ note, ignoredAttributes, shownAttributes+}: UserAttributesListProps) {+ const userAttributes = useNoteAttributesWithDefinitions(note, ignoredAttributes, shownAttributes);return userAttributes?.length > 0 && (<div className="user-attributes">{userAttributes?.map(attr => buildUserAttribute(attr))}@@ -35,15 +42,25 @@ export default function UserAttributesDisplay({ note, ignoredAttributes }: UserA}-function useNoteAttributesWithDefinitions(note: FNote, attributesToIgnore: string[] = []): AttributeWithDefinitions[] {- const [ userAttributes, setUserAttributes ] = useState<AttributeWithDefinitions[]>(getAttributesWithDefinitions(note, attributesToIgnore));+function useNoteAttributesWithDefinitions(+ note: FNote, attributesToIgnore: string[] = [], shown?: string[]+): AttributeWithDefinitions[] {+ const [ userAttributes, setUserAttributes ] = useState<AttributeWithDefinitions[]>(+ getAttributesWithDefinitions(note, attributesToIgnore, shown));useTriliumEvent("entitiesReloaded", ({ loadResults }) => {if (loadResults.getAttributeRows().some(attr => attributes.isAffecting(attr, note))) {- setUserAttributes(getAttributesWithDefinitions(note, attributesToIgnore));+ setUserAttributes(getAttributesWithDefinitions(note, attributesToIgnore, shown));}});+ // What is drawn and in what order is the caller's, and it changes as the reader arranges it.+ const key = shown?.join(",");+ useEffect(() => {+ setUserAttributes(getAttributesWithDefinitions(note, attributesToIgnore, shown));+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [ note, key ]);+return userAttributes;}@@ -115,7 +132,9 @@ function buildUserAttribute(attr: AttributeWithDefinitions): ComponentChildren {return <UserAttribute attr={attr} style={style}>{content}</UserAttribute>;}-function getAttributesWithDefinitions(note: FNote, attributesToIgnore: string[] = []): AttributeWithDefinitions[] {+function getAttributesWithDefinitions(+ note: FNote, attributesToIgnore: string[] = [], shown?: string[]+): AttributeWithDefinitions[] {const attributeDefintions = note.getAttributeDefinitions();const result: AttributeWithDefinitions[] = [];for (const attr of attributeDefintions) {@@ -140,5 +159,15 @@ function getAttributesWithDefinitions(note: FNote, attributesToIgnore: string[]}}}- return result;++ if (!shown) {+ return result;+ }++ // Sorted rather than gathered in the given order, so an attribute carrying several values keeps+ // them together: the sort is stable, and they were pushed one after another above.+ const at = new Map(shown.map((name, index) => [ name, index ]));+ return result+ .filter(attr => at.has(attr.name))+ .sort((a, b) => (at.get(a.name) ?? 0) - (at.get(b.name) ?? 0));}diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex bd6e69a222..375ba3c882 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -1562,3 +1562,60 @@ describe("filing a card under the inbox", () => {expect(removeRelation).toHaveBeenCalled();});});++describe("the promoted attributes a card shows", () => {+ /** A board defining two promoted labels, which is what the cards can show. */+ function boardWithAttributes() {+ return buildNote({+ title: "Board",+ "#label:dueDate(inheritable)": "promoted,single,date",+ "#label:owner(inheritable)": "promoted,single,text"+ });+ }++ /**+ * A board is usually given `#hidePromotedAttributes` so its own title row stays clear, and it+ * groups by a label its cards draw as columns rather than as a value.+ */+ it("lists what the cards can draw, whatever the board hides on itself", () => {+ const board = buildNote({+ title: "Board",+ "#hidePromotedAttributes": "",+ "#label:status(inheritable)": "promoted,single,text",+ "#label:dueDate(inheritable)": "promoted,single,date",+ "#label:internal(inheritable)": "single,text"+ });+ const { api } = createApi({}, [], board);++ // The label it groups by is drawn as a column, and an unpromoted one is still drawn.+ expect(api.getVisiblePromotedAttributeNames()).toEqual([ "dueDate", "internal" ]);+ });++ it("shows every one of them until the reader arranges them", () => {+ const { api } = createApi({}, [], boardWithAttributes());++ expect(api.getVisiblePromotedAttributeNames()).toEqual([ "dueDate", "owner" ]);+ expect(api.getStoredPromotedAttributes()).toBeUndefined();+ });++ it("follows the stored order, and leaves out what is hidden", () => {+ const stored = [ { name: "owner" }, { name: "dueDate", hidden: true } ];+ const { api } = createApi({ promotedAttributes: stored }, [], boardWithAttributes());++ expect(api.getVisiblePromotedAttributeNames()).toEqual([ "owner" ]);+ expect(api.getPromotedAttributes().map(attribute => attribute.name))+ .toEqual([ "owner", "dueDate" ]);+ expect(api.getStoredPromotedAttributes()).toBe(stored);+ });++ it("stores the whole list, an attribute the board has dropped along with it", async () => {+ const { api, saved } = createApi(+ { promotedAttributes: [ { name: "gone" } ] }, [], boardWithAttributes());++ await api.setPromotedAttributes(api.getPromotedAttributes().map(+ attribute => attribute.name === "owner" ? { ...attribute, hidden: true } : attribute));++ expect(saved.at(-1)?.promotedAttributes)+ .toEqual([ { name: "dueDate" }, { name: "owner", hidden: true } ]);+ });+});diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 550deb632b..aad3fe4428 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -14,6 +14,10 @@ import { type NoteTypeOption, resolveNoteTypeOptions } from "../../../services/nimport server from "../../../services/server";import ws from "../../../services/ws";import toast from "../../../services/toast";+import {+ type PromotedAttribute, resolvePromotedAttributes, storedPromotedAttributes,+ visiblePromotedAttributeNames+} from "../promoted_attributes";import { BoardColumnData, BoardViewData } from ".";import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";import {@@ -637,6 +641,32 @@ export default class BoardApi {return this.viewConfig?.template;}+ /** The order and what is hidden, as the view config holds it. */+ getStoredPromotedAttributes() {+ return this.viewConfig?.promotedAttributes;+ }++ /** The promoted attributes the board defines, in the order the reader put them. */+ getPromotedAttributes() {+ return resolvePromotedAttributes(+ this.parentNote, this.viewConfig?.promotedAttributes, [ this.statusAttribute ]);+ }++ /** Which of them a card draws, in order. */+ getVisiblePromotedAttributeNames() {+ return visiblePromotedAttributeNames(this.getPromotedAttributes());+ }++ /**+ * Stores the order and what is hidden.+ *+ * The whole list is written, so an attribute the board no longer defines is dropped from the+ * config by the same call that arranges the rest.+ */+ async setPromotedAttributes(attributes: PromotedAttribute[]) {+ this.storeConfig({ promotedAttributes: storedPromotedAttributes(attributes) });+ }+/** Sets what the board offers. An empty set would leave nothing to make a card from. */async setCardTemplateIds(templates: string[]) {if (!templates.length) {diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsxindex 91c5aff4a6..4adccad7f8 100644--- a/apps/client/src/widgets/collections/board/card.tsx+++ b/apps/client/src/widgets/collections/board/card.tsx@@ -5,7 +5,7 @@ import {import FBranch from "../../../entities/fbranch";import FNote from "../../../entities/fnote";import BoardApi from "./api";-import { BoardActionsContext, TitleEditor } from ".";+import { BoardActionsContext, BoardPromotedAttributesContext, TitleEditor } from ".";import { ContextMenuEvent } from "../../../menus/context_menu";import { openNoteContextMenu } from "./context_menu";import { t } from "../../../services/i18n";@@ -58,6 +58,7 @@ function Card({onInsert: (index: number) => void}) {const { setBranchIdToEdit } = useContext(BoardActionsContext);+ const shownAttributes = useContext(BoardPromotedAttributesContext);// Tracks the `color` label, which the board does not redraw a card for.const colorClass = useNoteColorClass(note) || "";const editorRef = useRef<HTMLInputElement>(null);@@ -182,7 +183,11 @@ function Card({title={t("board_view.edit-note-title")}onClick={handleEdit}/>- <UserAttributesDisplay note={note} ignoredAttributes={[statusAttribute]} />+ <UserAttributesDisplay+ note={note}+ ignoredAttributes={[statusAttribute]}+ shownAttributes={shownAttributes}+ /></>) : (<TitleEditordiff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 701899d197..5bea539a2e 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -2517,11 +2517,15 @@ describe("Board column rename", () => {expect(dialog).toBeTruthy();// What the board offers, in the order it stores them, each carried by a grip of its own.- const named = [ ...(dialog?.querySelectorAll(".template-selection-name") ?? []) ]+ const templates = dialog?.querySelector<HTMLElement>(".template-selection-card");+ const named = [ ...(templates?.querySelectorAll(".template-selection-name") ?? []) ].map(element => element.textContent);expect(named).toEqual([ "Text", "Markdown", "Canvas", "Spreadsheet" ]);- expect(dialog?.querySelectorAll(".tn-sortable-grip").length).toBe(4);- expect(dialog?.querySelectorAll(".tn-sortable-adder").length).toBe(2);+ expect(templates?.querySelectorAll(".tn-sortable-grip").length).toBe(4);+ expect(templates?.querySelectorAll(".tn-sortable-adder").length).toBe(2);++ // And the attributes the cards show, which the same dialog arranges.+ expect(dialog?.querySelector(".promoted-attributes-card")).toBeTruthy();await dismiss(dialog);});@@ -3225,3 +3229,69 @@ describe("Board grouped by a relation", () => {return { board: mountPoint, target };}});++describe("the promoted attributes a card shows", () => {+ let container: HTMLElement;+ let drawn = 0;++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ it("draws every one of them until the board's config arranges them", async () => {+ await draw();++ expect(pills()).toEqual([ "Due: 2026-01-01", "owner: Ada" ]);+ });++ it("draws them in the stored order, and leaves out what is hidden", async () => {+ await draw([ { name: "owner" }, { name: "dueDate", hidden: true } ]);++ expect(pills()).toEqual([ "owner: Ada" ]);+ });++ it("draws an attribute the config has never named, after the ones it has", async () => {+ await draw([ { name: "owner" } ]);++ expect(pills()).toEqual([ "owner: Ada", "Due: 2026-01-01" ]);+ });++ /** A board defining two promoted labels, one card carrying a value for each. */+ async function draw(promotedAttributes?: { name: string, hidden?: boolean }[]) {+ // The cache keeps what a note id was built with, so a card of its own is what keeps this+ // test's values off the one the test before it drew.+ const card = `promotedCard${++drawn}`;+ const note = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ "#label:dueDate(inheritable)": "promoted,alias=Due,single,text",+ "#label:owner(inheritable)": "promoted,single,text",+ children: [+ { id: card, title: "First", "#status": "To Do", "#dueDate": "2026-01-01",+ "#owner": "Ada" }+ ]+ });++ container = document.body.appendChild(document.createElement("div"));+ await act(async () => {+ render(+ <ParentComponent.Provider value={new Component()}>+ <Harness+ note={note}+ noteIds={[ ...note.getChildNoteIds() ]}+ initialConfig={{ columns: [ { value: "To Do" } ], promotedAttributes }}+ />+ </ParentComponent.Provider>,+ container+ );+ });+ await act(async () => { await flush(); });+ }++ function pills() {+ return [ ...container.querySelectorAll(".board-note .user-attribute") ]+ .map(element => element.textContent);+ }+});diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 5033222aaa..443c5e9110 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -18,6 +18,7 @@ import type { ShortcutHintDefinition } from "../../../services/shortcut_hints";import toast from "../../../services/toast";import { escapeHtml, isMobile } from "../../../services/utils";import { type NoteTypeOption, resolveNoteTypeOptions } from "../../../services/note_types";+import type { PromotedAttributeSetting } from "../promoted_attributes";import CollectionProperties from "../../note_bars/CollectionProperties";import FormTextArea from "../../react/FormTextArea";import FormTextBox from "../../react/FormTextBox";@@ -67,6 +68,11 @@ export interface BoardViewData {templates?: string[];/** The one last used, which the next card is made from. */template?: string;+ /**+ * Which promoted attributes the cards show, and in what order. An attribute the list does not+ * name is shown after the ones it does; see {@link resolvePromotedAttributes}.+ */+ promotedAttributes?: PromotedAttributeSetting[];}export interface BoardColumnData {@@ -172,6 +178,14 @@ export const BoardActionsContext = createContext<BoardActions>({setDropTarget: () => undefined});+/**+ * Which promoted attributes a card draws, in order.+ *+ * A context rather than a prop: a card is memoized, so this is what reaches one when the reader+ * arranges the attributes and nothing about the card itself has changed.+ */+export const BoardPromotedAttributesContext = createContext<string[] | undefined>(undefined);+export const BoardDragStateContext = createContext<BoardDragState>({draggedCard: null,draggedColumn: null,@@ -374,6 +388,14 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveConMore: () => setIsEditingProperties(true)}), [ api, viewConfig, offeredTemplates ]);+ // Held while the names are the same, since a new array would redraw every card on every render.+ const shownAttributesRef = useRef<string[]>([]);+ const resolvedAttributes = api.getVisiblePromotedAttributeNames();+ if (resolvedAttributes.join(",") !== shownAttributesRef.current.join(",")) {+ shownAttributesRef.current = resolvedAttributes;+ }+ const shownAttributes = shownAttributesRef.current;+const boardActions = useMemo<BoardActions>(() => ({setBranchIdToEdit,setColumnNameToEdit,@@ -692,6 +714,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC<div className="board-view"><CollectionProperties note={parentNote} /><BoardActionsContext.Provider value={boardActions}>+ <BoardPromotedAttributesContext.Provider value={shownAttributes}><BoardDragStateContext.Provider value={boardDragState}>{byColumn && columns && <divref={containerRef}@@ -790,6 +813,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC)}</div>}</BoardDragStateContext.Provider>+ </BoardPromotedAttributesContext.Provider></BoardActionsContext.Provider></div>);diff --git a/apps/client/src/widgets/collections/board/properties.spec.tsx b/apps/client/src/widgets/collections/board/properties.spec.tsxindex 7d73be640e..65f67507a5 100644--- a/apps/client/src/widgets/collections/board/properties.spec.tsx+++ b/apps/client/src/widgets/collections/board/properties.spec.tsx@@ -4,6 +4,7 @@ import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type FNote from "../../../entities/fnote";+import type { PromotedAttribute } from "../promoted_attributes";import BoardApi from "./api";import BoardProperties from "./properties";@@ -31,18 +32,43 @@ vi.mock("../../react/TemplateSelectionCard", () => ({)}));+// The card is tested in its own spec; what this dialog decides is the words it passes and where+// onChange writes.+vi.mock("../../react/PromotedAttributesCard", () => ({+ default: ({ heading, instruction, note, settings, onChange }: {+ heading: string, instruction: string, note: FNote,+ settings: { name: string }[] | undefined,+ onChange: (attributes: PromotedAttribute[]) => void+ }) => (+ <div+ className="attributes-stub"+ data-heading={heading}+ data-instruction={instruction}+ data-note={note.noteId}+ data-settings={settings?.map((setting) => setting.name).join(",")}+ onClick={() => onChange([ { name: "dueDate", hidden: true } as PromotedAttribute ])}+ />+ )+}));+describe("Board properties", () => {let container: HTMLElement;let stored: string[][];+ let storedAttributes: PromotedAttribute[][];beforeEach(() => {stored = [];+ storedAttributes = [];container = document.createElement("div");document.body.appendChild(container);const api = {getCardTemplateIds: () => [ "type:text:text/html" ],- setCardTemplateIds: async (ids: string[]) => { stored.push(ids); }+ setCardTemplateIds: async (ids: string[]) => { stored.push(ids); },+ getStoredPromotedAttributes: () => [ { name: "dueDate" }, { name: "owner" } ],+ setPromotedAttributes: async (attributes: PromotedAttribute[]) => {+ storedAttributes.push(attributes);+ }} as unknown as BoardApi;act(() => {@@ -87,6 +113,21 @@ describe("Board properties", () => {expect(card?.dataset.templates).toBe("type:text:text/html");});+ it("holds the promoted attributes, in the board's own words and from its own config", () => {+ const card = dialog()?.querySelector<HTMLElement>(".attributes-stub");++ expect(card?.dataset.heading).toBe("board_view.promoted-attributes");+ expect(card?.dataset.instruction).toBe("board_view.promoted-attributes-hint");+ expect(card?.dataset.note).toBe("board1");+ expect(card?.dataset.settings).toBe("dueDate,owner");+ });++ it("writes the order and what is hidden back to the board", () => {+ act(() => { dialog()?.querySelector<HTMLElement>(".attributes-stub")?.click(); });++ expect(storedAttributes).toEqual([ [ { name: "dueDate", hidden: true } ] ]);+ });+it("writes what the card answers with back to the board", () => {act(() => { dialog()?.querySelector<HTMLElement>(".templates-stub")?.click(); });diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsxindex 52e1106e07..564fd69096 100644--- a/apps/client/src/widgets/collections/board/properties.tsx+++ b/apps/client/src/widgets/collections/board/properties.tsx@@ -3,7 +3,9 @@ import { useCallback } from "preact/hooks";import type FNote from "../../../entities/fnote";import { t } from "../../../services/i18n";import Modal from "../../react/Modal";+import PromotedAttributesCard from "../../react/PromotedAttributesCard";import TemplateSelectionCard from "../../react/TemplateSelectionCard";+import type { PromotedAttribute } from "../promoted_attributes";import BoardApi from "./api";/** The board's settings, other than its columns and cards. */@@ -16,6 +18,8 @@ export default function BoardProperties({ api, note, shown, onClose }: {}) {const store = useCallback((templates: string[]) => api.setCardTemplateIds(templates), [ api ]);+ const storeAttributes = useCallback(+ (attributes: PromotedAttribute[]) => api.setPromotedAttributes(attributes), [ api ]);return (<Modal@@ -34,6 +38,15 @@ export default function BoardProperties({ api, note, shown, onClose }: {templates={api.getCardTemplateIds()}onChange={store}/>++ <PromotedAttributesCard+ heading={t("board_view.promoted-attributes")}+ instruction={t("board_view.promoted-attributes-hint")}+ note={note}+ settings={api.getStoredPromotedAttributes()}+ ignored={[ api.statusAttribute ]}+ onChange={storeAttributes}+ /></Modal>);}diff --git a/apps/client/src/widgets/collections/promoted_attributes.spec.ts b/apps/client/src/widgets/collections/promoted_attributes.spec.tsnew file mode 100644index 0000000000..f61344352b--- /dev/null+++ b/apps/client/src/widgets/collections/promoted_attributes.spec.ts@@ -0,0 +1,177 @@+import { describe, expect, it, vi } from "vitest";++import type FNote from "../../entities/fnote";+import {+ type PromotedAttributeSetting, resolvePromotedAttributes, storedPromotedAttributes,+ visiblePromotedAttributeNames+} from "./promoted_attributes";++const mocks = vi.hoisted(() => ({ bulk: vi.fn(async () => {}) }));+vi.mock("../../services/bulk_action", () => ({ executeBulkActions: mocks.bulk }));++/** A definition as the collection note carries it, `label:dueDate` naming `dueDate`. */+function definition(name: string, {+ alias, noteId = "board1", value = "promoted,single,text", isPromoted = true,+ isInheritable = true+}: {+ alias?: string, noteId?: string, value?: string, isPromoted?: boolean, isInheritable?: boolean+} = {}) {+ return {+ name,+ value,+ noteId,+ isInheritable,+ getDefinition: () => ({ isPromoted, promotedAlias: alias })+ };+}++/** A collection note offering the given definitions. */+function collection(definitions: ReturnType<typeof definition>[], noteId = "board1") {+ return {+ noteId,+ getAttributeDefinitions: () => definitions+ } as unknown as FNote;+}++const DEFINED = [+ definition("label:dueDate", { alias: "Due" }),+ definition("label:requiresResearch"),+ definition("relation:owner")+];++describe("resolvePromotedAttributes", () => {+ it("reads what the note defines, naming each by its alias where it has one", () => {+ const resolved = resolvePromotedAttributes(collection(DEFINED), undefined);++ expect(resolved).toEqual([+ {+ name: "dueDate",+ definitionName: "label:dueDate",+ type: "label",+ title: "Due",+ hidden: false,+ definitionValue: "promoted,single,text",+ isOwned: true,+ isInheritable: true+ },+ expect.objectContaining({ name: "requiresResearch", title: "requiresResearch" }),+ expect.objectContaining({ name: "owner", type: "relation" })+ ]);+ });++ it("puts them in the order the settings give, and hides what they hide", () => {+ const settings: PromotedAttributeSetting[] = [+ { name: "owner" },+ { name: "requiresResearch", hidden: true }+ ];++ const resolved = resolvePromotedAttributes(collection(DEFINED), settings);++ // What the settings arrange leads, in their order; what they say nothing of follows.+ expect(resolved.map((attribute) => attribute.name))+ .toEqual([ "owner", "requiresResearch", "dueDate" ]);+ expect(resolved.map((attribute) => attribute.hidden)).toEqual([ false, true, false ]);+ expect(visiblePromotedAttributeNames(resolved)).toEqual([ "owner", "dueDate" ]);+ });++ /** An attribute nobody has arranged is one the reader has yet to see. */+ it("shows an attribute the settings have never named", () => {+ const resolved = resolvePromotedAttributes(+ collection(DEFINED), [ { name: "dueDate", hidden: true } ]);++ expect(visiblePromotedAttributeNames(resolved)).toEqual([ "requiresResearch", "owner" ]);+ });++ /** Writing the result back is what prunes the config. */+ it("leaves out what the settings name and the note no longer defines", () => {+ const settings: PromotedAttributeSetting[] = [+ { name: "gone", hidden: true },+ { name: "dueDate", hidden: true }+ ];++ const resolved = resolvePromotedAttributes(+ collection([ definition("label:dueDate") ]), settings);++ expect(storedPromotedAttributes(resolved)).toEqual([ { name: "dueDate", hidden: true } ]);+ });++ it("stores a shown attribute as its name alone", () => {+ const resolved = resolvePromotedAttributes(collection(DEFINED), undefined);++ expect(storedPromotedAttributes(resolved))+ .toEqual([ { name: "dueDate" }, { name: "requiresResearch" }, { name: "owner" } ]);+ });++ it("names an attribute once, whichever of the two settings arranged it", () => {+ const resolved = resolvePromotedAttributes(+ collection(DEFINED), [ { name: "owner" }, { name: "owner", hidden: true } ]);++ expect(resolved.filter((attribute) => attribute.name === "owner").length).toBe(1);+ expect(resolved[0].hidden).toBe(false);+ });++ /** A collection whose definitions are its template's or an ancestor's still offers them. */+ it("marks a definition the collection does not carry itself", () => {+ const inherited = definition("label:dueDate", { noteId: "template1" });++ const [ resolved ] = resolvePromotedAttributes(collection([ inherited ]), undefined);++ expect(resolved.isOwned).toBe(false);+ });++ it("answers with nothing for a note that defines none, and for no note at all", () => {+ expect(resolvePromotedAttributes(collection([]), [ { name: "dueDate" } ])).toEqual([]);+ expect(resolvePromotedAttributes(undefined, undefined)).toEqual([]);+ });++ /** A definition names its kind before the colon; anything else is not one to draw. */+ it("passes over a definition of a kind it cannot draw", () => {+ const resolved = resolvePromotedAttributes(+ collection([ definition("dueDate"), definition("child:label:x") ]), undefined);++ expect(resolved).toEqual([]);+ });++ /**+ * An item draws every attribute it has a definition for, promoted or not, and a collection+ * carrying `#hidePromotedAttributes` reports no promoted ones at all: reading the promoted+ * subset would leave both out of the reader's hands.+ */+ it("lists a definition that is not promoted", () => {+ const resolved = resolvePromotedAttributes(collection([+ definition("label:dueDate", { alias: "Due" }),+ definition("label:internal", { isPromoted: false, value: "single,text" })+ ]), undefined);++ expect(resolved.map((attribute) => attribute.name)).toEqual([ "dueDate", "internal" ]);+ });++ /** A definition that does not pass down describes the collection alone, never its items. */+ it("leaves out a definition that is not inheritable", () => {+ const resolved = resolvePromotedAttributes(collection([+ definition("label:dueDate"),+ definition("label:boardSetting", { isInheritable: false })+ ]), undefined);++ expect(resolved.map((attribute) => attribute.name)).toEqual([ "dueDate" ]);+ });++ /** What the collection draws itself is not the reader's to arrange. */+ it("leaves out what the caller names as its own", () => {+ const resolved = resolvePromotedAttributes(+ collection(DEFINED), [ { name: "owner" } ], [ "owner" ]);++ expect(resolved.map((attribute) => attribute.name))+ .toEqual([ "dueDate", "requiresResearch" ]);+ });++ /** Two notes in the chain can define the same attribute; the nearer one is what applies. */+ it("keeps the first of two definitions of one name", () => {+ const resolved = resolvePromotedAttributes(collection([+ definition("label:dueDate", { alias: "Due" }),+ definition("label:dueDate", { alias: "Deadline", noteId: "template1" })+ ]), undefined);++ expect(resolved.map((attribute) => attribute.title)).toEqual([ "Due" ]);+ });+});diff --git a/apps/client/src/widgets/collections/promoted_attributes.ts b/apps/client/src/widgets/collections/promoted_attributes.tsnew file mode 100644index 0000000000..453cb5c359--- /dev/null+++ b/apps/client/src/widgets/collections/promoted_attributes.ts@@ -0,0 +1,128 @@+import type { BulkAction } from "@triliumnext/commons";++import type FNote from "../../entities/fnote";+import { executeBulkActions } from "../../services/bulk_action";++/** How one promoted attribute is shown, as a collection's view config stores it. */+export interface PromotedAttributeSetting {+ /** The attribute name without its `label:` or `relation:` prefix. */+ name: string;+ /** Whether the attribute is kept off the items. Absent while it is shown. */+ hidden?: boolean;+}++/** One promoted attribute a collection offers, resolved against what its view config stores. */+export interface PromotedAttribute {+ /** The name the values are keyed by, `dueDate` for instance. */+ name: string;+ /** The definition the collection note carries, `label:dueDate` for instance. */+ definitionName: string;+ type: "label" | "relation";+ /** What the reader sees: the definition's alias, or the name where it gives none. */+ title: string;+ /** Whether the attribute is kept off the items. */+ hidden: boolean;+ /** The definition as stored, which the attribute editor is handed to edit. */+ definitionValue: string;+ /** Whether the note that defines it is the collection itself rather than an ancestor. */+ isOwned: boolean;+ /**+ * Whether the definition passes to the notes below. Always true for a resolved attribute, and+ * held so that the editor is handed the definition as it stands.+ */+ isInheritable: boolean;+}++/**+ * The attributes a collection can show on its items, in the order the reader put them.+ *+ * The stored settings lead, in their own order, and anything the note has gained since is appended+ * and shown: an attribute nobody has arranged is one the reader has yet to see. What the settings+ * name but the note no longer defines is left out, so writing the result back prunes the config.+ *+ * Read from `getAttributeDefinitions()` rather than from the promoted ones: a definition that is+ * not promoted is still drawn on an item, only without an alias, and a note carrying+ * `#hidePromotedAttributes` (which a board is usually given) reports no promoted ones at all.+ *+ * Only the inheritable definitions are listed. One that is not describes the collection note alone+ * and never reaches the items, so there is nothing about it for the reader to arrange.+ */+export function resolvePromotedAttributes(+ note: FNote | null | undefined,+ settings: PromotedAttributeSetting[] | undefined,+ /** Names the collection draws itself, such as the label a board groups by. */+ ignored: string[] = []+): PromotedAttribute[] {+ const defined = new Map<string, PromotedAttribute>();++ for (const definition of note?.getAttributeDefinitions() ?? []) {+ const [ type, name ] = definition.name.split(":", 2);+ if ((type !== "label" && type !== "relation") || !name || defined.has(name)+ || ignored.includes(name) || !definition.isInheritable) {+ continue;+ }++ defined.set(name, {+ name,+ definitionName: definition.name,+ type,+ title: definition.getDefinition()?.promotedAlias || name,+ hidden: false,+ definitionValue: definition.value,+ isOwned: definition.noteId === note?.noteId,+ isInheritable: definition.isInheritable+ });+ }++ const ordered: PromotedAttribute[] = [];+ for (const setting of settings ?? []) {+ const attribute = defined.get(setting.name);+ if (attribute && !ordered.includes(attribute)) {+ attribute.hidden = !!setting.hidden;+ ordered.push(attribute);+ }+ }++ for (const attribute of defined.values()) {+ if (!ordered.includes(attribute)) {+ ordered.push(attribute);+ }+ }++ return ordered;+}++/** The attributes drawn on an item, in order, for a view showing their values. */+export function visiblePromotedAttributeNames(attributes: PromotedAttribute[]) {+ return attributes.filter((attribute) => !attribute.hidden).map((attribute) => attribute.name);+}++/** What a collection stores for the attributes it has resolved. */+export function storedPromotedAttributes(attributes: PromotedAttribute[]): PromotedAttributeSetting[] {+ return attributes.map(({ name, hidden }) => hidden ? { name, hidden } : { name });+}++/**+ * Renames an attribute on the collection and everything under it, so the values follow the+ * definition they were written against.+ */+export function renameAttributeInSubtree(+ parentNoteId: string, type: "label" | "relation", oldName: string, newName: string+) {+ const action: BulkAction = type === "label"+ ? { name: "renameLabel", oldLabelName: oldName, newLabelName: newName }+ : { name: "renameRelation", oldRelationName: oldName, newRelationName: newName };++ return executeBulkActions([ parentNoteId ], [ action ], { includeDescendants: true });+}++/** Deletes an attribute from the collection and everything under it. */+export function deleteAttributeInSubtree(+ parentNoteId: string, type: "label" | "relation", name: string+) {+ const action: BulkAction = type === "label"+ ? { name: "deleteLabel", labelName: name }+ : { name: "deleteRelation", relationName: name };++ return executeBulkActions([ parentNoteId ], [ action ], { includeDescendants: true });+}diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.css b/apps/client/src/widgets/react/PromotedAttributesCard.cssnew file mode 100644index 0000000000..ff13843f64--- /dev/null+++ b/apps/client/src/widgets/react/PromotedAttributesCard.css@@ -0,0 +1,19 @@+.tn-card.promoted-attributes-card {+ margin-block-start: 24px;++ /* The name takes the free space, pushing the edit button and the toggle to the trailing edge. */+ .promoted-attribute-name {+ flex-grow: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .promoted-attribute-edit {+ flex-shrink: 0;+ }++ .switch-widget {+ flex-shrink: 0;+ }+}diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx b/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsxnew file mode 100644index 0000000000..daaacdb4d1--- /dev/null+++ b/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx@@ -0,0 +1,369 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import Component from "../../components/component";+import type FNote from "../../entities/fnote";+import LoadResults from "../../services/load_results";+import type { AttributeDetailOpts } from "../attribute_widgets/attribute_detail";+import type { PromotedAttribute, PromotedAttributeSetting } from "../collections/promoted_attributes";+import PromotedAttributesCard from "./PromotedAttributesCard";+import { ParentComponent } from "./react_utils";++// i18next is never initialised under test, so every label would read as undefined.+vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));++const mocks = vi.hoisted(() => ({+ setLabel: vi.fn(),+ removeOwned: vi.fn(async () => {}),+ bulk: vi.fn(async () => {}),+ /** The editor the card opens, which the test drives through the callbacks it was given. */+ detail: { opts: null as AttributeDetailOpts | null, callbacks: {} as Record<string, Function> }+}));++vi.mock("../../services/attributes", () => ({+ default: {+ setLabel: mocks.setLabel,+ // Every change in these tests is one the card should answer to.+ isAffecting: () => true+ },+ removeOwnedAttributesByNameOrType: mocks.removeOwned+}));++vi.mock("../../services/bulk_action", () => ({ executeBulkActions: mocks.bulk }));++// The editor is tested where it lives; what the card answers for is what it hands over and what it+// writes once the editor reports a definition.+vi.mock("../attribute_widgets/attribute_detail", () => ({+ AttributeDetail: (props: { opts: AttributeDetailOpts | null }) => {+ mocks.detail.opts = props.opts;+ mocks.detail.callbacks = props as unknown as Record<string, Function>;+ return props.opts ? <div className="attribute-detail-stub" /> : null;+ }+}));++/** A definition as the collection note carries it. */+function definition(name: string, { alias, value = "promoted,single,text" }: {+ alias?: string, value?: string+} = {}) {+ return {+ name,+ value,+ noteId: "board1",+ isInheritable: true,+ getDefinition: () => ({ isPromoted: true, promotedAlias: alias })+ };+}++let defined = [ definition("label:dueDate", { alias: "Due" }), definition("label:owner") ];++const NOTE = {+ noteId: "board1",+ getAttributeDefinitions: () => defined+} as unknown as FNote;++describe("PromotedAttributesCard", () => {+ let container: HTMLElement;+ let host: Component;+ let stored: PromotedAttribute[][];+ let settings: PromotedAttributeSetting[] | undefined;++ beforeEach(() => {+ vi.clearAllMocks();+ stored = [];+ settings = undefined;+ defined = [ definition("label:dueDate", { alias: "Due" }), definition("label:owner") ];+ mocks.detail.opts = null;+ host = new Component();+ container = document.body.appendChild(document.createElement("div"));+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ it("lists what the note defines, named as the definitions name them", () => {+ draw();++ expect(names()).toEqual([ "Due", "owner" ]);+ expect(shown()).toEqual([ true, true ]);+ });++ it("follows the order the settings give, and turns off what they hide", () => {+ settings = [ { name: "owner", hidden: true }, { name: "dueDate" } ];+ draw();++ expect(names()).toEqual([ "owner", "Due" ]);+ expect(shown()).toEqual([ false, true ]);+ });++ it("reports the whole list in its new order", () => {+ draw();++ press(segments()[0], "ArrowDown", { ctrlKey: true });++ expect(stored.at(-1)?.map((attribute) => attribute.name)).toEqual([ "owner", "dueDate" ]);+ expect(names()).toEqual([ "owner", "Due" ]);+ });++ it("hides an attribute without taking it off the list, and shows it again", () => {+ draw();++ toggle(0);+ expect(stored.at(-1)).toEqual([+ expect.objectContaining({ name: "dueDate", hidden: true }),+ expect.objectContaining({ name: "owner", hidden: false })+ ]);+ expect(shown()).toEqual([ false, true ]);++ toggle(0);+ expect(stored.at(-1)?.[0].hidden).toBe(false);+ });++ describe("the attribute editor", () => {+ it("opens on the definition the entry stands for", () => {+ draw();++ edit(0);++ expect(mocks.detail.opts?.attribute).toEqual({+ type: "label",+ name: "label:dueDate",+ value: "promoted,single,text",+ isInheritable: true+ });+ // Portalled to the page, so it stands over the dialog the card is in.+ expect(document.body.querySelector(".attribute-detail-stub")).toBeTruthy();+ });++ it("writes what the editor reports back to the note", async () => {+ draw();+ edit(0);++ await save({+ type: "label", name: "label:dueDate", value: "promoted,single,date",+ isInheritable: true+ });++ expect(mocks.setLabel)+ .toHaveBeenCalledWith("board1", "label:dueDate", "promoted,single,date", true);+ expect(mocks.bulk).not.toHaveBeenCalled();+ // Nothing is removed: the definition keeps its name and its inheritance.+ expect(mocks.removeOwned).not.toHaveBeenCalled();+ expect(mocks.detail.opts).toBeNull();+ });++ /** The values were written against the old name, so they are renamed with it. */+ it("takes the values with it when the definition is renamed", async () => {+ draw();+ edit(0);++ await save({+ type: "label", name: "label:deadline", value: "promoted,single,text",+ isInheritable: true+ });++ expect(mocks.bulk).toHaveBeenCalledWith(+ [ "board1" ],+ [ { name: "renameLabel", oldLabelName: "dueDate", newLabelName: "deadline" } ],+ { includeDescendants: true });+ // The definition it was renamed from goes, and the new one is written.+ expect(mocks.removeOwned).toHaveBeenCalledWith(NOTE, "label", "label:dueDate");+ expect(mocks.setLabel)+ .toHaveBeenCalledWith("board1", "label:deadline", "promoted,single,text", true);+ });++ it("takes the definition and its values away when the editor deletes it", async () => {+ draw();+ edit(1);++ await act(async () => {+ mocks.detail.callbacks.onDelete();+ await flush();+ });++ expect(mocks.bulk).toHaveBeenCalledWith(+ [ "board1" ],+ [ { name: "deleteLabel", labelName: "owner" } ],+ { includeDescendants: true });+ expect(mocks.removeOwned).toHaveBeenCalledWith(NOTE, "label", "label:owner");+ });++ /**+ * `set-attribute` writes the value of a definition that already exists and nothing else,+ * so an inheritance the reader changed would be dropped by a plain write.+ */+ it("writes the definition afresh when its inheritance changed", async () => {+ draw();+ edit(0);++ await save({+ type: "label", name: "label:dueDate", value: "promoted,single,text",+ isInheritable: false+ });++ expect(mocks.removeOwned).toHaveBeenCalledWith(NOTE, "label", "label:dueDate");+ expect(mocks.setLabel)+ .toHaveBeenCalledWith("board1", "label:dueDate", "promoted,single,text", false);+ // Only the definition is rewritten; the values on the items are untouched.+ expect(mocks.bulk).not.toHaveBeenCalled();+ });++ it("writes nothing where the editor was dismissed or reported nothing", async () => {+ draw();+ edit(0);++ act(() => mocks.detail.callbacks.onDismiss());+ expect(mocks.detail.opts).toBeNull();++ edit(0);+ await act(async () => {+ mocks.detail.callbacks.onSaveAndClose();+ await flush();+ });++ expect(mocks.setLabel).not.toHaveBeenCalled();+ expect(mocks.bulk).not.toHaveBeenCalled();+ expect(mocks.removeOwned).not.toHaveBeenCalled();+ });+ });++ describe("creating one", () => {+ it("opens the editor on a new definition, named for the reader to change", () => {+ draw();++ act(() => { adder()?.click(); });++ expect(mocks.detail.opts?.attribute)+ .toEqual({ type: "label", name: "label:myLabel", value: "promoted,single,text", isInheritable: true });+ expect(mocks.detail.opts?.focus).toBe("name");+ // Nothing is listed until the note reports what was made.+ expect(names()).toEqual([ "Due", "owner" ]);+ expect(stored).toEqual([]);+ });++ it("lists what was made once the note reports it, at the end", async () => {+ draw();+ act(() => { adder()?.click(); });++ await save({+ type: "label", name: "label:priority", value: "promoted,single,text",+ isInheritable: true+ });+ defined = [ ...defined, definition("label:priority") ];+ await reported();++ expect(names()).toEqual([ "Due", "owner", "priority" ]);+ });++ /** A definition the reader left unpromoted is not one the items can show. */+ it("leaves out a definition that is not promoted", async () => {+ draw();+ act(() => { adder()?.click(); });++ await save({+ type: "label", name: "label:internal", value: "single,text", isInheritable: true+ });+ await reported();++ expect(names()).toEqual([ "Due", "owner" ]);+ });++ it("drops an attribute the note no longer defines, keeping the order of the rest", async () => {+ settings = [ { name: "owner" }, { name: "dueDate" } ];+ draw();++ defined = [ definition("label:dueDate", { alias: "Due" }) ];+ await reported();++ expect(names()).toEqual([ "Due" ]);+ });+ });++ // #region The card, and what the test does to it++ function draw() {+ act(() => {+ render(+ <ParentComponent.Provider value={host}>+ <PromotedAttributesCard+ heading="Promoted attributes"+ instruction="Pick what the items show."+ note={NOTE}+ settings={settings}+ onChange={(attributes) => stored.push(attributes)}+ />+ </ParentComponent.Provider>,+ container);+ });+ }++ function segments() {+ return [ ...container.querySelectorAll<HTMLElement>(".tn-sortable-segment") ];+ }++ function names() {+ return segments().map((segment) =>+ segment.querySelector(".promoted-attribute-name")?.textContent);+ }++ /** Which entries are drawn as shown on the items, read from their toggles. */+ function shown() {+ return segments().map((segment) =>+ !!segment.querySelector(".switch-button")?.classList.contains("on"));+ }++ function toggle(index: number) {+ act(() => { segments()[index].querySelector<HTMLElement>(".switch-button")?.click(); });+ }++ function edit(index: number) {+ act(() => {+ segments()[index].querySelector<HTMLElement>(".promoted-attribute-edit")?.click();+ });+ }++ function adder() {+ return container.querySelector<HTMLElement>(".tn-sortable-adder");+ }++ /** The editor reporting a definition and being told to save it. */+ async function save(definition: unknown) {+ await act(async () => {+ mocks.detail.callbacks.onAttributesChanged([ definition ]);+ mocks.detail.callbacks.onSaveAndClose();+ await flush();+ });+ }++ /** The app reporting an attribute change, which is how the card hears of a definition. */+ async function reported() {+ const results = new LoadResults([ {+ entityName: "attributes",+ entityId: "attr1",+ entity: { attributeId: "attr1", noteId: "board1", type: "label", name: "label:x" }+ } as never ]);+ results.addAttribute("attr1", "other");++ await act(async () => {+ host.handleEvent("entitiesReloaded", { loadResults: results });+ await flush();+ });+ }++ async function flush() {+ for (let step = 0; step < 4; step++) {+ await Promise.resolve();+ }+ }++ function press(target: Element, key: string, options: KeyboardEventInit = {}) {+ act(() => {+ target.dispatchEvent(+ new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...options }));+ });+ }++ // #endregion+});diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.tsx b/apps/client/src/widgets/react/PromotedAttributesCard.tsxnew file mode 100644index 0000000000..2a95216de6--- /dev/null+++ b/apps/client/src/widgets/react/PromotedAttributesCard.tsx@@ -0,0 +1,230 @@+import "./PromotedAttributesCard.css";++import { createPortal } from "preact/compat";+import { useCallback, useMemo, useRef, useState } from "preact/hooks";++import type FNote from "../../entities/fnote";+import type { Attribute } from "../../services/attribute_parser";+import attributes, { removeOwnedAttributesByNameOrType } from "../../services/attributes";+import { t } from "../../services/i18n";+import {+ AttributeDetail, type AttributeDetailOpts+} from "../attribute_widgets/attribute_detail";+import {+ deleteAttributeInSubtree, type PromotedAttribute, type PromotedAttributeSetting,+ renameAttributeInSubtree, resolvePromotedAttributes, storedPromotedAttributes+} from "../collections/promoted_attributes";+import ActionButton from "./ActionButton";+import FormToggle from "./FormToggle";+import { useTriliumEvent } from "./hooks";+import Icon from "./Icon";+import { type SortableItem, SortableCard } from "./SortableCard";++/** The definition a new attribute starts from, which the reader names in the editor. */+const NEW_DEFINITION: Attribute = {+ type: "label",+ name: "label:myLabel",+ value: "promoted,single,text",+ isInheritable: true+};++export interface PromotedAttributesCardProps {+ heading: string;+ /** Explains what arranging the attributes does. Shown under the heading. */+ instruction: string;+ /** The collection that defines them, and the note an attribute created here is written to. */+ note: FNote;+ /** The order and what is hidden, as the collection's view config stores it. */+ settings: PromotedAttributeSetting[] | undefined;+ /** Attributes the collection draws itself, such as the label a board groups by. */+ ignored?: string[];+ /** Called with the whole list after every change, for the caller to store. */+ onChange: (attributes: PromotedAttribute[]) => void;+}++/**+ * The promoted attributes a collection shows on its items, in the order they are shown.+ *+ * The reader reorders the list, turns an attribute off without deleting it, and edits or creates a+ * definition through the attribute editor. The definitions belong to `note`; the order and what is+ * hidden belong to the caller, which stores whatever `onChange` reports.+ */+export default function PromotedAttributesCard({+ heading, instruction, note, settings, ignored, onChange+}: PromotedAttributesCardProps) {+ const [ shown, setShown ] = useState(() => resolvePromotedAttributes(note, settings, ignored));+ const [ detail, setDetail ] = useState<AttributeDetailOpts | null>(null);+ /** What the editor last reported, which is what a save writes. */+ const edited = useRef<Attribute>();+ /** What the editor was handed, against which a renamed definition is recognised. */+ const original = useRef<Attribute>();++ // A definition created, renamed or deleted here arrives as an attribute change like any other,+ // and the order the reader has put the rest in is kept across it.+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {+ const affects = loadResults.getAttributeRows()+ .some((attribute) => attributes.isAffecting(attribute, note));+ if (affects) {+ setShown((was) =>+ resolvePromotedAttributes(note, storedPromotedAttributes(was), ignored));+ }+ });++ const items = useMemo(() => shown.map((attribute) => ({+ key: attribute.name,+ caption: attribute.title,+ icon: attribute.type === "relation" ? "bx bx-transfer" : "bx bx-tag"+ })), [ shown ]);++ const store = useCallback((next: PromotedAttribute[]) => {+ setShown(next);+ onChange(next);+ }, [ onChange ]);++ const reorder = useCallback((order: SortableItem[]) => {+ const byName = new Map(shown.map((attribute) => [ attribute.name, attribute ]));+ store(order.flatMap((item) => {+ const attribute = byName.get(item.key);+ return attribute ? [ attribute ] : [];+ }));+ }, [ shown, store ]);++ const setHidden = useCallback((name: string, hidden: boolean) => {+ store(shown.map((attribute) =>+ attribute.name === name ? { ...attribute, hidden } : attribute));+ }, [ shown, store ]);++ /** Opens the editor on a definition, or on a new one where none is given. */+ const openEditor = useCallback((event: MouseEvent | undefined, attribute?: PromotedAttribute) => {+ const definition: Attribute = attribute+ ? {+ type: "label",+ name: attribute.definitionName,+ value: attribute.definitionValue,+ isInheritable: attribute.isInheritable+ }+ : { ...NEW_DEFINITION };++ original.current = attribute ? { ...definition } : undefined;+ edited.current = undefined;+ setDetail({+ attribute: definition,+ allAttributes: [ definition ],+ isOwned: true,+ // Where the press was, or below the top of the page for one made from the keyboard.+ x: event?.pageX ?? 0,+ y: event?.pageY ?? 150,+ focus: attribute ? undefined : "name",+ hideMultiplicity: true+ });+ }, []);++ /**+ * Writes what the editor was left holding.+ *+ * A renamed definition takes its values with it, so the items keep what they carry. The+ * definition it was renamed from is removed, and so is one whose inheritance changed:+ * `set-attribute` writes the value of a definition that already exists and nothing else, so+ * the new inheritance would be dropped unless the definition is written afresh.+ */+ const save = useCallback(async () => {+ const definition = edited.current;+ const was = original.current;+ setDetail(null);+ if (!definition?.name.includes(":")) {+ return;+ }++ const [ type, name ] = definition.name.split(":", 2) as [ "label" | "relation", string ];+ const isRenamed = !!was && was.name !== definition.name;+ if (isRenamed && was) {+ const [ , previous ] = was.name.split(":", 2);+ await renameAttributeInSubtree(note.noteId, type, previous, name);+ }++ if (was && (isRenamed || was.isInheritable !== definition.isInheritable)) {+ await removeOwnedAttributesByNameOrType(note, "label", was.name);+ }++ await attributes.setLabel(+ note.noteId, definition.name, definition.value, definition.isInheritable);+ }, [ note ]);++ /** Takes the definition away, and with it the values written against it. */+ const remove = useCallback(async () => {+ const definition = original.current;+ setDetail(null);+ if (!definition?.name.includes(":")) {+ return;+ }++ const [ type, name ] = definition.name.split(":", 2) as [ "label" | "relation", string ];+ await deleteAttributeInSubtree(note.noteId, type, name);+ await removeOwnedAttributesByNameOrType(note, "label", definition.name);+ }, [ note ]);++ return (+ <>+ <SortableCard+ className="promoted-attributes-card"+ heading={heading}+ description={instruction}+ items={items}+ onChange={reorder}+ // The grip leads, so the trailing edge is left to the toggle each entry carries.+ gripPlacement="start"+ renderItem={(item) => {+ const attribute = shown.find((candidate) => candidate.name === item.key);+ return attribute && (+ <>+ {item.icon && <Icon icon={item.icon} />}+ <span className="promoted-attribute-name">{item.caption}</span>++ <ActionButton+ className="promoted-attribute-edit"+ icon="bx bx-edit"+ text={t("promoted_attributes.edit_attribute")}+ onClick={(event) => {+ event.stopPropagation();+ openEditor(event, attribute);+ }}+ />++ <FormToggle+ currentValue={!attribute.hidden}+ switchOnTooltip={t("promoted_attributes.shown_on_items")}+ switchOffTooltip={t("promoted_attributes.hidden_from_items")}+ onChange={(visible) => setHidden(attribute.name, !visible)}+ />+ </>+ );+ }}+ itemCreationButtons={[+ {+ label: t("promoted_attributes.create_attribute"),+ icon: "bx bx-plus",+ // The editor answers for what is made, and the definition it writes arrives+ // as an attribute change: one that is not promoted resolves to nothing and+ // so is never listed.+ onCreateItem: (event) => {+ openEditor(event);+ return undefined;+ }+ }+ ]}+ />++ {createPortal(+ <AttributeDetail+ opts={detail}+ currentNoteId={note.noteId}+ onDismiss={() => setDetail(null)}+ onCancel={() => setDetail(null)}+ onAttributesChanged={([ definition ]) => { edited.current = definition; }}+ onSaveAndClose={save}+ onDelete={remove}+ />,+ document.body)}+ </>+ );+}diff --git a/apps/client/src/widgets/react/SortableCard.tsx b/apps/client/src/widgets/react/SortableCard.tsxindex 4f366f1425..7337420112 100644--- a/apps/client/src/widgets/react/SortableCard.tsx+++ b/apps/client/src/widgets/react/SortableCard.tsx@@ -62,7 +62,8 @@ export interface ItemCreationButton<T extends SortableItem> {icon?: string;/** Turns the button off, for a caller that cannot make an entry yet. */disabled?: boolean;- onCreateItem: () => T | undefined | Promise<T | undefined>;+ /** Answers with the entry to add, or with nothing where none was made. */+ onCreateItem: (event?: MouseEvent) => T | undefined | Promise<T | undefined>;}export interface SortableCardProps<T extends SortableItem> extends CardProps {@@ -387,8 +388,10 @@ export function SortableCard<T extends SortableItem>({* Creates an entry at `at`, or appends it when no index is given. An entry created among the* others takes the focus; an appended one leaves it on the button, so several can be made.*/- const add = useCallback(async (create: ItemCreationButton<T>["onCreateItem"], at?: number) => {- const created = await create();+ const add = useCallback(async (+ create: ItemCreationButton<T>["onCreateItem"], at?: number, event?: MouseEvent+ ) => {+ const created = await create(event);if (!created) {return;}@@ -589,7 +592,7 @@ export function SortableCard<T extends SortableItem>({<span>{button.label}</span></>}disabled={button.disabled}- onClick={() => add(button.onCreateItem)}+ onClick={(event) => add(button.onCreateItem, undefined, event)}/>))}</section>diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.tsx b/apps/client/src/widgets/react/TemplateSelectionCard.tsxindex b301ec985d..d4633b7396 100644--- a/apps/client/src/widgets/react/TemplateSelectionCard.tsx+++ b/apps/client/src/widgets/react/TemplateSelectionCard.tsx@@ -145,6 +145,7 @@ export default function TemplateSelectionCard({return (<SortableCard+ className="template-selection-card"heading={heading}description={instruction}items={items}diff --git a/packages/commons/src/lib/script_api_preact.ts b/packages/commons/src/lib/script_api_preact.tsindex b797aa93a8..eeb991202b 100644--- a/packages/commons/src/lib/script_api_preact.ts+++ b/packages/commons/src/lib/script_api_preact.ts@@ -415,7 +415,7 @@ interface ItemCreationButton<T extends SortableItem> {icon?: string;/** Turns the button off, for a caller that cannot make an entry yet. */disabled?: boolean;- onCreateItem: () => T | undefined | Promise<T | undefined>;+ onCreateItem: (event?: MouseEvent) => T | undefined | Promise<T | undefined>;}interface SortableCardProps<T extends SortableItem> {/** See `CardProps`: the words a filter finds the card by, and whether it is filter-only. */