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
refactor(attributes): port the label definition fields to Preact
Elian Doran9612e01bffaa
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsxindex d30956e16e..bc1b969265 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx@@ -1,5 +1,6 @@import "./attribute_detail.css";+import type { DefinitionObject, LabelType, Multiplicity } from "@triliumnext/commons";import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";import appContext from "../../components/app_context.js";@@ -8,6 +9,7 @@ import { isExperimentalFeatureEnabled } from "../../services/experimental_featurimport { focusSavedElement, saveFocusedElement } from "../../services/focus.js";import froca from "../../services/froca.js";import { t } from "../../services/i18n.js";+import promotedAttributeDefinitionParser from "../../services/promoted_attribute_definition_parser.js";import server from "../../services/server.js";import { isIMEComposing } from "../../services/shortcuts.js";import utils from "../../services/utils.js";@@ -15,6 +17,8 @@ import NoteContextAwareWidget from "../note_context_aware_widget.js";import Button from "../react/Button.jsx";import FormAutocomplete, { AUTOCOMPLETE_DROPDOWN_SELECTOR } from "../react/FormAutocomplete.jsx";import FormCheckbox from "../react/FormCheckbox.jsx";+import FormSelect from "../react/FormSelect.jsx";+import FormTextBox, { FormTextBoxWithUnit } from "../react/FormTextBox.jsx";import NoteAutocomplete from "../react/NoteAutocomplete.jsx";import NoteLink from "../react/NoteLink.jsx";import { disposeReactWidget, renderReactWidgetAtElement } from "../react/react_utils.jsx";@@ -258,6 +262,7 @@ function AttributeForm({ opts, attrType, currentNoteId, onAttributesChanged, onSconst [ name, setName ] = useState(() => stripDefinitionPrefix(attribute.name, attrType));const [ value, setValue ] = useState(attribute.value ?? "");const [ isInheritable, setIsInheritable ] = useState(!!attribute.isInheritable);+ const [ definition, setDefinition ] = useState(() => parseDefinition(attribute, attrType));const nameRef = useRef<HTMLInputElement>(null);// The values known for a label name never change while the popup is open, so they are fetched// once per name and filtered locally afterwards.@@ -305,6 +310,15 @@ function AttributeForm({ opts, attrType, currentNoteId, onAttributesChanged, onSonAttributesChanged(allAttributes ?? []);}+ /** Definitions keep their settings serialized in the value, so any change rebuilds the whole thing. */+ function commitDefinition(changes: Partial<DefinitionObject>) {+ const newDefinition = { ...definition, ...changes };++ setDefinition(newDefinition);+ attribute.value = buildDefinitionValue(newDefinition, attrType);+ onAttributesChanged(allAttributes ?? []);+ }+// A relation stores the target note's id as its value; clearing the field clears the target.const commitTargetNote = useCallback((targetNoteId?: string) => {attribute.value = targetNoteId ?? "";@@ -370,6 +384,87 @@ function AttributeForm({ opts, attrType, currentNoteId, onAttributesChanged, onS</tr>)}+ {isDefinition(attrType) && (+ <tr class="attr-row-promoted" title={t("attribute_detail.promoted_title")}>+ <th></th>+ <td>+ <FormCheckbox+ label={t("attribute_detail.promoted")}+ currentValue={!!definition.isPromoted}+ disabled={!isOwned}+ onChange={(isPromoted) => commitDefinition({ isPromoted })}+ />+ </td>+ </tr>+ )}++ {isDefinition(attrType) && definition.isPromoted && (+ <tr class="attr-row-promoted-alias">+ <th title={t("attribute_detail.promoted_alias_title")}>{t("attribute_detail.promoted_alias")}</th>+ <td>+ <FormTextBox+ className="attr-input-promoted-alias"+ currentValue={definition.promotedAlias ?? ""}+ disabled={!isOwned}+ onChange={(promotedAlias) => commitDefinition({ promotedAlias })}+ />+ </td>+ </tr>+ )}++ {isDefinition(attrType) && !opts.hideMultiplicity && (+ <tr class="attr-row-multiplicity">+ <th title={t("attribute_detail.multiplicity_title")}>{t("attribute_detail.multiplicity")}</th>+ <td>+ <FormSelect+ className="attr-input-multiplicity"+ values={MULTIPLICITIES}+ keyProperty="value"+ titleProperty="title"+ currentValue={definition.multiplicity ?? "single"}+ disabled={!isOwned}+ onChange={(multiplicity) => commitDefinition({ multiplicity: multiplicity as Multiplicity })}+ />+ </td>+ </tr>+ )}++ {attrType === "label-definition" && (+ <tr class="attr-row-label-type">+ <th title={t("attribute_detail.label_type_title")}>{t("attribute_detail.label_type")}</th>+ <td>+ <FormSelect+ className="attr-input-label-type"+ values={LABEL_TYPES}+ keyProperty="value"+ titleProperty="title"+ currentValue={definition.labelType ?? "text"}+ disabled={!isOwned}+ onChange={(labelType) => commitDefinition({ labelType: labelType as LabelType })}+ />+ </td>+ </tr>+ )}++ {attrType === "label-definition" && definition.labelType === "number" && (+ <tr class="attr-row-number-precision">+ <th title={t("attribute_detail.precision_title")}>{t("attribute_detail.precision")}</th>+ <td>+ <FormTextBoxWithUnit+ className="attr-input-number-precision"+ type="number"+ min={0}+ unit={t("attribute_detail.digits")}+ currentValue={definition.numberPrecision?.toString() ?? ""}+ disabled={!isOwned}+ onChange={(precision) => commitDefinition({+ numberPrecision: precision === "" ? undefined : parseInt(precision, 10)+ })}+ />+ </td>+ </tr>+ )}+<tr title={t("attribute_detail.inheritable_title")}><th></th><td>@@ -416,6 +511,65 @@ function AttributeForm({ opts, attrType, currentNoteId, onAttributesChanged, onS/** Constant so it does not re-initialise the autocomplete on every render. */const TARGET_NOTE_OPTS = { allowCreatingNotes: true };+const MULTIPLICITIES = [+ { value: "single", title: t("attribute_detail.single_value") },+ { value: "multi", title: t("attribute_detail.multi_value") }+];++const LABEL_TYPES = [+ { value: "text", title: t("attribute_detail.text") },+ { value: "textarea", title: t("attribute_detail.textarea") },+ { value: "number", title: t("attribute_detail.number") },+ { value: "boolean", title: t("attribute_detail.boolean") },+ { value: "date", title: t("attribute_detail.date") },+ { value: "datetime", title: t("attribute_detail.date_time") },+ { value: "time", title: t("attribute_detail.time") },+ { value: "url", title: t("attribute_detail.url") },+ { value: "color", title: t("attribute_detail.color_type") }+];++function isDefinition(attrType: AttrType) {+ return attrType === "label-definition" || attrType === "relation-definition";+}++function parseDefinition(attribute: Attribute, attrType: AttrType): DefinitionObject {+ return isDefinition(attrType) ? promotedAttributeDefinitionParser.parse(attribute.value || "") : {};+}++/**+ * Serializes a definition back into the comma separated form stored in the attribute value, e.g.+ * `promoted,alias=Foo,single,number,precision=2`.+ *+ * Unlike the legacy widget, the multiplicity and label type always land in the output with their+ * effective defaults rather than as an empty token, which the parser only warned about.+ */+function buildDefinitionValue(definition: DefinitionObject, attrType: AttrType) {+ const props: string[] = [];++ if (definition.isPromoted) {+ props.push("promoted");++ if (definition.promotedAlias) {+ props.push(`alias=${definition.promotedAlias}`);+ }+ }++ props.push(definition.multiplicity ?? "single");++ if (attrType === "label-definition") {+ const labelType = definition.labelType ?? "text";+ props.push(labelType);++ if (labelType === "number" && definition.numberPrecision !== undefined) {+ props.push(`precision=${definition.numberPrecision}`);+ }+ } else if (definition.inverseRelation?.trim()) {+ props.push(`inverse=${utils.filterAttributeName(definition.inverseRelation)}`);+ }++ return props.join(",");+}+const DISPLAYED_NOTES = 10;/** Edits keep arriving while typing, so the lookup waits for a pause instead of running per keystroke. */const RELATED_NOTES_DEBOUNCE_MS = 1000;diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts b/apps/client/src/widgets/attribute_widgets/attribute_detail_old.tsindex 96fbf6a922..84128d16c5 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts@@ -2,7 +2,7 @@ import type { Attribute } from "../../services/attribute_parser.js";import { t } from "../../services/i18n.js";import linkService from "../../services/link.js";import promotedAttributeDefinitionParser from "../../services/promoted_attribute_definition_parser.js";-import utils, { openInAppHelpFromUrl } from "../../services/utils.js";+import { openInAppHelpFromUrl } from "../../services/utils.js";import NoteContextAwareWidget from "../note_context_aware_widget.js";import { ATTR_HELP } from "./attr_help.js";import type { AttributeDetailOpts } from "./attribute_detail.jsx";@@ -13,58 +13,6 @@ const TPL = /*html*/`<table class="attr-edit-table"><tr class="attr-help"></tr>- <tr class="attr-row-promoted"- title="${t("attribute_detail.promoted_title")}">- <th></th>- <td>- <label class="tn-checkbox">- <input type="checkbox" class="attr-input-promoted" />- ${t("attribute_detail.promoted")}- </label>- </td>- </tr>- <tr class="attr-row-promoted-alias">- <th title="${t("attribute_detail.promoted_alias_title")}">${t("attribute_detail.promoted_alias")}</th>- <td>- <div class="input-group">- <input type="text" class="attr-input-promoted-alias form-control" />- </div>- </td>- </tr>- <tr class="attr-row-multiplicity">- <th title="${t("attribute_detail.multiplicity_title")}">${t("attribute_detail.multiplicity")}</th>- <td>- <select class="attr-input-multiplicity form-control">- <option value="single">${t("attribute_detail.single_value")}</option>- <option value="multi">${t("attribute_detail.multi_value")}</option>- </select>- </td>- </tr>- <tr class="attr-row-label-type">- <th title="${t("attribute_detail.label_type_title")}">${t("attribute_detail.label_type")}</th>- <td>- <select class="attr-input-label-type form-control">- <option value="text">${t("attribute_detail.text")}</option>- <option value="textarea">${t("attribute_detail.textarea")}</option>- <option value="number">${t("attribute_detail.number")}</option>- <option value="boolean">${t("attribute_detail.boolean")}</option>- <option value="date">${t("attribute_detail.date")}</option>- <option value="datetime">${t("attribute_detail.date_time")}</option>- <option value="time">${t("attribute_detail.time")}</option>- <option value="url">${t("attribute_detail.url")}</option>- <option value="color">${t("attribute_detail.color_type")}</option>- </select>- </td>- </tr>- <tr class="attr-row-number-precision">- <th title="${t("attribute_detail.precision_title")}">${t("attribute_detail.precision")}</th>- <td>- <div class="input-group">- <input type="number" class="form-control attr-input-number-precision" style="text-align: end">- <span class="input-group-text">${t("attribute_detail.digits")}</span>- </div>- </td>- </tr><tr class="attr-row-inverse-relation"><th title="${t("attribute_detail.inverse_relation_title")}">${t("attribute_detail.inverse_relation")}</th><td>@@ -78,18 +26,8 @@ const TPL = /*html*/`export default class AttributeDetailWidget extends NoteContextAwareWidget {private $inputName!: JQuery<HTMLElement>;- private $rowPromoted!: JQuery<HTMLElement>;- private $inputPromoted!: JQuery<HTMLElement>;- private $inputPromotedAlias!: JQuery<HTMLElement>;- private $inputMultiplicity!: JQuery<HTMLElement>;private $inputInverseRelation!: JQuery<HTMLElement>;- private $inputLabelType!: JQuery<HTMLElement>;- private $inputNumberPrecision!: JQuery<HTMLElement>;- private $rowMultiplicity!: JQuery<HTMLElement>;- private $rowLabelType!: JQuery<HTMLElement>;- private $rowNumberPrecision!: JQuery<HTMLElement>;private $rowInverseRelation!: JQuery<HTMLElement>;- private $rowPromotedAlias!: JQuery<HTMLElement>;private $attrIsOwnedBy!: JQuery<HTMLElement>;private $attrHelp!: JQuery<HTMLElement>;@@ -102,26 +40,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {this.$inputName = this.$widget.find(".attr-input-name");- this.$rowPromoted = this.$widget.find(".attr-row-promoted");- this.$inputPromoted = this.$widget.find(".attr-input-promoted");- this.$inputPromoted.on("change", () => this.userEditedAttribute());-- this.$rowPromotedAlias = this.$widget.find(".attr-row-promoted-alias");- this.$inputPromotedAlias = this.$widget.find(".attr-input-promoted-alias");- this.$inputPromotedAlias.on("change", () => this.userEditedAttribute());-- this.$rowMultiplicity = this.$widget.find(".attr-row-multiplicity");- this.$inputMultiplicity = this.$widget.find(".attr-input-multiplicity");- this.$inputMultiplicity.on("change", () => this.userEditedAttribute());-- this.$rowLabelType = this.$widget.find(".attr-row-label-type");- this.$inputLabelType = this.$widget.find(".attr-input-label-type");- this.$inputLabelType.on("change", () => this.userEditedAttribute());-- this.$rowNumberPrecision = this.$widget.find(".attr-row-number-precision");- this.$inputNumberPrecision = this.$widget.find(".attr-input-number-precision");- this.$inputNumberPrecision.on("change", () => this.userEditedAttribute());-this.$rowInverseRelation = this.$widget.find(".attr-row-inverse-relation");this.$inputInverseRelation = this.$widget.find(".attr-input-inverse-relation");this.$inputInverseRelation.on("input", (ev) => {@@ -157,21 +75,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {const disabledFn = () => (!isOwned ? "true" : undefined);- this.$rowPromoted.toggle(["label-definition", "relation-definition"].includes(this.attrType || ""));- this.$inputPromoted.prop("checked", !!definition.isPromoted).attr("disabled", disabledFn);-- this.$rowPromotedAlias.toggle(!!definition.isPromoted);- this.$inputPromotedAlias.val(definition.promotedAlias || "").attr("disabled", disabledFn);-- this.$rowMultiplicity.toggle(["label-definition", "relation-definition"].includes(this.attrType || "") && !hideMultiplicity);- this.$inputMultiplicity.val(definition.multiplicity || "").attr("disabled", disabledFn);-- this.$rowLabelType.toggle(this.attrType === "label-definition");- this.$inputLabelType.val(definition.labelType || "").attr("disabled", disabledFn);-- this.$rowNumberPrecision.toggle(this.attrType === "label-definition" && definition.labelType === "number");- this.$inputNumberPrecision.val(definition.numberPrecision || "").attr("disabled", disabledFn);-this.$rowInverseRelation.toggle(this.attrType === "relation-definition");this.$inputInverseRelation.val(definition.inverseRelation || "").attr("disabled", disabledFn);@@ -181,7 +84,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {}userEditedAttribute() {- this.updateAttributeInEditor();this.updateHelp();}@@ -224,46 +126,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {}}- updateAttributeInEditor() {- if (this.attrType?.endsWith("-definition")) {- this.attribute.value = this.buildDefinitionValue();- }-- this.triggerCommand("updateAttributeList", { attributes: this.allAttributes ?? [] });- }-- buildDefinitionValue() {- const props: string[] = [];-- if (this.$inputPromoted.is(":checked")) {- props.push("promoted");-- if (this.$inputPromotedAlias.val() !== "") {- props.push(`alias=${this.$inputPromotedAlias.val()}`);- }- }-- props.push(this.$inputMultiplicity.val() as string);-- if (this.attrType === "label-definition") {- props.push(this.$inputLabelType.val() as string);-- if (this.$inputLabelType.val() === "number" && this.$inputNumberPrecision.val() !== "") {- props.push(`precision=${this.$inputNumberPrecision.val()}`);- }- } else if (this.attrType === "relation-definition" && String(this.$inputInverseRelation.val())?.trim().length > 0) {- const inverseRelationName = this.$inputInverseRelation.val();-- props.push(`inverse=${utils.filterAttributeName(String(inverseRelationName))}`);- }-- this.$rowNumberPrecision.toggle(this.attrType === "label-definition" && this.$inputLabelType.val() === "number");-- this.$rowPromotedAlias.toggle(this.$inputPromoted.is(":checked"));-- return props.join(",");- }-hide() {this.toggleInt(false);}