Skip to content

Build your personal knowledge base with Trilium Notes

refactor(attributes): port the related notes list to Preact

Elian Doran0ab74bf6d9d7
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.css b/apps/client/src/widgets/attribute_widgets/attribute_detail.css
index cdcf789ca8..4098560bfb 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.css
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.css
@@ -18,6 +18,10 @@
padding: 5px;
}
+.related-notes-container {
+ margin-top: 20px;
+}
+
.related-notes-list {
padding-inline-start: 20px;
margin-top: 10px;
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
index 34eaacc5f4..e2fcb31522 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
@@ -2,9 +2,11 @@ import "./attribute_detail.css";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
+import appContext from "../../components/app_context.js";
import type { Attribute } from "../../services/attribute_parser.js";
import { isExperimentalFeatureEnabled } from "../../services/experimental_features.js";
import { focusSavedElement, saveFocusedElement } from "../../services/focus.js";
+import froca from "../../services/froca.js";
import { t } from "../../services/i18n.js";
import server from "../../services/server.js";
import { isIMEComposing } from "../../services/shortcuts.js";
@@ -13,6 +15,7 @@ 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 NoteLink from "../react/NoteLink.jsx";
import { disposeReactWidget, renderReactWidgetAtElement } from "../react/react_utils.jsx";
export interface AttributeDetailOpts {
@@ -120,6 +123,7 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {
<AttributeDetail
opts={this.opts}
showId={this.showId}
+ currentNoteId={this.noteId}
parentOffset={this.parent?.$widget?.offset() ?? { top: 0, left: 0 }}
onDismiss={() => this.hide()}
onCancel={() => this.cancelAndClose()}
@@ -134,6 +138,8 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {
interface AttributeDetailProps extends AttributeFormCallbacks {
opts: AttributeDetailOpts | null;
showId: number;
+ /** The note being viewed, excluded from the related notes list. */
+ currentNoteId?: string | null;
/** 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. */
@@ -142,7 +148,7 @@ interface AttributeDetailProps extends AttributeFormCallbacks {
onCancel: () => void;
}
-function AttributeDetail({ opts, showId, parentOffset, onDismiss, onCancel, ...formCallbacks }: AttributeDetailProps) {
+function AttributeDetail({ opts, showId, currentNoteId, parentOffset, onDismiss, onCancel, ...formCallbacks }: AttributeDetailProps) {
const popupRef = useRef<HTMLDivElement>(null);
const shown = !!opts;
const { onSaveAndClose } = formCallbacks;
@@ -218,7 +224,7 @@ function AttributeDetail({ opts, showId, parentOffset, onDismiss, onCancel, ...f
/>
</div>
- <AttributeForm key={showId} opts={opts} attrType={attrType} {...formCallbacks} />
+ <AttributeForm key={showId} opts={opts} attrType={attrType} currentNoteId={currentNoteId} {...formCallbacks} />
</div>
);
}
@@ -234,9 +240,10 @@ interface AttributeFormCallbacks {
* 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 & {
+function AttributeForm({ opts, attrType, currentNoteId, onAttributesChanged, onSaveAndClose, onDelete }: AttributeFormCallbacks & {
opts: AttributeDetailOpts;
attrType: AttrType;
+ currentNoteId?: string | null;
}) {
const { attribute, allAttributes, isOwned, focus } = opts;
// Definitions describe the attribute they define, so they complete against its own type.
@@ -376,10 +383,92 @@ function AttributeForm({ opts, attrType, onAttributesChanged, onSaveAndClose, on
/>
</div>
)}
+
+ <RelatedNotes attribute={attribute} currentNoteId={currentNoteId} />
</>
);
}
+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;
+
+interface SearchRelatedResponse {
+ // TODO: Deduplicate once we split client from server.
+ results: {
+ noteId: string;
+ notePathArray: string[];
+ }[];
+ count: number;
+}
+
+/** Lists the other notes carrying the same attribute, hidden entirely when there are none. */
+function RelatedNotes({ attribute, currentNoteId }: { attribute: Attribute; currentNoteId?: string | null }) {
+ const [ related, setRelated ] = useState<{ notePaths: string[]; moreCount: number }>();
+ const latestRequest = useRef(0);
+ const isInitialLookup = useRef(true);
+ const { type, name, value } = attribute;
+
+ useEffect(() => {
+ const requestId = ++latestRequest.current;
+
+ async function lookup() {
+ const { results, count } = await server.post<SearchRelatedResponse>("search-related", attribute);
+ const otherNotes = results.filter((result) => result.notePathArray.at(-1) !== currentNoteId);
+ const notes = await froca.getNotes(otherNotes
+ .slice(0, DISPLAYED_NOTES)
+ .map((result) => result.notePathArray.at(-1) ?? ""));
+
+ // A newer edit superseded this lookup while it was awaiting.
+ if (latestRequest.current !== requestId) {
+ return;
+ }
+
+ const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;
+ setRelated({
+ notePaths: notes.map((note) => note.getBestNotePathString(hoistedNoteId)),
+ // Counted against the server's total, so it also covers what the search itself capped.
+ moreCount: otherNotes.length > DISPLAYED_NOTES ? count - DISPLAYED_NOTES : 0
+ });
+ }
+
+ // The attribute the popup opened on is looked up right away; later edits are debounced.
+ if (isInitialLookup.current) {
+ isInitialLookup.current = false;
+ void lookup();
+ return;
+ }
+
+ const timeout = setTimeout(() => void lookup(), RELATED_NOTES_DEBOUNCE_MS);
+ return () => clearTimeout(timeout);
+ // `attribute` is edited in place, so its fields rather than its identity are the real inputs.
+ }, [ type, name, value, currentNoteId ]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ if (!related?.notePaths.length) {
+ return null;
+ }
+
+ return (
+ <div class="related-notes-container">
+ <h5 class="related-notes-title">
+ {t("attribute_detail.other_notes_with_name", { attributeType: type, attributeName: name })}
+ </h5>
+
+ <ul class="related-notes-list">
+ {related.notePaths.map((notePath) => (
+ <li key={notePath}><NoteLink notePath={notePath} showNotePath /></li>
+ ))}
+ </ul>
+
+ {related.moreCount > 0 && (
+ <div class="related-notes-more-notes">
+ {t("attribute_detail.and_more", { count: related.moreCount })}
+ </div>
+ )}
+ </div>
+ );
+}
+
const ATTR_TITLES: Record<string, string> = {
label: t("attribute_detail.label"),
"label-definition": t("attribute_detail.label_definition"),
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts b/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts
index 2f10e6de0a..48dc7aef6b 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail_old.ts
@@ -1,12 +1,9 @@
-import appContext from "../../components/app_context.js";
import type { Attribute } from "../../services/attribute_parser.js";
import froca from "../../services/froca.js";
import { t } from "../../services/i18n.js";
import linkService from "../../services/link.js";
import noteAutocompleteService from "../../services/note_autocomplete.js";
import promotedAttributeDefinitionParser from "../../services/promoted_attribute_definition_parser.js";
-import server from "../../services/server.js";
-import SpacedUpdate from "../../services/spaced_update.js";
import utils, { openInAppHelpFromUrl } from "../../services/utils.js";
import NoteContextAwareWidget from "../note_context_aware_widget.js";
import { ATTR_HELP } from "./attr_help.js";
@@ -87,29 +84,8 @@ const TPL = /*html*/`
</td>
</tr>
</table>
-
- <div class="related-notes-container">
- <br/>
-
- <h5 class="related-notes-tile">${t("attribute_detail.related_notes_title")}</h5>
-
- <ul class="related-notes-list"></ul>
-
- <div class="related-notes-more-notes">${t("attribute_detail.more_notes")}</div>
- </div>
</div>`;
-const DISPLAYED_NOTES = 10;
-
-interface SearchRelatedResponse {
- // TODO: Deduplicate once we split client from server.
- results: {
- noteId: string;
- notePathArray: string[];
- }[];
- count: number;
-}
-
export default class AttributeDetailWidget extends NoteContextAwareWidget {
private $inputName!: JQuery<HTMLElement>;
private $rowPromoted!: JQuery<HTMLElement>;
@@ -127,20 +103,13 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {
private $rowTargetNote!: JQuery<HTMLElement>;
private $rowPromotedAlias!: JQuery<HTMLElement>;
private $attrIsOwnedBy!: JQuery<HTMLElement>;
- private $relatedNotesContainer!: JQuery<HTMLElement>;
- private $relatedNotesTitle!: JQuery<HTMLElement>;
- private $relatedNotesList!: JQuery<HTMLElement>;
- private $relatedNotesMoreNotes!: JQuery<HTMLElement>;
private $attrHelp!: JQuery<HTMLElement>;
- private relatedNotesSpacedUpdate!: SpacedUpdate;
private attribute!: Attribute;
private allAttributes?: Attribute[];
private attrType!: ReturnType<AttributeDetailWidget["getAttrType"]>;
doRender() {
- this.relatedNotesSpacedUpdate = new SpacedUpdate(async () => this.updateRelatedNotes(), 1000);
-
this.$widget = $(TPL);
this.$inputName = this.$widget.find(".attr-input-name");
@@ -187,17 +156,11 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {
this.attribute.value = pathChunks[pathChunks.length - 1]; // noteId
this.triggerCommand("updateAttributeList", { attributes: this.allAttributes ?? [] });
- this.updateRelatedNotes();
});
this.$attrIsOwnedBy = this.$widget.find(".attr-is-owned-by");
this.$attrHelp = this.$widget.find(".attr-help");
-
- this.$relatedNotesContainer = this.$widget.find(".related-notes-container");
- this.$relatedNotesTitle = this.$relatedNotesContainer.find(".related-notes-tile");
- this.$relatedNotesList = this.$relatedNotesContainer.find(".related-notes-list");
- this.$relatedNotesMoreNotes = this.$relatedNotesContainer.find(".related-notes-more-notes");
}
async showAttributeDetail({ allAttributes, attribute, isOwned, x, y, focus, hideMultiplicity }: AttributeDetailOpts) {
@@ -208,9 +171,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {
this.allAttributes = allAttributes;
this.attribute = attribute;
- // can be slightly slower so just make it async
- this.updateRelatedNotes();
-
if (isOwned) {
this.$attrIsOwnedBy.hide();
} else if (attribute.noteId) {
@@ -264,7 +224,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {
userEditedAttribute() {
this.updateAttributeInEditor();
this.updateHelp();
- this.relatedNotesSpacedUpdate.scheduleUpdate();
}
updateHelp() {
@@ -292,42 +251,6 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {
}
}
- async updateRelatedNotes() {
- let { results, count } = await server.post<SearchRelatedResponse>("search-related", this.attribute);
-
- for (const res of results) {
- res.noteId = res.notePathArray[res.notePathArray.length - 1];
- }
-
- results = results.filter(({ noteId }) => noteId !== this.noteId);
-
- if (results.length === 0) {
- this.$relatedNotesContainer.hide();
- } else {
- this.$relatedNotesContainer.show();
- this.$relatedNotesTitle.text(t("attribute_detail.other_notes_with_name", { attributeType: this.attribute.type, attributeName: this.attribute.name }));
-
- this.$relatedNotesList.empty();
-
- const displayedResults = results.length <= DISPLAYED_NOTES ? results : results.slice(0, DISPLAYED_NOTES);
- const displayedNotes = await froca.getNotes(displayedResults.map((res) => res.noteId));
- const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;
-
- for (const note of displayedNotes) {
- const notePath = note.getBestNotePathString(hoistedNoteId);
- const $noteLink = await linkService.createLink(notePath, { showNotePath: true });
-
- this.$relatedNotesList.append($("<li>").append($noteLink));
- }
-
- if (results.length > DISPLAYED_NOTES) {
- this.$relatedNotesMoreNotes.show().text(t("attribute_detail.and_more", { count: count - DISPLAYED_NOTES }));
- } else {
- this.$relatedNotesMoreNotes.hide();
- }
- }
- }
-
getAttrType(attribute: Attribute) {
if (attribute.type === "label") {
if (attribute.name.startsWith("label:")) {