Skip to content

Build your personal knowledge base with Trilium Notes

feat(attributes): gather a relation's several targets as chips

Elian Doran86155f0bf4f9
diff --git a/apps/client/src/services/attributes.ts b/apps/client/src/services/attributes.ts
index f35af3f8be..221b07b147 100644
--- a/apps/client/src/services/attributes.ts
+++ b/apps/client/src/services/attributes.ts
@@ -118,7 +118,19 @@ function removeOwnedRelationByName(note: FNote, relationName: string) {
* the note it is written on.
*/
export async function setLabelValues(note: FNote, name: string, values: string[], componentId?: string) {
- const existing = note.getOwnedLabels(name);
+ await setAttributeValues(note, "label", name, values, componentId);
+}
+
+/**
+ * Sets the relations of one name on a note to exactly `values` — the targets' noteIds — as
+ * {@link setLabelValues} sets a set of labels.
+ */
+export async function setRelationValues(note: FNote, name: string, values: string[], componentId?: string) {
+ await setAttributeValues(note, "relation", name, values, componentId);
+}
+
+async function setAttributeValues(note: FNote, type: "label" | "relation", name: string, values: string[], componentId?: string) {
+ const existing = type === "label" ? note.getOwnedLabels(name) : note.getOwnedRelations(name);
for (const [ index, value ] of values.entries()) {
const attributeId = existing[index]?.attributeId;
@@ -127,7 +139,7 @@ export async function setLabelValues(note: FNote, name: string, values: string[]
}
await server.put(
`notes/${note.noteId}/attribute`,
- { attributeId, type: "label", name, value },
+ { attributeId, type, name, value },
componentId
);
}
@@ -322,6 +334,7 @@ export default {
setRelation,
setAttribute,
setLabelValues,
+ setRelationValues,
addSelectOption,
setBooleanWithInheritance,
removeAttributeById,
diff --git a/apps/client/src/widgets/PromotedAttributes.spec.tsx b/apps/client/src/widgets/PromotedAttributes.spec.tsx
index 9721ea8fc2..525ab4a372 100644
--- a/apps/client/src/widgets/PromotedAttributes.spec.tsx
+++ b/apps/client/src/widgets/PromotedAttributes.spec.tsx
@@ -62,7 +62,7 @@ describe("buildPromotedCells", () => {
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", () => {
+ it("gathers a relation's targets into one field, as it gathers a label's values", () => {
const note = buildNote({
title: "Task",
"#relation:related": "promoted,multi",
@@ -72,9 +72,10 @@ describe("buildPromotedCells", () => {
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 ]);
+ expect(cells).toHaveLength(1);
+ // The chips carry the targets' noteIds; naming the notes they point at is the field's affair.
+ expect(cells[0].values).toEqual([ "aaaaaaaaaaaa", "bbbbbbbbbbbb" ]);
+ expect(cells[0].valueAttr).toMatchObject({ attributeId: "", type: "relation", name: "related" });
});
});
diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsx
index 3e8e26016c..afdb0790e8 100644
--- a/apps/client/src/widgets/PromotedAttributes.tsx
+++ b/apps/client/src/widgets/PromotedAttributes.tsx
@@ -2,7 +2,7 @@ import "./PromotedAttributes.css";
import { DefinitionObject, extractAttributeDefinitionTypeAndName, UpdateAttributeResponse } from "@triliumnext/commons";
import clsx from "clsx";
-import { ComponentChild, MouseEventHandler, TargetedEvent } from "preact";
+import { ComponentChild, TargetedEvent } from "preact";
import { Dispatch, StateUpdater, useCallback, useEffect, useState } from "preact/hooks";
import NoteContext from "../components/note_context";
@@ -16,6 +16,7 @@ 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 RelationValuesInput from "./attribute_widgets/relation_values_input";
import { useNoteContext, useNoteLabel, useTriliumEvent, useUniqueName } from "./react/hooks";
import NoteAutocomplete from "./react/NoteAutocomplete";
@@ -26,11 +27,11 @@ interface Cell {
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.
+ * Every value the note holds under this name, for a definition that allows several — the whole
+ * set being edited as one field of chips rather than as a field per value. For a relation the
+ * values are the targets' noteIds, shown as the notes they name.
*
- * 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.
+ * Absent for a definition holding one value.
*/
values?: string[];
}
@@ -39,10 +40,7 @@ interface CellProps {
note: FNote;
componentId: string;
cell: Cell,
- cells: Cell[],
- shouldFocus: boolean;
setCells: Dispatch<StateUpdater<Cell[] | undefined>>;
- setCellToFocus(cell: Cell): void;
}
type OnChangeEventData = TargetedEvent<HTMLInputElement | HTMLTextAreaElement, Event> | InputEvent | JQuery.TriggeredEvent<HTMLInputElement, undefined, HTMLInputElement, HTMLInputElement>;
@@ -60,16 +58,13 @@ export function PromotedAttributesContent({ note, componentId, cells, setCells }
cells: Cell[] | undefined;
setCells: Dispatch<StateUpdater<Cell[] | undefined>>;
}) {
- const [ cellToFocus, setCellToFocus ] = useState<Cell>();
-
return (
<div className="promoted-attributes-widget">
{cells && cells.length > 0 && <div className="promoted-attributes-container">
{note && cells?.map(cell => <PromotedAttributeCell
key={cell.uniqueId}
cell={cell}
- cells={cells} setCells={setCells}
- shouldFocus={cell === cellToFocus} setCellToFocus={setCellToFocus}
+ setCells={setCells}
componentId={componentId} note={note}
/>)}
</div>}
@@ -78,11 +73,11 @@ export function PromotedAttributesContent({ note, componentId, cells, setCells }
}
/**
- * 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}.
+ * Handles the individual cells (fields for promoted attributes, including empty ones). A definition
+ * allowing several values is one cell holding the whole set — 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.
+ * The cells are returned as a state since they can also be altered internally if needed, for example
+ * to patch a value the grid itself has just written.
*/
export function usePromotedAttributeData(note: FNote | null | undefined, componentId: string, noteContext: NoteContext | undefined): [ Cell[] | undefined, Dispatch<StateUpdater<Cell[] | undefined>> ] {
const [ viewType ] = useNoteLabel(note, "viewType");
@@ -109,9 +104,9 @@ export function usePromotedAttributeData(note: FNote | null | undefined, compone
/**
* 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.
+ * One definition is one field, however many values it allows: a definition allowing several is a
+ * field of chips holding the whole set — a label's values as the text they are, a relation's as the
+ * notes they point at.
*
* 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
@@ -140,7 +135,7 @@ export function buildPromotedCells(note: FNote): Cell[] {
value: ""
};
- if (definition.multiplicity === "multi" && valueType === "label") {
+ if (definition.multiplicity === "multi") {
cells.push({
definitionAttr,
definition,
@@ -177,14 +172,6 @@ function PromotedAttributeCell(props: CellProps) {
const { valueName, valueAttr, definition } = props.cell;
const inputId = useUniqueName(`value-${valueAttr.name}`);
- useEffect(() => {
- if (!props.shouldFocus) return;
- const inputEl = document.getElementById(inputId);
- if (inputEl) {
- inputEl.focus();
- }
- }, [ props.shouldFocus ]);
-
const holdsSet = !!props.cell.values;
let correspondingInput: ComponentChild;
@@ -197,7 +184,9 @@ function PromotedAttributeCell(props: CellProps) {
className = `promoted-attribute-label-${definition.labelType}`;
break;
case "relation":
- correspondingInput = <RelationInput inputId={inputId} {...props} />;
+ correspondingInput = holdsSet
+ ? <MultiRelationInput inputId={inputId} {...props} />
+ : <RelationInput inputId={inputId} {...props} />;
className = "promoted-attribute-relation";
break;
default:
@@ -213,7 +202,6 @@ function PromotedAttributeCell(props: CellProps) {
{(definition.labelType !== "boolean" || holdsSet) &&
<label for={inputId}>{definition.promotedAlias ?? valueName}</label>}
{correspondingInput}
- <MultiplicityCell {...props} />
</div>
);
}
@@ -344,82 +332,29 @@ 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.
+ * The field a relation allowing several targets is edited through: one field holding the whole set
+ * as chips naming their notes, written back by name as {@link MultiLabelInput} writes a set of
+ * labels — every target under the name at once, through no one attribute in particular.
*/
-function MultiplicityCell({ cell, cells, setCells, setCellToFocus, note, componentId }: CellProps) {
- return (cell.definition.multiplicity === "multi" && !cell.values &&
- <td className="multiplicity">
- <PromotedActionButton
- icon="bx bx-plus"
- title={t("promoted_attributes.add_new_attribute")}
- onClick={() => {
- const index = cells.indexOf(cell);
- const newCell: Cell = {
- ...cell,
- uniqueId: randomString(),
- valueAttr: {
- attributeId: "",
- type: cell.valueAttr.type,
- name: cell.valueName,
- value: ""
- }
- };
- setCells([
- ...cells.slice(0, index + 1),
- newCell,
- ...cells.slice(index + 1)
- ]);
- setCellToFocus(newCell);
- }}
- />{' '}
- <PromotedActionButton
- icon="bx bx-trash"
- title={t("promoted_attributes.remove_this_attribute")}
- onClick={async () => {
- // Remove the attribute from the server if it exists.
- const { attributeId, type } = cell.valueAttr;
- const valueName = cell.valueName;
- if (attributeId) {
- await server.remove(`notes/${note.noteId}/attributes/${attributeId}`, componentId);
- }
+function MultiRelationInput({ inputId, note, cell, componentId, setCells }: CellProps & { inputId: string }) {
+ const { valueName, definitionAttr, values, uniqueId } = cell;
- const index = cells.indexOf(cell);
- const isLastOneOfType = cells.filter(c => c.valueAttr.type === type && c.valueAttr.name === valueName).length < 2;
- const newOnesToInsert: Cell[] = [];
- if (isLastOneOfType) {
- newOnesToInsert.push({
- ...cell,
- valueAttr: {
- attributeId: "",
- type: cell.valueAttr.type,
- name: cell.valueName,
- value: ""
- }
- });
- }
- setCells(cells.toSpliced(index, 1, ...newOnesToInsert));
- }}
- />
- </td>
- );
-}
+ const commit = useCallback(async (edited: string[]) => {
+ await attributes.setRelationValues(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 — otherwise the chips would not follow the pick just made.
+ setCells(prev => prev?.map(c => c.uniqueId === uniqueId ? { ...c, values: edited } : c));
+ }, [ note, valueName, componentId, uniqueId, setCells ]);
-function PromotedActionButton({ icon, title, onClick }: {
- icon: string,
- title: string,
- onClick: MouseEventHandler<HTMLSpanElement>
-}) {
return (
- <span
- className={clsx("tn-tool-button pointer", icon)}
- title={title}
- onClick={onClick}
- />
+ <div className="promoted-attribute-values">
+ <RelationValuesInput
+ values={values ?? []}
+ inputId={inputId}
+ tabIndex={200 + definitionAttr.position}
+ onCommit={commit}
+ />
+ </div>
);
}
diff --git a/apps/client/src/widgets/attribute_widgets/relation_values_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/relation_values_input.spec.tsx
new file mode 100644
index 0000000000..e15e47f3ec
--- /dev/null
+++ b/apps/client/src/widgets/attribute_widgets/relation_values_input.spec.tsx
@@ -0,0 +1,92 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// The real box is an Algolia autocomplete bound to jQuery, which is not loaded here; the mock hands
+// the test the props instead, `noteIdChanged` being the one the field's behaviour hangs off.
+const autocomplete = vi.hoisted(() => ({ current: null as Record<string, unknown> | null }));
+vi.mock("../react/NoteAutocomplete", async () => {
+ const { h } = await import("preact");
+ return {
+ default: (props: Record<string, unknown>) => {
+ autocomplete.current = props;
+ return h("input", { id: props.id as string | undefined });
+ }
+ };
+});
+
+import { buildNote } from "../../test/easy-froca";
+import RelationValuesInput, { RelationValueChips } from "./relation_values_input";
+
+describe("RelationValuesInput", () => {
+ let container: HTMLElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ async function mount(props: Parameters<typeof RelationValuesInput>[0]) {
+ await act(async () => render(<RelationValuesInput {...props} />, container));
+ return container;
+ }
+
+ it("shows the targets as chips naming their notes, and drops the one pressed", async () => {
+ const alpha = buildNote({ title: "Alpha" });
+ const beta = buildNote({ title: "Beta" });
+ const onCommit = vi.fn();
+ await mount({ values: [ alpha.noteId, beta.noteId ], onCommit });
+
+ const chips = [ ...container.querySelectorAll(".tn-chip") ];
+ expect(chips.map((chip) => chip.textContent?.trim())).toEqual([ "Alpha", "Beta" ]);
+
+ await act(async () => chips[0]?.querySelector<HTMLElement>(".tn-chip-remove")?.click());
+ expect(onCommit).toHaveBeenCalledWith([ beta.noteId ]);
+ });
+
+ it("takes a picked note once, refusing a second of the same and a pick of nothing", async () => {
+ const alpha = buildNote({ title: "Alpha" });
+ const gamma = buildNote({ title: "Gamma" });
+ const onCommit = vi.fn();
+ await mount({ values: [ alpha.noteId ], onCommit });
+
+ const pick = autocomplete.current?.noteIdChanged as (noteId: string) => void;
+
+ await act(async () => pick(gamma.noteId));
+ expect(onCommit).toHaveBeenCalledWith([ alpha.noteId, gamma.noteId ]);
+
+ // A target already held would come out as a second chip there is no telling apart — and
+ // clearing the box reports an empty pick, which is not a target at all.
+ onCommit.mockClear();
+ await act(async () => pick(alpha.noteId));
+ await act(async () => pick(""));
+ expect(onCommit).not.toHaveBeenCalled();
+ });
+
+ it("points a host's own label at the box", async () => {
+ await mount({ values: [], onCommit: vi.fn(), inputId: "field-id" });
+ expect(container.querySelector("input")?.id).toBe("field-id");
+ });
+});
+
+describe("RelationValueChips", () => {
+ it("names each target and links to it, the set being read rather than edited", async () => {
+ const alpha = buildNote({ title: "Alpha" });
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+
+ await act(async () => render(<RelationValueChips values={[ alpha.noteId ]} />, container));
+
+ const link = container.querySelector(".tn-chip .reference-link");
+ expect(link?.textContent?.trim()).toBe("Alpha");
+ expect(link?.getAttribute("data-href")).toBe(`#root/${alpha.noteId}`);
+
+ render(null, container);
+ container.remove();
+ });
+});
diff --git a/apps/client/src/widgets/attribute_widgets/relation_values_input.tsx b/apps/client/src/widgets/attribute_widgets/relation_values_input.tsx
new file mode 100644
index 0000000000..e55ee1a46d
--- /dev/null
+++ b/apps/client/src/widgets/attribute_widgets/relation_values_input.tsx
@@ -0,0 +1,152 @@
+import { useEffect, useRef, useState } from "preact/hooks";
+
+import type FNote from "../../entities/fnote";
+import froca from "../../services/froca";
+import { t } from "../../services/i18n";
+import Chip from "../react/Chip";
+import Icon from "../react/Icon";
+import NoteAutocomplete from "../react/NoteAutocomplete";
+
+interface RelationValuesInputProps {
+ /** The targets' noteIds, in the order they are shown. */
+ values: readonly string[];
+ /** Receives the noteIds as they now stand, whenever a target is taken or dropped. */
+ onCommit(values: string[]): 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 relation holding several targets is edited through: the targets as chips naming their
+ * notes, and after them the search box a single relation is already picked in.
+ *
+ * A chip only names its note — icon and title — rather than linking to it: the field is for editing
+ * the set, and a link inside it would carry a press meant for the chip off to the note instead. What
+ * the box takes is a made choice, never text: a note has to be picked, so nothing typed is ever kept,
+ * and a target already held is not taken a second time — the chips are a set.
+ */
+export default function RelationValuesInput({ values, onCommit, inputId, tabIndex, disabled }: RelationValuesInputProps) {
+ const inputRef = useRef<HTMLInputElement>(null);
+ const notes = useNotes(values);
+
+ // Set by hand because {@link NoteAutocomplete} does not carry the attribute through to the box
+ // it builds, which is the element the focus actually lands on.
+ useEffect(() => {
+ if (tabIndex !== undefined) {
+ inputRef.current?.setAttribute("tabindex", String(tabIndex));
+ }
+ }, [ tabIndex ]);
+
+ function take(noteId: string) {
+ // The box is emptied either way — what was in it is spent on the choice made — but a target
+ // already held is not taken twice, and clearing an empty pick has nothing to add.
+ const picker = inputRef.current;
+ if (picker) {
+ // Through the plugin rather than the element: the plugin holds text of its own, and would
+ // write the picked title right back over a cleared box.
+ $(picker).autocomplete("val", "").setSelectedNotePath("");
+ }
+ if (!noteId || values.includes(noteId)) return;
+ onCommit([ ...values, noteId ]);
+ }
+
+ function drop(noteId: string) {
+ onCommit(values.filter((held) => held !== noteId));
+ }
+
+ return (
+ <div className="tn-field relation-values-input">
+ {values.map((noteId) => (
+ <Chip
+ key={noteId}
+ removeButtonText={t("promoted_attributes.remove_value")}
+ disabled={disabled}
+ onRemove={() => drop(noteId)}
+ >
+ <span><NoteTitle note={notes[noteId]} /></span>
+ </Chip>
+ ))}
+ <NoteAutocomplete
+ id={inputId}
+ inputRef={inputRef}
+ opts={{ allowCreatingNotes: true, hideAllButtons: true }}
+ noteIdChanged={take}
+ />
+ </div>
+ );
+}
+
+/**
+ * The targets a relation holding several shows, read-only: the same chips the field edits, each
+ * naming its note and — the set not being edited here — carrying the link a relation cell already
+ * offers for its one target.
+ */
+export function RelationValueChips({ values }: { values: readonly string[] }) {
+ const notes = useNotes(values);
+
+ return (
+ <span className="label-value-chips">
+ {values.map((noteId) => (
+ <span key={noteId} className="tn-chip">
+ <span
+ className={`reference-link ${notes[noteId]?.getColorClass() ?? ""}`}
+ data-href={`#root/${noteId}`}
+ >
+ <NoteTitle note={notes[noteId]} />
+ </span>
+ </span>
+ ))}
+ </span>
+ );
+}
+
+/**
+ * A note as its chip names it: icon and title, or nothing while the note is still being fetched — a
+ * placeholder would only flash for the moment froca takes.
+ */
+function NoteTitle({ note }: { note: FNote | null | undefined }) {
+ if (!note) return null;
+ return <><Icon icon={note.getIcon()} />{" "}{note.title}</>;
+}
+
+/**
+ * The notes the ids name, from the cache first and fetched where the cache does not hold them —
+ * a relation can point at a note not yet loaded, or one since deleted, which stays absent.
+ */
+function useNotes(noteIds: readonly string[]): Record<string, FNote | null> {
+ const [ notes, setNotes ] = useState<Record<string, FNote | null>>({});
+
+ useEffect(() => {
+ const missing = noteIds.filter((noteId) => notes[noteId] === undefined);
+ if (!missing.length) return;
+
+ setNotes((known) => {
+ const fromCache = { ...known };
+ for (const noteId of missing) {
+ fromCache[noteId] = froca.getNoteFromCache(noteId) ?? null;
+ }
+ return fromCache;
+ });
+
+ let cancelled = false;
+ froca.getNotes(missing, true).then((fetched) => {
+ if (cancelled || !fetched.length) return;
+ setNotes((known) => {
+ const resolved = { ...known };
+ for (const note of fetched) {
+ resolved[note.noteId] = note;
+ }
+ return resolved;
+ });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [ noteIds ]);
+
+ return notes;
+}
+
diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.ts
index f0d741f59b..2e26028bc5 100644
--- a/apps/client/src/widgets/collections/table/columns.spec.ts
+++ b/apps/client/src/widgets/collections/table/columns.spec.ts
@@ -479,6 +479,34 @@ describe("buildColumnDefinitions — relation columns", () => {
// A cell without a target sorts as nothing rather than by its absence crashing the grid.
expect(compare(undefined, "Alpha")).toBe(-1);
});
+
+ it("keeps the title sort for a column of several targets, whose cells hold noteId arrays", () => {
+ const column = buildColumnDefinitions({
+ info: [ { name: "crew", type: "relation", isMulti: true } ],
+ movableRows: false,
+ existingColumnData: undefined,
+ rowNumberHint: 1
+ }).find((candidate) => candidate.field === "relations.crew");
+
+ // The set is edited and shown as chips of notes, not as the text the ids are.
+ expect(typeof column?.editor).toBe("function");
+ expect(typeof column?.formatter).toBe("function");
+ const params = column?.editorParams;
+ if (typeof params !== "function") throw new Error("expected the params to be a function");
+ expect((params({} as CellComponent) as ValuesEditorParams).labelType).toBe("relation");
+
+ const sorter = column?.sorter;
+ if (typeof sorter !== "function") throw new Error("expected a sorter of its own");
+ const columnComponent = { getField: () => "relations.crew" } as ColumnComponent;
+ const row = (titles: string) =>
+ ({ getData: () => ({ relationTitles: { crew: titles } }) }) as unknown as RowComponent;
+
+ // Compared by the joined titles the row carries — the ids the cells hold would order
+ // "Beta, Gamma" before "Alpha, Zed" whenever their ids happened to.
+ expect(Math.sign((sorter as (...args: unknown[]) => number)(
+ [ "id1", "id2" ], [ "id3" ], row("Alpha, Zed"), row("Beta, Gamma"), columnComponent, "asc", {}
+ ))).toBe(-1);
+ });
});
describe("formatLabelDate", () => {
diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsx
index 8136bc24f3..19a626ec43 100644
--- a/apps/client/src/widgets/collections/table/columns.tsx
+++ b/apps/client/src/widgets/collections/table/columns.tsx
@@ -11,6 +11,7 @@ import { safeUrlHref } from "../../../utils/url.js";
import { applyLinkScheme, asLabelValues, formatLabelDate, LabelValueChips } from "../../attribute_widgets/label_value_display.jsx";
import LabelValueInput from "../../attribute_widgets/label_value_input.jsx";
import MultiValueInput from "../../attribute_widgets/multi_value_input.jsx";
+import RelationValuesInput, { RelationValueChips } from "../../attribute_widgets/relation_values_input.jsx";
import Icon from "../../react/Icon.jsx";
import NoteAutocomplete from "../../react/NoteAutocomplete.jsx";
import { renderReactWidget } from "../../react/react_utils.jsx";
@@ -199,12 +200,17 @@ export function buildColumnDefinitions({ info, movableRows, existingColumnData,
} satisfies ValuesEditorParams)
}),
// A set is shown as the chips it is edited as, whatever it holds — and sorted by those
- // values rather than by the array Tabulator would otherwise compare as an object.
+ // values rather than by the array Tabulator would otherwise compare as an object. A set
+ // of relations keeps the relation sorter: its values are noteIds, and the titles the
+ // cell shows are what the rows should order by, carried in `relationTitles` for one
+ // target and several alike.
...(isMulti && {
editor: wrapEditor(ValuesEditor),
formatter: wrapFormatter(ValuesFormatter),
formatterParams: { type: type ?? "text" },
- sorter: (a, b) => joinValues(a).localeCompare(joinValues(b))
+ ...(type !== "relation" && {
+ sorter: ((a, b) => joinValues(a).localeCompare(joinValues(b))) as ColumnDefinition["sorter"]
+ })
})
});
seenFields.add(field);
@@ -426,16 +432,19 @@ function ValuesEditor({ cell, success, editorParams }: EditorOpts) {
return (
<div ref={containerRef} className={clsx("table-values-editor", growsUpwards && "grows-upwards")}>
- {/* 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}
- />
+ {/* The very fields the note's own promoted grid offers, so that a definition is edited
+ the same way whichever way the note is opened. */}
+ {labelType === "relation" ? (
+ <RelationValuesInput values={values} onCommit={editValues} />
+ ) : (
+ <MultiValueInput
+ labelType={labelType}
+ values={values}
+ options={options}
+ onCreateOption={onCreateOption}
+ onCommit={editValues}
+ />
+ )}
</div>
);
}
@@ -443,9 +452,12 @@ 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 };
+ if (type === "relation") {
+ return <RelationValueChips values={asLabelValues(cell.getValue())} />;
+ }
return <LabelValueChips
values={asLabelValues(cell.getValue())}
- labelType={type === "relation" ? undefined : type}
+ labelType={type}
/>;
}
diff --git a/apps/client/src/widgets/collections/table/row_editing.ts b/apps/client/src/widgets/collections/table/row_editing.ts
index 57f6598ee5..f70575a4f6 100644
--- a/apps/client/src/widgets/collections/table/row_editing.ts
+++ b/apps/client/src/widgets/collections/table/row_editing.ts
@@ -3,7 +3,7 @@ import { EventCallBackMethods, RowComponent, Tabulator } from "tabulator-tables"
import { CommandListenerData } from "../../../components/app_context";
import FNote from "../../../entities/fnote";
-import { setAttribute, setLabel, setLabelValues } from "../../../services/attributes";
+import { setAttribute, setLabel, setLabelValues, setRelationValues } from "../../../services/attributes";
import branches from "../../../services/branches";
import froca from "../../../services/froca";
import note_create, { CreateNoteOpts } from "../../../services/note_create";
@@ -68,7 +68,13 @@ export default function useRowTableEditing(api: RefObject<Tabulator>, attributeD
} else if (type === "relations") {
const note = await froca.getNote(noteId);
if (note) {
- setAttribute(note, "relation", name, newValue);
+ // A set of targets is written as the several relations it is, as a set of
+ // label values is.
+ if (Array.isArray(newValue)) {
+ await setRelationValues(note, name, newValue as string[]);
+ } else {
+ setAttribute(note, "relation", name, newValue);
+ }
}
}
}
diff --git a/apps/client/src/widgets/collections/table/rows.spec.ts b/apps/client/src/widgets/collections/table/rows.spec.ts
index 3b7cf35836..6f98a5cce6 100644
--- a/apps/client/src/widgets/collections/table/rows.spec.ts
+++ b/apps/client/src/widgets/collections/table/rows.spec.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
+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 getAttributeDefinitionInformation, { buildRowDefinitions } from "./rows.js";
@@ -25,7 +30,7 @@ describe("getAttributeDefinitionInformation", () => {
]);
});
- it("holds several values of every kind of label, a relation excepted", async () => {
+ it("holds several values of every kind of attribute, relations included", async () => {
const note = buildNote({
title: "Note 1",
"#label:tags(inheritable)": "promoted,multi,text",
@@ -34,6 +39,7 @@ describe("getAttributeDefinitionInformation", () => {
"#label:status(inheritable)": "promoted,multi,select,options=Todo;Done",
"#label:tint(inheritable)": "promoted,multi,color",
"#label:done(inheritable)": "promoted,multi,boolean",
+ "#relation:crew(inheritable)": "promoted,multi",
"#label:owner(inheritable)": "promoted,single,text"
});
@@ -44,6 +50,7 @@ describe("getAttributeDefinitionInformation", () => {
{ name: "status", type: "select", isMulti: true },
{ name: "tint", type: "color", isMulti: true },
{ name: "done", type: "boolean", isMulti: true },
+ { name: "crew", type: "relation", isMulti: true },
{ name: "owner", type: "text", isMulti: false }
]);
});
@@ -72,4 +79,51 @@ describe("buildRowDefinitions", () => {
{ title: "Task 3", relations: { assignee: null }, relationTitles: { assignee: "" } }
]);
});
+
+ it("holds every target of a multi relation, titled as one string for the sort to read", async () => {
+ const alpha = buildNote({ title: "Alpha" });
+ const beta = buildNote({ title: "Beta" });
+ const parent = buildNote({
+ title: "Collection",
+ "#relation:crew(inheritable)": "promoted,multi",
+ children: [
+ { title: "Task 1", "~crew": alpha.noteId },
+ // A row without the relation holds an empty set rather than nothing at all.
+ { title: "Task 2" }
+ ]
+ });
+ const taskOne = await parent.getChildBranches()[0]?.getNote();
+ if (!taskOne) throw new Error("expected the child note to be built");
+ // A second target under the same name, which one object literal cannot spell.
+ holdRelation(taskOne, "crew", beta.noteId);
+
+ const info = getAttributeDefinitionInformation(parent);
+ const { definitions } = await buildRowDefinitions(parent, info, false);
+ expect(definitions).toMatchObject([
+ {
+ title: "Task 1",
+ relations: { crew: [ alpha.noteId, beta.noteId ] },
+ relationTitles: { crew: "Alpha, Beta" }
+ },
+ { title: "Task 2", relations: { crew: [] }, relationTitles: { crew: "" } }
+ ]);
+ });
});
+
+/** Gives the note another relation under a name it already carries, which one literal cannot. */
+function holdRelation(note: FNote, name: string, value: string) {
+ const attributeId = randomString(12);
+ const attribute = new FAttribute(froca, {
+ noteId: note.noteId,
+ attributeId,
+ type: "relation",
+ name,
+ value,
+ position: 100,
+ isInheritable: false
+ });
+
+ froca.attributes[attributeId] = attribute;
+ note.attributes.push(attributeId);
+ noteAttributeCache.attributes[note.noteId]?.push(attribute);
+}
diff --git a/apps/client/src/widgets/collections/table/rows.ts b/apps/client/src/widgets/collections/table/rows.ts
index 6725b321c8..4f406b6553 100644
--- a/apps/client/src/widgets/collections/table/rows.ts
+++ b/apps/client/src/widgets/collections/table/rows.ts
@@ -9,11 +9,12 @@ export type TableData = {
noteId: string;
title: string;
labels: Record<string, boolean | string | string[] | null>;
- relations: Record<string, boolean | string | null>;
+ relations: Record<string, boolean | string | string[] | null>;
/**
* The relation targets' titles, keyed as `relations` is. A relation cell stores the target's
* noteId but shows its title, and a sort compares synchronously — so the title a column sorts
- * by has to be in the row data before the table is handed it.
+ * by has to be in the row data before the table is handed it. A cell holding several targets
+ * carries their titles joined, which is also the order the sort should read the set in.
*/
relationTitles: Record<string, string>;
branchId: string;
@@ -42,7 +43,10 @@ export async function buildRowDefinitions(parentNote: FNote, infos: AttributeDef
const relations: typeof definitions[0]["relations"] = {};
for (const { name, type, isMulti } of infos) {
if (type === "relation") {
- relations[name] = note.getRelationValue(name);
+ // Every target of the name for a set, blanks dropped as for a set of labels.
+ relations[name] = isMulti
+ ? note.getRelations(name).map((relation) => relation.value).filter(Boolean)
+ : note.getRelationValue(name);
} else if (isMulti) {
// Every label of the name rather than the first, blanks dropped: the cell holds the
// set, and an empty one is a value the field never offered.
@@ -96,8 +100,8 @@ async function fillRelationTitles(definitions: TableData[]) {
const targetIds = new Set<string>();
visitRows(definitions, ({ relations }) => {
for (const value of Object.values(relations)) {
- if (typeof value === "string" && value) {
- targetIds.add(value);
+ for (const targetId of asTargetIds(value)) {
+ targetIds.add(targetId);
}
}
});
@@ -108,12 +112,19 @@ async function fillRelationTitles(definitions: TableData[]) {
await froca.getNotes([ ...targetIds ], true);
visitRows(definitions, (def) => {
for (const [ name, value ] of Object.entries(def.relations)) {
- const target = typeof value === "string" && value ? froca.getNoteFromCache(value) : undefined;
- def.relationTitles[name] = target?.title ?? "";
+ def.relationTitles[name] = asTargetIds(value)
+ .map((targetId) => froca.getNoteFromCache(targetId)?.title ?? "")
+ .join(", ");
}
});
}
+/** A relation cell's targets: the one it holds, the several a set holds, or none at all. */
+function asTargetIds(value: TableData["relations"][string]): string[] {
+ if (Array.isArray(value)) return value.filter(Boolean);
+ return typeof value === "string" && value ? [ value ] : [];
+}
+
function visitRows(definitions: TableData[], visit: (def: TableData) => void) {
for (const def of definitions) {
visit(def);
@@ -155,14 +166,11 @@ export default function getAttributeDefinitionInformation(parentNote: FNote) {
}
/**
- * The types a column can hold several values of, shown and edited as chips: every kind of label a
- * note can carry, since a note can carry any of them more than once and the table has no business
- * showing fewer than it holds.
- *
- * Only a relation is left out, its values being notes rather than text — a column of them is still
- * a column of one.
+ * The types a column can hold several values of, shown and edited as chips: every kind of attribute
+ * a note can carry, since a note can carry any of them more than once and the table has no business
+ * showing fewer than it holds. A relation's chips name the notes its values point at.
*/
const MULTI_VALUE_TYPES = new Set<LabelType | "relation">([
"text", "textarea", "number", "boolean", "select", "date", "datetime", "time", "url", "email",
- "phone", "color"
+ "phone", "color", "relation"
]);
diff --git a/apps/client/src/widgets/react/Chip.css b/apps/client/src/widgets/react/Chip.css
index 931c654a2e..2d6c128936 100644
--- a/apps/client/src/widgets/react/Chip.css
+++ b/apps/client/src/widgets/react/Chip.css
@@ -56,11 +56,21 @@
}
}
- /* A chip standing for a value holds text rather than a box to type in, so it needs none of the
- field styling the chip leaves to its contents — only room for the word itself. */
- > .tn-chip > span {
- padding-block: 2px;
- white-space: nowrap;
+ /* Never wider than the field it lies in: a value long enough to outgrow the line — a note's
+ full title — is clipped to an ellipsis rather than carrying the chip past the field's edge.
+ The remove button keeps its place either way, having already refused to shrink. */
+ > .tn-chip {
+ max-width: 100%;
+
+ /* A chip standing for a value holds text rather than a box to type in, so it needs none of
+ the field styling the chip leaves to its contents — only room for the word itself. */
+ > span {
+ padding-block: 2px;
+ white-space: nowrap;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
}
}