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
fix(table): let a colour column hold a set, and survive its own picker
Elian Dorana3c0b4c9fe8a
diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.tsxindex 512920cd55..f4428a1152 100644--- a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx@@ -30,7 +30,8 @@ export const LABEL_MAPPINGS: Record<LabelType, HTMLInputTypeAttribute | undefinephone: "tel"};-const DEFAULT_COLOR = "#ffffff";+/** What a colour picker shows where the value names no colour, a picker having no empty of its own. */+export const DEFAULT_COLOR = "#ffffff";/*** The button beside a link-like field, opening what the field holds: a url as a page, an email or adiff --git a/apps/client/src/widgets/attribute_widgets/values_input.css b/apps/client/src/widgets/attribute_widgets/values_input.cssnew file mode 100644index 0000000000..304abaef9c--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/values_input.css@@ -0,0 +1,15 @@+/*+ * The picker at the end of a field of colours. A colour is chosen rather than typed, so it asks for+ * no room to type in: it sits at its own size beside the chips instead of taking the line a text box+ * would, and keeps a frame of its own — a swatch with nothing around it would read as another chip.+ */+.values-input > input[type="color"].form-control {+ flex: 0 0 auto;+ /* Cleared as well as set: the field gives a box room to type in, which a picker would otherwise+ hold on to — it is the wider of the two that decides. */+ min-width: 0;+ width: 1.75em;+ height: 1.75em;+ padding: 2px;+ border: 1px solid var(--main-border-color);+}diff --git a/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/values_input.spec.tsxindex fbbd32c75e..a3d4cebe5e 100644--- a/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx+++ b/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx@@ -80,6 +80,67 @@ describe("ValuesInput", () => {expect(onCommit).toHaveBeenCalledWith([ "2026-07-29" ]);});+ it("takes a colour when the pick is settled, not through the drag, and shows it as given", async () => {+ const onCommit = vi.fn();+ const input = await mount({+ labelType: "color",+ values: [ "#ff0000" ],+ onCommit,+ renderValue: (value) => <i data-color={value} />+ });++ // Stored as text a picker cannot show, so the chip is whatever the host makes of it.+ expect(container.querySelector(".tn-chip i")?.getAttribute("data-color")).toBe("#ff0000");+ expect(input?.type).toBe("color");++ // Nothing may be written into the picker while the pick is being made: the browser takes its+ // value changing underneath an open dialog as reason to close it, losing the pick with it.+ const picker = watch(input);++ // A picker reports every shade the pointer passes through on its way to the one chosen.+ for (const shade of [ "#00ff00", "#00ee00" ]) {+ await act(async () => picker.dragTo(shade));+ }+ expect(onCommit).not.toHaveBeenCalled();++ await act(async () => {+ input?.dispatchEvent(new Event("change", { bubbles: true }));+ });+ expect(onCommit).toHaveBeenCalledWith([ "#ff0000", "#00ee00" ]);+ // Not once through the whole gesture, the settling included: a dialog can still be open when+ // it reports, and writing then is what closes it.+ expect(picker.writes()).toBe(0);+ });++ /**+ * A picker whose value can be moved as the user moves it, apart from anything the component+ * writes into it — which is what is being counted.+ */+ function watch(element: HTMLInputElement | null) {+ const own = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");+ const read = own?.get;+ const write = own?.set;+ if (!element || !read || !write) throw new Error("expected a picker holding its own value");++ let written = 0;+ Object.defineProperty(element, "value", {+ get: read,+ set(value: string) {+ written++;+ write.call(this, value);+ },+ configurable: true+ });++ return {+ writes: () => written,+ dragTo(shade: string) {+ write.call(element, shade);+ element.dispatchEvent(new Event("input", { bubbles: true }));+ }+ };+ }+it("drops the last chip on backspace in an empty box, and leaves a filled one alone", async () => {const onCommit = vi.fn();const input = await mount({ labelType: "text", values: [ "one", "two" ], onCommit });diff --git a/apps/client/src/widgets/attribute_widgets/values_input.tsx b/apps/client/src/widgets/attribute_widgets/values_input.tsxindex 82c63d55fc..6a95254b8f 100644--- a/apps/client/src/widgets/attribute_widgets/values_input.tsx+++ b/apps/client/src/widgets/attribute_widgets/values_input.tsx@@ -1,11 +1,13 @@+import "./values_input.css";+import { type LabelType } from "@triliumnext/commons";-import type { TargetedKeyboardEvent } from "preact";-import { useState } from "preact/hooks";+import type { ComponentChildren, TargetedKeyboardEvent } from "preact";+import { useEffect, useRef, useState } from "preact/hooks";import { t } from "../../services/i18n";import Chip from "../react/Chip";import FormTextBox from "../react/FormTextBox";-import { LABEL_MAPPINGS } from "./label_value_input";+import { DEFAULT_COLOR, LABEL_MAPPINGS } from "./label_value_input";interface ValuesInputProps {/** What kind of value is being entered, deciding the box the next one is typed into. */@@ -14,6 +16,11 @@ interface ValuesInputProps {values: readonly string[];/** Receives the values as they now stand, whenever one is taken or dropped. */onCommit(values: string[]): void;+ /**+ * Shows a value as something other than the text it is stored as — a colour as its swatch. Left+ * out, a chip reads as what is stored, which for most types is what is being edited anyway.+ */+ renderValue?(value: string): ComponentChildren;placeholder?: string;disabled?: boolean;}@@ -27,8 +34,35 @@ interface ValuesInputProps {* rather than quietly dropped. A value already held is not taken a second time: the chips are a set,* and two alike could not be told apart.*/-export default function ValuesInput({ labelType, values, onCommit, placeholder, disabled }: ValuesInputProps) {+export default function ValuesInput({ labelType, values, onCommit, renderValue, placeholder, disabled }: ValuesInputProps) {const [ draft, setDraft ] = useState("");+ const pickerRef = useRef<HTMLInputElement>(null);+ // A colour is picked rather than typed, so there is no Enter to end it and nothing worth keeping+ // half-entered: the pick itself is the whole gesture, and `change` is when it is settled.+ const isPicked = labelType === "color";++ // The picker holds its own value and is never told one: it is set at birth and only read from+ // after that. Anything written into it can reach a dialog that is still open — a colour input+ // reports its pick before the dialog is dismissed — and the browser takes its value changing+ // underneath as reason to close, dropping the pick. So it keeps showing the colour last taken,+ // which is also the truer thing for it to show.+ useEffect(() => {+ if (pickerRef.current) {+ pickerRef.current.value = DEFAULT_COLOR;+ }+ }, []);++ useEffect(() => {+ const picker = pickerRef.current;+ if (!picker) return;++ // Bound by hand rather than through the JSX: preact/compat — loaded module-graph-wide by any+ // compat-using import — remaps `onChange` onto the input event, which a colour picker fires+ // at every step of a drag through it, taking a chip for each shade passed over.+ const onPicked = () => take(picker.value);+ picker.addEventListener("change", onPicked);+ return () => picker.removeEventListener("change", onPicked);+ });function take(value: string) {const trimmed = value.trim();@@ -65,19 +99,28 @@ export default function ValuesInput({ labelType, values, onCommit, placeholder,disabled={disabled}onRemove={() => drop(value)}>- <span>{value}</span>+ <span>{renderValue ? renderValue(value) : value}</span></Chip>))}- <FormTextBox- type={LABEL_MAPPINGS[labelType] ?? "text"}- currentValue={draft}- // Only while the field is empty: beside chips it would read as one of them.- placeholder={values.length ? undefined : placeholder}- disabled={disabled}- onChange={setDraft}- onBlur={take}- onKeyDown={handleKeyDown}- />+ {isPicked ? (+ <input+ ref={pickerRef}+ className="form-control"+ type="color"+ disabled={disabled}+ />+ ) : (+ <FormTextBox+ type={LABEL_MAPPINGS[labelType] ?? "text"}+ currentValue={draft}+ // Only while the field is empty: beside chips it would read as one of them.+ placeholder={values.length ? undefined : placeholder}+ disabled={disabled}+ onChange={setDraft}+ onBlur={take}+ onKeyDown={handleKeyDown}+ />+ )}</div>);}diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.tsindex 2b99056b2c..1f49ebebb5 100644--- a/apps/client/src/widgets/collections/table/columns.spec.ts+++ b/apps/client/src/widgets/collections/table/columns.spec.ts@@ -302,7 +302,7 @@ describe("buildColumnDefinitions — multi-valued columns", () => {}it("edits and shows a set as chips whatever it holds, not only a set of options", () => {- for (const type of [ "text", "date", "url", "select" ] as const) {+ for (const type of [ "text", "date", "url", "select", "color" ] as const) {const column = multiColumn(type);// The type's own single-value editor would show one of the values and store back one.expect(typeof column?.editor).toBe("function");@@ -315,6 +315,49 @@ describe("buildColumnDefinitions — multi-valued columns", () => {}});+ /** Opens a multi-valued cell's editor, as Tabulator does, and puts it in the document. */+ async function editMultiCell(type: AttributeDefinitionInformation["type"], values: string[]) {+ const column = multiColumn(type);+ const editor = column?.editor;+ const params = column?.editorParams;+ if (typeof editor !== "function") throw new Error("expected an editor of its own");+ if (typeof params !== "function") throw new Error("expected the params to be a function");++ const success = vi.fn();+ let element: HTMLElement | false = false;+ await act(async () => {+ element = editor(+ { getValue: () => values } as CellComponent,+ () => {}, success, () => {}, params({} as CellComponent)+ );+ });+ if (!element) throw new Error("expected the editor to build a field");++ // Focus only means anything for an element the document holds.+ const built = element as HTMLElement;+ document.body.appendChild(built);+ return { element: built, success };+ }++ it("stays open where the focus leaves the page rather than the cell", async () => {+ const { element, success } = await editMultiCell("color", [ "#ff0000" ]);+ const picker = element.querySelector<HTMLInputElement>("input[type=color]");+ if (!picker) throw new Error("expected a colour picker");+ picker.focus();++ // A native picker's dialog takes the focus with nothing in the page gaining it. Ending the+ // edit here would take the editor down, and the dialog with it, before it reported a colour.+ picker.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));+ expect(success).not.toHaveBeenCalled();++ // Whereas the cell being left for good: nothing in the editor holds the focus any more.+ picker.blur();+ picker.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));+ expect(success).toHaveBeenCalledWith([ "#ff0000" ]);++ element.remove();+ });+it("sorts by the values a cell holds, not by the array they arrive in", () => {const sorter = multiColumn("text")?.sorter;if (typeof sorter !== "function") throw new Error("expected a sorter of its own");diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsxindex e5c78238af..f5c430f41a 100644--- a/apps/client/src/widgets/collections/table/columns.tsx+++ b/apps/client/src/widgets/collections/table/columns.tsx@@ -402,6 +402,15 @@ function ValuesEditor({ cell, success, editorParams }: EditorOpts) {// leaving it. Picking from a list does not blur at all: the list keeps the focus in the// box, which is what lets it stay open across picks.if (e.relatedTarget instanceof Node && editor.contains(e.relatedTarget)) return;++ // Nothing in the page took the focus over, and either the editor still holds it or the+ // window itself has lost it — which is what opening a native picker's dialog does. The+ // cell has not been left, and ending the edit here would take the dialog down with it+ // before it could report the colour picked.+ if (!e.relatedTarget && (!document.hasFocus() || editor.contains(document.activeElement))) {+ return;+ }+success(editedValues.current);};@@ -428,6 +437,9 @@ function ValuesEditor({ cell, success, editorParams }: EditorOpts) {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}/>)}@@ -459,6 +471,10 @@ function renderValue(value: string, type: ColumnType | undefined) {return formatLabelDate(value, type === "datetime");}+ if (type === "color") {+ return <ColorSwatch color={value} />;+ }+const scheme = type && LINK_SCHEMES[type];return scheme !== undefined? <a href={applyLinkScheme(value, scheme)}>{value}</a>@@ -546,9 +562,19 @@ function ColorFormatter({ cell }: FormatterOpts) {// A formatter hands back an element, so an unset cell is an empty one rather than nothing at all.if (!color) return <span />;- // 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.+ 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 }} />;}diff --git a/apps/client/src/widgets/collections/table/rows.spec.ts b/apps/client/src/widgets/collections/table/rows.spec.tsindex ae19d17671..f718197070 100644--- a/apps/client/src/widgets/collections/table/rows.spec.ts+++ b/apps/client/src/widgets/collections/table/rows.spec.ts@@ -31,22 +31,21 @@ describe("getAttributeDefinitionInformation", () => {"#label:due(inheritable)": "promoted,multi,date","#label:site(inheritable)": "promoted,multi,url","#label:status(inheritable)": "promoted,multi,select,options=Todo;Done",- // A flag means what it means by being there at all, so several are the same one flag;- // a colour is a single quality of the thing it describes.- "#label:done(inheritable)": "promoted,multi,boolean","#label:tint(inheritable)": "promoted,multi,color",+ // A flag means what it means by being there at all, so several are the same one flag.+ "#label:done(inheritable)": "promoted,multi,boolean","#label:owner(inheritable)": "promoted,single,text"});- // Those left out still have a column — one holding the first value, as before they were- // declared to hold many. They used to be dropped from the table altogether.+ // The one left out still has a column — holding the first value, as before it was declared+ // to hold many. It used to be dropped from the table altogether.expect(getAttributeDefinitionInformation(note)).toMatchObject([{ name: "tags", type: "text", isMulti: true },{ name: "due", type: "date", isMulti: true },{ name: "site", type: "url", isMulti: true },{ name: "status", type: "select", isMulti: true },+ { name: "tint", type: "color", isMulti: true },{ name: "done", type: "boolean", isMulti: false },- { name: "tint", type: "color", isMulti: false },{ name: "owner", type: "text", isMulti: false }]);});diff --git a/apps/client/src/widgets/collections/table/rows.ts b/apps/client/src/widgets/collections/table/rows.tsindex 6853f11c86..520a14142f 100644--- a/apps/client/src/widgets/collections/table/rows.ts+++ b/apps/client/src/widgets/collections/table/rows.ts@@ -107,11 +107,11 @@ export default function getAttributeDefinitionInformation(parentNote: FNote) {/*** The types a column can hold several values of, shown and edited as chips.*- * The two left out are the ones a set says nothing for: a flag means what it means by being there at- * all, so several of them are the same one flag; and a colour is a single quality of the thing it- * describes. A column of either shows the first value it finds, as it did before it was declared to- * hold many — better a value than a column that quietly goes missing.+ * The one left out is the one a set says nothing for: a flag means what it means by being there at+ * all, so several of them are the same one flag. Such a column shows the first value it finds, as it+ * did before it was declared to hold many — better a value than a column that quietly goes missing.*/const MULTI_VALUE_TYPES = new Set<LabelType | "relation">([- "text", "textarea", "number", "select", "date", "datetime", "time", "url", "email", "phone"+ "text", "textarea", "number", "select", "date", "datetime", "time", "url", "email", "phone",+ "color"]);