Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(attributes): mark the system names in the name completion
Elian Doranc952aa1addae
diff --git a/apps/client/src/services/attributes.spec.ts b/apps/client/src/services/attributes.spec.tsindex 6b30bcbae0..8a2013ab2a 100644--- a/apps/client/src/services/attributes.spec.ts+++ b/apps/client/src/services/attributes.spec.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { buildNote } from "../test/easy-froca";-import attributeService, { removeOwnedAttributesByNameOrType, setAttribute, setBooleanWithInheritance, setLabel, setRelation } from "./attributes";+import attributeService, { isBuiltinAttribute, removeOwnedAttributesByNameOrType, setAttribute, setBooleanWithInheritance, setLabel, setRelation } from "./attributes";import froca from "./froca";import server from "./server.js";@@ -368,3 +368,29 @@ describe("getNameWithoutDangerousPrefix", () => {expect(attributeService.getNameWithoutDangerousPrefix("run")).toBe("run");});});++describe("isBuiltinAttribute", () => {+ it("recognizes built-ins of each type and rejects user-invented names", () => {+ expect(isBuiltinAttribute("label", "archived")).toBe(true);+ expect(isBuiltinAttribute("relation", "template")).toBe(true);+ expect(isBuiltinAttribute("label", "myOwnLabel")).toBe(false);+ expect(isBuiltinAttribute("relation", "myOwnRelation")).toBe(false);+ });++ it("does not confuse the two types", () => {+ // `archived` is a label only, `renderNote` a relation only.+ expect(isBuiltinAttribute("relation", "archived")).toBe(false);+ expect(isBuiltinAttribute("label", "renderNote")).toBe(false);+ // `template` and `widget` exist as both, so both must be recognized.+ expect(isBuiltinAttribute("label", "template")).toBe(true);+ expect(isBuiltinAttribute("relation", "widget")).toBe(true);+ });++ it("matches exactly, so prefixed names are not built-ins", () => {+ // A definition describes a built-in without being one, and a disabled one is inert.+ expect(isBuiltinAttribute("label", "label:archived")).toBe(false);+ expect(isBuiltinAttribute("label", "disabled:run")).toBe(false);+ // Casing is part of the name; the server's own lookup is likewise name-sensitive.+ expect(isBuiltinAttribute("label", "Archived")).toBe(false);+ });+});diff --git a/apps/client/src/services/attributes.ts b/apps/client/src/services/attributes.tsindex 77558c9464..8611f7d44e 100644--- a/apps/client/src/services/attributes.ts+++ b/apps/client/src/services/attributes.ts@@ -1,4 +1,4 @@-import { AttributeType } from "@triliumnext/commons";+import { AttributeType, BUILTIN_ATTRIBUTES } from "@triliumnext/commons";import type FNote from "../entities/fnote.js";import froca from "./froca.js";@@ -211,6 +211,23 @@ function getNameWithoutDangerousPrefix(name: string) {return name.startsWith("disabled:") ? name.substring(9) : name;}+/**+ * Whether the name is one Trilium itself attaches a meaning to, rather than one the user invented.+ *+ * Matched exactly, on purpose: a definition (`label:archived`) describes a system attribute without+ * being one, and a disabled one (`disabled:run`) has been deliberately made inert. Both are ordinary+ * attributes as far as the name alone is concerned.+ */+export function isBuiltinAttribute(type: "label" | "relation", name: string) {+ return BUILTIN_ATTRIBUTE_KEYS.has(`${type}:${name}`);+}++/**+ * The built-ins keyed by type and name. There is no ambiguity in joining the two with a colon: the+ * type is always exactly `label` or `relation`, so the first segment of a key is never in doubt.+ */+const BUILTIN_ATTRIBUTE_KEYS = new Set(BUILTIN_ATTRIBUTES.map(({ type, name }) => `${type}:${name}`));+export default {addLabel,setLabel,diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b92a46d0e6..87b7aef131 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -674,6 +674,9 @@"type_label_definition": "Label definition","type_relation_definition": "Relation definition"},+ "attribute_names": {+ "system": "System"+ },"abstract_bulk_action": {"remove_this_search_action": "Remove this search action"},diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsxindex e35114e9b8..3d86197a9b 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx@@ -1,4 +1,5 @@import "./attribute_detail.css";+import "./attribute_name_suggestion.css";import { type DefinitionObject, type LabelType, promotedAttributeDefinitionParser } from "@triliumnext/commons";import { ComponentProps } from "preact";@@ -7,6 +8,7 @@ import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState }import appContext from "../../components/app_context.js";import { isDefinitionName } from "../../entities/fattribute.js";import type { Attribute } from "../../services/attribute_parser.js";+import { isBuiltinAttribute } from "../../services/attributes.js";import { isExperimentalFeatureEnabled } from "../../services/experimental_features.js";import { focusSavedElement, saveFocusedElement } from "../../services/focus.js";import froca from "../../services/froca.js";@@ -287,11 +289,14 @@ function AttributeForm({ opts, attrType, currentNoteId, onCancel, onAttributesCh}) {const { attribute, allAttributes, isOwned, focus } = opts;// Definitions describe the attribute they define, so they complete against its own type.- const suggestAttributeNames = useCallback((query: string) => fetchAttributeNames(- attrType === "relation" || attrType === "relation-definition" ? "relation" : "label", query- ), [ attrType ]);+ const nameType = attrType === "relation" || attrType === "relation-definition" ? "relation" : "label";+ const suggestAttributeNames = useCallback((query: string) => fetchAttributeNames(nameType, query), [ nameType ]);+ const renderNameSuggestion = useCallback(+ (suggestion: string) => <AttributeNameSuggestion type={nameType} name={suggestion} />, [ nameType ]);// Whatever a relation is the inverse of is itself a relation.const suggestRelationNames = useCallback((query: string) => fetchAttributeNames("relation", query), []);+ const renderRelationSuggestion = useCallback(+ (suggestion: string) => <AttributeNameSuggestion type="relation" name={suggestion} />, []);const [ name, setName ] = useState(() => stripDefinitionPrefix(attribute.name, attrType));const [ value, setValue ] = useState(attribute.value ?? "");const [ isInheritable, setIsInheritable ] = useState(!!attribute.isInheritable);@@ -396,6 +401,7 @@ function AttributeForm({ opts, attrType, currentNoteId, onCancel, onAttributesChcurrentValue={name}readOnly={!isOwned}source={suggestAttributeNames}+ renderItem={renderNameSuggestion}openOnFocusonChange={(newName) => isComposing.current ? setName(newName) : commitName(newName)}onCompositionStart={() => isComposing.current = true}@@ -448,12 +454,12 @@ function AttributeForm({ opts, attrType, currentNoteId, onCancel, onAttributesChvalues={LABEL_TYPES}keyProperty="value"titleProperty="title"+ iconProperty="icon"currentValue={definition.labelType ?? "text"}disabled={!isOwned}onChange={(labelType) => commitDefinition({ labelType: labelType as LabelType })}/></OptionsRow>- iconProperty="icon")}{attrType === "label-definition" && definition.labelType === "number" && (@@ -487,6 +493,7 @@ function AttributeForm({ opts, attrType, currentNoteId, onCancel, onAttributesChcurrentValue={definition.inverseRelation ?? ""}disabled={!isOwned}source={suggestRelationNames}+ renderItem={renderRelationSuggestion}openOnFocusonChange={(inverseRelation) => commitDefinition({// A relation name, so the same characters are dropped as in the name field@@ -590,6 +597,20 @@ 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.+ */+function AttributeNameSuggestion({ type, name }: { type: "label" | "relation"; name: string }) {+ return (+ <span class="attr-name-suggestion">+ <span class="attr-name-suggestion-name">{name}</span>+ {isBuiltinAttribute(type, name) && <Badge outline text={t("attribute_names.system")} />}+ </span>+ );+}+/** Normalised so that the shorthand entries, which are the description alone, read like the rest. */function lookupAttributeHelp(attrType: AttrType, name: string): AttrHelpEntry | undefined {const entry = attrType ? ATTR_HELP[attrType]?.[name] : undefined;diff --git a/apps/client/src/widgets/attribute_widgets/attribute_name_suggestion.css b/apps/client/src/widgets/attribute_widgets/attribute_name_suggestion.cssnew file mode 100644index 0000000000..074491435d--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/attribute_name_suggestion.css@@ -0,0 +1,48 @@+/*+ * One row of an attribute name completion, shared by the detail popup's name field and by the `#`/`~`+ * completion in the inline attribute editor. Both list the very same names, so both mark the ones+ * Trilium attaches a meaning to in the same way.+ *+ * Deliberately not nested under a widget root: the popup portals its dropdown to the body and the+ * inline editor's panel lives in a CKEditor balloon, so neither row shares an ancestor with the+ * widget that spawned it.+ */++.attr-name-suggestion {+ display: flex;+ width: 100%;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+}++.attr-name-suggestion .attr-name-suggestion-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.attr-name-suggestion .ext-badge {+ --color: var(--muted-text-color);+ flex-shrink: 0;+}++/*+ * The badge is sized relative to the row it sits in, and the popup's dropdown carries a larger font+ * than the mention panel does — so the same rule leaves the marker noticeably heavier here. Nudged+ * down so that the two lists read alike.+ */+.form-autocomplete-dropdown .attr-name-suggestion .ext-badge {+ font-size: 0.65em;+}++/*+ * The mention panel sizes its rows to their content, so without a width the markers would sit right+ * after each name and zig-zag down the list. The popup's dropdown takes the width of its input and+ * needs none of this.+ */+.ck-mentions .ck.ck-button.attr-name-suggestion-button {+ display: flex;+ justify-content: flex-start;+ min-width: 220px;+}diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsxindex fdd8bb91db..452859bcac 100644--- a/apps/client/src/widgets/react/FormAutocomplete.tsx+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx@@ -1,6 +1,6 @@import "./FormAutocomplete.css";-import type { TargetedKeyboardEvent } from "preact";+import type { ComponentChildren, TargetedKeyboardEvent } from "preact";import { createPortal, type CSSProperties } from "preact/compat";import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";@@ -27,6 +27,12 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {source(query: string): Promise<string[]>;/** Opens the dropdown as soon as the field receives focus, not just on typing. */openOnFocus?: boolean;+ /**+ * Renders one suggestion, for lists where the bare text does not tell the whole story. Only the+ * appearance of the row is affected: what a suggestion means and what selecting it commits stay+ * the string the source returned. Defaults to showing that string.+ */+ renderItem?(item: string): ComponentChildren;}/**@@ -35,7 +41,7 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {* The dropdown is portalled to the body and positioned over everything else, so it is not clipped* by scrolling ancestors. Selecting a suggestion reports it through `onChange`, exactly like typing.*/-export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {+export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, renderItem, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {const ownInputRef = useRef<HTMLInputElement>(null);const inputEl = inputRef ?? ownInputRef;const dropdownRef = useRef<HTMLUListElement>(null);@@ -187,7 +193,7 @@ export default function FormAutocomplete({ currentValue, onChange, source, openOonMouseEnter={() => setActiveIndex(index)}onClick={() => selectItem(item)}>- {item}+ {renderItem ? renderItem(item) : item}</li>))}</ul>,diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsxindex 8a117fcd36..bfe2c235b8 100644--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx@@ -1,3 +1,4 @@+import "../../attribute_widgets/attribute_name_suggestion.css";import "./AttributeEditor.css";import type { AttributeEditor as CKEditorAttributeEditor, ModelElement, ModelNode, ModelPosition, TriliumMentionFeed } from "@triliumnext/ckeditor5";@@ -12,7 +13,7 @@ import FNote from "../../../entities/fnote";import contextMenu from "../../../menus/context_menu";import attribute_parser, { Attribute } from "../../../services/attribute_parser";import attribute_renderer from "../../../services/attribute_renderer";-import attributes from "../../../services/attributes";+import attributes, { isBuiltinAttribute } from "../../../services/attributes";import froca from "../../../services/froca";import { t } from "../../../services/i18n";import link from "../../../services/link";@@ -57,31 +58,15 @@ const mentionSetup: TriliumMentionFeed[] = [},{marker: "#",- feed: async (queryText) => {- const names = await server.get<string[]>(`attribute-names/?type=label&query=${encodeURIComponent(queryText)}`);-- return names.map((name) => {- return {- id: `#${name}`,- name- };- });- },+ feed: (queryText) => fetchAttributeNames("label", queryText),+ itemRenderer: (item) => renderAttributeName("label", (item as AttributeNameItem).name),minimumCharacters: 0,preselectFirstItem: false},{marker: "~",- feed: async (queryText) => {- const names = await server.get<string[]>(`attribute-names/?type=relation&query=${encodeURIComponent(queryText)}`);-- return names.map((name) => {- return {- id: `~${name}`,- name- };- });- },+ feed: (queryText) => fetchAttributeNames("relation", queryText),+ itemRenderer: (item) => renderAttributeName("relation", (item as AttributeNameItem).name),minimumCharacters: 0,preselectFirstItem: false}@@ -453,6 +438,63 @@ export default function AttributeEditor({ api, note, componentId, notePath, ntxI);}+interface AttributeNameItem {+ /** The marker and the name, which is what committing the suggestion inserts. */+ id: string;+ name: string;+}++async function fetchAttributeNames(type: "label" | "relation", queryText: string): Promise<AttributeNameItem[]> {+ const names = await server.get<string[]>(`attribute-names/?type=${type}&query=${encodeURIComponent(queryText)}`);+ const marker = type === "label" ? "#" : "~";++ return names.map((name) => ({ id: `${marker}${name}`, name }));+}++/**+ * One completed attribute name, marking the ones Trilium itself attaches a meaning to — the same+ * distinction the detail popup's name field draws, on the same names, so that the two agree.+ *+ * Built as DOM rather than rendered from the popup's `AttributeNameSuggestion` component: the mention+ * panel drops and rebuilds its rows on every keystroke with no unmount hook to run, so a Preact root+ * per row would leak. The badge markup is mirrored from `Badge` rather than restyled, so that both+ * surfaces still take their look from the one stylesheet.+ */+function renderAttributeName(type: "label" | "relation", name: string) {+ const button = document.createElement("button");+ button.type = "button";+ button.tabIndex = -1;+ // `ck-button_with-text` is load-bearing, not cosmetic: the base button styles hide+ // `.ck-button__label` outright without it, leaving the row showing nothing but its badge.+ button.classList.add("ck", "ck-button", "ck-button_with-text", "attr-name-suggestion-button");++ const row = document.createElement("span");+ // The balloon hosting the panel resets everything inside it (`.ck-reset_all` zeroes borders,+ // padding, width, colour and font on every descendant), which would strip the badge back to bare+ // text. `ck-reset_all-excluded` is CKEditor's opt-out for embedded content and covers the whole+ // subtree, so the row is styled by the client's stylesheets exactly as the popup's row is.+ row.classList.add("attr-name-suggestion", "ck-reset_all-excluded");+ button.append(row);++ const label = document.createElement("span");+ label.classList.add("ck", "ck-button__label", "attr-name-suggestion-name");+ label.textContent = name;+ row.append(label);++ if (isBuiltinAttribute(type, name)) {+ const badge = document.createElement("span");+ badge.classList.add("ext-badge", "outline");+ row.append(badge);++ const badgeText = document.createElement("span");+ badgeText.classList.add("text");+ badgeText.textContent = t("attribute_names.system");+ badge.append(badgeText);+ }++ return button;+}+function getPreprocessedData(currentValue: string) {const str = currentValue.replace(/<a[^>]+href="(#[A-Za-z0-9_/]*)"[^>]*>[^<]*<\/a>/g, "$1")