Skip to content

Build your personal knowledge base with Trilium Notes

feat(attributes): create a label or relation in a row of its own

Elian Doran2c36c862b55a
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
index 0a64f6d5d1..991457fcf3 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
@@ -775,8 +775,11 @@ function AttributeNameField({ help, ...autocompleteProps }: { help?: AttrHelpEnt
* One row of an attribute name completion, marking the names Trilium itself attaches a meaning to.
* The mark answers what a list of bare names cannot: whether picking one buys behaviour, or is only
* a name. The inline editor's `#`/`~` completion lists the same names and marks them the same way.
+ *
+ * Exported, with {@link fetchAttributeNames}, for whatever else completes an attribute name — the
+ * attribute panel's in-row creation — so every name box offers the same list the same way.
*/
-function AttributeNameSuggestion({ type, name }: { type: "label" | "relation"; name: string }) {
+export function AttributeNameSuggestion({ type, name }: { type: "label" | "relation"; name: string }) {
return (
<span class="attr-name-suggestion">
<span class="attr-name-suggestion-name">{name}</span>
@@ -844,7 +847,7 @@ export const DEFINITION_TYPES: { value: string; title: string; icon: string; sta
}
];
-function fetchAttributeNames(type: "label" | "relation", query: string) {
+export function fetchAttributeNames(type: "label" | "relation", query: string) {
return server.get<string[]>(`attribute-names/?type=${type}&query=${encodeURIComponent(query)}`);
}
diff --git a/apps/client/src/widgets/sidebar/AttributeCreationEditor.css b/apps/client/src/widgets/sidebar/AttributeCreationEditor.css
new file mode 100644
index 0000000000..a9819a9617
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/AttributeCreationEditor.css
@@ -0,0 +1,25 @@
+/* The two fields a creation row is made of, on the overlay shell (AttributeEditorOverlay.css): the
+ name leading and the value taking the rest, weighted rather than measured — with only the two of
+ them, a fixed split would starve one side on a narrow pane and waste it on a wide one. */
+.attribute-list-panel .attribute-creation-editor {
+ & .attribute-creation-name,
+ & .attribute-creation-value {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ min-width: 0;
+ }
+
+ & .attribute-creation-name {
+ flex: 2 1 0;
+
+ & input {
+ flex: 1;
+ min-width: 0;
+ }
+ }
+
+ & .attribute-creation-value {
+ flex: 3 1 0;
+ }
+}
diff --git a/apps/client/src/widgets/sidebar/AttributeCreationEditor.tsx b/apps/client/src/widgets/sidebar/AttributeCreationEditor.tsx
new file mode 100644
index 0000000000..6fe3864d55
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/AttributeCreationEditor.tsx
@@ -0,0 +1,146 @@
+import "./AttributeCreationEditor.css";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
+
+import type FNote from "../../entities/fnote";
+import type { Attribute } from "../../services/attribute_parser";
+import { t } from "../../services/i18n";
+import utils from "../../services/utils";
+import { AttributeNameSuggestion, fetchAttributeNames } from "../attribute_widgets/attribute_detail";
+import LabelValueInput from "../attribute_widgets/label_value_input";
+import FormAutocomplete from "../react/FormAutocomplete";
+import NoteAutocomplete from "../react/NoteAutocomplete";
+import AttributeEditorOverlay from "./AttributeEditorOverlay";
+import { resolveValueField, TARGET_NOTE_OPTS } from "./AttributeValueEditor";
+
+interface AttributeCreationEditorProps {
+ /** The note the attribute is created on, read for the definition that types the value field. */
+ note: FNote;
+ /** The draft the host appended to its rows; the name and value are written into it as typed. */
+ attribute: Attribute;
+ /** Close keeping the draft — which the host saves, or discards if it was never given a name. */
+ onCommit(): void;
+ /** Close un-creating the draft. */
+ onRevert(): void;
+}
+
+/**
+ * A label or relation created in a row of its own, without opening the detail form: the two things a
+ * plain attribute is made of side by side — the name, completed from the names already in use, and
+ * the value the name calls for (see {@link resolveValueField}) or the note search a relation's target
+ * is picked in. Everything else the form collects — inheritability, a definition's settings — is
+ * rare enough to stay with the form, reachable from the row once it exists.
+ *
+ * Stands on the {@link AttributeEditorOverlay} shell: leaving keeps the draft, escape drops it. In
+ * the name box, enter walks on to the value field once the completion has had its say.
+ */
+export default function AttributeCreationEditor({ note, attribute, onCommit, onRevert }: AttributeCreationEditorProps) {
+ const containerRef = useRef<HTMLSpanElement>(null);
+ const nameRef = useRef<HTMLInputElement>(null);
+ const isRelation = attribute.type === "relation";
+ const nameType = isRelation ? "relation" : "label";
+ // The one field state here: the value lives in the draft alone, but the name is what the value
+ // field's kind hangs off, so typing it has to re-render.
+ const [ name, setName ] = useState(attribute.name);
+ // Committing mid-composition would filter the characters being composed out from under the IME;
+ // the same guard the detail form keeps (https://github.com/zadam/trilium/pull/3812).
+ const isComposing = useRef(false);
+
+ const suggestNames = useCallback((query: string) => fetchAttributeNames(nameType, query), [ nameType ]);
+ const renderNameSuggestion = useCallback(
+ (suggestion: string) => <AttributeNameSuggestion type={nameType} name={suggestion} />, [ nameType ]);
+
+ // What the name as it stands would be typed as, so a name with a definition behind it gets its
+ // field the moment the name settles — type `due`, and the value side becomes its date picker.
+ const typed = useMemo(
+ () => isRelation ? undefined : resolveValueField(note, name),
+ [ isRelation, note, name ]);
+
+ useEffect(() => nameRef.current?.focus(), []);
+
+ function commitName(newName: string) {
+ // Invalid characters are simply ignored, as the detail form ignores them.
+ const filtered = utils.filterAttributeName(newName);
+ setName(filtered);
+ attribute.name = filtered;
+ }
+
+ /** Enter in the name box walks on to the value field, the completion having had its say first. */
+ function focusValueField() {
+ containerRef.current
+ ?.querySelector<HTMLElement>(".attribute-creation-value input:not([type=hidden]), .attribute-creation-value textarea, .attribute-creation-value select")
+ ?.focus();
+ }
+
+ return (
+ <AttributeEditorOverlay
+ overlayRef={containerRef}
+ className="attribute-creation-editor"
+ onCommit={onCommit}
+ onRevert={onRevert}
+ onKeyDown={(e) => {
+ if (e.key !== "Enter") return;
+
+ if (e.target instanceof Element && e.target.closest(".attribute-creation-name")) {
+ e.preventDefault();
+ e.stopPropagation();
+ focusValueField();
+ // Enter is the note search's own key — it is what picks — so only a label's value
+ // commits on it; a textarea keeps it for its newlines unless held with the modifier.
+ } else if (typed && (typed.labelType !== "textarea" || e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ e.stopPropagation();
+ onCommit();
+ }
+ }}
+ >
+ <span className="attribute-creation-name">
+ <FormAutocomplete
+ inputRef={nameRef}
+ currentValue={name}
+ placeholder={t("attribute_detail.name")}
+ source={suggestNames}
+ renderItem={renderNameSuggestion}
+ openOnFocus
+ onChange={(newName) => isComposing.current ? setName(newName) : commitName(newName)}
+ onCompositionStart={() => isComposing.current = true}
+ onCompositionEnd={(e) => {
+ isComposing.current = false;
+ commitName(e.currentTarget.value);
+ }}
+ />
+ </span>
+ <span className="attribute-creation-value">
+ {isRelation ? (
+ <NoteAutocomplete
+ noteId={attribute.value || undefined}
+ opts={TARGET_NOTE_OPTS}
+ noteIdChanged={(noteId) => {
+ attribute.value = noteId ?? "";
+ }}
+ />
+ ) : typed && (
+ <LabelValueInput
+ // Remounted when the name resolves to another kind of field, reseeded from
+ // whatever the draft holds by then.
+ labelType={typed.labelType}
+ value={attribute.value ?? ""}
+ onCommit={(value) => {
+ attribute.value = value;
+ }}
+ commitOn="input"
+ numberPrecision={typed.numberPrecision}
+ selectOptions={typed.selectOptions}
+ hideOpenButton
+ inputProps={{
+ className: "form-control",
+ ...(typed.labelType === "select" && {
+ placeholder: t("promoted_attributes.unset-field-placeholder")
+ })
+ }}
+ />
+ )}
+ </span>
+ </AttributeEditorOverlay>
+ );
+}
diff --git a/apps/client/src/widgets/sidebar/AttributeEditorOverlay.css b/apps/client/src/widgets/sidebar/AttributeEditorOverlay.css
new file mode 100644
index 0000000000..326ab5c1b9
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/AttributeEditorOverlay.css
@@ -0,0 +1,66 @@
+/*
+ * The overlay an attribute row's editor stands on — see AttributeEditorOverlay.tsx for what it is,
+ * and AttributeList.css for the row's own part (un-clipping, coming forward).
+ */
+.attribute-list-panel .attribute-editor-overlay {
+ position: absolute;
+ /* A hair past the row on every side, so the surface reads as standing over it rather than cut
+ to its shape; a host may hold the leading edge off instead (see AttributeValueEditor.css). */
+ inset-block-start: -2px;
+ inset-inline: -2px;
+
+ /* The surface of its own it stands on: opaque, because a field's background is a translucent
+ film meant for the page behind it, through which the row would otherwise be read along. */
+ padding: 2px;
+ background-color: var(--main-background-color);
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, var(--dropdown-shadow-opacity, 0.2));
+
+ display: flex;
+ align-items: center;
+ gap: 4px;
+
+ /* Sized to sit in a row of text rather than in a form. The colour swatch is left out: it has a
+ size of its own (see label_value_input.css), stated at the same weight as this rule — matching
+ it here would leave the winner to stylesheet order. */
+ & .form-control:not(.label-color-picker),
+ & .form-select {
+ min-width: 0;
+ height: auto;
+ padding: 0 6px;
+ font-size: inherit;
+ line-height: 1.5;
+ }
+
+ /* A checkbox is its own size; the field class would stretch it across the row. */
+ & input[type="checkbox"] {
+ flex: 0 0 auto;
+ width: auto;
+ height: auto;
+ }
+
+ /* The one field that grows, downwards only: sideways there is nothing to grow into. */
+ & textarea.form-control {
+ resize: vertical;
+ }
+
+ /* The buttons beside a field (a colour's reset), trimmed to the row's height. */
+ & .input-group-text {
+ padding: 0 5px;
+ cursor: pointer;
+ }
+
+ /* The group the note search wraps its box in takes the room the box is owed. */
+ & .input-group {
+ flex: 1;
+ min-width: 0;
+ }
+}
+
+/* Anchored by its foot instead, so that what it outgrows the row by rises over what has been read
+ already rather than pressing past the foot of the pane. Applied from the shell, which is what can
+ tell the room is short (see useGrowsUpwards). */
+.attribute-list-panel .attribute-editor-overlay.grows-upwards {
+ inset-block-start: auto;
+ inset-block-end: -2px;
+}
diff --git a/apps/client/src/widgets/sidebar/AttributeEditorOverlay.tsx b/apps/client/src/widgets/sidebar/AttributeEditorOverlay.tsx
new file mode 100644
index 0000000000..ee5bfa600a
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/AttributeEditorOverlay.tsx
@@ -0,0 +1,96 @@
+import "./AttributeEditorOverlay.css";
+
+import clsx from "clsx";
+import type { ComponentChildren, RefObject } from "preact";
+import { useEffect } from "preact/hooks";
+
+import { AUTOCOMPLETE_DROPDOWN_SELECTOR } from "../react/FormAutocomplete";
+import { useGrowsUpwards } from "../react/grows_upwards";
+
+interface AttributeEditorOverlayProps {
+ /** The host's own ref to the overlay element, through which it reaches the fields within. */
+ overlayRef: RefObject<HTMLSpanElement>;
+ /** Names the host's kind of overlay, for the styles of its own it adds to the shell's. */
+ className?: string;
+ children: ComponentChildren;
+ /** Close keeping the edits; leaving the overlay is what asks for it. */
+ onCommit(): void;
+ /** Close dropping the edits; escape is what asks for it. */
+ onRevert(): void;
+ /** Receives the keys the shell leaves alone — everything but escape. Enter above all, which
+ * means something different per field (commit, next field, the note search's pick), so the
+ * host is the one to read it. */
+ onKeyDown?(e: KeyboardEvent): void;
+}
+
+/**
+ * The shell of an editor that opens over an attribute row rather than in it — the turn the table's
+ * cell editor takes (see columns.css): a row is one line of a hand-wide pane, which a field with room
+ * to type in outgrows at once. The shell is the standing-over alone — the surface, the anchoring, and
+ * when the edit is over — while what is edited on it is the host's: a value in its row, an attribute
+ * being created. The row underneath stops clipping and comes forward meanwhile (see AttributeList.css).
+ *
+ * Leaving the overlay is what ends the edit and keeps it, matching the attributes editor's
+ * save-on-blur; escape closes it dropping them instead. Near the foot of the pane the overlay is
+ * anchored by its foot, what it outgrows the row by rising over what has been read already.
+ */
+export default function AttributeEditorOverlay({ overlayRef, className, children, onCommit, onRevert, onKeyDown }: AttributeEditorOverlayProps) {
+ const growsUpwards = useGrowsUpwards(overlayRef);
+
+ useEffect(() => {
+ const editor = overlayRef.current;
+ if (!editor) return;
+
+ const onFocusOut = (e: FocusEvent) => {
+ // Focus moving within the editor — the field to a button beside it — is not leaving it.
+ if (e.relatedTarget instanceof Node && editor.contains(e.relatedTarget)) return;
+
+ // Nor is it leaving for floating UI that belongs to the field: the note search's dropdown
+ // is appended to the body, and creating a note from it opens the note type chooser — the
+ // same company the detail popup keeps itself open over.
+ if (e.relatedTarget instanceof Element
+ && e.relatedTarget.closest(`${AUTOCOMPLETE_DROPDOWN_SELECTOR}, .algolia-autocomplete, .modal, .modal-backdrop`)) {
+ 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
+ // row has not been left, and committing here would close the editor under the dialog.
+ if (!e.relatedTarget && (!document.hasFocus() || editor.contains(document.activeElement))) {
+ return;
+ }
+
+ onCommit();
+ };
+
+ editor.addEventListener("focusout", onFocusOut);
+ return () => editor.removeEventListener("focusout", onFocusOut);
+ }, [ overlayRef, onCommit ]);
+
+ return (
+ <span
+ ref={overlayRef}
+ className={clsx("attribute-editor-overlay", className, growsUpwards && "grows-upwards")}
+ // Keep the press from reaching the row, which would open the popup over the edit.
+ onClick={(e) => e.stopPropagation()}
+ onMouseDown={(e) => {
+ // The buttons beside a field (a colour's reset) take no focus of their own: letting
+ // the press blur the field would commit and unmount the editor before the click
+ // could land on them.
+ if (e.target instanceof Element && !e.target.closest("input, textarea, select")) {
+ e.preventDefault();
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ onRevert();
+ } else {
+ onKeyDown?.(e);
+ }
+ }}
+ >
+ {children}
+ </span>
+ );
+}
diff --git a/apps/client/src/widgets/sidebar/AttributeList.css b/apps/client/src/widgets/sidebar/AttributeList.css
index 577d991b42..8accca0e7f 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.css
+++ b/apps/client/src/widgets/sidebar/AttributeList.css
@@ -28,9 +28,9 @@
background-color: var(--hover-item-background-color);
}
-/* While its value is edited, the row is what the editor stands over (see AttributeValueEditor.css):
- it anchors the overlay, lets it spill past the one line the row keeps to, and comes forward so the
- editor is drawn over the rows below rather than under them. */
+/* While its value is edited (or the attribute created), the row is what the editor stands over (see
+ AttributeEditorOverlay.css): it anchors the overlay, lets it spill past the one line the row keeps
+ to, and comes forward so the editor is drawn over the rows below rather than under them. */
.attribute-list-panel .attribute-row.editing {
position: relative;
overflow: visible;
diff --git a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
index 294e5ee7ce..49e3297125 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
@@ -318,7 +318,7 @@ describe("AttributeList", () => {
expect(namesIn(container)).not.toContain("author");
});
- it("adds an attribute of the kind picked from the card's menu, saving them once the popup is closed", async () => {
+ it("adds a definition through the popup, saving it once the popup is closed", async () => {
renderPanel(noteWithAttributes());
// The panel's own button offers every kind; the definitions card offers the two definitions.
@@ -330,27 +330,100 @@ describe("AttributeList", () => {
// Four kinds and the rule setting the definitions apart, against the two definitions on their own.
expect(offered).toEqual([ 5, 2 ]);
- for (const item of showContextMenu.mock.calls[0][0].items) {
- act(() => item.handler?.());
- }
-
- // The popup opens on whatever was added; nothing is saved until it is closed.
+ // A definition still goes through the form, its settings needing one; nothing is saved until
+ // it is closed, and a press beside it keeps the edits — which for a list of rows means saving.
+ act(() => showContextMenu.mock.calls[1][0].items[0].handler?.());
expect(document.querySelector(".attr-detail")).not.toBeNull();
expect(put).not.toHaveBeenCalled();
- // A press beside the popup keeps the edits, which for a list of rows means saving them.
await act(async () => {
document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
});
expect(document.querySelector(".attr-detail")).toBeNull();
const [ , saved ] = put.mock.calls[0] as [ string, { name: string; value: string }[] ];
- expect(saved.slice(-4)).toEqual([
- { type: "label", name: "myLabel", value: "", isInheritable: false },
- { type: "relation", name: "myRelation", value: "", isInheritable: false },
- { type: "label", name: "label:myLabel", value: "promoted,single,text", isInheritable: false },
- { type: "label", name: "relation:myRelation", value: "promoted,single", isInheritable: false }
- ]);
+ expect(saved.at(-1)).toEqual(
+ { type: "label", name: "label:myLabel", value: "promoted,single,text", isInheritable: false });
+ });
+
+ it("creates a label straight in its row, and a draft left nameless not at all", async () => {
+ renderPanel(noteWithAttributes());
+
+ const ownedMenu = container.querySelector<HTMLElement>(".card-header-buttons .bx-plus");
+ act(() => ownedMenu?.click());
+ act(() => showContextMenu.mock.calls[0][0].items[0].handler?.());
+
+ // The row is created in place — no popup — name box first, value beside it.
+ expect(document.querySelector(".attr-detail")).toBeNull();
+ const editor = container.querySelector<HTMLElement>(".attribute-creation-editor");
+ expect(editor).not.toBeNull();
+
+ const nameInput = editor?.querySelector<HTMLInputElement>(".attribute-creation-name input");
+ const valueInput = editor?.querySelector<HTMLInputElement>(".attribute-creation-value input");
+ act(() => {
+ if (nameInput) {
+ nameInput.value = "mood";
+ nameInput.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ act(() => {
+ if (valueInput) {
+ valueInput.value = "great";
+ valueInput.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ await act(async () => {
+ editor?.dispatchEvent(new FocusEvent("focusout", { bubbles: true, relatedTarget: document.body }));
+ });
+
+ // Leaving the row keeps and saves the creation, and the row now stands for it.
+ expect(container.querySelector(".attribute-creation-editor")).toBeNull();
+ expect(put).toHaveBeenCalledOnce();
+ const [ , saved ] = put.mock.calls[0] as [ string, { name: string; value: string }[] ];
+ expect(saved.at(-1)).toMatchObject({ type: "label", name: "mood", value: "great" });
+
+ // Left nameless, the draft is nothing yet: closing it creates nothing and saves nothing.
+ act(() => ownedMenu?.click());
+ act(() => showContextMenu.mock.calls[1][0].items[0].handler?.());
+ await act(async () => {
+ container.querySelector(".attribute-creation-editor")
+ ?.dispatchEvent(new FocusEvent("focusout", { bubbles: true, relatedTarget: document.body }));
+ });
+ expect(container.querySelector(".attribute-creation-editor")).toBeNull();
+ expect(put).toHaveBeenCalledOnce();
+ expect(namesIn(container)).not.toContain("");
+ });
+
+ it("creates a relation in its row, its target picked in the note search", async () => {
+ buildNote({ id: "target-note", title: "Target" });
+ renderPanel(noteWithAttributes());
+
+ act(() => container.querySelector<HTMLElement>(".card-header-buttons .bx-plus")?.click());
+ act(() => showContextMenu.mock.calls[0][0].items[1].handler?.());
+
+ const editor = container.querySelector<HTMLElement>(".attribute-creation-editor");
+ const nameInput = editor?.querySelector<HTMLInputElement>(".attribute-creation-name input");
+ // The target field is the note search, stubbed here (see the mock above).
+ const targetInput = editor?.querySelector<HTMLInputElement>(".attribute-creation-value .note-autocomplete-stub");
+ act(() => {
+ if (nameInput) {
+ nameInput.value = "depicts";
+ nameInput.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ act(() => {
+ if (targetInput) {
+ targetInput.value = "target-note";
+ targetInput.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ await act(async () => {
+ editor?.dispatchEvent(new FocusEvent("focusout", { bubbles: true, relatedTarget: document.body }));
+ });
+
+ expect(put).toHaveBeenCalledOnce();
+ const [ , saved ] = put.mock.calls[0] as [ string, { name: string; value: string }[] ];
+ expect(saved.at(-1)).toMatchObject({ type: "relation", name: "depicts", value: "target-note" });
});
it("edits an owned label's value in place, saving it once the field is left", async () => {
diff --git a/apps/client/src/widgets/sidebar/AttributeList.tsx b/apps/client/src/widgets/sidebar/AttributeList.tsx
index 4b9ce06b6c..4444a63609 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeList.tsx
@@ -28,6 +28,7 @@ import NoteLink from "../react/NoteLink";
import { ParentComponent } from "../react/react_utils";
import { ATTRIBUTE_HELP_PAGE } from "../ribbon/components/AttributeHelp";
import OptionsSection from "../type_widgets/options/components/OptionsSection";
+import AttributeCreationEditor from "./AttributeCreationEditor";
import AttributeValueEditor, { resolveValueField } from "./AttributeValueEditor";
import RightPanelWidget, { CollapsibleWidgets } from "./RightPanelWidget";
@@ -53,6 +54,9 @@ export default function AttributeList() {
// The row whose value is being typed straight into it — the in-place alternative to the popup for
// a label — and the value to put back if the edit is thrown away rather than kept.
const [ valueEdit, setValueEdit ] = useState<{ attribute: Attribute; original: string } | null>(null);
+ // The draft a label or relation is created through in a row of its own, already among the owned
+ // rows; un-creating it is taking it back out of them.
+ const [ creating, setCreating ] = useState<Attribute | null>(null);
const componentId = parentComponent?.componentId;
// The owned rows double as the detail popup's working copy: it edits the very objects it is handed,
@@ -74,9 +78,13 @@ export default function AttributeList() {
// An attribute left open for editing — in the popup or in its own row — is closed by the
// change of note, and closing keeps what was typed into it — as a press outside does — rather
// than dropping it. Which the list cannot do itself once it holds another note's attributes,
- // hence the hand-over.
- if ((detail?.isOwned || valueEdit) && shownNoteId.current) {
- draftToFlush.current = { noteId: shownNoteId.current, attributes: owned.current };
+ // hence the hand-over. A creation left without a name is the one thing not kept: nameless, it
+ // is nothing yet, and the endpoint would refuse it for the whole list's sake.
+ if ((detail?.isOwned || valueEdit || creating) && shownNoteId.current) {
+ draftToFlush.current = {
+ noteId: shownNoteId.current,
+ attributes: owned.current.filter((attribute) => attribute.name)
+ };
}
shownNoteId.current = note?.noteId ?? null;
@@ -85,10 +93,11 @@ export default function AttributeList() {
internal.current = collectInternal(note);
}
- // Either editor works on one attribute of the note being left, so both close with the note.
+ // Every editor works on one attribute of the note being left, so all of them close with the note.
useEffect(() => {
setDetail(null);
setValueEdit(null);
+ setCreating(null);
const draft = draftToFlush.current;
draftToFlush.current = null;
@@ -98,11 +107,11 @@ export default function AttributeList() {
}, [ note ]);
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
- // While either editor is open, the changes this widget itself made are skipped: its edits are
- // the freshest state, and reloading over them would discard what is being typed. Once both are
+ // While any editor is open, the changes this widget itself made are skipped: its edits are
+ // the freshest state, and reloading over them would discard what is being typed. Once all are
// closed our own saves count too, which is how the list drops a row the server refused to keep
// (a relation left without a target note).
- const changed = detail || valueEdit ? loadResults.getAttributeRows(componentId) : loadResults.getAttributeRows();
+ const changed = detail || valueEdit || creating ? loadResults.getAttributeRows(componentId) : loadResults.getAttributeRows();
if (note && changed.some((attr) => attributes.isAffecting(attr, note))) {
owned.current = collectOwned(note);
inherited.current = collectInherited(note);
@@ -113,6 +122,9 @@ export default function AttributeList() {
if (valueEdit && !owned.current.includes(valueEdit.attribute)) {
setValueEdit(null);
}
+ if (creating && !owned.current.includes(creating)) {
+ setCreating(null);
+ }
rerender();
}
@@ -154,6 +166,23 @@ export default function AttributeList() {
}
function addAttribute(attrType: AttributeKind, e: MouseEvent) {
+ // Whatever was being edited is wrapped up first, the new row taking over from it.
+ commit();
+ commitValueEdit();
+ commitCreation();
+
+ // A plain label or relation is two things — a name and a value — which its own row can take:
+ // it is created there, in a nameless draft the creation editor fills in. The popup stays for
+ // the definitions, whose settings need the form, and for a phone, which keeps the page flow
+ // for every kind.
+ if (!IS_MOBILE && (attrType === "label" || attrType === "relation")) {
+ const attribute: Attribute = { type: attrType, name: "", value: "", isInheritable: false };
+
+ owned.current = [ ...owned.current, attribute ];
+ setCreating(attribute);
+ return;
+ }
+
const attribute = createAttribute(attrType);
owned.current = [ ...owned.current, attribute ];
@@ -180,11 +209,12 @@ export default function AttributeList() {
}
}
- /** Opens the in-place editor over a row's value, taking over from the popup if one is open. */
+ /** Opens the in-place editor over a row's value, taking over from whatever else was being edited. */
function startValueEdit(attribute: Attribute) {
if (detail) {
commit();
}
+ commitCreation();
setValueEdit({ attribute, original: attribute.value ?? "" });
}
@@ -206,6 +236,34 @@ export default function AttributeList() {
setValueEdit(null);
}
+ /**
+ * Closes the creation row keeping what it was given — which, still nameless, is nothing: an
+ * attribute is its name at the least, so a draft without one is quietly taken back out rather
+ * than sent to an endpoint that would refuse the whole list over it.
+ */
+ function commitCreation() {
+ if (!creating) {
+ return;
+ }
+
+ setCreating(null);
+ if (creating.name) {
+ void save();
+ } else {
+ owned.current = owned.current.filter((attribute) => attribute !== creating);
+ rerender();
+ }
+ }
+
+ /** Closes the creation row un-creating its draft, saving nothing. */
+ function revertCreation() {
+ if (creating) {
+ owned.current = owned.current.filter((attribute) => attribute !== creating);
+ }
+ setCreating(null);
+ rerender();
+ }
+
// A master-detail host heads the page it shows the form on with the attribute's name, and goes back
// to the list by closing it. Nothing happens outside such a host, where the form is a popup.
useMasterDetailPage(detail ? getDisplayName(detail.attribute, getAttributeKind(detail.attribute)) : null, commit);
@@ -232,6 +290,9 @@ export default function AttributeList() {
// Not built for an attribute the list no longer holds: a reload can rebuild the rows out from
// under the editor within this very render, before the state has caught up (see above).
const activeValueEdit = valueEdit && owned.current.includes(valueEdit.attribute) ? valueEdit : null;
+ const activeCreation = creating && owned.current.includes(creating) ? creating : null;
+ // At most one of the two is open — starting either commits the other — and both stand over their
+ // row the same way, so they share the one editor slot a row offers.
const valueEditor = note && activeValueEdit ? {
attribute: activeValueEdit.attribute,
element: (
@@ -247,6 +308,16 @@ export default function AttributeList() {
onRevert={revertValueEdit}
/>
)
+ } : note && activeCreation ? {
+ attribute: activeCreation,
+ element: (
+ <AttributeCreationEditor
+ note={note}
+ attribute={activeCreation}
+ onCommit={commitCreation}
+ onRevert={revertCreation}
+ />
+ )
} : undefined;
const rowProps = {
note,
diff --git a/apps/client/src/widgets/sidebar/AttributeValueEditor.css b/apps/client/src/widgets/sidebar/AttributeValueEditor.css
index 98b79f1e52..1ac53904f7 100644
--- a/apps/client/src/widgets/sidebar/AttributeValueEditor.css
+++ b/apps/client/src/widgets/sidebar/AttributeValueEditor.css
@@ -1,75 +1,9 @@
-/*
- * The editor opens over its row rather than in it — the turn the table's cell editor takes (see
- * columns.css): a row is one line of a hand-wide pane, which a field with room to type in outgrows
- * at once. Laid out within, the field got only what was left after the name; standing over the row
- * it takes all of it past the name — which keeps saying what is being edited, out from under the
- * surface — though never more than the row's leading fifth is spared for one: past the cap a long
- * name is cut at the overlay's edge rather than the field squeezed for its sake.
- *
- * The row it belongs to therefore stops clipping while it is edited (see AttributeList.css), and
- * comes forward so the editor is drawn over the rows below rather than under them.
- */
-.attribute-list-panel .attribute-value-editor {
- position: absolute;
- /* A hair past the row block-wise and at its trailing edge, so the surface reads as standing
- over the row rather than cut to its shape; held off the name's own reach (measured by the
- editor, which hands it over in the variable), the cap catching where there is none to hold. */
- inset-block-start: -2px;
+/* The one thing the value editor adds to the overlay shell it stands on (AttributeEditorOverlay.css):
+ its leading edge is held off so the row's name stays readable beside it — as far as the name
+ actually reaches (measured by the editor, which hands it over in the variable), and never further
+ than the row's leading fifth: past the cap a long name is cut at the overlay's edge rather than
+ the field squeezed for its sake. Doubled with the shell's class to outweigh its edge-to-edge
+ default whichever stylesheet loads last. */
+.attribute-list-panel .attribute-editor-overlay.attribute-value-editor {
inset-inline-start: min(var(--value-editor-name-end, 20%), 20%);
- inset-inline-end: -2px;
-
- /* The surface of its own it stands on: opaque, because a field's background is a translucent
- film meant for the page behind it, through which the row would otherwise be read along. */
- padding: 2px;
- background-color: var(--main-background-color);
- border-radius: 8px;
- box-shadow: 0 4px 12px rgba(0, 0, 0, var(--dropdown-shadow-opacity, 0.2));
-
- display: flex;
- align-items: center;
- gap: 4px;
-
- /* Sized to sit in a row of text rather than in a form. The colour swatch is left out: it has a
- size of its own (see label_value_input.css), stated at the same weight as this rule — matching
- it here would leave the winner to stylesheet order. */
- & .form-control:not(.label-color-picker),
- & .form-select {
- min-width: 0;
- height: auto;
- padding: 0 6px;
- font-size: inherit;
- line-height: 1.5;
- }
-
- /* A checkbox is its own size; the field class would stretch it across the row. */
- & input[type="checkbox"] {
- flex: 0 0 auto;
- width: auto;
- height: auto;
- }
-
- /* The one field that grows, downwards only: sideways there is nothing to grow into. */
- & textarea.form-control {
- resize: vertical;
- }
-
- /* The buttons beside a field (a colour's reset, a link's open), trimmed to the row's height. */
- & .input-group-text {
- padding: 0 5px;
- cursor: pointer;
- }
-
- /* The group the note search wraps its box in takes the room the box is owed. */
- & .input-group {
- flex: 1;
- min-width: 0;
- }
-}
-
-/* Anchored by its foot instead, so that what it outgrows the row by rises over what has been read
- already rather than pressing past the foot of the pane. Applied from the editor, which is what
- can tell the room is short (see useGrowsUpwards). */
-.attribute-list-panel .attribute-value-editor.grows-upwards {
- inset-block-start: auto;
- inset-block-end: -2px;
}
diff --git a/apps/client/src/widgets/sidebar/AttributeValueEditor.tsx b/apps/client/src/widgets/sidebar/AttributeValueEditor.tsx
index fe3443c127..7efb633806 100644
--- a/apps/client/src/widgets/sidebar/AttributeValueEditor.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeValueEditor.tsx
@@ -1,7 +1,6 @@
import "./AttributeValueEditor.css";
import type { LabelType } from "@triliumnext/commons";
-import clsx from "clsx";
import { useEffect, useLayoutEffect, useMemo, useRef } from "preact/hooks";
import type FNote from "../../entities/fnote";
@@ -9,9 +8,8 @@ import type { Attribute } from "../../services/attribute_parser";
import { getBuiltinLabelSelectOptions, getBuiltinLabelValueType, isBuiltinAttribute } from "../../services/attributes";
import { t } from "../../services/i18n";
import LabelValueInput, { getTypedInputForLabel } from "../attribute_widgets/label_value_input";
-import { AUTOCOMPLETE_DROPDOWN_SELECTOR } from "../react/FormAutocomplete";
-import { useGrowsUpwards } from "../react/grows_upwards";
import NoteAutocomplete from "../react/NoteAutocomplete";
+import AttributeEditorOverlay from "./AttributeEditorOverlay";
interface AttributeValueEditorProps {
/** The note the label belongs to, read for the definition that says what kind of field to offer. */
@@ -29,18 +27,15 @@ interface AttributeValueEditorProps {
* An attribute's value edited in the row that previews it, without opening the detail form: for a
* label the same field its promoted counterpart offers — a date picker for a date, a palette for a
* colour, a dropdown for a closed set, a plain box where nothing says more about the value than that
- * it is one — and for a relation the note search its target is picked in everywhere else.
+ * it is one — and for a relation the note search its target is picked in everywhere else. Only the
+ * value is edited here — the name, the flags and the definitions stay with the form the rest of the
+ * row opens.
*
- * Leaving the field is what ends the edit and keeps it, matching the attributes editor's save-on-blur;
- * escape puts the value back instead. Only the value is edited here — the name, the flags and the
- * definitions stay with the form the rest of the row opens.
+ * The field stands on the {@link AttributeEditorOverlay} shell, which is what says when the edit is
+ * over: leaving keeps it, escape puts the value back.
*/
export default function AttributeValueEditor({ note, attribute, onEdit, onCommit, onRevert }: AttributeValueEditorProps) {
const containerRef = useRef<HTMLSpanElement>(null);
- // The editor stands over its row rather than in it (see the stylesheet), so near the foot of the
- // pane it is anchored by its foot instead, what it outgrows the row by rising over what has been
- // read already — the same turn the table's cell editor takes, through the same measure.
- const growsUpwards = useGrowsUpwards(containerRef);
const isRelation = attribute.type === "relation";
// The overlay is held off the row's leading edge so the name stays readable (see the stylesheet)
@@ -85,57 +80,16 @@ export default function AttributeValueEditor({ note, attribute, onEdit, onCommit
}
}, []);
- useEffect(() => {
- const editor = containerRef.current;
- if (!editor) return;
-
- const onFocusOut = (e: FocusEvent) => {
- // Focus moving within the editor — the field to a button beside it — is not leaving it.
- if (e.relatedTarget instanceof Node && editor.contains(e.relatedTarget)) return;
-
- // Nor is it leaving for floating UI that belongs to the field: the note search's dropdown
- // is appended to the body, and creating a note from it opens the note type chooser — the
- // same company the detail popup keeps itself open over.
- if (e.relatedTarget instanceof Element
- && e.relatedTarget.closest(`${AUTOCOMPLETE_DROPDOWN_SELECTOR}, .algolia-autocomplete, .modal, .modal-backdrop`)) {
- 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
- // row has not been left, and committing here would close the editor under the dialog.
- if (!e.relatedTarget && (!document.hasFocus() || editor.contains(document.activeElement))) {
- return;
- }
-
- onCommit();
- };
-
- editor.addEventListener("focusout", onFocusOut);
- return () => editor.removeEventListener("focusout", onFocusOut);
- }, [ onCommit ]);
-
return (
- <span
- ref={containerRef}
- className={clsx("attribute-value-editor", growsUpwards && "grows-upwards")}
- // Keep the press from reaching the row, which would open the popup over the edit.
- onClick={(e) => e.stopPropagation()}
- onMouseDown={(e) => {
- // The buttons beside a field (a colour's reset, a link's open) take no focus of their
- // own: letting the press blur the field would commit and unmount the editor before the
- // click could land on them.
- if (e.target instanceof Element && !e.target.closest("input, textarea, select")) {
- e.preventDefault();
- }
- }}
+ <AttributeEditorOverlay
+ overlayRef={containerRef}
+ className="attribute-value-editor"
+ onCommit={onCommit}
+ onRevert={onRevert}
+ // Enter is the note search's own key — it is what picks — so only a label commits on it;
+ // a textarea keeps it for its newlines unless it is held down with the modifier.
onKeyDown={(e) => {
- if (e.key === "Escape") {
- e.stopPropagation();
- onRevert();
- // Enter is the note search's own key — it is what picks — so only a label commits on
- // it; a textarea keeps it for its newlines unless it is held down with the modifier.
- } else if (e.key === "Enter" && typed && (typed.labelType !== "textarea" || e.ctrlKey || e.metaKey)) {
+ if (e.key === "Enter" && typed && (typed.labelType !== "textarea" || e.ctrlKey || e.metaKey)) {
e.preventDefault();
e.stopPropagation();
onCommit();
@@ -168,21 +122,21 @@ export default function AttributeValueEditor({ note, attribute, onEdit, onCommit
noteIdChanged={(noteId) => onEdit(noteId ?? "")}
/>
)}
- </span>
+ </AttributeEditorOverlay>
);
}
-/** Constant so it does not re-initialise the autocomplete on every render, as in the detail form —
- * less the buttons beside the box (go to, search, recent), which are more furniture than a row has
- * room for; the field a relation holding several targets offers leaves them out the same way. */
-const TARGET_NOTE_OPTS = { allowCreatingNotes: true, hideAllButtons: true };
-
/** The input types whose content `select()` applies to; the pickers select nothing and mind nothing. */
const SELECT_ALL_TYPES = new Set([ "text", "number", "url", "email", "tel" ]);
/** The breath between the name and the overlay's edge: the gap the row lays its items out with. */
const ROW_GAP = 6;
+/** Constant so it does not re-initialise the autocomplete on every render, as in the detail form —
+ * less the buttons beside the box (go to, search, recent), which are more furniture than a row has
+ * room for; the field a relation holding several targets offers leaves them out the same way. */
+export const TARGET_NOTE_OPTS = { allowCreatingNotes: true, hideAllButtons: true };
+
/**
* What kind of field the label's value is edited through: for a system label the same closed sets and
* kinds the detail form offers, exclusions included (a flag means what its presence means, so no