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(attributes): edit a multi-valued label as chips in one field
Elian Doran51ff467353e7
diff --git a/apps/client/src/stylesheets/theme-next/shell.css b/apps/client/src/stylesheets/theme-next/shell.cssindex 1d3b47b9dd..39d1cdb17c 100644--- a/apps/client/src/stylesheets/theme-next/shell.css+++ b/apps/client/src/stylesheets/theme-next/shell.css@@ -1553,6 +1553,23 @@ div.promoted-attribute-cell div.input-group {padding: 1px 6px;}+/*+ * The field of a label holding several values, which in this theme sits inside a card of its own. The+ * card is the frame — as it already is for the group around a single value's box, whose input gives up+ * its border and background here — so the field brings none, a second rounded edge just within the+ * first reading as two boxes where there is one.+ *+ * The border is kept and made invisible rather than dropped, so the chips sit where they would in a+ * theme that does frame the field.+ */+div.promoted-attribute-cell div.promoted-attribute-values {+ min-height: auto;++ > .tn-field {+ border-color: transparent;+ }+}+div.promoted-attribute-cell input {padding: 2px 8px;font-weight: 500;diff --git a/apps/client/src/widgets/PromotedAttributes.css b/apps/client/src/widgets/PromotedAttributes.cssindex 9ab82358e1..8afa5813e6 100644--- a/apps/client/src/widgets/PromotedAttributes.css+++ b/apps/client/src/widgets/PromotedAttributes.css@@ -65,3 +65,32 @@ body.experimental-feature-new-layout .promoted-attributes-container {text-align: right;width: 120px;}++/*+ * A label holding several values: one field carrying the whole set as chips, where the other kinds+ * carry a single box. Laid out as the group around a single field is — the same gap after the name,+ * the same height to sit against — so a note mixing the two reads as one grid rather than two.+ *+ * It is given room to grow across as well: chips take the width of the words on them, and a field+ * clamped to a box's width would wrap after the first of them.+ */+.promoted-attribute-cell > .promoted-attribute-values {+ display: flex;+ flex: 1;+ align-items: center;+ min-height: 40px;+ min-width: 250px;+ margin-inline-start: 10px;+ padding: 1px 0;++ > * {+ flex: 1;+ }+}++/* A number is read right-aligned in a box of its own; a chip is as wide as the number on it, and+ pushing the text to its trailing edge would only leave a gap inside the chip. */+.promoted-attribute-label-number .promoted-attribute-values input {+ text-align: start;+ width: auto;+}diff --git a/apps/client/src/widgets/PromotedAttributes.spec.tsx b/apps/client/src/widgets/PromotedAttributes.spec.tsxnew file mode 100644index 0000000000..9721ea8fc2--- /dev/null+++ b/apps/client/src/widgets/PromotedAttributes.spec.tsx@@ -0,0 +1,97 @@+import { describe, expect, it, vi } from "vitest";++// A relation's target is picked in an Algolia autocomplete bound to jQuery, which is not loaded here.+vi.mock("./react/NoteAutocomplete", () => ({ default: () => null }));++import FAttribute from "../entities/fattribute";+import type FNote from "../entities/fnote";+import froca from "../services/froca";+import noteAttributeCache from "../services/note_attribute_cache";+import { randomString } from "../services/utils";+import { buildNote } from "../test/easy-froca";+import { buildPromotedCells } from "./PromotedAttributes";++describe("buildPromotedCells", () => {+ it("gathers a label allowing several values into one field, leaving a single-valued one its own", () => {+ const note = buildNote({+ title: "Task",+ "#label:tags": "promoted,multi,text",+ "#label:status": "promoted,single,text",+ "#tags": "alpha",+ "#status": "open"+ });+ hold(note, "label", "tags", "beta");++ const cells = buildPromotedCells(note);++ // One field per definition, in the order the definitions are declared.+ expect(cells.map((cell) => cell.valueName)).toEqual([ "tags", "status" ]);+ // The set as it will be shown: chips in the one field, not a field apiece.+ expect(cells[0].values).toEqual([ "alpha", "beta" ]);+ // A single value is still edited through the very attribute holding it, so that typing into+ // the field updates that attribute rather than rewriting everything under the name.+ expect(cells[1].values).toBeUndefined();+ expect(cells[1].valueAttr.value).toBe("open");+ });++ it("shows the values in the order the note holds them, whichever order they were loaded in", () => {+ const note = buildNote({ title: "Task", "#label:tags": "promoted,multi,text" });+ hold(note, "label", "tags", "second", 20);+ hold(note, "label", "tags", "first", 10);++ expect(buildPromotedCells(note)[0].values).toEqual([ "first", "second" ]);+ });++ it("offers an empty field where the note holds nothing under the name", () => {+ const note = buildNote({ title: "Task", "#label:tags": "promoted,multi,text" });++ const [ cell ] = buildPromotedCells(note);++ // A blank value among the chips would be a chip standing for nothing, whose remove button+ // would remove nothing; the field simply opens with none.+ expect(cell.values).toEqual([]);+ expect(cell.valueAttr).toMatchObject({ attributeId: "", type: "label", name: "tags" });+ });++ it("leaves a value stored empty out of the chips", () => {+ // A definition retyped from single to multi can leave one behind, as can an attribute created+ // and never filled in.+ const note = buildNote({ title: "Task", "#label:tags": "promoted,multi,text", "#tags": "" });+ hold(note, "label", "tags", "alpha");++ expect(buildPromotedCells(note)[0].values).toEqual([ "alpha" ]);+ });++ it("keeps a relation a field per value, its values being note ids no chip can name yet", () => {+ const note = buildNote({+ title: "Task",+ "#relation:related": "promoted,multi",+ "~related": "aaaaaaaaaaaa"+ });+ hold(note, "relation", "related", "bbbbbbbbbbbb");++ const cells = buildPromotedCells(note);++ expect(cells.map((cell) => cell.valueAttr.value)).toEqual([ "aaaaaaaaaaaa", "bbbbbbbbbbbb" ]);+ // Which is what keeps the buttons for adding and removing a field beside each of them.+ expect(cells.map((cell) => cell.values)).toEqual([ undefined, undefined ]);+ });+});++/** Gives the note another attribute under a name it already carries, which one literal cannot. */+function hold(note: FNote, type: "label" | "relation", name: string, value: string, position = 100) {+ const attributeId = randomString(12);+ const attribute = new FAttribute(froca, {+ noteId: note.noteId,+ attributeId,+ type,+ name,+ value,+ position,+ isInheritable: false+ });++ froca.attributes[attributeId] = attribute;+ note.attributes.push(attributeId);+ noteAttributeCache.attributes[note.noteId]?.push(attribute);+}diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsxindex cbe7ad1146..3e8e26016c 100644--- a/apps/client/src/widgets/PromotedAttributes.tsx+++ b/apps/client/src/widgets/PromotedAttributes.tsx@@ -15,6 +15,7 @@ import server from "../services/server";import { randomString } from "../services/utils";import ws from "../services/ws";import LabelValueInput from "./attribute_widgets/label_value_input";+import MultiValueInput from "./attribute_widgets/multi_value_input";import { useNoteContext, useNoteLabel, useTriliumEvent, useUniqueName } from "./react/hooks";import NoteAutocomplete from "./react/NoteAutocomplete";@@ -24,6 +25,14 @@ interface Cell {definition: DefinitionObject;valueAttr: Attribute;valueName: string;+ /**+ * Every value the note holds under this name, for a label whose definition allows several — the+ * whole set being edited as one field of chips rather than as a field per value.+ *+ * Absent for a definition holding one value, and for a relation, which is still a field per value:+ * a relation's values are note ids, which the chips have no way of naming yet.+ */+ values?: string[];}interface CellProps {@@ -69,8 +78,9 @@ export function PromotedAttributesContent({ note, componentId, cells, setCells }}/**- * Handles the individual cells (instances for promoted attributes including empty attributes). Promoted attributes with "multiple" multiplicity will have- * each value represented as a separate cell.+ * Handles the individual cells (fields for promoted attributes, including empty ones). A label+ * allowing several values is one cell holding the whole set; a relation allowing several is still a+ * cell per value — see {@link buildPromotedCells}.** The cells are returned as a state since they can also be altered internally if needed, for example to add a new empty cell.*/@@ -83,45 +93,7 @@ export function usePromotedAttributeData(note: FNote | null | undefined, componesetCells([]);return;}- const promotedDefAttrs = note.getPromotedDefinitionAttributes();- const ownedAttributes = note.getOwnedAttributes();- // attrs are not resorted if position changes after the initial load- // promoted attrs are sorted primarily by order of definitions, but with multi-valued promoted attrs- // the order of attributes is important as well- ownedAttributes.sort((a, b) => a.position - b.position);-- const cells: Cell[] = [];- for (const definitionAttr of promotedDefAttrs) {- const [ valueType, valueName ] = extractAttributeDefinitionTypeAndName(definitionAttr.name);-- let valueAttrs = ownedAttributes.filter((el) => el.name === valueName && el.type === valueType) as Attribute[];-- if (valueAttrs.length === 0) {- valueAttrs.push({- attributeId: "",- type: valueType,- name: valueName,- value: ""- });- }-- if (definitionAttr.getDefinition().multiplicity === "single") {- valueAttrs = valueAttrs.slice(0, 1);- }-- for (const valueAttr of valueAttrs) {- const definition = definitionAttr.getDefinition();-- // if not owned, we'll force creation of a new attribute instead of updating the inherited one- if (valueAttr.noteId !== note.noteId) {- valueAttr.attributeId = "";- }-- const uniqueId = randomString();- cells.push({ definitionAttr, definition, valueAttr, valueName, uniqueId });- }- }- setCells(cells);+ setCells(buildPromotedCells(note));}useEffect(refresh, [ note, viewType, noteContext ]);@@ -134,6 +106,73 @@ export function usePromotedAttributeData(note: FNote | null | undefined, componereturn [ cells, setCells ];}+/**+ * The fields a note's promoted definitions ask for, in the order they are shown.+ *+ * One definition is usually one field. A label allowing several values is still one — the set is+ * edited as chips within it, so the note shows one field however many values it holds — while a+ * relation allowing several is a field per value, there being no chip yet that can name a note.+ *+ * A definition the note holds nothing under still gets its field, empty, so that a value can be+ * entered where there is none. For a set that is the field with no chips in it rather than a blank+ * value among them: an empty chip would stand for nothing, and pressing its remove button would+ * remove nothing.+ *+ * Exported for its own tests.+ */+export function buildPromotedCells(note: FNote): Cell[] {+ const promotedDefAttrs = note.getPromotedDefinitionAttributes();+ const ownedAttributes = note.getOwnedAttributes();+ // attrs are not resorted if position changes after the initial load+ // promoted attrs are sorted primarily by order of definitions, but with multi-valued promoted attrs+ // the order of attributes is important as well+ ownedAttributes.sort((a, b) => a.position - b.position);++ const cells: Cell[] = [];+ for (const definitionAttr of promotedDefAttrs) {+ const [ valueType, valueName ] = extractAttributeDefinitionTypeAndName(definitionAttr.name);+ const definition = definitionAttr.getDefinition();+ const held = ownedAttributes.filter((el) => el.name === valueName && el.type === valueType) as Attribute[];+ const blank: Attribute = {+ attributeId: "",+ type: valueType,+ name: valueName,+ value: ""+ };++ if (definition.multiplicity === "multi" && valueType === "label") {+ cells.push({+ definitionAttr,+ definition,+ valueName,+ // The set is written back by name rather than through any one attribute, so the field+ // carries the definition's own blank: what it needs from an attribute is the type and+ // the name, which every value under it shares.+ valueAttr: blank,+ values: held.map((attr) => attr.value).filter((value): value is string => !!value),+ uniqueId: randomString()+ });+ continue;+ }++ let valueAttrs = held.length ? held : [ blank ];+ if (definition.multiplicity === "single") {+ valueAttrs = valueAttrs.slice(0, 1);+ }++ for (const valueAttr of valueAttrs) {+ // if not owned, we'll force creation of a new attribute instead of updating the inherited one+ if (valueAttr.noteId !== note.noteId) {+ valueAttr.attributeId = "";+ }++ cells.push({ definitionAttr, definition, valueAttr, valueName, uniqueId: randomString() });+ }+ }++ return cells;+}+function PromotedAttributeCell(props: CellProps) {const { valueName, valueAttr, definition } = props.cell;const inputId = useUniqueName(`value-${valueAttr.name}`);@@ -146,11 +185,15 @@ function PromotedAttributeCell(props: CellProps) {}}, [ props.shouldFocus ]);+ const holdsSet = !!props.cell.values;+let correspondingInput: ComponentChild;let className: string | undefined;switch (valueAttr.type) {case "label":- correspondingInput = <LabelInput inputId={inputId} {...props} />;+ correspondingInput = holdsSet+ ? <MultiLabelInput inputId={inputId} {...props} />+ : <LabelInput inputId={inputId} {...props} />;className = `promoted-attribute-label-${definition.labelType}`;break;case "relation":@@ -164,7 +207,11 @@ function PromotedAttributeCell(props: CellProps) {return (<div className={clsx("promoted-attribute-cell", className)}>- {definition.labelType !== "boolean" && <label for={inputId}>{definition.promotedAlias ?? valueName}</label>}+ {/* A single flag names itself after its own box, a checkbox before its name reading as the+ sentence it is. A field of flags is a field like any other: the chips in it stand for+ values, not for the field being on, so the name goes ahead of it as elsewhere. */}+ {(definition.labelType !== "boolean" || holdsSet) &&+ <label for={inputId}>{definition.promotedAlias ?? valueName}</label>}{correspondingInput}<MultiplicityCell {...props} /></div>@@ -180,19 +227,7 @@ function LabelInput(props: CellProps & { inputId: string }) {(value: string) => updateAttribute(note, cell, componentId, value, setCells),[ cell, componentId, note, setCells ]);- // An option created straight from the field is added to the definition — on whichever note owns- // it, typically a parent or template — so every note sharing the field offers it from now on.- const createOption = useCallback(async (option: string) => {- const newDefinition = await attributes.addSelectOption(definitionAttr, option, componentId);- // The grid ignores reloads it is itself the source of (see usePromotedAttributeData), so the- // cells sharing the definition are patched in place, as updateAttribute does for a value —- // otherwise the list keeps offering the old options until something else changes.- setCells(prev => prev?.map(c =>- c.definitionAttr.attributeId === definitionAttr.attributeId- ? { ...c, definition: newDefinition }- : c- ));- }, [ definitionAttr, componentId, setCells ]);+ const createOption = useCreateSelectOption(definitionAttr, componentId, setCells);useTextLabelAutocomplete(inputId, valueAttr, definition, (e) => {if (e.currentTarget instanceof HTMLInputElement) {@@ -239,6 +274,60 @@ function LabelInput(props: CellProps & { inputId: string }) {return <div className="input-group">{input}</div>;}+/**+ * The field a label allowing several values is edited through: one field holding the whole set as+ * chips, rather than a field per value with buttons beside each for adding and removing one.+ *+ * The set is written back by name — every value under it at once — so nothing here holds an attribute+ * of its own: which attribute ends up carrying which value is neither knowable from here nor worth+ * knowing, the note holding a set rather than an ordered list of rows.+ */+function MultiLabelInput({ inputId, note, cell, componentId, setCells }: CellProps & { inputId: string }) {+ const { valueName, definition, definitionAttr, values, uniqueId } = cell;+ const labelType = definition.labelType ?? "text";+ const createOption = useCreateSelectOption(definitionAttr, componentId, setCells);++ const commit = useCallback(async (edited: string[]) => {+ await attributes.setLabelValues(note, valueName, edited, componentId);+ // The grid ignores reloads it is itself the source of (see usePromotedAttributeData), so the+ // set it shows is patched in place, as updateAttribute does for a single value — otherwise+ // the chips would not follow the value just taken.+ setCells(prev => prev?.map(c => c.uniqueId === uniqueId ? { ...c, values: edited } : c));+ }, [ note, valueName, componentId, uniqueId, setCells ]);++ return (+ <div className="promoted-attribute-values">+ <MultiValueInput+ labelType={labelType}+ values={values ?? []}+ options={definition.selectOptions}+ onCreateOption={labelType === "select" ? createOption : undefined}+ inputId={inputId}+ tabIndex={200 + definitionAttr.position}+ onCommit={commit}+ />+ </div>+ );+}++/**+ * Adds an option to a `select` definition from the very field being typed into. Written to whichever+ * note owns the definition — typically a parent or a template — so every note sharing the field+ * offers the new option from now on.+ */+function useCreateSelectOption(definitionAttr: FAttribute, componentId: string, setCells: Dispatch<StateUpdater<Cell[] | undefined>>) {+ return useCallback(async (option: string) => {+ const newDefinition = await attributes.addSelectOption(definitionAttr, option, componentId);+ // The grid ignores reloads it is itself the source of (see usePromotedAttributeData), so the+ // cells sharing the definition are patched in place, as updateAttribute does for a value —+ // otherwise the list keeps offering the old options until something else changes.+ setCells(prev => prev?.map(c =>+ c.definitionAttr.attributeId === definitionAttr.attributeId+ ? { ...c, definition: newDefinition }+ : c+ ));+ }, [ definitionAttr, componentId, setCells ]);+}function RelationInput({ inputId, ...props }: CellProps & { inputId: string }) {return (@@ -254,8 +343,16 @@ function RelationInput({ inputId, ...props }: CellProps & { inputId: string }) {);}+/**+ * The buttons beside a field that is one value of several: one adding a field after it, one removing+ * the value it holds.+ *+ * Only for the kinds still shown a field per value — which is to say relations. A label holding+ * several is one field of chips, where a value is added by entering it and removed by pressing the+ * chip it is on, so a pair of buttons beside it would offer the same twice.+ */function MultiplicityCell({ cell, cells, setCells, setCellToFocus, note, componentId }: CellProps) {- return (cell.definition.multiplicity === "multi" &&+ return (cell.definition.multiplicity === "multi" && !cell.values &&<td className="multiplicity"><PromotedActionButtonicon="bx bx-plus"diff --git a/apps/client/src/widgets/attribute_widgets/label_value_display.css b/apps/client/src/widgets/attribute_widgets/label_value_display.cssnew file mode 100644index 0000000000..0bc3ce2a0a--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/label_value_display.css@@ -0,0 +1,41 @@+/* The chips a multi-valued label is read as: the whole set, wrapping rather than being clipped one+ word in — whatever holds them growing to the tallest of what is in it. */+.label-value-chips {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px;++ > .tn-chip {+ padding-inline: 8px;+ padding-block: 1px;+ }+}++/* A flag among several, marked as a single flag's own field marks it: set is told from unset by the+ mark itself, so an unset one is drawn back rather than in a colour of its own. */+.label-flag-set {+ color: var(--muted-text-color);+}++.label-flag-unset {+ color: var(--muted-text-color);+ opacity: 0.55;+}++/*+ * A colour as its own square. Sized to the line rather than to a field's own height: a swatch as tall+ * as that would make every row of a table taller, rows being of one height whether there are colours+ * in them or not.+ */+.label-color-swatch {+ display: inline-block;+ width: 1.25em;+ height: 1.25em;+ vertical-align: middle;+ border-radius: 25%;++ /* Drawn within, so that a colour close to whatever it sits on still reads as a swatch rather than+ as a gap — and so that a value naming no colour at all is an empty swatch rather than nothing. */+ box-shadow: inset 0 0 0 1px var(--main-border-color);+}diff --git a/apps/client/src/widgets/attribute_widgets/label_value_display.tsx b/apps/client/src/widgets/attribute_widgets/label_value_display.tsxnew file mode 100644index 0000000000..eea9107255--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/label_value_display.tsx@@ -0,0 +1,120 @@+import "./label_value_display.css";++import { type LabelType } from "@triliumnext/commons";+import clsx from "clsx";++import { formatDateNumeric } from "../../utils/formatters";+import { safeUrlHref } from "../../utils/url";+import Icon from "../react/Icon";++/**+ * One stored label value as its type reads it: a date through the user's locale, a colour as its+ * swatch, a flag as its mark, a link-like value as something to follow. Anything else is the value+ * as stored, which for most types is already what it means.+ *+ * Shared by everything that shows a label value it is not editing — a table cell, a chip in a field+ * holding several — so that the same stored text reads the same way wherever it turns up.+ */+export function renderLabelValue(value: string, labelType: LabelType | undefined) {+ if (labelType === "date" || labelType === "datetime") {+ return formatLabelDate(value, labelType === "datetime");+ }++ if (labelType === "color") {+ return <ColorSwatch color={value} />;+ }++ if (labelType === "boolean") {+ return renderFlag(value);+ }++ if (labelType === "url") {+ return <a href={safeUrlHref(value)}>{value}</a>;+ }++ const scheme = labelType && LINK_SCHEMES[labelType];+ return scheme !== undefined+ ? <a href={applyLinkScheme(value, scheme)}>{value}</a>+ : value;+}++/** The schemes that make a value of a link-like type clickable; a url is linked by {@link safeUrlHref}. */+const LINK_SCHEMES: Partial<Record<LabelType, string>> = { email: "mailto:", phone: "tel:" };++/** Gives an email/phone value its clickable scheme unless it (an older value, stored as a url) already carries it. */+export function applyLinkScheme(value: unknown, scheme: string): string {+ if (typeof value !== "string" || !value) return "";+ return value.startsWith(scheme) ? value : `${scheme}${value}`;+}++/**+ * Renders a stored date label through the user's formatting locale, all-numeric so that columns stay+ * narrow and every locale shows a four-digit year.+ *+ * Unparseable values are echoed back rather than formatted: label values are free text, so a+ * date-typed field can hold anything a user typed, imported, or left behind by retyping a text+ * label as a date. `Intl.DateTimeFormat` throws a `RangeError` on an invalid date, and since this+ * can run inside a Tabulator formatter, that would take down the whole grid rather than one cell.+ */+export function formatLabelDate(value: unknown, withTime: boolean) {+ if (typeof value !== "string" || !value) return "";+ // Passed as a string so that formatDateNumeric() keeps its date-only ("YYYY-MM-DD") handling,+ // which pins the value to the local calendar day instead of shifting it across timezones.+ if (Number.isNaN(new Date(value).getTime())) return value;+ return formatDateNumeric(value, withTime);+}++/**+ * A flag as the mark a single-valued field shows, so that a field holding several reads the same way+ * as one holding the one. The stored text is kept in the tooltip, a value that is neither of the two+ * being a thing worth being able to see.+ */+function renderFlag(value: string) {+ return <Icon+ className={value === "true" ? "label-flag-set" : "label-flag-unset"}+ icon={value === "true" ? "bx bx-check" : "bx bx-x"}+ title={value}+ />;+}++/**+ * A colour as the square it is read as, wherever one is shown: a field of its own, or a chip in a+ * field holding several. Shown as a swatch rather than by flooding what holds it with the colour, so+ * that a table row keeps its own striping, hover and selection.+ *+ * The colour is the one thing about the swatch that cannot be told beforehand; its shape and size are+ * its class's. A value naming no colour is dropped by the browser, leaving the outline behind rather+ * than showing it as a colour it is not — and the text behind it is carried in the tooltip, colours+ * being read by eye and their values wanted only now and then.+ */+export function ColorSwatch({ color }: { color: string }) {+ return <span className="label-color-swatch" title={color} style={{ backgroundColor: color }} />;+}++/**+ * The values a field holding several shows, read-only: the set as the very chips it is edited as, so+ * that reading and editing show the same thing.+ */+export function LabelValueChips({ values, labelType, className }: {+ values: readonly string[];+ labelType: LabelType | undefined;+ className?: string;+}) {+ return (+ <span className={clsx("label-value-chips", className)}>+ {values.map((value) => (+ <span key={value} className="tn-chip"><span>{renderLabelValue(value, labelType)}</span></span>+ ))}+ </span>+ );+}++/**+ * The values a multi-valued label holds, as a set. Stored as an array where one is passed around as+ * such, but a single-valued definition retyped as a multi one leaves a bare string behind, and an+ * unset field leaves nothing at all — so anything else is read as the set it stands for.+ */+export function asLabelValues(value: unknown): string[] {+ if (Array.isArray(value)) return value.filter((item): item is string => typeof item === "string");+ return typeof value === "string" && value ? [ value ] : [];+}diff --git a/apps/client/src/widgets/attribute_widgets/multi_value_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/multi_value_input.spec.tsxnew file mode 100644index 0000000000..fd34ec68f9--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/multi_value_input.spec.tsx@@ -0,0 +1,92 @@+import { type LabelType } from "@triliumnext/commons";+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import MultiValueInput from "./multi_value_input";++describe("MultiValueInput", () => {+ let container: HTMLElement;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ async function mount(props: Partial<Parameters<typeof MultiValueInput>[0]> & { labelType: LabelType }) {+ await act(async () => render(+ <MultiValueInput values={[]} onCommit={vi.fn()} {...props} />, container+ ));+ return container;+ }++ it("picks a closed set from a list, and takes anything else through a box of its type", async () => {+ // A select's options and the two values a flag can be are both closed sets, so neither may be+ // typed into: a value has to be picked, which is what the list-backed box is for.+ for (const labelType of [ "select", "boolean" ] as const) {+ await mount({ labelType, options: [ "Todo", "Done" ] });+ expect(container.querySelector(".select-values-input")).not.toBeNull();+ }++ // Everything else is entered directly, through the field a single value of that type uses —+ // a calendar for a date, a dialog for a colour, a plain box for text.+ for (const [ labelType, type ] of [+ [ "text", "text" ], [ "date", "date" ], [ "datetime", "datetime-local" ],+ [ "time", "time" ], [ "color", "color" ], [ "number", "number" ], [ "email", "email" ]+ ] as const) {+ await mount({ labelType });+ expect(container.querySelector(".select-values-input")).toBeNull();+ expect(container.querySelector("input")?.type).toBe(type);+ }+ });++ it("shows each value as its type reads it, rather than as the text it is stored as", async () => {+ // `#3d5a80` names nothing to the eye, so a colour is its swatch even while being edited.+ await mount({ labelType: "color", values: [ "#3d5a80" ] });+ expect(container.querySelector(".tn-chip .label-color-swatch")?.getAttribute("title"))+ .toBe("#3d5a80");++ // And a flag is the mark a single flag's own field shows, not the word "true".+ await mount({ labelType: "boolean", values: [ "true", "false" ] });+ const marks = [ ...container.querySelectorAll(".tn-chip .tn-icon") ];+ expect(marks.map((mark) => mark.getAttribute("title"))).toEqual([ "true", "false" ]);+ expect(marks[0]?.className).toContain("label-flag-set");+ expect(marks[0]?.className).toContain("bx-check");+ expect(marks[1]?.className).toContain("label-flag-unset");+ expect(marks[1]?.className).toContain("bx-x");+ });++ it("offers a flag no way of adding to its options, there being nothing a flag can also be", async () => {+ const onCreateOption = vi.fn();+ await mount({ labelType: "boolean", values: [], onCreateOption });++ const input = container.querySelector("input");+ await act(async () => input?.focus());+ await act(async () => {+ if (input) {+ input.value = "maybe";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ }+ });+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 200));+ });++ expect(document.querySelector(".select-create-option")).toBeNull();+ expect(onCreateOption).not.toHaveBeenCalled();+ });++ it("points a host's own label and tab order at the box, whichever box that is", async () => {+ for (const labelType of [ "select", "text", "color" ] as const) {+ await mount({ labelType, inputId: "field-id", tabIndex: 207 });+ const input = container.querySelector("input");+ expect(input?.id).toBe("field-id");+ expect(input?.tabIndex).toBe(207);+ }+ });+});diff --git a/apps/client/src/widgets/attribute_widgets/multi_value_input.tsx b/apps/client/src/widgets/attribute_widgets/multi_value_input.tsxnew file mode 100644index 0000000000..d3bfc5de79--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/multi_value_input.tsx@@ -0,0 +1,83 @@+import { type LabelType } from "@triliumnext/commons";++import { t } from "../../services/i18n";+import { ColorSwatch, renderLabelValue } from "./label_value_display";+import { SelectValuesInput } from "./select_input";+import ValuesInput from "./values_input";++interface MultiValueInputProps {+ /** What kind of value the field holds, which decides how one is entered and how one reads. */+ labelType: LabelType;+ /** The values held, in the order they are shown. */+ values: readonly string[];+ /** Receives the values as they now stand, whenever one is taken or dropped. */+ onCommit(values: string[]): void;+ /** The options a `select` holds, from the definition that declared it. Ignored by other types. */+ options?: readonly string[];+ /**+ * Adds an option to a `select` field's definition, for the entry offered on text naming none of+ * them. Left out, the field picks from the options as they stand.+ */+ onCreateOption?(option: string): void | Promise<void>;+ /** Set onto the box, so that a host's own label points at the field. */+ inputId?: string;+ /** Set onto the box, for a host placing its fields in a tab order of its own. */+ tabIndex?: number;+ disabled?: boolean;+}++/**+ * The field a label holding several values is edited through: the values as chips, and a box after+ * them for the next one.+ *+ * Which box that is depends on the kind of value. A closed set — the options of a `select`, or the+ * two a flag can be — is picked from a list, so nothing typed is ever kept. Everything else is+ * entered directly, through the same box a single value of that type is typed or picked in.+ *+ * Shared by the promoted-attribute grid and the table's own cells, so that the same definition is+ * edited the same way wherever the note is opened.+ */+export default function MultiValueInput({ labelType, values, onCommit, options, onCreateOption, inputId, tabIndex, disabled }: MultiValueInputProps) {+ if (labelType === "select" || labelType === "boolean") {+ return (+ <SelectValuesInput+ options={labelType === "boolean" ? BOOLEAN_OPTIONS : options ?? []}+ values={values}+ placeholder={t("promoted_attributes.select_values_placeholder")}+ // A flag's options are the whole of what a flag can be, so there is nothing to add.+ onCreateOption={labelType === "boolean" ? undefined : onCreateOption}+ renderValue={labelType === "boolean" ? renderBooleanValue : undefined}+ inputId={inputId}+ tabIndex={tabIndex}+ disabled={disabled}+ onCommit={onCommit}+ />+ );+ }++ return (+ <ValuesInput+ labelType={labelType}+ values={values}+ placeholder={t("promoted_attributes.values_placeholder")}+ // A colour reads as its swatch even while being edited, `#3d5a80` naming nothing to the+ // eye. The rest show what is stored, which is what is being edited.+ renderValue={labelType === "color" ? renderColorValue : undefined}+ inputId={inputId}+ tabIndex={tabIndex}+ disabled={disabled}+ onCommit={onCommit}+ />+ );+}++/** The whole of what a flag can be, which is what a field of flags picks its values from. */+export const BOOLEAN_OPTIONS = [ "true", "false" ];++function renderBooleanValue(value: string) {+ return renderLabelValue(value, "boolean");+}++function renderColorValue(value: string) {+ return <ColorSwatch color={value} />;+}diff --git a/apps/client/src/widgets/attribute_widgets/select_input.tsx b/apps/client/src/widgets/attribute_widgets/select_input.tsxindex 1dcefa7241..e887a11c06 100644--- a/apps/client/src/widgets/attribute_widgets/select_input.tsx+++ b/apps/client/src/widgets/attribute_widgets/select_input.tsx@@ -128,6 +128,10 @@ interface SelectValuesInputProps {* a chip reads as the option it stands for, which is what a list of options names it.*/renderValue?(value: string): ComponentChildren;+ /** Set onto the box, so that a host's own label points at the field. */+ inputId?: string;+ /** Set onto the box, for a host placing its fields in a tab order of its own. */+ tabIndex?: number;placeholder?: string;disabled?: boolean;}@@ -140,7 +144,7 @@ interface SelectValuesInputProps {* is ever kept: an entry has to be picked, and what is left behind is dropped when the field is. The* list stays open across picks, since taking one value is rarely the end of it.*/-export function SelectValuesInput({ options, values, onCommit, onCreateOption, renderValue, placeholder, disabled }: SelectValuesInputProps) {+export function SelectValuesInput({ options, values, onCommit, onCreateOption, renderValue, inputId, tabIndex, placeholder, disabled }: SelectValuesInputProps) {const [ filter, setFilter ] = useState("");// Taken values leave the list: what is held is shown as a chip, so offering it again would only@@ -171,6 +175,8 @@ export function SelectValuesInput({ options, values, onCommit, onCreateOption, rreturn (<FormAutocomplete+ id={inputId}+ tabIndex={tabIndex}className="select-values-input"currentValue={filter}placeholder={values.length ? undefined : placeholder}diff --git a/apps/client/src/widgets/collections/table/columns.css b/apps/client/src/widgets/collections/table/columns.cssindex ae84e0c1ab..ea6ac872ee 100644--- a/apps/client/src/widgets/collections/table/columns.css+++ b/apps/client/src/widgets/collections/table/columns.css@@ -1,27 +1,8 @@-/* The chips of a multi-valued cell, read-only here: the cell shows the set, the editor edits it.- They wrap rather than being clipped one word in, a row growing to the tallest cell in it. */-.table-values {- display: flex;- flex-wrap: wrap;- align-items: center;- gap: 4px;-- > .tn-chip {- padding-inline: 8px;- padding-block: 1px;- }-}--/* A flag among several, marked as the cell of a single flag marks it: set is told from unset by the- mark itself, so an unset one is drawn back rather than in a colour of its own. */-.table-flag-set {- color: var(--muted-text-color);-}--.table-flag-unset {- color: var(--muted-text-color);- opacity: 0.55;-}+/*+ * How a cell's values read — the chips, the swatch of a colour, the mark of a flag — is dressed with+ * the values themselves, in label_value_display.css, so that a set reads the same in a cell as in the+ * note's own promoted field. Only what is the table's own is here.+ *//** The editor opens over its cell rather than inside it. A cell is as tall as one line and as wide as@@ -103,23 +84,3 @@max-height: 100%;}}--/*- * A colour cell says its colour with a swatch of its own, as its editor does, rather than by being- * filled with it: a row keeps the striping, hover and selection that a flood of colour covers over,- * and a cell reads the same whether it is being looked at or edited.- *- * Sized to the line rather than to the editor's field, a swatch as tall as that one would make every- * row in the table taller — rows being of one height, colours in them or not.- */-.table-color-swatch {- display: inline-block;- width: 1.25em;- height: 1.25em;- vertical-align: middle;- border-radius: 25%;-- /* Drawn within, so that a colour close to the row's own still reads as a swatch rather than as a- gap — and so that a value naming no colour at all is an empty swatch rather than nothing. */- box-shadow: inset 0 0 0 1px var(--main-border-color);-}diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.tsindex 7653a60969..d0bd9e074e 100644--- a/apps/client/src/widgets/collections/table/columns.spec.ts+++ b/apps/client/src/widgets/collections/table/columns.spec.ts@@ -1,9 +1,10 @@import { act } from "preact/test-utils";-import { describe, expect, it, vi } from "vitest";-import { type AttributeDefinitionInformation, buildColumnDefinitions, formatLabelDate, restoreExistingData, type ValuesEditorParams } from "./columns";import type { CellComponent, ColumnDefinition } from "tabulator-tables";+import { describe, expect, it, vi } from "vitest";import options from "../../../services/options";+import { formatLabelDate } from "../../attribute_widgets/label_value_display";+import { type AttributeDefinitionInformation, buildColumnDefinitions, restoreExistingData, type ValuesEditorParams } from "./columns";describe("restoreExistingData", () => {it("maintains important columns properties", () => {@@ -102,7 +103,7 @@ describe("restoreExistingData", () => {{ title: "#", headerSort: false, hozAlign: "center", resizable: false, frozen: true, rowHandle: false },{ field: "noteId", title: "Note ID", visible: false },{ field: "title", title: "Title", editor: "input", width: 400 }- ]+ ];const oldDefs: ColumnDefinition[] = [{ title: "#", headerSort: false, hozAlign: "center", resizable: false, rowHandle: false },{ field: "noteId", title: "Note ID", visible: false },@@ -115,7 +116,7 @@ describe("restoreExistingData", () => {it("allows hiding the row number column", () => {const newDefs: ColumnDefinition[] = [{ title: "#", headerSort: false, hozAlign: "center", resizable: false, frozen: true, rowHandle: false },- ]+ ];const oldDefs: ColumnDefinition[] = [{ title: "#", headerSort: false, hozAlign: "center", resizable: false, rowHandle: false, visible: false },];@@ -126,7 +127,7 @@ describe("restoreExistingData", () => {it("enforces size for non-resizable columns", () => {const newDefs: ColumnDefinition[] = [{ title: "#", resizable: false, width: "100px" },- ]+ ];const oldDefs: ColumnDefinition[] = [{ title: "#", resizable: false, width: "120px" },];@@ -230,7 +231,7 @@ describe("buildColumnDefinitions — colour columns", () => {// Filling the cell instead would paint over the row's own striping, hover and selection.const swatch = format("#ff2e88");- expect(swatch.className).toBe("table-color-swatch");+ expect(swatch.className).toBe("label-color-swatch");expect(swatch.style.backgroundColor).toBe("#ff2e88");expect(swatch.title).toBe("#ff2e88");@@ -386,11 +387,11 @@ describe("buildColumnDefinitions — multi-valued columns", () => {const flags = format("boolean", [ "true", "false" ]);expect([ ...flags.querySelectorAll(".tn-icon") ].map((mark) => mark.getAttribute("title"))).toEqual([ "true", "false" ]);- expect(flags.querySelector(".table-flag-set")?.className).toContain("bx-check");- expect(flags.querySelector(".table-flag-unset")?.className).toContain("bx-x");+ expect(flags.querySelector(".label-flag-set")?.className).toContain("bx-check");+ expect(flags.querySelector(".label-flag-unset")?.className).toContain("bx-x");// And a colour as the same swatch a single one is shown by.- expect(format("color", [ "#ff2e88" ]).querySelector(".table-color-swatch")?.getAttribute("title"))+ expect(format("color", [ "#ff2e88" ]).querySelector(".label-color-swatch")?.getAttribute("title")).toBe("#ff2e88");});diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsxindex 79b7209556..5aee1c57a1 100644--- a/apps/client/src/widgets/collections/table/columns.tsx+++ b/apps/client/src/widgets/collections/table/columns.tsx@@ -7,12 +7,10 @@ import { useEffect, useRef, useState } from "preact/hooks";import type { CellComponent, ColumnDefinition, EmptyCallback, FormatterParams, RowComponent, ValueBooleanCallback, ValueVoidCallback } from "tabulator-tables";import froca from "../../../services/froca.js";-import { t } from "../../../services/i18n.js";-import { formatDateNumeric } from "../../../utils/formatters.js";import { safeUrlHref } from "../../../utils/url.js";+import { applyLinkScheme, asLabelValues, ColorSwatch, formatLabelDate, LabelValueChips } from "../../attribute_widgets/label_value_display.jsx";import LabelValueInput from "../../attribute_widgets/label_value_input.jsx";-import { SelectValuesInput } from "../../attribute_widgets/select_input.jsx";-import ValuesInput from "../../attribute_widgets/values_input.jsx";+import MultiValueInput from "../../attribute_widgets/multi_value_input.jsx";import Icon from "../../react/Icon.jsx";import NoteAutocomplete from "../../react/NoteAutocomplete.jsx";import { renderReactWidget } from "../../react/react_utils.jsx";@@ -105,29 +103,6 @@ const labelTypeMappings: Record<ColumnType, Partial<ColumnDefinition>> = {}};-/** Gives an email/phone value its clickable scheme unless it (an older value, stored as a url) already carries it. */-function applyLinkScheme(value: unknown, scheme: string): string {- if (typeof value !== "string" || !value) return "";- return value.startsWith(scheme) ? value : `${scheme}${value}`;-}--/**- * Renders a stored date label through the user's formatting locale, all-numeric so that columns stay- * narrow and every locale shows a four-digit year.- *- * Unparseable values are echoed back rather than formatted: label values are free text, so a- * date-typed column can hold anything a user typed, imported, or left behind by retyping a text- * label as a date. `Intl.DateTimeFormat` throws a `RangeError` on an invalid date, and since this- * runs inside a Tabulator formatter, that would take down the whole grid rather than one cell.- */-export function formatLabelDate(value: unknown, withTime: boolean) {- if (typeof value !== "string" || !value) return "";- // Passed as a string so that formatDateNumeric() keeps its date-only ("YYYY-MM-DD") handling,- // which pins the value to the local calendar day instead of shifting it across timezones.- if (Number.isNaN(new Date(value).getTime())) return value;- return formatDateNumeric(value, withTime);-}-interface BuildColumnArgs {info: AttributeDefinitionInformation[];movableRows: boolean;@@ -382,9 +357,9 @@ function SelectEditor({ cell, success, editorParams }: EditorOpts) {}/**- * A cell holding several values is edited as the chips it shows: a select picks them from its- * options, anything else takes what is typed. Either way the set is what is being edited, so the two- * share everything around the field — how the set is gathered, and when it is handed over.+ * A cell holding several values is edited as the chips it shows, through the very field the note's own+ * promoted grid offers. All this adds is what a cell needs and a note does not: standing over the row+ * rather than in it, and saying when the edit is over.** Reporting a value as it is taken would close the editor on the first one — reporting is Tabulator's* "the edit is done" — so the set is held here and handed over once, when the cell is left.@@ -394,7 +369,7 @@ function ValuesEditor({ cell, success, editorParams }: EditorOpts) {const containerRef = useRef<HTMLDivElement>(null);useEffect(() => containerRef.current?.querySelector("input")?.focus(), []);- const [ values, setValues ] = useState<string[]>(() => asValues(cell.getValue()));+ const [ values, setValues ] = useState<string[]>(() => asLabelValues(cell.getValue()));// The set as the handler below will read it. Written as the edit is made rather than left to the// next render, because leaving the field both takes what was typed and ends the edit — in that// order, and within the one event, which a value only reachable through a render would miss.@@ -435,28 +410,16 @@ function ValuesEditor({ cell, success, editorParams }: EditorOpts) {return (<div ref={containerRef} className={clsx("table-values-editor", growsUpwards && "grows-upwards")}>- {/* A flag is picked from a closed set as a select is — its set is simply the two values- a flag has — so the two are gathered through the same field. */}- {labelType === "select" || labelType === "boolean" ? (- <SelectValuesInput- options={labelType === "boolean" ? BOOLEAN_OPTIONS : options}- values={values}- placeholder={t("promoted_attributes.select_values_placeholder")}- onCreateOption={labelType === "boolean" ? undefined : onCreateOption}- renderValue={labelType === "boolean" ? renderFlag : undefined}- onCommit={editValues}- />- ) : (- <ValuesInput- labelType={labelType === "relation" ? "text" : labelType}- values={values}- placeholder={t("promoted_attributes.values_placeholder")}- // A colour reads as its swatch even while being edited, `#3d5a80` naming nothing- // to the eye. The rest show what is stored, which is what is being edited.- renderValue={labelType === "color" ? (value) => <ColorSwatch color={value} /> : undefined}- onCommit={editValues}- />- )}+ {/* The very field the note's own promoted grid offers, so that a definition is edited the+ same way whichever way the note is opened. A relation is not yet gathered as a set, so+ one arriving here is taken as the text it is stored as. */}+ <MultiValueInput+ labelType={labelType === "relation" ? "text" : labelType}+ values={values}+ options={options}+ onCreateOption={onCreateOption}+ onCommit={editValues}+ /></div>);}@@ -464,73 +427,15 @@ function ValuesEditor({ cell, success, editorParams }: EditorOpts) {/** A multi-valued cell as the chips it is edited as, so reading and editing show the same set. */function ValuesFormatter({ cell, formatterParams }: FormatterOpts) {const { type } = formatterParams as { type?: ColumnType };- return (- <span className="table-values">- {asValues(cell.getValue()).map((value) => (- <span key={value} className="tn-chip"><span>{renderValue(value, type)}</span></span>- ))}- </span>- );-}--/** The schemes that make a value of a link-like type clickable; a url is linked by {@link safeUrlHref}. */-const LINK_SCHEMES: Partial<Record<ColumnType, string>> = { email: "mailto:", phone: "tel:" };--/** The whole of what a flag can be, which is what a column of flags picks its values from. */-const BOOLEAN_OPTIONS = [ "true", "false" ];--/**- * One value of a set, read as its type reads it — so that a set of dates is as legible as a single- * one, and a set of addresses is as clickable. Anything else is the value as stored.- */-function renderValue(value: string, type: ColumnType | undefined) {- if (type === "date" || type === "datetime") {- return formatLabelDate(value, type === "datetime");- }-- if (type === "color") {- return <ColorSwatch color={value} />;- }-- if (type === "boolean") {- return renderFlag(value);- }-- if (type === "url") {- return <a href={safeUrlHref(value)}>{value}</a>;- }-- const scheme = type && LINK_SCHEMES[type];- return scheme !== undefined- ? <a href={applyLinkScheme(value, scheme)}>{value}</a>- : value;-}--/**- * A flag as the mark a column of single flags shows, so that a cell holding several reads the same- * way as one holding the one. The stored text is kept in the tooltip, a value that is neither of the- * two being a thing worth being able to see.- */-function renderFlag(value: string) {- return <Icon- className={value === "true" ? "table-flag-set" : "table-flag-unset"}- icon={value === "true" ? "bx bx-check" : "bx bx-x"}- title={value}+ return <LabelValueChips+ values={asLabelValues(cell.getValue())}+ labelType={type === "relation" ? undefined : type}/>;}-/**- * A multi-valued cell's values. Stored as an array, but a cell can hold what an older single-valued- * definition left behind, or nothing at all, so anything else is read as the set it stands for.- */-function asValues(value: unknown): string[] {- if (Array.isArray(value)) return value.filter((item): item is string => typeof item === "string");- return typeof value === "string" && value ? [ value ] : [];-}-/** The values as one string, for comparing two sets in a sort. */function joinValues(value: unknown) {- return asValues(value).join(", ");+ return asLabelValues(value).join(", ");}/**@@ -589,10 +494,6 @@ function ColorEditor({ cell, success }: EditorOpts) {* A colour cell as the swatch its editor shows, so that reading and editing a colour look alike, and* so that the row keeps its own striping, hover and selection — all of which a cell flooded with the* colour, as Tabulator's own colour formatter fills it, hides.- *- * The value itself is carried in the tooltip rather than set beside the swatch: a column of colours is- * read by eye, and the text behind one is wanted only now and then — including where it names no- * colour at all, a cell holding whatever the label does, which the swatch alone could not say.*/function ColorFormatter({ cell }: FormatterOpts) {const value = cell.getValue();@@ -603,19 +504,6 @@ function ColorFormatter({ cell }: FormatterOpts) {return <ColorSwatch color={color} />;}-/**- * A colour as the square it is read as, wherever one is shown: a cell of its own, or a chip in a cell- * holding several.- *- * The colour is the one thing about the swatch that cannot be told beforehand; its shape and size are- * its class's. A value naming no colour is dropped by the browser, leaving the outline behind rather- * than showing it as a colour it is not — and the text behind it is carried in the tooltip, a column- * of colours being read by eye and its values wanted only now and then.- */-export function ColorSwatch({ color }: { color: string }) {- return <span className="table-color-swatch" title={color} style={{ backgroundColor: color }} />;-}-function RelationEditor({ cell, success }: EditorOpts) {const inputRef = useRef<HTMLInputElement>(null);useEffect(() => inputRef.current?.focus());