Skip to content

Build your personal knowledge base with Trilium Notes

feat(attributes): list Trilium's own bookkeeping in the panel

Elian Doran4896922337ae
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index a4d416812b..7604e7d97c 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -667,6 +667,8 @@
"inherited_other": "{{count}} inherited attributes",
"definitions_one": "{{count}} definition",
"definitions_other": "{{count}} definitions",
+ "internal_one": "{{count}} internal system attribute",
+ "internal_other": "{{count}} internal system attributes",
"inheritable": "Inheritable: applies to this note and to its whole subtree",
"delete": "Delete this attribute",
"delete_confirm": "Delete the attribute \"{{name}}\"?",
@@ -1140,9 +1142,6 @@
"no_inherited_attributes": "No inherited attributes.",
"none": "none"
},
- "auto_link_attribute_list": {
- "title": "System Attributes"
- },
"note_info_widget": {
"note_id": "Note ID",
"created": "Created",
diff --git a/apps/client/src/widgets/layout/StatusBar.css b/apps/client/src/widgets/layout/StatusBar.css
index 76d709bbf1..90267bf1f7 100644
--- a/apps/client/src/widgets/layout/StatusBar.css
+++ b/apps/client/src/widgets/layout/StatusBar.css
@@ -90,8 +90,7 @@
font-weight: 600;
}
- .inherited-attributes-widget,
- .auto-link-attributes-widget {
+ .inherited-attributes-widget {
display: inline;
> div {
diff --git a/apps/client/src/widgets/layout/StatusBar.tsx b/apps/client/src/widgets/layout/StatusBar.tsx
index 9a5ab530d1..8c83124e3f 100644
--- a/apps/client/src/widgets/layout/StatusBar.tsx
+++ b/apps/client/src/widgets/layout/StatusBar.tsx
@@ -25,7 +25,6 @@ import { useActiveNoteContext, useLegacyImperativeHandlers, useNoteLabel, useNot
import Icon from "../react/Icon";
import LinkButton from "../react/LinkButton";
import { ParentComponent } from "../react/react_utils";
-import AutoLinkAttributesTab from "../ribbon/AutoLinkAttributesTab";
import { ContentLanguagesModal, NoteTypeCodeNoteList, NoteTypeOptionsModal, useLanguageSwitcher, useMimeTypes } from "../ribbon/BasicPropertiesTab";
import AttributeEditor, { AttributeEditorImperativeHandlers } from "../ribbon/components/AttributeEditor";
import AttributeHelp, { ATTRIBUTE_HELP_PAGE } from "../ribbon/components/AttributeHelp";
@@ -416,11 +415,6 @@ function AttributesPane({ note, noteContext, attributesShown, setAttributesShown
<span class="attributes-panel-label">{t("inherited_attribute_list.title")}</span>
<InheritedAttributesTab {...context} emptyListString="inherited_attribute_list.none" />
- {glob.isDev && <div>
- <span class="attributes-panel-label">{t("auto_link_attribute_list.title")}</span>
- <AutoLinkAttributesTab {...context} />
- </div>}
-
{editorMounted && <AttributeEditor
{...context}
api={api}
diff --git a/apps/client/src/widgets/ribbon/AutoLinkAttributesTab.tsx b/apps/client/src/widgets/ribbon/AutoLinkAttributesTab.tsx
deleted file mode 100644
index 1d54edbfb6..0000000000
--- a/apps/client/src/widgets/ribbon/AutoLinkAttributesTab.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { useEffect, useState } from "preact/hooks";
-
-import FAttribute from "../../entities/fattribute";
-import attributes from "../../services/attributes";
-import froca from "../../services/froca";
-import { useTriliumEvent } from "../react/hooks";
-import { joinElements } from "../react/react_utils";
-import { TabContext } from "./ribbon-interface";
-
-type AutoLinkAttributesTabArgs = Pick<TabContext, "note" | "componentId">;
-
-export default function AutoLinkAttributesTab({ note, componentId }: AutoLinkAttributesTabArgs) {
- const [autoLinkAttributes, setAutoLinkAttributes] = useState<FAttribute[]>();
-
- function refresh() {
- if (!note) return;
- const attrs = note.getAttributes().filter((attr) => attr.isAutoLink && attr.noteId === note.noteId);
- setAutoLinkAttributes(attrs);
- }
-
- useEffect(refresh, [note]);
- useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
- if (loadResults.getAttributeRows(componentId).find((attr) => attributes.isAffecting(attr, note))) {
- refresh();
- }
- });
-
- if (!autoLinkAttributes?.length) {
- return null;
- }
-
- return (
- <div className="auto-link-attributes-widget">
- <div className="auto-link-attributes-container selectable-text">
- {joinElements(autoLinkAttributes.map((attribute) => (
- <AutoLinkAttribute key={attribute.attributeId} attribute={attribute} />
- )), " ")}
- </div>
- </div>
- );
-}
-
-function AutoLinkAttribute({ attribute }: { attribute: FAttribute }) {
- const [html, setHtml] = useState<string>("");
-
- useEffect(() => {
- renderAutoLink(attribute).then(setHtml);
- }, [attribute]);
-
- return <span dangerouslySetInnerHTML={{ __html: html }} />;
-}
-
-async function renderAutoLink(attribute: FAttribute) {
- if (attribute.type === "label") {
- return `#${escapeHtml(attribute.name)}=${escapeHtml(attribute.value)}`;
- }
-
- const note = await froca.getNote(attribute.value);
- if (!note) return "";
-
- const link = `<a href="#root/${attribute.value}" class="reference-link">${escapeHtml(note.title)}</a>`;
- return `~${escapeHtml(attribute.name)}=${link}`;
-}
-
-function escapeHtml(text: string) {
- const el = document.createElement("span");
- el.textContent = text;
- return el.innerHTML;
-}
diff --git a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
index 0c1b617f34..f5417ee78b 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
@@ -33,7 +33,7 @@ import noteAttributeCache from "../../services/note_attribute_cache";
import options from "../../services/options";
import server from "../../services/server";
import { buildNote } from "../../test/easy-froca";
-import AttributeList, { getAttributeKind, getDisplayName, listInherited, listOwned, splitIntoSections } from "./AttributeList";
+import AttributeList, { getAttributeKind, getDisplayName, listInherited, listInternal, listOwned, splitIntoSections } from "./AttributeList";
describe("listOwned", () => {
it("orders by position and leaves out the attributes Trilium maintains itself", () => {
@@ -64,6 +64,18 @@ describe("listInherited", () => {
});
});
+describe("listInternal", () => {
+ it("keeps exactly what the owned list leaves out: what Trilium wrote from the note's content", () => {
+ const rows = listInternal([
+ attribute({ name: "author", value: "Elian" }),
+ attribute({ type: "relation", name: "internalLink", value: "target", position: 30 }),
+ attribute({ type: "relation", name: "imageLink", value: "image", position: 20 })
+ ]);
+
+ expect(rows.map((row) => row.name)).toEqual([ "imageLink", "internalLink" ]);
+ });
+});
+
describe("splitIntoSections", () => {
it("sets the definitions of either aside, the note's own first, and splits the rest by ownership", () => {
const sections = splitIntoSections(
@@ -117,6 +129,8 @@ describe("AttributeList", () => {
beforeEach(() => {
vi.clearAllMocks();
options.set("rightPaneCollapsedItems", "[]");
+ // A release build, unless the test at hand is about what only a development one shows.
+ setDevBuild(false);
put = vi.fn(async () => ({}));
server.put = put as unknown as typeof server.put;
// The detail popup looks up the notes sharing the attribute it opens on, against the tab the
@@ -184,6 +198,29 @@ describe("AttributeList", () => {
expect(container.querySelector(".no-items")).not.toBeNull();
});
+ it("leaves what Trilium wrote for itself out of a release build, and gives it its own card in a development one", () => {
+ buildNote({ id: "target", title: "Target" });
+ const note = buildNote({ id: "linking", title: "Linking", "#author": "Elian", "~internalLink": "target" });
+
+ renderPanel(note);
+ expect(cardIds()).toEqual([ "attributes" ]);
+
+ // Unmounted first, the panel collecting the attributes of the note it is handed as it mounts.
+ setDevBuild(true);
+ render(null, container);
+ renderPanel(note);
+
+ const cards = [ ...container.querySelectorAll(".card") ];
+ expect(cardIds()).toEqual([ "attributes", "attributes-internal" ]);
+ expect(namesIn(cards[1])).toEqual([ "internalLink" ]);
+ // Nothing on such a row is the note's to change, and nothing marks it as Trilium's own: the
+ // card it is in says as much of every row it holds.
+ expect(cards[1].querySelectorAll(".attribute-delete-button")).toHaveLength(0);
+ expect(cards[1].querySelectorAll(".attribute-owner")).toHaveLength(0);
+ expect(cards[1].querySelector(".attribute-kind")?.className).not.toContain("marker-system");
+ expect(cards[1].querySelectorAll("hr.attribute-rows-divider")).toHaveLength(0);
+ });
+
it("opens the detail popup on a row and closes it again on a press beside the rows", () => {
renderPanel(noteWithAttributes());
@@ -277,6 +314,10 @@ describe("AttributeList", () => {
act(() => render(<AttributeList />, container));
}
+ function cardIds() {
+ return [ ...container.querySelectorAll(".card") ].map((card) => card.id);
+ }
+
function firstRow() {
const row = container.querySelector<HTMLElement>(".attribute-row");
expect(row).not.toBeNull();
@@ -284,6 +325,11 @@ describe("AttributeList", () => {
}
});
+/** Which build the panel believes it is running in, which is all that decides one of its cards. */
+function setDevBuild(isDev: boolean) {
+ (window as unknown as { glob: { isDev: boolean } }).glob.isDev = isDev;
+}
+
function namesIn(root: Element) {
return [ ...root.querySelectorAll(".attribute-name") ].map((name) => name.textContent);
}
diff --git a/apps/client/src/widgets/sidebar/AttributeList.tsx b/apps/client/src/widgets/sidebar/AttributeList.tsx
index 3372d7e1c9..7e0432a5f0 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeList.tsx
@@ -41,6 +41,7 @@ export default function AttributeList() {
// 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 internal = useRef<Attribute[]>([]);
const [ , setRevision ] = useState(0);
const rerender = () => setRevision((revision) => revision + 1);
@@ -51,6 +52,7 @@ export default function AttributeList() {
shownNoteId.current = note?.noteId ?? null;
owned.current = collectOwned(note);
inherited.current = collectInherited(note);
+ internal.current = collectInternal(note);
}
// The popup edits one attribute of the note being left, so it closes with the note.
@@ -65,6 +67,7 @@ export default function AttributeList() {
if (note && changed.some((attr) => attributes.isAffecting(attr, note))) {
owned.current = collectOwned(note);
inherited.current = collectInherited(note);
+ internal.current = collectInternal(note);
rerender();
}
});
@@ -143,13 +146,17 @@ export default function AttributeList() {
}
const sections = splitIntoSections(owned.current, inherited.current);
+ const internalRows = internal.current.map((attribute) => toEntry(attribute, true));
const rowProps = {
activeAttribute: detail?.attribute,
onOpen: openDetail,
onDelete: (attribute: Attribute) => void deleteAttribute(attribute)
};
- // The cards a section has nothing for are left out, so an ordinary note sees one or two of the three.
- const shownCards = 1 + (sections.inherited.length ? 1 : 0) + (sections.definitions.length ? 1 : 0);
+ // The cards a section has nothing for are left out, so an ordinary note sees one or two of the four.
+ const shownCards = 1
+ + (sections.inherited.length ? 1 : 0)
+ + (sections.definitions.length ? 1 : 0)
+ + (internalRows.length ? 1 : 0);
return (
<>
@@ -213,6 +220,17 @@ export default function AttributeList() {
</div>
</RightPanelWidget>
)}
+
+ {internalRows.length > 0 && (
+ <RightPanelWidget
+ id="attributes-internal"
+ title={t("attribute_list_panel.internal", { count: internalRows.length })}
+ >
+ <div class="attribute-list-panel" onClick={() => setDetail(null)}>
+ <AttributeRowList rows={internalRows} readOnly {...rowProps} />
+ </div>
+ </RightPanelWidget>
+ )}
</CollapsibleWidgets.Provider>
{createPortal(
@@ -245,6 +263,13 @@ interface AttributeRowListProps {
rows: AttributeEntry[];
/** The attribute the detail popup is showing, marked as such in the list. */
activeAttribute?: Attribute;
+ /**
+ * The rows stand for attributes Trilium writes and keeps up to date itself, which leaves them
+ * nothing to offer: nothing to edit, nothing to delete, no note to name as their source (they are
+ * always the current one's), and no split to draw between the note's own names and Trilium's —
+ * every one of them is Trilium's, which is what the card they are in says.
+ */
+ readOnly?: boolean;
onOpen: (attribute: Attribute, isOwned: boolean, anchor: HTMLElement | null, e: MouseEvent) => void;
onDelete: (attribute: Attribute) => void;
}
@@ -254,7 +279,7 @@ interface AttributeRowListProps {
* Trilium reads for itself. What a row offers follows from whether the note owns its attribute rather
* than from the card it is in: the definitions card holds the note's own alongside a template's.
*/
-function AttributeRowList({ rows, activeAttribute, onOpen, onDelete }: AttributeRowListProps) {
+function AttributeRowList({ rows, activeAttribute, readOnly, onOpen, onDelete }: AttributeRowListProps) {
function renderRows(group: AttributeEntry[]) {
return (
<ul class="attribute-rows">
@@ -263,11 +288,12 @@ function AttributeRowList({ rows, activeAttribute, onOpen, onDelete }: Attribute
key={attribute.attributeId ?? `new-${index}`}
attribute={attribute}
active={activeAttribute === attribute}
- isSystem={isSystem}
+ isSystem={isSystem && !readOnly}
// An attribute of another note names it; the current note's own would name itself.
- showOwner={!isOwned}
- onOpen={(anchor, e) => onOpen(attribute, isOwned, anchor, e)}
- onDelete={isOwned ? () => onDelete(attribute) : undefined}
+ showOwner={!isOwned && !readOnly}
+ // A read-only row opens the popup as an inherited one does: to be read, not edited.
+ onOpen={(anchor, e) => onOpen(attribute, isOwned && !readOnly, anchor, e)}
+ onDelete={isOwned && !readOnly ? () => onDelete(attribute) : undefined}
/>
))}
</ul>
@@ -275,7 +301,7 @@ function AttributeRowList({ rows, activeAttribute, onOpen, onDelete }: Attribute
}
// The system attributes are sorted last (see splitIntoSections), so one index is the whole boundary.
- const boundary = rows.findIndex((entry) => entry.isSystem);
+ const boundary = readOnly ? -1 : rows.findIndex((entry) => entry.isSystem);
const userDefined = boundary < 0 ? rows : rows.slice(0, boundary);
const system = boundary < 0 ? [] : rows.slice(boundary);
@@ -572,13 +598,8 @@ export interface AttributeSections {
export function splitIntoSections(owned: Attribute[], inherited: Attribute[]): AttributeSections {
const isDefinitionEntry = ({ attribute }: AttributeEntry) => isDefinition(getAttributeKind(attribute));
- const toEntry = (isOwned: boolean) => (attribute: Attribute): AttributeEntry => ({
- attribute,
- isOwned,
- isSystem: isBuiltinAttribute(attribute.type, attribute.name)
- });
- const ownedEntries = owned.map(toEntry(true));
- const inheritedEntries = inherited.map(toEntry(false));
+ const ownedEntries = owned.map((attribute) => toEntry(attribute, true));
+ const inheritedEntries = inherited.map((attribute) => toEntry(attribute, false));
return {
owned: sortSystemLast(ownedEntries.filter((entry) => !isDefinitionEntry(entry))),
@@ -587,6 +608,10 @@ export function splitIntoSections(owned: Attribute[], inherited: Attribute[]): A
};
}
+function toEntry(attribute: Attribute, isOwned: boolean): AttributeEntry {
+ return { attribute, isOwned, isSystem: isBuiltinAttribute(attribute.type, attribute.name) };
+}
+
/**
* The names the note was given first, the ones Trilium reads for itself after them: the note's own
* vocabulary is what its reader is looking for, and `cssClass` or `template` is plumbing they set once.
@@ -604,6 +629,15 @@ function collectInherited(note: FNote | null | undefined): Attribute[] {
return listInherited(note?.getAttributes() ?? [], note?.noteId);
}
+/**
+ * The attributes Trilium writes for itself. They are bookkeeping rather than metadata — of interest
+ * when working on Trilium and noise to everyone else — so they are collected in a development build
+ * alone, as the attributes pane listed them in one before this panel took them over.
+ */
+function collectInternal(note: FNote | null | undefined): Attribute[] {
+ return glob.isDev ? listInternal(note?.getOwnedAttributes() ?? []) : [];
+}
+
/** The note's own attributes, in the order it holds them. */
export function listOwned(ownedAttributes: FAttribute[]): Attribute[] {
return ownedAttributes
@@ -624,6 +658,18 @@ export function listInherited(effectiveAttributes: FAttribute[], noteId: string
.map(toPlainAttribute);
}
+/**
+ * The other half of what the note holds: exactly the attributes the two lists above leave out, which
+ * Trilium wrote from the note's own content (a link in it is a `~internalLink`) and rewrites whenever
+ * that content is saved. Only the note's own, an inherited one being the source note's bookkeeping.
+ */
+export function listInternal(ownedAttributes: FAttribute[]): Attribute[] {
+ return ownedAttributes
+ .filter((attribute) => attribute.isAutoLink)
+ .toSorted((a, b) => a.position - b.position)
+ .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.