Skip to content

Build your personal knowledge base with Trilium Notes

feat(attributes): list the attributes in a right panel widget

Elian Dorance13161b0369
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
index a1f9e696a0..29402f5f10 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
@@ -43,6 +43,12 @@ export interface AttributeDetailOpts {
*/
parent?: HTMLElement;
hideMultiplicity?: boolean;
+ /**
+ * Places the popup beside this element instead of at `x`/`y`. For hosts whose attributes are shown
+ * far from the note attributes pane the coordinates are otherwise resolved against, e.g. the
+ * attributes panel in the right pane.
+ */
+ anchor?: HTMLElement;
}
/**
@@ -759,7 +765,9 @@ function positionPopup(popup: HTMLElement, { x, y, anchor }: AttributeDetailOpts
return;
}
- if (isNewLayout) {
+ if (anchor) {
+ positionPopupBesideAnchor(popup, anchor);
+ } else if (isNewLayout) {
// The popup always sits above the note attributes pane so it never covers it;
// when the pane is closed (e.g. opened from the collection column editor),
// it docks to the status bar instead.
@@ -791,6 +799,35 @@ function positionPopup(popup: HTMLElement, { x, y, anchor }: AttributeDetailOpts
}
}
+/** How far the popup stays from its anchor, and from the edges of the viewport. */
+const ANCHOR_GAP = 8;
+const VIEWPORT_MARGIN = 10;
+
+/**
+ * Beside the anchor rather than over it: the hosts that anchor sit against an edge of the viewport
+ * (the right pane), so the popup takes whichever side of the anchor has the room for it.
+ */
+function positionPopupBesideAnchor(popup: HTMLElement, anchor: HTMLElement) {
+ const anchorRect = anchor.getBoundingClientRect();
+ const windowWidth = document.documentElement.clientWidth;
+ const windowHeight = document.documentElement.clientHeight;
+
+ // Set before measuring the height below, which the cap may well decide.
+ popup.style.maxHeight = `${windowHeight - 2 * VIEWPORT_MARGIN}px`;
+
+ const outerWidth = popup.offsetWidth;
+ const outerHeight = popup.offsetHeight;
+ const left = anchorRect.left >= outerWidth + ANCHOR_GAP + VIEWPORT_MARGIN
+ ? anchorRect.left - outerWidth - ANCHOR_GAP
+ : Math.min(anchorRect.right + ANCHOR_GAP, windowWidth - outerWidth - VIEWPORT_MARGIN);
+
+ popup.style.left = `${Math.max(left, VIEWPORT_MARGIN)}px`;
+ popup.style.right = "";
+ // Level with the anchor, slid up as far as needed to stay wholly on screen.
+ popup.style.top = `${Math.max(Math.min(anchorRect.top, windowHeight - outerHeight - VIEWPORT_MARGIN), VIEWPORT_MARGIN)}px`;
+ popup.style.bottom = "";
+}
+
function getDetailPosition(x: number, offsetLeft: number, outerWidth: number) {
let left: number | string = x - offsetLeft - outerWidth / 2;
let right: number | string = "";
diff --git a/apps/client/src/widgets/sidebar/AttributeList.css b/apps/client/src/widgets/sidebar/AttributeList.css
new file mode 100644
index 0000000000..37edcce6a2
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/AttributeList.css
@@ -0,0 +1,131 @@
+.attribute-list-panel {
+ display: flex;
+ flex-direction: column;
+}
+
+.attribute-list-panel .attribute-rows {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.attribute-list-panel .attribute-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 3px 4px;
+ border-radius: var(--border-radius-size, 4px);
+ cursor: pointer;
+ /* A row stands for its attribute rather than spelling it out, so nothing wraps: the name and the
+ value are cut off instead, and the popup the row opens has them in full. */
+ white-space: nowrap;
+ overflow: hidden;
+}
+
+.attribute-list-panel .attribute-row:hover,
+.attribute-list-panel .attribute-row.active {
+ background-color: var(--hover-item-background-color);
+}
+
+/*
+ * The kind of the attribute, as the icon of what it is (a label or a relation). It is the only thing
+ * saying so, the row carrying neither the `#`/`~` prefix nor the type as a word.
+ */
+.attribute-list-panel .attribute-kind {
+ position: relative;
+ display: flex;
+ flex-shrink: 0;
+ color: var(--muted-text-color);
+}
+
+/* A definition is the same icon with a cog on it: it configures the label or relation it names, so it
+ reads as one, rather than as a third kind of thing with an icon of its own. */
+.attribute-list-panel .attribute-kind.definition::after {
+ content: "\ea6e"; /* lookup code for "cog" in boxicons.css */
+ position: absolute;
+ inset-inline-end: -3px;
+ bottom: -2px;
+ font-family: boxicons;
+ font-size: 0.62em;
+ font-weight: normal;
+ line-height: 1;
+ /* Punched out of the icon it sits on, so the two glyphs stay legible where they overlap. */
+ text-shadow:
+ 0 0 2px var(--card-background-color, var(--main-background-color)),
+ 0 0 2px var(--card-background-color, var(--main-background-color));
+}
+
+.attribute-list-panel .attribute-name {
+ flex-shrink: 0;
+ max-width: 65%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-weight: bold;
+}
+
+.attribute-list-panel .attribute-value {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ color: var(--muted-text-color);
+}
+
+.attribute-list-panel .attribute-value.empty {
+ font-style: italic;
+ opacity: 0.7;
+}
+
+/* The settings of a definition, which are a summary and not a value: quieter than one, and never the
+ reason the row is as wide as it is. */
+.attribute-list-panel .attribute-value.definition {
+ font-size: 0.85em;
+ text-transform: lowercase;
+}
+
+.attribute-list-panel .attribute-marker,
+.attribute-list-panel .attribute-owner {
+ flex-shrink: 0;
+ color: var(--muted-text-color);
+ font-size: 0.85em;
+}
+
+.attribute-list-panel .attribute-owner {
+ max-width: 40%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* Deleting is destructive and one row deep, so the button only appears on the row being pointed at. */
+.attribute-list-panel .attribute-delete-button {
+ flex-shrink: 0;
+ visibility: hidden;
+}
+
+.attribute-list-panel .attribute-row:hover .attribute-delete-button,
+.attribute-list-panel .attribute-row.active .attribute-delete-button {
+ visibility: visible;
+}
+
+.attribute-list-panel .attribute-group-header {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ margin-top: 8px;
+ padding: 2px 4px;
+ border: none;
+ background: none;
+ color: var(--muted-text-color);
+ font-size: 0.85em;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ cursor: pointer;
+}
+
+.attribute-list-panel .attribute-group-header .group-chevron {
+ transition: transform 0.2s ease;
+}
+
+.attribute-list-panel .attribute-group-header .group-chevron.collapsed {
+ transform: rotate(-90deg);
+}
diff --git a/apps/client/src/widgets/sidebar/AttributeList.spec.ts b/apps/client/src/widgets/sidebar/AttributeList.spec.ts
new file mode 100644
index 0000000000..c1e399ca79
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/AttributeList.spec.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+
+import FAttribute, { FAttributeRow } from "../../entities/fattribute";
+import froca from "../../services/froca";
+import { getAttributeKind, getDisplayName, listInherited, listOwned } from "./AttributeList";
+
+describe("listOwned", () => {
+ it("orders by position and leaves out the attributes Trilium maintains itself", () => {
+ const rows = listOwned([
+ attribute({ name: "second", position: 20 }),
+ attribute({ type: "relation", name: "internalLink", value: "target", position: 30 }),
+ attribute({ name: "first", position: 10, value: "red", isInheritable: true })
+ ]);
+
+ expect(rows.map((row) => row.name)).toEqual([ "first", "second" ]);
+ expect(rows[0]).toMatchObject({
+ type: "label", name: "first", value: "red", isInheritable: true
+ });
+ });
+});
+
+describe("listInherited", () => {
+ it("keeps only what comes from other notes, grouped by the note it comes from", () => {
+ const rows = listInherited([
+ attribute({ noteId: "bbb", name: "fromB2", position: 20 }),
+ attribute({ noteId: "own", name: "ownLabel" }),
+ attribute({ noteId: "aaa", name: "fromA" }),
+ attribute({ noteId: "bbb", name: "fromB1", position: 10 })
+ ], "own");
+
+ expect(rows.map((row) => row.name)).toEqual([ "fromA", "fromB1", "fromB2" ]);
+ expect(rows.map((row) => row.noteId)).toEqual([ "aaa", "bbb", "bbb" ]);
+ });
+});
+
+describe("getAttributeKind / getDisplayName", () => {
+ it("tells a definition from what it defines, and shows it without its prefix", () => {
+ const cases: [ FAttributeRow["type"], string, string, string ][] = [
+ // type, name, expected kind, expected displayed name
+ [ "label", "color", "label", "color" ],
+ [ "relation", "template", "relation", "template" ],
+ [ "label", "label:color", "label-definition", "color" ],
+ [ "label", "relation:author", "relation-definition", "author" ],
+ // A bare prefix defines nothing, so it stays an ordinary label — name and all.
+ [ "label", "label:", "label", "label:" ]
+ ];
+
+ for (const [ type, name, expectedKind, expectedName ] of cases) {
+ const attrType = getAttributeKind({ type, name });
+ expect(attrType, name).toBe(expectedKind);
+ expect(getDisplayName({ type, name }, attrType), name).toBe(expectedName);
+ }
+ });
+});
+
+function attribute(row: Partial<FAttributeRow>) {
+ return new FAttribute(froca, {
+ attributeId: `attr-${row.name ?? "x"}`,
+ noteId: "own",
+ type: "label",
+ name: "label",
+ value: "",
+ position: 10,
+ isInheritable: false,
+ ...row
+ });
+}
diff --git a/apps/client/src/widgets/sidebar/AttributeList.tsx b/apps/client/src/widgets/sidebar/AttributeList.tsx
new file mode 100644
index 0000000000..7d6908662e
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/AttributeList.tsx
@@ -0,0 +1,428 @@
+import "./AttributeList.css";
+
+import clsx from "clsx";
+import { createPortal } from "preact/compat";
+import { useContext, useEffect, useRef, useState } from "preact/hooks";
+
+import FAttribute from "../../entities/fattribute";
+import FNote from "../../entities/fnote";
+import contextMenu from "../../menus/context_menu";
+import type { Attribute } from "../../services/attribute_parser";
+import attributes from "../../services/attributes";
+import { t } from "../../services/i18n";
+import promotedAttributeDefinitionParser from "../../services/promoted_attribute_definition_parser";
+import server from "../../services/server";
+import { AttributeDetail, AttributeDetailOpts, AttrType, getAttrType, LABEL_TYPES } from "../attribute_widgets/attribute_detail";
+import ActionButton from "../react/ActionButton";
+import HelpButton from "../react/HelpButton";
+import { useActiveNoteContext, useTriliumEvent } from "../react/hooks";
+import Icon from "../react/Icon";
+import NoItems from "../react/NoItems";
+import NoteLink from "../react/NoteLink";
+import { ParentComponent } from "../react/react_utils";
+import { ATTRIBUTE_HELP_PAGE } from "../ribbon/components/AttributeHelp";
+import RightPanelWidget from "./RightPanelWidget";
+
+/**
+ * The note's attributes as a list, one row per attribute: the kind (label, relation, or either's
+ * definition) is carried by an icon instead of by the `#`/`~`/`label:` syntax the attributes editor
+ * spells out, and the value is shown as a preview rather than in full. Rows open the same detail
+ * popup the editor uses, which is where an attribute is actually edited.
+ */
+export default function AttributeList() {
+ const { note } = useActiveNoteContext();
+ const parentComponent = useContext(ParentComponent);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [ detail, setDetail ] = useState<AttributeDetailOpts | null>(null);
+ const [ inheritedShown, setInheritedShown ] = useState(false);
+ const componentId = parentComponent?.componentId;
+
+ // The owned rows double as the detail popup's working copy: it edits the very objects it is handed,
+ // so both lists are kept in refs (whose identity the popup holds on to) and redrawn by hand.
+ const owned = useRef<Attribute[]>([]);
+ const inherited = useRef<Attribute[]>([]);
+ const [ , setRevision ] = useState(0);
+ const rerender = () => setRevision((revision) => revision + 1);
+
+ // Collected while rendering rather than in an effect, which would leave one frame listing the
+ // attributes of the note navigated away from. The initial `undefined` is what collects the first.
+ const shownNoteId = useRef<string | null>();
+ if (shownNoteId.current !== (note?.noteId ?? null)) {
+ shownNoteId.current = note?.noteId ?? null;
+ owned.current = collectOwned(note);
+ inherited.current = collectInherited(note);
+ }
+
+ // The popup edits one attribute of the note being left, so it closes with the note.
+ useEffect(() => setDetail(null), [ note ]);
+
+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
+ // While the popup 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 it is 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 ? loadResults.getAttributeRows(componentId) : loadResults.getAttributeRows();
+ if (note && changed.some((attr) => attributes.isAffecting(attr, note))) {
+ owned.current = collectOwned(note);
+ inherited.current = collectInherited(note);
+ rerender();
+ }
+ });
+
+ /** Persists the whole draft: the endpoint replaces the note's owned attributes with the list. */
+ async function save() {
+ if (note) {
+ await server.put(`notes/${note.noteId}/attributes`, owned.current, componentId);
+ }
+ }
+
+ function openDetail(attribute: Attribute, isOwned: boolean, anchor: HTMLElement | null, e: MouseEvent) {
+ setDetail({
+ allAttributes: isOwned ? owned.current : undefined,
+ attribute,
+ isOwned,
+ x: e.pageX,
+ y: e.pageY,
+ anchor: anchor ?? undefined,
+ // Presses on another row swap the shown attribute instead of dismissing the popup first.
+ parent: containerRef.current ?? undefined
+ });
+ }
+
+ function addAttribute(attrType: AttributeKind, e: MouseEvent) {
+ const attribute = createAttribute(attrType);
+
+ owned.current = [ ...owned.current, attribute ];
+ setDetail({
+ allAttributes: owned.current,
+ attribute,
+ isOwned: true,
+ x: e.pageX,
+ y: e.pageY,
+ focus: "name",
+ // There is no row to anchor to yet: the attribute only joins the list once it is saved.
+ anchor: containerRef.current ?? undefined,
+ parent: containerRef.current ?? undefined
+ });
+ }
+
+ /** Closes the popup keeping its edits: a list of rows has no save step of its own. */
+ function commit() {
+ const isOwned = detail?.isOwned;
+
+ setDetail(null);
+ if (isOwned) {
+ void save();
+ }
+ }
+
+ async function deleteAttribute(attribute: Attribute) {
+ owned.current = owned.current.filter((candidate) => candidate !== attribute);
+ setDetail(null);
+ rerender();
+
+ await save();
+ }
+
+ return (
+ <RightPanelWidget
+ id="attributes"
+ title={t("attribute_list_panel.title")}
+ buttons={note && (
+ <>
+ <HelpButton helpPage={ATTRIBUTE_HELP_PAGE} />
+ <ActionButton
+ icon="bx bx-plus"
+ text={t("attribute_editor.add_a_new_attribute")}
+ onClick={(e) => {
+ // Keep the press from reaching the card header, which would collapse the card.
+ e.stopPropagation();
+ showAddMenu(e, (attrType) => addAttribute(attrType, e));
+ }}
+ />
+ </>
+ )}
+ >
+ {/* Presses inside the container do not dismiss the popup (see `parent` above), which leaves
+ closing on a press next to a row up to this handler. */}
+ <div class="attribute-list-panel" ref={containerRef} onClick={() => setDetail(null)}>
+ {!owned.current.length && !inherited.current.length && (
+ <NoItems icon="bx bx-hash" text={t("attribute_list_panel.no_attributes")} />
+ )}
+
+ {owned.current.length > 0 && (
+ <ul class="attribute-rows">
+ {owned.current.map((attribute, index) => (
+ <AttributeRow
+ key={attribute.attributeId ?? `new-${index}`}
+ attribute={attribute}
+ active={detail?.attribute === attribute}
+ onOpen={(anchor, e) => openDetail(attribute, true, anchor, e)}
+ onDelete={() => void deleteAttribute(attribute)}
+ />
+ ))}
+ </ul>
+ )}
+
+ {inherited.current.length > 0 && (
+ <>
+ {/* Inherited attributes are read-only and usually outnumber the note's own, so
+ they stay folded away behind their count. */}
+ <button
+ class="attribute-group-header"
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ setInheritedShown(!inheritedShown);
+ }}
+ >
+ <Icon icon="bx bx-chevron-down" className={clsx("group-chevron", !inheritedShown && "collapsed")} />
+ {t("attribute_list_panel.inherited", { count: inherited.current.length })}
+ </button>
+
+ {inheritedShown && (
+ <ul class="attribute-rows">
+ {inherited.current.map((attribute) => (
+ <AttributeRow
+ key={attribute.attributeId}
+ attribute={attribute}
+ active={detail?.attribute === attribute}
+ showOwner
+ onOpen={(anchor, e) => openDetail(attribute, false, anchor, e)}
+ />
+ ))}
+ </ul>
+ )}
+ </>
+ )}
+ </div>
+
+ {createPortal(
+ <AttributeDetail
+ opts={detail}
+ currentNoteId={note?.noteId}
+ // A press outside keeps the edits, matching the attributes editor (which saves on
+ // blur); the close button and escape go through onCancel and revert instead.
+ onDismiss={commit}
+ onCancel={() => {
+ if (note) {
+ owned.current = collectOwned(note);
+ }
+ setDetail(null);
+ rerender();
+ }}
+ // The popup edits the attribute in place, so there is nothing to apply here: the
+ // rows only need to be redrawn to follow along as it is typed into.
+ onAttributesChanged={rerender}
+ // An inherited attribute is shown read-only, so it has neither of the two.
+ onSaveAndClose={detail?.isOwned ? commit : undefined}
+ onDelete={detail?.isOwned ? () => void deleteAttribute(detail.attribute) : undefined}
+ />,
+ document.body)}
+ </RightPanelWidget>
+ );
+}
+
+interface AttributeRowProps {
+ attribute: Attribute;
+ /** Whether the detail popup is currently showing this attribute. */
+ active: boolean;
+ /** Names the note the attribute is inherited from, for attributes not owned by the current note. */
+ showOwner?: boolean;
+ onOpen: (anchor: HTMLElement | null, e: MouseEvent) => void;
+ onDelete?: () => void;
+}
+
+function AttributeRow({ attribute, active, showOwner, onOpen, onDelete }: AttributeRowProps) {
+ const rowRef = useRef<HTMLLIElement>(null);
+ const attrType = getAttributeKind(attribute);
+
+ return (
+ <li
+ ref={rowRef}
+ class={clsx("attribute-row", active && "active")}
+ title={t(KIND_TITLES[attrType])}
+ onClick={(e) => {
+ // Keep the container's closing handler from undoing this.
+ e.stopPropagation();
+ onOpen(rowRef.current, e);
+ }}
+ >
+ {/* The kind is the icon: a definition carries the icon of what it defines, marked as a
+ definition, so `label:foo` reads as a label rather than as a label named "label:foo". */}
+ <span class={clsx("attribute-kind", isDefinition(attrType) && "definition")}>
+ <Icon icon={attrType === "relation" || attrType === "relation-definition" ? "bx bx-transfer" : "bx bx-hash"} />
+ </span>
+
+ <span class="attribute-name">{getDisplayName(attribute, attrType)}</span>
+
+ <AttributeValue attribute={attribute} attrType={attrType} />
+
+ {attribute.isInheritable && (
+ <Icon
+ className="attribute-marker"
+ icon="bx bx-sitemap"
+ title={t("attribute_list_panel.inheritable")}
+ />
+ )}
+
+ {showOwner && attribute.noteId && (
+ <NoteLink containerClassName="attribute-owner" notePath={attribute.noteId} noPreview />
+ )}
+
+ {onDelete && (
+ <ActionButton
+ className="attribute-delete-button"
+ icon="bx bx-x"
+ text={t("attribute_list_panel.delete")}
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete();
+ }}
+ />
+ )}
+ </li>
+ );
+}
+
+/** A preview of what the attribute holds — the row stands for the attribute, the popup shows it in full. */
+function AttributeValue({ attribute, attrType }: { attribute: Attribute; attrType: AttributeKind }) {
+ if (attrType === "relation") {
+ // A relation just created from the add menu has no target yet.
+ return attribute.value
+ ? <NoteLink containerClassName="attribute-value" notePath={attribute.value} showNoteIcon noPreview />
+ : <span class="attribute-value empty">{t("attribute_list_panel.no_target")}</span>;
+ }
+
+ if (isDefinition(attrType)) {
+ return <span class="attribute-value definition">{summarizeDefinition(attribute, attrType)}</span>;
+ }
+
+ return attribute.value
+ ? <span class="attribute-value" title={attribute.value}>{attribute.value}</span>
+ : null;
+}
+
+/** What a definition sets up, in the order the popup offers it: type, multiplicity, then the extras. */
+function summarizeDefinition(attribute: Attribute, attrType: AttributeKind) {
+ const definition = promotedAttributeDefinitionParser.parse(attribute.value ?? "");
+ const parts: string[] = [];
+
+ if (attrType === "label-definition") {
+ const labelType = definition.labelType ?? "text";
+ parts.push(LABEL_TYPES.find(({ value }) => value === labelType)?.title ?? labelType);
+ }
+
+ if (definition.multiplicity === "multi") {
+ parts.push(t("attribute_detail.multi_value"));
+ }
+
+ if (definition.isPromoted) {
+ parts.push(t("attribute_detail.promoted"));
+ }
+
+ if (definition.inverseRelation) {
+ parts.push(t("attribute_list_panel.inverse_of", { name: definition.inverseRelation }));
+ }
+
+ return parts.join(" · ");
+}
+
+type AttributeKind = NonNullable<AttrType>;
+
+export function getAttributeKind(attribute: Attribute): AttributeKind {
+ // The popup resolves the kind of what it is about to edit the same way; an attribute that is
+ // neither a label nor a relation cannot reach a list built from the note's own attributes.
+ return getAttrType(attribute) ?? attribute.type;
+}
+
+function isDefinition(attrType: AttributeKind) {
+ return attrType === "label-definition" || attrType === "relation-definition";
+}
+
+/** Definitions are stored prefixed (`label:foo`), but the prefix is what the icon already says. */
+export function getDisplayName(attribute: Attribute, attrType: AttributeKind) {
+ return isDefinition(attrType)
+ ? attribute.name.substring(attribute.name.indexOf(":") + 1)
+ : attribute.name;
+}
+
+const KIND_TITLES: Record<AttributeKind, string> = {
+ label: t("attribute_list_panel.type_label"),
+ relation: t("attribute_list_panel.type_relation"),
+ "label-definition": t("attribute_list_panel.type_label_definition"),
+ "relation-definition": t("attribute_list_panel.type_relation_definition")
+};
+
+function showAddMenu(e: MouseEvent, onSelect: (attrType: AttributeKind) => void) {
+ void contextMenu.show({
+ x: e.pageX,
+ y: e.pageY,
+ orientation: "left",
+ items: [
+ { title: t("attribute_editor.add_new_label"), uiIcon: "bx bx-hash", handler: () => onSelect("label") },
+ { title: t("attribute_editor.add_new_relation"), uiIcon: "bx bx-transfer", handler: () => onSelect("relation") },
+ { kind: "separator" },
+ { title: t("attribute_editor.add_new_label_definition"), uiIcon: "bx bx-hash", handler: () => onSelect("label-definition") },
+ { title: t("attribute_editor.add_new_relation_definition"), uiIcon: "bx bx-transfer", handler: () => onSelect("relation-definition") }
+ ],
+ selectMenuItemHandler: () => {}
+ });
+}
+
+/** The defaults the attributes editor's add menu creates, so both entry points agree. */
+function createAttribute(attrType: AttributeKind): Attribute {
+ switch (attrType) {
+ case "label":
+ return { type: "label", name: "myLabel", value: "", isInheritable: false };
+ case "relation":
+ return { type: "relation", name: "myRelation", value: "", isInheritable: false };
+ case "label-definition":
+ return { type: "label", name: "label:myLabel", value: "promoted,single,text", isInheritable: false };
+ case "relation-definition":
+ return { type: "label", name: "relation:myRelation", value: "promoted,single", isInheritable: false };
+ }
+}
+
+function collectOwned(note: FNote | null | undefined): Attribute[] {
+ return listOwned(note?.getOwnedAttributes() ?? []);
+}
+
+function collectInherited(note: FNote | null | undefined): Attribute[] {
+ return listInherited(note?.getAttributes() ?? [], note?.noteId);
+}
+
+/** The note's own attributes, in the order it holds them. */
+export function listOwned(ownedAttributes: FAttribute[]): Attribute[] {
+ return ownedAttributes
+ // Attributes Trilium maintains itself (the links of the note's content) are not metadata the
+ // note was given, and are preserved across a save regardless, so they are left out.
+ .filter((attribute) => !attribute.isAutoLink)
+ .toSorted((a, b) => a.position - b.position)
+ .map(toPlainAttribute);
+}
+
+/** Everything reaching the note from elsewhere, out of the effective attributes it is mixed into. */
+export function listInherited(effectiveAttributes: FAttribute[], noteId: string | undefined): Attribute[] {
+ return effectiveAttributes
+ .filter((attribute) => attribute.noteId !== noteId && !attribute.isAutoLink)
+ // Inherited attributes stay grouped by the note they come from:
+ // https://github.com/zadam/trilium/issues/3761
+ .toSorted((a, b) => a.noteId === b.noteId ? a.position - b.position : a.noteId.localeCompare(b.noteId))
+ .map(toPlainAttribute);
+}
+
+/**
+ * The rows and the detail popup work on plain attributes, which the popup is free to edit in place
+ * without touching the cached entity behind them.
+ */
+function toPlainAttribute(attribute: FAttribute): Attribute {
+ return {
+ attributeId: attribute.attributeId,
+ noteId: attribute.noteId,
+ type: attribute.type,
+ name: attribute.name,
+ value: attribute.value,
+ isInheritable: attribute.isInheritable
+ };
+}
diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
index a5c2c5d6da..c3d933a6e9 100644
--- a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
@@ -19,6 +19,7 @@ import LazyComponent from "../react/LazyComponent";
import NoItems from "../react/NoItems";
import { PaneMode, usePaneMode, usePeekDismiss } from "../react/peek_pane";
import LegacyRightPanelWidget from "../right_panel_widget";
+import AttributeList from "./AttributeList";
import ChatHighlightsList from "./ChatHighlightsList";
import HighlightsList from "./HighlightsList";
import PdfAnnotations from "./pdf/PdfAnnotations";
@@ -117,6 +118,10 @@ function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent) {
if (!rightPaneVisible) return [];
const definitions: RightPanelWidgetDefinition[] = [
+ {
+ el: <AttributeList />,
+ enabled: !!note
+ },
{
el: <TableOfContents />,
enabled: (noteType === "text" || noteType === "doc" || isPdf || noteType === "llmChat" || !!note?.isMarkdown()),