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 label detail fields to Preact
Elian Dorane87df7570e10
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 1a1b57defc..40438121ee 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -554,7 +554,7 @@"inverse_relation": "Inverse relation","inheritable_title": "Inheritable attribute will be inherited to all descendants under this tree.","inheritable": "Inheritable",- "save_and_close": "Save & close <kbd>Ctrl+Enter</kbd>",+ "save_and_close_button": "Save & close","delete": "Delete","related_notes_title": "Other notes with this label","more_notes": "More notes",diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.css b/apps/client/src/widgets/attribute_widgets/attribute_detail.cssindex ad78cb3a83..cdcf789ca8 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.css+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.css@@ -55,6 +55,11 @@margin-top: 15px;}+.attr-save-delete-button-container .attr-save-changes-and-close-button {+ flex-grow: 1;+ margin-inline-end: 20px;+}+.attr-detail input[readonly] {background-color: var(--accented-background-color) !important;}diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsxindex ba6fdc2108..b8bfe6663a 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx@@ -1,12 +1,16 @@import "./attribute_detail.css";-import { useEffect, useLayoutEffect, useRef } from "preact/hooks";+import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";import type { Attribute } from "../../services/attribute_parser.js";import { isExperimentalFeatureEnabled } from "../../services/experimental_features.js";import { focusSavedElement, saveFocusedElement } from "../../services/focus.js";import { t } from "../../services/i18n.js";+import utils from "../../services/utils.js";import NoteContextAwareWidget from "../note_context_aware_widget.js";+import Button from "../react/Button.jsx";+import FormCheckbox from "../react/FormCheckbox.jsx";+import FormTextBox from "../react/FormTextBox.jsx";import { disposeReactWidget, renderReactWidgetAtElement } from "../react/react_utils.jsx";export interface AttributeDetailOpts {@@ -31,6 +35,8 @@ export interface AttributeDetailOpts {*/export default class AttributeDetailWidget extends NoteContextAwareWidget {private opts: AttributeDetailOpts | null = null;+ /** Bumped on every show so the form remounts with state seeded from the new attribute. */+ private showId = 0;doRender() {// No initial renderComponent() here: doRender() runs synchronously inside the@@ -58,6 +64,7 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {saveFocusedElement();this.opts = opts;+ this.showId++;// The widget has no note context, so isEnabled() is falsy and render()// stamps the container with hidden-int; visibility is driven manually,// exactly like the legacy widget did. The container must be visible@@ -85,21 +92,46 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {focusSavedElement();}+ private async saveAndClose() {+ await this.triggerCommand("saveAttributes");++ this.hide();++ focusSavedElement();+ }++ private async deleteAndClose() {+ await this.triggerCommand("updateAttributeList", {+ // the popup edits the very attribute object it was handed, so identity+ // is what identifies the attribute to remove+ attributes: (this.opts?.allAttributes ?? []).filter((attr) => attr !== this.opts?.attribute)+ });++ await this.triggerCommand("saveAttributes");++ this.hide();+ }+private renderComponent() {renderReactWidgetAtElement(this,<AttributeDetailopts={this.opts}+ showId={this.showId}parentOffset={this.parent?.$widget?.offset() ?? { top: 0, left: 0 }}onDismiss={() => this.hide()}onCancel={() => this.cancelAndClose()}+ onAttributesChanged={(attributes) => this.triggerCommand("updateAttributeList", { attributes })}+ onSaveAndClose={() => this.saveAndClose()}+ onDelete={() => this.deleteAndClose()}/>,this.$widget[0]);}}-interface AttributeDetailProps {+interface AttributeDetailProps extends AttributeFormCallbacks {opts: AttributeDetailOpts | null;+ showId: number;/** Offset of the spawning widget, the reference point for classic-layout coordinates. */parentOffset: { top: number; left: number };/** Plain close, e.g. on click outside the popup. */@@ -108,7 +140,7 @@ interface AttributeDetailProps {onCancel: () => void;}-function AttributeDetail({ opts, parentOffset, onDismiss, onCancel }: AttributeDetailProps) {+function AttributeDetail({ opts, showId, parentOffset, onDismiss, onCancel, ...formCallbacks }: AttributeDetailProps) {const popupRef = useRef<HTMLDivElement>(null);const shown = !!opts;@@ -164,11 +196,141 @@ function AttributeDetail({ opts, parentOffset, onDismiss, onCancel }: AttributeD/></div>- Hello world+ <AttributeForm key={showId} opts={opts} attrType={attrType} {...formCallbacks} /></div>);}+interface AttributeFormCallbacks {+ /** Reports the edited attribute list back to the spawning widget, which re-renders from it. */+ onAttributesChanged: (attributes: Attribute[]) => void;+ onSaveAndClose: () => void;+ onDelete: () => void;+}++/**+ * The editable part of the popup. Remounted per show (keyed on `showId`) so the field state is+ * simply seeded from the attribute instead of being synchronized to it on every change.+ */+function AttributeForm({ opts, attrType, onAttributesChanged, onSaveAndClose, onDelete }: AttributeFormCallbacks & {+ opts: AttributeDetailOpts;+ attrType: AttrType;+}) {+ const { attribute, allAttributes, isOwned, focus } = opts;+ const [ name, setName ] = useState(() => stripDefinitionPrefix(attribute.name, attrType));+ const [ value, setValue ] = useState(attribute.value ?? "");+ const [ isInheritable, setIsInheritable ] = useState(!!attribute.isInheritable);+ const nameRef = useRef<HTMLInputElement>(null);+ // Committing mid-composition makes the spawning editor re-render and swallow the+ // characters being composed: https://github.com/zadam/trilium/pull/3812+ const isComposing = useRef(false);++ useEffect(() => {+ if (focus === "name") {+ nameRef.current?.focus();+ nameRef.current?.select();+ }+ }, [ focus ]);++ // The attribute object is shared with the spawning widget: it is edited in place so that+ // its identity survives, which is how the delete path recognizes it.+ function commitName(newName: string) {+ // invalid characters are simply ignored (from the user's perspective they are not even entered)+ const filteredName = utils.filterAttributeName(newName);++ setName(filteredName);+ attribute.name = addDefinitionPrefix(filteredName, attrType);+ onAttributesChanged(allAttributes ?? []);+ }++ function commitValue(newValue: string) {+ setValue(newValue);+ attribute.value = newValue;+ onAttributesChanged(allAttributes ?? []);+ }++ return (+ <>+ <table class="attr-edit-table">+ <tbody>+ <tr title={t("attribute_detail.attr_name_title")}>+ <th>{t("attribute_detail.name")}</th>+ <td>+ <FormTextBox+ className="attr-input-name"+ inputRef={nameRef}+ currentValue={name}+ readOnly={!isOwned}+ onChange={(newName) => isComposing.current ? setName(newName) : commitName(newName)}+ onCompositionStart={() => isComposing.current = true}+ onCompositionEnd={(e) => {+ isComposing.current = false;+ commitName(e.currentTarget.value);+ }}+ />+ </td>+ </tr>++ {attrType === "label" && (+ <tr class="attr-row-value">+ <th>{t("attribute_detail.value")}</th>+ <td>+ <FormTextBox+ className="attr-input-value"+ currentValue={value}+ readOnly={!isOwned}+ onChange={(newValue) => isComposing.current ? setValue(newValue) : commitValue(newValue)}+ onCompositionStart={() => isComposing.current = true}+ onCompositionEnd={(e) => {+ isComposing.current = false;+ commitValue(e.currentTarget.value);+ }}+ />+ </td>+ </tr>+ )}++ <tr title={t("attribute_detail.inheritable_title")}>+ <th></th>+ <td>+ <FormCheckbox+ label={t("attribute_detail.inheritable")}+ currentValue={isInheritable}+ disabled={!isOwned}+ onChange={(checked) => {+ setIsInheritable(checked);+ attribute.isInheritable = checked;+ onAttributesChanged(allAttributes ?? []);+ }}+ />+ </td>+ </tr>+ </tbody>+ </table>++ {isOwned && (+ <div class="attr-save-delete-button-container">+ <Button+ className="attr-save-changes-and-close-button"+ kind="primary"+ size="small"+ text={t("attribute_detail.save_and_close_button")}+ keyboardShortcut="Ctrl+Enter"+ onClick={onSaveAndClose}+ />++ <Button+ className="attr-delete-button"+ size="small"+ text={t("attribute_detail.delete")}+ onClick={onDelete}+ />+ </div>+ )}+ </>+ );+}+const ATTR_TITLES: Record<string, string> = {label: t("attribute_detail.label"),"label-definition": t("attribute_detail.label_definition"),@@ -246,7 +408,9 @@ function toCssPos(value: number | string) {return typeof value === "number" ? `${value}px` : value;}-function getAttrType(attribute: Attribute) {+type AttrType = "label" | "label-definition" | "relation" | "relation-definition" | undefined;++function getAttrType(attribute: Attribute): AttrType {if (attribute.type === "label") {if (attribute.name.startsWith("label:")) {return "label-definition";@@ -258,3 +422,22 @@ function getAttrType(attribute: Attribute) {return "relation";}}++/** Definitions are stored prefixed (`label:foo`), but the popup edits the bare name. */+function stripDefinitionPrefix(name: string, attrType: AttrType) {+ if (attrType === "label-definition") {+ return name.substring("label:".length);+ } else if (attrType === "relation-definition") {+ return name.substring("relation:".length);+ }+ return name;+}++function addDefinitionPrefix(name: string, attrType: AttrType) {+ if (attrType === "label-definition") {+ return `label:${name}`;+ } else if (attrType === "relation-definition") {+ return `relation:${name}`;+ }+ return name;+}diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts b/apps/client/src/widgets/attribute_widgets/attribute_detail_old.tsindex f4d36b3e67..1e1de2ed66 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts@@ -20,15 +20,7 @@ const TPL = /*html*/`<div class="attr-is-owned-by">${t("attribute_detail.attr_is_owned_by")}</div><table class="attr-edit-table">- <tr title="${t("attribute_detail.attr_name_title")}">- <th>${t("attribute_detail.name")}</th>- <td><input type="text" class="attr-input-name form-control" /></td>- </tr><tr class="attr-help"></tr>- <tr class="attr-row-value">- <th>${t("attribute_detail.value")}</th>- <td><input type="text" class="attr-input-value form-control" /></td>- </tr><tr class="attr-row-target-note"><th title="${t("attribute_detail.target_note_title")}">${t("attribute_detail.target_note")}</th><td>@@ -97,26 +89,8 @@ const TPL = /*html*/`</div></td></tr>- <tr title="${t("attribute_detail.inheritable_title")}">- <th></th>- <td>- <label class="tn-checkbox">- <input type="checkbox" class="attr-input-inheritable" />- ${t("attribute_detail.inheritable")}- </label>- </td>- </tr></table>- <div class="attr-save-delete-button-container">- <button class="btn btn-primary btn-sm attr-save-changes-and-close-button"- style="flex-grow: 1; margin-inline-end: 20px">- ${t("attribute_detail.save_and_close")}</button>-- <button class="btn btn-secondary btn-sm attr-delete-button">- ${t("attribute_detail.delete")}</button>- </div>-<div class="related-notes-container"><br/>@@ -150,8 +124,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {private $inputLabelType!: JQuery<HTMLElement>;private $inputTargetNote!: JQuery<HTMLElement>;private $inputNumberPrecision!: JQuery<HTMLElement>;- private $inputInheritable!: JQuery<HTMLElement>;- private $rowValue!: JQuery<HTMLElement>;private $rowMultiplicity!: JQuery<HTMLElement>;private $rowLabelType!: JQuery<HTMLElement>;private $rowNumberPrecision!: JQuery<HTMLElement>;@@ -159,9 +131,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {private $rowTargetNote!: JQuery<HTMLElement>;private $rowPromotedAlias!: JQuery<HTMLElement>;private $attrIsOwnedBy!: JQuery<HTMLElement>;- private $attrSaveDeleteButtonContainer!: JQuery<HTMLElement>;- private $saveAndCloseButton!: JQuery<HTMLElement>;- private $deleteButton!: JQuery<HTMLElement>;private $relatedNotesContainer!: JQuery<HTMLElement>;private $relatedNotesTitle!: JQuery<HTMLElement>;private $relatedNotesList!: JQuery<HTMLElement>;@@ -182,13 +151,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {shortcutService.bindElShortcut(this.$widget, "esc", () => this.cancelAndClose());this.$inputName = this.$widget.find(".attr-input-name");- this.$inputName.on("input", (ev) => {- if (!(ev.originalEvent as KeyboardEvent)?.isComposing) {- // https://github.com/zadam/trilium/pull/3812- this.userEditedAttribute();- }- });- this.$inputName.on("change", () => this.userEditedAttribute());this.$inputName.on("autocomplete:closed", () => this.userEditedAttribute());this.$inputName.on("focus", () => {@@ -199,15 +161,7 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {});});- this.$rowValue = this.$widget.find(".attr-row-value");this.$inputValue = this.$widget.find(".attr-input-value");- this.$inputValue.on("input", (ev) => {- if (!(ev.originalEvent as KeyboardEvent)?.isComposing) {- // https://github.com/zadam/trilium/pull/3812- this.userEditedAttribute();- }- });- this.$inputValue.on("change", () => this.userEditedAttribute());this.$inputValue.on("autocomplete:closed", () => this.userEditedAttribute());this.$inputValue.on("focus", () => {attributeAutocompleteService.initLabelValueAutocomplete({@@ -262,27 +216,8 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {this.updateRelatedNotes();});- this.$inputInheritable = this.$widget.find(".attr-input-inheritable");- this.$inputInheritable.on("change", () => this.userEditedAttribute());-this.$attrIsOwnedBy = this.$widget.find(".attr-is-owned-by");- this.$attrSaveDeleteButtonContainer = this.$widget.find(".attr-save-delete-button-container");-- this.$saveAndCloseButton = this.$widget.find(".attr-save-changes-and-close-button");- this.$saveAndCloseButton.on("click", () => this.saveAndClose());-- this.$deleteButton = this.$widget.find(".attr-delete-button");- this.$deleteButton.on("click", async () => {- await this.triggerCommand("updateAttributeList", {- attributes: (this.allAttributes || []).filter((attr) => attr !== this.attribute)- });-- await this.triggerCommand("saveAttributes");-- this.hide();- });-this.$attrHelp = this.$widget.find(".attr-help");this.$relatedNotesContainer = this.$widget.find(".related-notes-container");@@ -294,8 +229,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {async showAttributeDetail({ allAttributes, attribute, isOwned, x, y, focus, hideMultiplicity }: AttributeDetailOpts) {this.attrType = this.getAttrType(attribute);- const attrName = this.attrType === "label-definition" ? attribute.name.substr(6) : this.attrType === "relation-definition" ? attribute.name.substr(9) : attribute.name;-const definition = this.attrType?.endsWith("-definition") ? promotedAttributeDefinitionParser.parse(attribute.value || "") : {};this.allAttributes = allAttributes;@@ -304,8 +237,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {// can be slightly slower so just make it asyncthis.updateRelatedNotes();- this.$attrSaveDeleteButtonContainer.toggle(!!isOwned);-if (isOwned) {this.$attrIsOwnedBy.hide();} else if (attribute.noteId) {@@ -319,9 +250,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {const disabledFn = () => (!isOwned ? "true" : undefined);- this.$inputName.val(attrName).attr("readonly", disabledFn);-- this.$rowValue.toggle(this.attrType === "label");this.$rowTargetNote.toggle(this.attrType === "relation");this.$rowPromoted.toggle(["label-definition", "relation-definition"].includes(this.attrType || ""));@@ -342,9 +270,7 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {this.$rowInverseRelation.toggle(this.attrType === "relation-definition");this.$inputInverseRelation.val(definition.inverseRelation || "").attr("disabled", disabledFn);- if (attribute.type === "label") {- this.$inputValue.val(attribute.value || "").attr("readonly", disabledFn);- } else if (attribute.type === "relation") {+ if (attribute.type === "relation") {this.$inputTargetNote.attr("readonly", disabledFn).val("").setSelectedNotePath("");if (attribute.value) {@@ -356,15 +282,9 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {}}- this.$inputInheritable.prop("checked", !!attribute.isInheritable).attr("disabled", disabledFn);-this.updateHelp();this.toggleInt(true);-- if (focus === "name") {- this.$inputName.trigger("focus").trigger("select");- }}async saveAndClose() {@@ -465,30 +385,10 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {}updateAttributeInEditor() {- let attrName = String(this.$inputName.val());-- if (!utils.isValidAttributeName(attrName)) {- // invalid characters are simply ignored (from user perspective they are not even entered)- attrName = utils.filterAttributeName(attrName);-- this.$inputName.val(attrName);- }-- if (this.attrType === "label-definition") {- attrName = `label:${attrName}`;- } else if (this.attrType === "relation-definition") {- attrName = `relation:${attrName}`;- }-- this.attribute.name = attrName;- this.attribute.isInheritable = this.$inputInheritable.is(":checked");-if (this.attrType?.endsWith("-definition")) {this.attribute.value = this.buildDefinitionValue();} else if (this.attrType === "relation") {this.attribute.value = this.$inputTargetNote.getSelectedNoteId() || "";- } else {- this.attribute.value = String(this.$inputValue.val());}this.triggerCommand("updateAttributeList", { attributes: this.allAttributes ?? [] });