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
Merge remote-tracking branch 'origin/main' into feature/attribute_selection
Elian Doran8fd65ffd1d1a
diff --cc apps/client/src/widgets/attribute_widgets/AttributeEditor.spec.tsxindex 0000000000,b9e5f42a5a..1f3fa9491fmode 000000,100644..100644--- a/apps/client/src/widgets/attribute_widgets/AttributeEditor.spec.tsx+++ b/apps/client/src/widgets/attribute_widgets/AttributeEditor.spec.tsx@@@ -1,0 -1,38 +1,26 @@@+ import type { ModelPosition } from "@triliumnext/ckeditor5";+ import { describe, expect, it } from "vitest";+-import { getClickIndex, getPreprocessedData } from "./AttributeEditor";--describe("getPreprocessedData", () => {- it("reduces a reference link back to the note path it stands for, and resolves the entities around it", () => {- expect(getPreprocessedData(- "<p>#author=Elian ~parent=<a class=\"reference-link\" href=\"#root/abc123\">Some note</a> </p>"- )).toBe("#author=Elian ~parent=#root/abc123 ");-- // A link to anywhere else is not a note path, so it is left to the text extraction below it.- expect(getPreprocessedData("<a href=\"https://example.com\">Example</a>")).toBe("Example");- expect(getPreprocessedData("#a&b")).toBe("#a&b");- });-});++import { getClickIndex } from "./AttributeEditor";++ describe("getClickIndex", () => {+ it("measures every sibling before the pressed one as the text it stands for", () => {+ const reference = { name: "reference", getAttribute: () => "#root/abc123" };+ const text = { data: "#author=Elian ", previousSibling: null };+ // …#author=Elian ~parent=#root/abc123 |~other+ const pressed = {+ data: "~other",+ startOffset: 3,+ previousSibling: { data: "~parent=", previousSibling: { ...reference, previousSibling: text } }+ };++ // The offset the editor reports counts the reference as a single node; the index does not.+ const index = getClickIndex({ offset: 5, textNode: pressed } as unknown as ModelPosition);+ expect(index).toBe(2 + "#author=Elian ".length + "~parent=".length + "#root/abc123".length + 1);++ // A press in the first node of all is its own offset.+ expect(getClickIndex({ offset: 4, textNode: text } as unknown as ModelPosition)).toBe(4);+ // A press where there is no text node at all still resolves to a position.+ expect(getClickIndex({ offset: 7, textNode: null } as unknown as ModelPosition)).toBe(7);+ });+ });diff --cc apps/client/src/widgets/attribute_widgets/AttributeEditor.tsxindex 0000000000,c808a5df41..cc314c02fdmode 000000,100644..100644--- a/apps/client/src/widgets/attribute_widgets/AttributeEditor.tsx+++ b/apps/client/src/widgets/attribute_widgets/AttributeEditor.tsx@@@ -1,0 -1,447 +1,439 @@@+ import "./AttributeEditor.css";++ import type { AttributeEditor as CKEditorAttributeEditor, ModelElement, ModelNode, ModelPosition, MentionHostedFeed } from "@triliumnext/ckeditor5";+ import { AttributeType } from "@triliumnext/commons";+ import clsx from "clsx";+ import { createPortal, RefObject } from "preact";+ import { useEffect, useImperativeHandle, useMemo, useRef, useState } from "preact/hooks";++ import type { CommandData, FilteredCommandNames } from "../../components/app_context";+ import FAttribute from "../../entities/fattribute";+ import FNote from "../../entities/fnote";+ import contextMenu from "../../menus/context_menu";++import { getPreprocessedData } from "../../services/attribute_clipboard";+ import attribute_parser, { Attribute } from "../../services/attribute_parser";+ import attribute_renderer from "../../services/attribute_renderer";+ import attributes from "../../services/attributes";+ import froca from "../../services/froca";+ import { t } from "../../services/i18n";+ import link from "../../services/link";+ import server from "../../services/server";+ import { isIMEComposing } from "../../services/shortcuts";+ import { escapeQuotes, getErrorMessage } from "../../services/utils";+ import ActionButton from "../react/ActionButton";+ import CKEditor, { CKEditorApi } from "../react/CKEditor";+ import { useLegacyImperativeHandlers, useLegacyWidget, useTriliumEvent } from "../react/hooks";+ import { createAutocompleteMentionList, createNoteMentionList } from "../type_widgets/text/mention_list_view";+ import AttributeDetailWidget, { AttributeNameSuggestion, fetchAttributeNames } from "./attribute_detail";++ type AttributeCommandNames = FilteredCommandNames<CommandData>;++ /**+ * How long the post-save blink runs for. Matches the animation in the CSS, and only serves to take the+ * class back off again — shortening it would cut the animation short.+ */+ const BLINK_DURATION = 300;++ interface AttributeEditorProps {+ api: RefObject<AttributeEditorImperativeHandlers | null>;+ note: FNote;+ componentId: string;+ notePath?: string | null;+ ntxId?: string | null;+ hidden?: boolean;+ /** Runs once the editor is ready, for the shortcut that caused it to be mounted. */+ initialCommand?: "addNewLabel" | "addNewRelation";+ }++ export interface AttributeEditorImperativeHandlers {+ save(): Promise<void>;+ refresh(): void;+ focus(): void;+ renderOwnedAttributes(ownedAttributes: FAttribute[]): Promise<void>;+ }++ export default function AttributeEditor({ api, note, componentId, notePath, ntxId, hidden, initialCommand }: AttributeEditorProps) {+ const [ currentValue, setCurrentValue ] = useState("");+ const [ error, setError ] = useState<unknown>();+ const [ needsSaving, setNeedsSaving ] = useState(false);+ const [ isBlinking, setIsBlinking ] = useState(false);+ const [isMenuOpen, setIsMenuOpen] = useState(false);+ const suppressNextOnHide = useRef(false);++ const blinkTimeout = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ const lastSavedContent = useRef<string | undefined>(undefined);+ const currentValueRef = useRef(currentValue);+ const wrapperRef = useRef<HTMLDivElement>(null);+ const editorRef = useRef<CKEditorApi | undefined>(undefined);+ // The editor outlives a switch to another note, so its `@` list reads the path as it opens.+ const notePathRef = useRef(notePath);+ notePathRef.current = notePath;+ const hostedMentions = useMemo(() => buildHostedMentions(() => notePathRef.current), []);++ // The CKEditor bundle is heavy and this component mounts in always-visible containers+ // (e.g. the status bar), so the editor class is loaded on demand to keep CKEditor out+ // of the startup module graph.+ const [ editorClass, setEditorClass ] = useState<typeof CKEditorAttributeEditor>();+ useEffect(() => {+ let active = true;+ void import("@triliumnext/ckeditor5").then((ckeditor) => {+ // Avoid a state update if the editor unmounted before the bundle finished loading.+ if (active) {+ setEditorClass(() => ckeditor.AttributeEditor);+ }+ });+ return () => {+ active = false;+ };+ }, []);++ const [ attributeDetailWidgetEl, attributeDetailWidget ] = useLegacyWidget(() => new AttributeDetailWidget());++ useEffect(() => () => clearTimeout(blinkTimeout.current), []);++ async function renderOwnedAttributes(ownedAttributes: FAttribute[], saved: boolean) {+ // attrs are not resorted if position changes after the initial load+ ownedAttributes.sort((a, b) => a.position - b.position);++ let htmlAttrs = (`<p>${(await attribute_renderer.renderAttributes(ownedAttributes, true)).html()}</p>`);++ if (saved) {+ lastSavedContent.current = htmlAttrs;+ setNeedsSaving(false);+ }++ if (htmlAttrs.length > 0) {+ htmlAttrs += " ";+ }++ editorRef.current?.setText(htmlAttrs);+ setCurrentValue(htmlAttrs);+ }++ function parseAttributes() {+ try {+ return attribute_parser.lexAndParse(getPreprocessedData(currentValueRef.current));+ } catch (e: unknown) {+ setError(e);+ }+ }++ async function save() {+ const attributes = parseAttributes();+ if (!attributes || !needsSaving) {+ // An error occurred and will be reported to the user, or nothing to save.+ return;+ }++ await server.put(`notes/${note.noteId}/attributes`, attributes, componentId);+ setNeedsSaving(false);++ // blink the attribute text to give a visual hint that save has been executed+ setIsBlinking(true);+ clearTimeout(blinkTimeout.current);+ blinkTimeout.current = setTimeout(() => setIsBlinking(false), BLINK_DURATION);+ }++ async function handleAddNewAttributeCommand(command: AttributeCommandNames | undefined) {+ // TODO: Not sure what the relation between FAttribute[] and Attribute[] is.+ const attrs = parseAttributes() as FAttribute[];++ if (!attrs) {+ return;+ }++ let type: AttributeType;+ let name;+ let value;++ if (command === "addNewLabel") {+ type = "label";+ name = "myLabel";+ value = "";+ } else if (command === "addNewRelation") {+ type = "relation";+ name = "myRelation";+ value = "";+ } else if (command === "addNewLabelDefinition") {+ type = "label";+ name = "label:myLabel";+ value = "promoted,single,text";+ } else if (command === "addNewRelationDefinition") {+ type = "label";+ name = "relation:myRelation";+ value = "promoted,single";+ } else {+ return;+ }++ //@ts-expect-error TODO: Incomplete type+ attrs.push({+ type,+ name,+ value,+ isInheritable: false+ });++ await renderOwnedAttributes(attrs, false);++ // this.$editor.scrollTop(this.$editor[0].scrollHeight);+ const rect = wrapperRef.current?.getBoundingClientRect();++ attributeDetailWidget.showAttributeDetail({+ allAttributes: attrs,+ attribute: attrs[attrs.length - 1],+ isOwned: true,+ x: rect ? (rect.left + rect.right) / 2 : 0,+ focus: "name",+ parent: wrapperRef.current ?? undefined+ });+ }++ // Refresh with note+ function refresh() {+ renderOwnedAttributes(note.getOwnedAttributes(), true);+ }++ useEffect(() => refresh(), [ note ]);+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {+ if (loadResults.getAttributeRows(componentId).find((attr) => attributes.isAffecting(attr, note))) {+ refresh();+ }+ });++ // Interaction with CKEditor.+ useLegacyImperativeHandlers(useMemo(() => ({+ loadReferenceLinkTitle: async ($el: JQuery<HTMLElement>, href: string) => {+ const { noteId } = link.parseNavigationStateFromUrl(href);+ const note = noteId ? await froca.getNote(noteId, true) : null;+ const title = note ? note.title : "[missing]";++ $el.text(title);+ }+ }), []));++ // Keyboard shortcuts+ useTriliumEvent("addNewLabel", ({ ntxId: eventNtxId }) => {+ if (eventNtxId !== ntxId) return;+ handleAddNewAttributeCommand("addNewLabel");+ });+ useTriliumEvent("addNewRelation", ({ ntxId: eventNtxId }) => {+ if (eventNtxId !== ntxId) return;+ handleAddNewAttributeCommand("addNewRelation");+ });++ // Imperative API+ useImperativeHandle(api, () => ({+ save,+ refresh,+ renderOwnedAttributes: (attributes) => renderOwnedAttributes(attributes as FAttribute[], false),+ focus: () => editorRef.current?.focus()+ }), [ save, refresh, renderOwnedAttributes ]);++ return (+ <>+ {!hidden && <div+ className={clsx("attribute-list-editor-wrapper", isBlinking && "blink")}+ ref={wrapperRef}+ style="position: relative; padding-top: 10px; padding-bottom: 10px"+ onKeyDown={(e) => {+ // Skip processing during IME composition+ if (isIMEComposing(e)) {+ return;+ }++ if (e.key === "Enter") {+ // allow autocomplete to fill the result textarea+ setTimeout(() => save(), 100);+ }+ }}+ > <div style="position: relative;">+ {editorClass && <CKEditor+ apiRef={editorRef}+ className="attribute-list-editor"+ tabIndex={200}+ editor={editorClass}+ currentValue={currentValue}+ config={{+ toolbar: { items: [] },+ placeholder: t("attribute_editor.placeholder"),+ mention: { feeds: [], hostedFeeds: hostedMentions },+ licenseKey: "GPL",+ language: "en"+ }}+ onChange={(currentValue) => {+ currentValueRef.current = currentValue ?? "";++ const oldValue = getPreprocessedData(lastSavedContent.current ?? "").trimEnd();+ const newValue = getPreprocessedData(currentValue ?? "").trimEnd();+ setNeedsSaving(oldValue !== newValue);+ setError(undefined);+ }}+ onClick={(e, pos) => {+ if (pos && pos.textNode && pos.textNode.data) {+ const clickIndex = getClickIndex(pos);++ let parsedAttrs: Attribute[];++ try {+ parsedAttrs = attribute_parser.lexAndParse(getPreprocessedData(currentValueRef.current), true);+ } catch (e: unknown) {+ // the input is incorrect because the user messed up with it and now needs to fix it manually+ console.log(e);+ return null;+ }++ let matchedAttr: Attribute | null = null;++ for (const attr of parsedAttrs) {+ if (attr.startIndex !== undefined && clickIndex > attr.startIndex &&+ attr.endIndex !== undefined && clickIndex <= attr.endIndex) {+ matchedAttr = attr;+ break;+ }+ }++ if (matchedAttr) {+ attributeDetailWidget.showAttributeDetail({+ allAttributes: parsedAttrs,+ attribute: matchedAttr,+ isOwned: true,+ x: e.pageX,+ parent: wrapperRef.current ?? undefined+ });+ } else {+ // Presses inside the editor no longer dismiss the popup, so+ // clicking next to an attribute has to close it explicitly.+ attributeDetailWidget.hide();+ }+ } else {+ attributeDetailWidget.hide();+ }+ }}+ onKeyDown={() => attributeDetailWidget.hide()}+ onBlur={() => save()}+ onInitialized={() => {+ editorRef.current?.focus();+ if (initialCommand) {+ void handleAddNewAttributeCommand(initialCommand);+ }+ }}+ disableNewlines disableSpellcheck+ />}++ <div className="attribute-editor-buttons">+ { needsSaving && <ActionButton+ icon="bx bx-save"+ className="save-attributes-button tn-tool-button"+ text={escapeQuotes(t("attribute_editor.save_attributes"))}+ onClick={save}+ /> }++ <ActionButton+ icon="bx bx-plus"+ className="add-new-attribute-button tn-tool-button"+ text={escapeQuotes(t("attribute_editor.add_a_new_attribute"))}+ onClick={(e) => {+ // Prevent automatic hiding of the context menu due to the button being clicked.+ e.stopPropagation();+ if (isMenuOpen) {+ // If we re-show the menu, ContextMenu.show() will call hide()+ // and immediately trigger onHide. Suppress that transient hide.+ suppressNextOnHide.current = true;+ }+ setIsMenuOpen(true);++ contextMenu.show<AttributeCommandNames>({+ x: e.pageX,+ y: e.pageY,+ orientation: "left",+ items: [+ { title: t("attribute_editor.add_new_label"), command: "addNewLabel", uiIcon: "bx bx-hash" },+ { title: t("attribute_editor.add_new_relation"), command: "addNewRelation", uiIcon: "bx bx-transfer" },+ { kind: "separator" },+ { title: t("attribute_editor.add_new_label_definition"), command: "addNewLabelDefinition", uiIcon: "bx bx-empty" },+ { title: t("attribute_editor.add_new_relation_definition"), command: "addNewRelationDefinition", uiIcon: "bx bx-empty" }+ ],+ selectMenuItemHandler: (item) => handleAddNewAttributeCommand(item.command),+ onHide: () => {+ if (suppressNextOnHide.current) {+ suppressNextOnHide.current = false;+ return;+ }+ setIsMenuOpen(false);+ },+ });+ }}+ />+ </div>+ </div>++ { error && (+ <div className="attribute-errors">+ {getErrorMessage(error)}+ </div>+ )}+ </div>}++ {createPortal(attributeDetailWidgetEl, document.body)}+ </>+ );+ }++ /**+ * Completes the name typed after `marker` as the attributes panel's name box completes it, from the+ * same names drawn the same way, and inserts the name picked behind the marker.+ */+ /**+ * The lists for the markers typed in the editor. Every list opens with nothing highlighted: in this+ * editor Enter means "save the attributes", so an open list must not swallow it into committing+ * whichever suggestion happens to be first.+ */+ function buildHostedMentions(getNotePath: () => string | null | undefined): MentionHostedFeed[] {+ return [+ attributeNameMention("#", "label"),+ attributeNameMention("~", "relation"),+ {+ marker: "@",+ minimumCharacters: 0,+ // Relation targets are note titles, which contain spaces.+ allowSpaces: true,+ list: () => createNoteMentionList({ allowCreatingNotes: true, preselect: false, getParentNotePath: getNotePath })+ }+ ];+ }++ function attributeNameMention(marker: "#" | "~", type: "label" | "relation"): MentionHostedFeed {+ return {+ marker,+ minimumCharacters: 0,+ list: () => createAutocompleteMentionList({+ source: (query) => fetchAttributeNames(type, query),+ renderItem: (name, query) => <AttributeNameSuggestion type={type} name={name} query={query} />,+ toMention: (name) => ({ id: `${marker}${name}` })+ })+ };+ }+-/** The attributes as plain text: reference links back down to their note path, entities resolved. */-export function getPreprocessedData(currentValue: string) {- const str = currentValue- .replace(/<a[^>]+href="(#[A-Za-z0-9_/]*)"[^>]*>[^<]*<\/a>/g, "$1")- .replace(/ /g, " "); // otherwise .text() below outputs non-breaking space in unicode-- return $("<div>").html(str).text();-}-+ /**+ * Where the press landed in {@link getPreprocessedData}'s text, which is what the parsed attributes+ * carry their offsets in: the editor's own offset counts a reference link as one node, so every+ * sibling before the pressed one is measured as the text it stands for.+ */+ export function getClickIndex(pos: ModelPosition) {+ let clickIndex = pos.offset - (pos.textNode?.startOffset ?? 0);++ let curNode: ModelNode | Text | ModelElement | null = pos.textNode;++ while (curNode?.previousSibling) {+ curNode = curNode.previousSibling;++ if ((curNode as ModelElement).name === "reference") {+ clickIndex += (curNode.getAttribute("href") as string).length + 1;+ } else if ("data" in curNode) {+ clickIndex += (curNode.data as string).length;+ }+ }++ return clickIndex;+ }diff --cc apps/client/src/widgets/sidebar/AttributeList.cssindex 9edd1b2116,1e5dd1c5af..1525cbf57a--- a/apps/client/src/widgets/sidebar/AttributeList.css+++ b/apps/client/src/widgets/sidebar/AttributeList.css@@@ -69,278 -38,13 +69,234 @@@z-index: 10;}- /*- * The kind of the attribute, as the icon of what it is (a label or a relation). It is the only thing- * saying so, the row carrying neither the `#`/`~` prefix nor the type as a word.- */- .attribute-list-panel .attribute-kind {- position: relative;- display: flex;- flex-shrink: 0;- color: var(--muted-text-color);- }-- /*- * A badge on the corner of the icon: a cog for the names Trilium reads for itself (settings of the note- * rather than a word for it), a chevron for a definition of a promoted field (one lifted out of the- * attributes and into the note's own ribbon). A second glyph rather than an icon of its own, so- * `cssClass` still reads as the label it is, and a promoted date field as the date field it defines.- */- .attribute-list-panel .attribute-kind.marker-system::after,- .attribute-list-panel .attribute-kind.marker-promoted::after {- position: absolute;- inset-inline-end: -3px;- bottom: -2px;- font-family: boxicons;- font-size: 0.62em;- font-weight: normal;- line-height: 1;- /* Punched out of the icon it sits on, so the two glyphs stay legible where they overlap. */- text-shadow:- 0 0 2px var(--card-background-color, var(--main-background-color)),- 0 0 2px var(--card-background-color, var(--main-background-color));- }-- .attribute-list-panel .attribute-kind.marker-system::after {- content: "\ea6e"; /* lookup code for "cog" in boxicons.css */- }-- .attribute-list-panel .attribute-kind.marker-promoted::after {- content: "\ea57"; /* lookup code for "chevron-up" in boxicons.css */- /* A single stroke where the cog is a whole shape, so it is drawn a size up to weigh the same. */- font-size: 0.8em;- inset-inline-end: -4px;- bottom: -4px;- }--/* What separates the note's own vocabulary from the names Trilium reads for itself. Quiet: the sort is- what carries the split, the rule only marks where it falls. */+/*+ * The checkbox a row is picked out by, standing in the slot the kind icon holds rather than in a+ * column of its own: the pane is narrow, and a column would take from the names what it took for+ * itself. Only the row being pointed at shows one — until rows are being picked out, when every row+ * shows its own, the way a list of mail turns over once one of it is picked.+ */+.attribute-list-panel .attribute-kind-check {+ position: absolute;+ inset: 0;+ display: none;+ align-items: center;+ justify-content: center;+}++.attribute-list-panel .attribute-row:hover .attribute-kind-check,+.attribute-list-panel.selecting .attribute-kind-check {+ display: flex;+}++.attribute-list-panel .attribute-kind-check .form-check-input {+ /* The icon's own size, so that the row is laid out the same whichever of the two is showing. */+ width: 13px;+ height: 13px;+ margin: 0;+ cursor: pointer;+}++/* The glyph the checkbox stands in for — badge and all, which would otherwise hang off its corner+ saying something about an attribute that is not what the checkbox is asking. Hidden rather than+ left out, so the slot keeps the width the icon gave it.++ Only where there is a checkbox to stand in for it, which is a pointer's rows: a phone marks a+ picked row by turning its icon into a check (see AttributeRow), so its unpicked rows keep theirs+ — and would otherwise be stripped of a badge that says the attribute is Trilium's own or its+ field promoted, neither of which the picking is about. The wrapper holding the icon is what+ these are about; on a phone the icon is itself `.attribute-kind`, hence the `.tn-icon` it always+ carries telling the two apart. */+.attribute-list-panel .attribute-row:hover .attribute-kind:not(.tn-icon) > .tn-icon,+.attribute-list-panel.selecting .attribute-kind:not(.tn-icon) > .tn-icon {+ visibility: hidden;+}++.attribute-list-panel .attribute-row:hover .attribute-kind:not(.tn-icon)::after,+.attribute-list-panel.selecting .attribute-kind:not(.tn-icon)::after {+ display: none;+}++/*+ * What can be done to the rows picked out, at the foot of the card. It stands where the add row+ * stands and takes its turn, so that picking rows out costs the list no room of its own.+ *+ * Held at the foot of what can be seen of the card rather than left at the end of the rows: a note+ * carrying more attributes than the card can show at once would otherwise have the bar scrolled off+ * below them, and rows are picked out to be acted on. It sticks against the card's body, which is+ * what scrolls (see RightPanelContainer.css); where the rows all fit, there is nothing to stick to+ * and it sits at their end as before. It is lifted just clear of the rows — but left under the row+ * an editor stands over (which reaches 10), that editor being the taller thing to read.+ *+ * Drawn as a surface of its own standing over the list rather than as a strip ruled off from it:+ * held off the card's edges so that it reads as a thing laid on the card and not as furniture the+ * card was built with. A rule across the card would have said instead that the list ends there,+ * which it does not.+ *+ * The theme's card recipe, as the chat's composer island wears it (see ChatInputBar.css): the 10px+ * radius shared by the centre pane, the dropdown menus and the tool dialogs, the card's own border+ * and fill, and no shadow of its own — a Trilium surface is told by its fill, not by being lifted+ * off what it sits on.+ *+ * Its fill is the one thing held apart from that recipe. A card's fill is a film over the pane+ * rather than a colour, which the rows sliding under this one would be read straight through; so+ * the film is laid over the app's surface here instead of straight onto the card, which comes out+ * the shade the recipe asks for and hides what passes beneath it besides.+ */+.attribute-selection-bar {+ position: sticky;+ bottom: 0;+ z-index: 1;+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 2px 3px 2px 10px;+ margin: 6px 4px 4px;+ border: 1px solid var(--card-border-color, var(--main-border-color));+ border-radius: 10px;+ box-shadow: var(--card-box-shadow, none);+ background-color: var(--main-background-color);+ background-image: linear-gradient(+ var(--card-background-color, var(--accented-background-color)),+ var(--card-background-color, var(--accented-background-color)));+}++/* The same island over a ground that is already carrying that wash. Where a run is a card of its own+ — a phone (see AttributeSection) — the card paints exactly the fill composited above, so the bar+ mixed to the card's own colour and disappeared into it, leaving its border to do all the work. The+ plain surface instead, which is what those cards are washed over: the island reads as lifted off+ them rather than as one more of them. */+body.mobile .attribute-selection-bar {+ background-image: none;+}++.attribute-selection-bar .attribute-selection-count {+ /* Pushes the buttons to the trailing edge, where the values read from. */+ margin-inline-end: auto;+ color: var(--muted-text-color);+ font-size: 0.85em;+}++/* At the compact size the row's own actions keep, the two rows of buttons reading as one kind. */+.attribute-selection-bar .icon-action {+ --icon-button-size: 24px;+ --icon-button-icon-ratio: 0.8;++ border-radius: 50%;+}++/*+ * The heading a run of rows folds away under, where a card and its own header stood before. Dressed+ * as those headers were — the pane's heading colour at its weight, its size and its letter spacing+ * (see shell.css) — so that the runs still read as the sections they were, one notch quieter for+ * standing inside a card rather than being one.+ *+ * Held at the top of what can be seen while its rows are scrolled past, so that a row is never read+ * without the heading that says what it is; the heading of the run below pushes it out of the way in+ * its turn. Opaque for the same reason the selection's island is, the rows passing under it — but+ * the app's surface plainly, not the card's fill over it: a right-pane card paints no ground of its+ * own, so its rows lie on that same surface, and a heading carrying the fill besides would read as+ * a band laid across them rather than as words above them.+ *+ * The room above it is padding rather than margin, which a sticky box is held off its edge by: the+ * rows would then be read through the gap that opened above the heading as they passed under it.+ */+.attribute-list-panel .attribute-group-header {+ position: sticky;+ top: 0;+ z-index: 1;+ display: flex;+ align-items: center;+ /* The row's own gap, so that a heading's words start where a row's name does. */+ gap: 6px;+ padding: 7px 4px 3px;+ cursor: pointer;+ color: var(--right-pane-heading-color, var(--muted-text-color));+ font-weight: 600;+ font-size: 0.85em;+ background-color: var(--main-background-color);+}++/* The room above a heading sets its run apart from the one before it. The first has none before it,+ only the card's own header, which has set it apart already. */+.attribute-list-panel .attribute-group:first-child .attribute-group-header {+ padding-top: 2px;+}++.attribute-list-panel .attribute-group-header:hover {+ color: var(--main-text-color);+}++/*+ * What makes the runs read as one thing branching rather than as three things stacked: the rows of a+ * run hang under its heading, set in from it and gathered by a line drawn down the heading's own+ * chevron — the branch the rows are on. The chevron folds the branch as a tree's does, and the line+ * ends where the branch does, so the eye is told where a run stops without a rule across the card.+ */+.attribute-list-panel .attribute-group-body {+ /* Set so the line lands under the middle of the chevron above it. */+ margin-inline-start: 11px;+ padding-inline-start: 6px;+ border-inline-start: 1px solid var(--main-border-color);+}++/* Turned as the cards turned theirs (see RightPanelContainer.css), so that folding a run away reads+ as folding a card away did. */+.attribute-list-panel .attribute-group-chevron {+ flex-shrink: 0;+ transition: transform 100ms ease;+}++.attribute-list-panel .attribute-group.collapsed .attribute-group-chevron {+ transform: rotate(-90deg);+}++.attribute-list-panel .attribute-group-title {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* How many the run holds, beside its name rather than away at the trailing edge: it is read as part+ of what the run is called, not as a column of its own. Sized and worn as the note tree wears the+ count of a node's hidden children (see note_tree.css) — the same wash, a shade of the ink over the+ page rather than a colour, and small enough to be answered rather than announced. */+/* The same figure where a run is a card of its own rather than a heading of one — a phone (see+ AttributeSection). Scoped by its own class rather than by the panel: the heading it sits in is the+ card's, which stands outside the list. The card's name is set uppercase and letter-spaced, neither+ of which a number takes any part in. */+.attribute-run-count {+ margin-inline-start: 6px;+ padding: 0.1em 0.5em;+ border-radius: 0.5em;+ color: var(--muted-text-color);+ font-size: 0.7rem;+ font-weight: normal;+ letter-spacing: 0;+ text-transform: none;+ vertical-align: middle;+}++.attribute-list-panel .attribute-group-count {+ flex-shrink: 0;+ /* The heading's own gap sets it off; the base badge's margin would set it adrift of the name. */+ margin-inline-start: 0;+ padding: 0.1em 0.5em;+ border-radius: 0.5em;+ color: var(--muted-text-color);+ font-size: 0.7rem;+ font-weight: normal;+ letter-spacing: 0;+}++/* What separates the note's own vocabulary from the names Trilium reads for itself. Quiet: the sort+ is what carries the split, the rule only marks where it falls — and quieter still than the line+ the run hangs from, which it crosses: a split within a branch, not a cut through it. Held off the+ leading edge for the same reason, so the branch reads as running past it unbroken. */.attribute-list-panel .attribute-rows-divider {- margin: 4px 4px 5px;+ margin: 5px 4px 6px 8px;border: none;border-top: 1px solid var(--main-border-color);- opacity: 0.6;+ opacity: 0.45;}.attribute-list-panel .attribute-name {diff --cc apps/client/src/widgets/sidebar/AttributeList.mobile.spec.tsxindex a701de8bc2,0000000000..55b7d959ecmode 100644,000000..100644--- a/apps/client/src/widgets/sidebar/AttributeList.mobile.spec.tsx+++ b/apps/client/src/widgets/sidebar/AttributeList.mobile.spec.tsx@@@ -1,218 -1,0 +1,218 @@@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import FNote from "../../entities/fnote";++// What this file is for: the panel draws its runs one way for a pointer and another for a thumb, and+// the device is read once at module load (see `IS_MOBILE`), so the two cannot be told apart within a+// single file. Everything else about the panel is covered against a pointer in AttributeList.spec.+vi.mock("../../services/utils", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../services/utils")>()),+ isMobile: () => true+}));++const shownNote = vi.hoisted(() => ({ current: null as FNote | null }));+vi.mock("../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../react/hooks")>()),+ useActiveNoteContext: () => ({ note: shownNote.current })+}));++const showContextMenu = vi.hoisted(() => vi.fn(async () => {}));+vi.mock("../../menus/context_menu", () => ({ default: { show: showContextMenu } }));+vi.mock("../../services/dialog", () => ({ default: { confirm: vi.fn(async () => true) } }));+vi.mock("../../services/toast", () => ({ default: { showMessage: vi.fn(), showError: vi.fn() } }));++import FAttribute, { FAttributeRow } from "../../entities/fattribute";+import { holdAttributes } from "../../services/attribute_clipboard";+import froca from "../../services/froca";+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 from "./AttributeList";++describe("AttributeList on a phone", () => {+ let container: HTMLElement;+ let put: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ vi.clearAllMocks();+ options.set("rightPaneCollapsedItems", "[]");+ // What Trilium last copied outlives a render, so each test says for itself whether there is+ // anything to paste.+ holdAttributes([]);+ put = vi.fn(async () => ({}));+ server.put = put as unknown as typeof server.put;+ server.post = (async () => ({ results: [], count: 0 })) as unknown as typeof server.post;+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ vi.useRealTimers();+ });++ it("draws a card per run rather than the tree a pointer gets", () => {+ renderPanel(noteWithRuns());++ // A card each, as the panel had before its runs became headings of one card: the tree that+ // gathers them is a pointer's affordance — hairlines, hover, a fold — drawn for a pane a hand+ // wide, and a phone has neither the pointer nor the want of room.+ expect(container.querySelectorAll(".attribute-group")).toHaveLength(0);+ expect(container.querySelectorAll(".attribute-group-header")).toHaveLength(0);+ expect(sectionIds()).toEqual([ "attributes-owned", "attributes-inherited", "attributes-definitions" ]);++ // Each card names its run and counts it beside the name, as the headings do on a desktop.+ expect(section("attributes-owned").querySelector(".attribute-run-count")?.textContent).toBe("2");+ expect(section("attributes-definitions").querySelector(".attribute-run-count")?.textContent).toBe("2");++ // The rows themselves are unchanged — menu items, which is what a phone's lists are made of.+ expect(namesIn(section("attributes-owned"))).toEqual([ "author", "template" ]);+ expect(section("attributes-owned").querySelector(".attribute-row")?.className).toContain("dropdown-item");+ });++ it("keeps the ways in on the cards' own headers, there being no row to hover for one", () => {+ renderPanel(noteWithRuns());++ // The panel's own two ride on the first card, there being no header above the cards; the+ // menu is also the only way to a relation here, whose creation editor is a pointer's.+ expect(iconsIn(header("attributes-owned"))).toEqual([ "bx bx-help-circle", "bx bx-plus" ]);- // A run that can be added to says so in its own header, definitions included; one that- // cannot — the inherited, which are another note's — says nothing.- expect(iconsIn(header("attributes-definitions"))).toEqual([ "bx bx-plus" ]);- expect(iconsIn(header("attributes-inherited"))).toEqual([]);++ // Each card has its own help. A run that can be added to also has an add button, definitions++ // included; the inherited run, whose attributes belong to another note, has none.++ expect(iconsIn(header("attributes-definitions"))).toEqual([ "bx bx-help-circle", "bx bx-plus" ]);++ expect(iconsIn(header("attributes-inherited"))).toEqual([ "bx bx-help-circle" ]);++ // The ghost row at the foot of a run is a hover affordance, so it stays on the desktop.+ expect(container.querySelector(".attribute-add-row")).toBeNull();+ });++ it("says a run holds nothing, which a pointer's runs leave to the add row beneath them", () => {+ renderPanel(buildNote({ id: "phone-bare-run", title: "Bare" }));++ // The card would otherwise stand empty and say nothing: a phone keeps what is done to a run+ // in the card's header, so there is no add row inside it to imply the run is waiting to be+ // filled. AttributeList.spec asserts the other half — that a pointer gets no such notice.+ expect(container.querySelectorAll(".attribute-row")).toHaveLength(0);+ expect(section("attributes-owned").querySelector(".no-items")).not.toBeNull();+ // Only the note's own run is ever shown empty; the rest are left out when they hold nothing.+ expect(sectionIds()).toEqual([ "attributes-owned" ]);+ });++ it("offers pasting from the first card's header, which is a phone's only way to it", async () => {+ // Nothing copied, nothing offered — as the row menu and the selection's bar do.+ renderPanel(noteWithRuns());+ expect(iconsIn(header("attributes-owned"))).not.toContain("bx bx-paste");++ // The note that most wants pasting into is the one carrying nothing, and it is exactly the+ // note where every other way in is gone: no row to hold down, so no selection and no bar,+ // and the list a press beside the rows would land on has no rows to give it a height. The+ // header stands whatever the run holds, which is why the way in belongs there.+ render(null, container);+ holdAttributes([ { type: "label", name: "author", value: "Elian", isInheritable: false } ]);+ renderPanel(buildNote({ id: "phone-bare", title: "Bare" }));++ expect(container.querySelectorAll(".attribute-row")).toHaveLength(0);+ expect(container.querySelector(".attribute-selection-bar")).toBeNull();+ expect(iconsIn(header("attributes-owned"))).toEqual([ "bx bx-help-circle", "bx bx-paste", "bx bx-plus" ]);++ const paste = header("attributes-owned")?.querySelector<HTMLElement>(".bx-paste");+ await act(async () => paste?.click());++ const [ url, saved ] = put.mock.calls[0] as [ string, { name: string; value: string }[] ];+ expect(url).toBe("notes/phone-bare/attributes");+ expect(saved).toEqual([ { type: "label", name: "author", value: "Elian", isInheritable: false } ]);+ });++ it("still picks rows out, by the press held down, and says what can be done with them", () => {+ vi.useFakeTimers();+ renderPanel(noteWithRuns());++ const row = section("attributes-owned").querySelector(".attribute-row");+ act(() => {+ row?.dispatchEvent(new Event("touchstart", { bubbles: true }));+ });+ // Held long enough, the press picks the row out rather than opening it.+ act(() => void vi.advanceTimersByTime(600));++ expect(row?.className).toContain("selected");+ // The mark a menu item is checked with, in the slot the kind icon holds — a phone has no+ // checkbox to put there.+ expect(row?.querySelector(".bx-check")).not.toBeNull();+ expect(container.querySelector(".attribute-list-panel")?.className).toContain("selecting");++ // The bar stands after the cards, the rows it acts on being picked out among any of them.+ const bar = container.querySelector(".attribute-selection-bar");+ expect(bar).not.toBeNull();+ expect(iconsIn(bar)).toEqual([ "bx bx-copy", "bx bx-trash", "bx bx-x" ]);+ expect(bar?.compareDocumentPosition(section("attributes-definitions")))+ .toBe(Node.DOCUMENT_POSITION_PRECEDING);+ });++ function renderPanel(note: FNote) {+ shownNote.current = note;+ act(() => render(<AttributeList />, container));+ }++ function sectionIds() {+ return [ ...container.querySelectorAll(".options-section") ]+ .map((el) => [ ...el.classList ].find((name) => name.startsWith("attributes-")));+ }++ function section(id: string) {+ const el = container.querySelector<HTMLElement>(`.options-section.${id}`);+ expect(el, id).not.toBeNull();+ return el as HTMLElement;+ }++ function header(id: string) {+ return section(id).querySelector<HTMLElement>(".options-section-header");+ }+});++function namesIn(root: Element) {+ return [ ...root.querySelectorAll(".attribute-name") ].map((name) => name.textContent);+}++/** The icons a header (or the selection bar) offers, which is what its buttons are known by: the+ * titles are translated, and translations stay unloaded in these tests. */+function iconsIn(root: Element | null) {+ return [ ...(root?.querySelectorAll(".bx") ?? []) ]+ .map((icon) => [ ...icon.classList ].filter((name) => name.startsWith("bx")).join(" "));+}++/** A note with all three of the runs a phone can be shown, each holding more than one row. */+function noteWithRuns() {+ buildNote({ id: "tpl", title: "Template" });+ const note = buildNote({+ id: "phone-subject",+ title: "Subject",+ "#author": "Elian",+ "~template": "tpl",+ "#label:priority": "promoted,single,date"+ });++ noteAttributeCache.attributes[note.noteId] = [+ ...note.getOwnedAttributes(),+ inherited({ name: "inheritedLabel", value: "x" }),+ inherited({ name: "archived", value: "" }),+ inherited({ name: "label:status", value: "promoted,multi" })+ ];++ return note;+}++function inherited(row: Partial<FAttributeRow>) {+ return new FAttribute(froca, {+ attributeId: `inh-${row.name}`,+ noteId: "tpl",+ type: "label",+ name: "",+ value: "",+ position: 0,+ isInheritable: true,+ ...row+ } as FAttributeRow);+}diff --cc apps/client/src/widgets/sidebar/AttributeList.spec.tsxindex 9d36198753,3e16b46b66..d531c5abe4--- a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx+++ b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx@@@ -222,45 -215,48 +222,65 @@@ describe("AttributeList", () =>// An inheritable attribute is marked, and every definition previews what it sets up — a// set-holding one (label:status, "multi") by a mark of its own rather than by words.- expect(cards[1].querySelectorAll(".attribute-marker")).toHaveLength(2);- expect(cards[2].querySelectorAll(".attribute-value.definition")).toHaveLength(2);- expect(cards[2].querySelectorAll(".definition-marker")).toHaveLength(1);+ expect(group("attributes-inherited").querySelectorAll(".attribute-marker")).toHaveLength(2);+ expect(group("attributes-definitions").querySelectorAll(".attribute-value.definition")).toHaveLength(2);+ expect(group("attributes-definitions").querySelectorAll(".definition-marker")).toHaveLength(1);});+ it("lists the attributes of a note that cannot be edited, offering no way to change them", () => {+ const note = noteWithAttributes();+ note.isContentWritable = false;+ renderPanel(note);+- const cards = [ ...container.querySelectorAll(".card") ];- expect(namesIn(cards[0])).toEqual([ "author", "cssClass", "template" ]);++ expect(namesIn(group("attributes-owned"))).toEqual([ "author", "cssClass", "template" ]);+ // Read as any other note's: Trilium's own names below the rule, inherited ones naming their note.- expect(cards[0].querySelectorAll("hr.attribute-rows-divider")).toHaveLength(1);- expect(cards[1].querySelectorAll(".attribute-owner")).toHaveLength(2);++ expect(group("attributes-owned").querySelectorAll("hr.attribute-rows-divider")).toHaveLength(1);++ expect(group("attributes-inherited").querySelectorAll(".attribute-owner")).toHaveLength(2);+ expect(container.querySelectorAll(".attribute-delete-button")).toHaveLength(0);+ expect(container.querySelectorAll(".attribute-edit-button")).toHaveLength(0);+ expect(container.querySelector(".attribute-add-row")).toBeNull();+ expect(container.querySelector(".bx-plus")).toBeNull();+ });+- it("keeps to one card, collapsing and all, for a note with nothing but its own attributes", () => {- renderPanel(buildNote({ id: "bare", title: "Bare", "#author": "Elian" }));+ it("folds a run of rows away by its heading, and remembers it folded", async () => {+ options.set("rightPaneCollapsedItems", JSON.stringify([ "attributes-inherited" ]));+ renderPanel(noteWithAttributes());- expect(container.querySelectorAll(".card")).toHaveLength(1);- // Down to a single card there is nothing to put away, so no chevron is offered.+ // Remembered from before, so the run arrives folded and its rows are not drawn at all.+ expect(group("attributes-inherited").className).toContain("collapsed");+ expect(namesIn(group("attributes-inherited"))).toEqual([]);+ // The card is the only one its tab has, so it is not itself something to fold away.expect(container.querySelector(".card")?.className).toContain("not-collapsible");++ await act(async () => groupHeader("attributes-inherited").click());+ expect(group("attributes-inherited").className).not.toContain("collapsed");+ expect(namesIn(group("attributes-inherited"))).toEqual([ "inheritedLabel", "archived" ]);+ expect(JSON.parse(options.get("rightPaneCollapsedItems") ?? "[]")).not.toContain("attributes-inherited");++ // And folding one back up is remembered the same way.+ await act(async () => groupHeader("attributes-definitions").click());+ expect(JSON.parse(options.get("rightPaneCollapsedItems") ?? "[]")).toContain("attributes-definitions");});- it("says so, rather than showing an empty list, for a note carrying no attributes at all", () => {+ it("leaves a note carrying no attributes its heading and the way in, and says nothing besides", () => {renderPanel(buildNote({ id: "empty", title: "Empty" }));+ // The run stands, empty. Nothing stands in for its rows: the heading counts them — at zero —+ // and the add row says what there is to do about it, so any "no attributes" beside those two+ // would be a third telling of the one fact, and the loudest of the three at that.expect(container.querySelectorAll(".attribute-row")).toHaveLength(0);- expect(container.querySelector(".no-items")).not.toBeNull();+ expect(container.querySelector(".no-items")).toBeNull();+ expect(groupIds()).toEqual([ "attributes-owned" ]);+ expect(group("attributes-owned").querySelector(".attribute-group-count")?.textContent).toBe("0");+ expect(group("attributes-owned").querySelector(".attribute-add-row")).not.toBeNull();++ // Adding takes the placeholder's place: there is a row again, draft though it still is.+ act(() => container.querySelector<HTMLElement>(".attribute-add-row")?.click());+ expect(container.querySelectorAll(".attribute-row")).toHaveLength(1);+ expect(container.querySelector(".no-items")).toBeNull();});- it("leaves what Trilium wrote for itself out of a release build, and gives it its own card in a development one", () => {+ it("leaves what Trilium wrote for itself out of a release build, and gives it its own run in a development one", () => {buildNote({ id: "target", title: "Target" });const note = buildNote({ id: "linking", title: "Linking", "#author": "Elian", "~internalLink": "target" });@@@ -455,6 -432,12 +475,12 @@@expect(editor?.querySelector(".attribute-creation-value input")).not.toBeNull();expect(editor?.querySelector(".note-autocomplete-stub")).toBeNull();+ // ...in a row at the foot of the list, where the press that opened it was — and not where+ // the sort would file a name it does not have yet, above the ones Trilium reads for itself.- const ownedCard = container.querySelector("#attributes");- expect(namesIn(ownedCard ?? container)).toEqual([ "author", "cssClass", "template", "" ]);- expect([ ...(ownedCard?.querySelectorAll(".attribute-row") ?? []) ].at(-1)?.contains(editor ?? null)).toBe(true);++ const ownedRun = group("attributes-owned");++ expect(namesIn(ownedRun)).toEqual([ "author", "cssClass", "template", "" ]);++ expect([ ...ownedRun.querySelectorAll(".attribute-row") ].at(-1)?.contains(editor ?? null)).toBe(true);+// ...until the `~` the attributes editor spells relations with is typed at the name's head:// the prefix is spent on the switch, the name keeping only what follows it.const nameInput = editor?.querySelector<HTMLInputElement>(".attribute-creation-name input");diff --cc apps/client/src/widgets/sidebar/AttributeList.tsxindex 1d756aa967,bf04e2f14e..3cd4f2aedf--- a/apps/client/src/widgets/sidebar/AttributeList.tsx+++ b/apps/client/src/widgets/sidebar/AttributeList.tsx@@@ -14,16 -13,14 +14,17 @@@ import type { Attribute } from "../../simport attributes, { isBuiltinAttribute } from "../../services/attributes";import dialog from "../../services/dialog";import { t } from "../../services/i18n";++import type { SidebarSectionId } from "../../services/in_app_help";import server from "../../services/server";-import { isMobile } from "../../services/utils";+import toast from "../../services/toast";+import { getErrorMessage, isMobile } from "../../services/utils";- import { AttributeDetail, AttributeDetailOpts, AttributeForm, AttrType, DEFINITION_TYPES, getAttrType, RELATION_DEFINITION_TYPE } from "../attribute_widgets/attribute_detail";+ import { AttributeDetail, AttributeDetailOpts, AttributeForm, AttrType, DEFINITION_TYPES, getAttrType } from "../attribute_widgets/attribute_detail";+ import { attributeKindIcon, RELATION_DEFINITION_TYPE } from "../attribute_widgets/attribute_types";import { ColorChip, renderLabelValue } from "../attribute_widgets/label_value_display";import ActionButton from "../react/ActionButton";+import SimpleBadge from "../react/Badge";import { FormListItem } from "../react/FormList";- import HelpButton from "../react/HelpButton";-import { useActiveNoteContext, useTriliumEvent } from "../react/hooks";+import { useActiveNoteContext, useTriliumEvent, useTriliumOptionJson } from "../react/hooks";import Icon from "../react/Icon";import { DetailPane, MasterPane, useMasterDetail, useMasterDetailPage } from "../react/master_detail";import NoItems from "../react/NoItems";@@@ -315,302 -294,8 +314,303 @@@ export default function AttributeList(}const sections = splitIntoSections(owned.current, inherited.current);+ const canEdit = !!note && note.isContentWritable;const internalRows = internal.current.map((attribute) => toEntry(attribute, true));++ //#region Selection and the clipboard+ /**+ * Every row that can be picked out, in the order the panel draws them — the three cards read as+ * one list, so a range drawn with shift runs from any row to any other. The internal card is left+ * out: its rows are Trilium's own bookkeeping, rewritten whenever the note's content is saved,+ * which there is nothing to be gained by carrying elsewhere. A row is picked out by its+ * attributeId, so a draft still being created is not among them — it is not an attribute yet.+ */+ const selectableRows = [ ...sections.owned, ...sections.inherited, ...sections.definitions ]+ .filter((entry) => entry.attribute.attributeId);+ const selectableIds = selectableRows.flatMap((entry) => entry.attribute.attributeId ?? []);++ /**+ * Whether rows are being picked out, which is the panel's second standing: every row shows the+ * checkbox only the pointed-at one shows otherwise, the actions over the rows picked out are at+ * the foot of the card, and a row's own — its pencil, its trash — are put away, being about the+ * one row. There is no mode to turn on and off beside the selection itself: picking the first+ * row out is what starts it, and letting the last one go is what ends it.+ */+ const isSelecting = selection.size > 0;++ /** The picked-out rows in the order they are drawn, whichever cards they were picked out from. */+ function selectedAttributes() {+ return selectableRows+ .filter((entry) => entry.attribute.attributeId && selection.has(entry.attribute.attributeId))+ .map((entry) => entry.attribute);+ }++ function clearSelection() {+ selectionAnchor.current = null;+ setSelection(EMPTY_SELECTION);+ }++ /** Drops from the selection whatever the note no longer holds, so what is copied is what is shown. */+ function pruneSelection() {+ setSelection((current) => {+ if (current.size === 0) {+ return current;+ }++ const shown = new Set([ ...owned.current, ...inherited.current ].flatMap((attribute) => attribute.attributeId ?? []));+ const next = new Set([ ...current ].filter((attributeId) => shown.has(attributeId)));++ return next.size === current.size ? current : next;+ });+ }++ /**+ * Picks a row out or takes it back out. A range is drawn from the row last picked out on its own,+ * replacing whatever was picked out before it — what shift asks for; otherwise the one row is+ * added or removed, as a list of files is picked through and as a checkbox means.+ */+ function selectRow(attributeId: string, range = false) {+ // Whatever is being edited is wrapped up: picking rows out is about the rows, not the value.+ commit();+ commitValueEdit();+ commitCreation();++ if (range && selectionAnchor.current) {+ const from = selectableIds.indexOf(selectionAnchor.current);+ const to = selectableIds.indexOf(attributeId);++ if (from >= 0 && to >= 0) {+ setSelection(new Set(selectableIds.slice(Math.min(from, to), Math.max(from, to) + 1)));+ return;+ }+ }++ const next = new Set(selection);+ if (next.has(attributeId)) {+ next.delete(attributeId);+ } else {+ next.add(attributeId);+ }++ selectionAnchor.current = attributeId;+ setSelection(next);+ }++ /**+ * The copy key, which the panel receives by holding the focus (see {@link clipboardProps}). With+ * no rows picked out it is left alone: the press is then about whatever text is selected in the+ * panel, which is the browser's to copy.+ */+ function copySelection(e: ClipboardEvent) {+ const picked = selectedAttributes();+ if (picked.length === 0) {+ return;+ }++ e.preventDefault();+ writeAttributes(e.clipboardData, picked);+ // What is held is what says whether pasting is on offer at all, so the offer is redrawn.+ rerender();+ toast.showMessage(t("attribute_list_panel.copied", { count: picked.length }));+ }++ /**+ * The same from a button or a menu, where there is no event to write onto. What is held is set+ * before the system clipboard is written to: it is what says whether pasting is on offer, and+ * the offer has no reason to wait on a round trip the panel does not read back.+ */+ function copyPickedAttributes(picked: Attribute[]) {+ holdAttributes(picked);+ rerender();+ toast.showMessage(t("attribute_list_panel.copied", { count: picked.length }));++ void copyAttributesToClipboard(picked);+ }++ /**+ * The paste key. What the clipboard holds is read as the text the attributes editor spells+ * attributes out in — which is what this panel copies, and what that editor holds — so a paste+ * from either lands here whole, as does one written out by hand.+ */+ async function pasteAttributes(e: ClipboardEvent) {+ if (!note) {+ return;+ }+ e.preventDefault();++ let pasted: Attribute[];+ try {+ pasted = readAttributes(e.clipboardData);+ } catch (error: unknown) {+ // What was on the clipboard was not attributes; the parser says what it made of it.+ toast.showError(t("attribute_list_panel.paste_failed", { message: getErrorMessage(error) }));+ return;+ }++ if (pasted.length === 0) {+ toast.showMessage(t("attribute_list_panel.nothing_to_paste"));+ return;+ }++ await applyPaste(pasted);+ }++ /** The attributes folded into the note's own and saved, wherever the paste came from. */+ async function applyPaste(pasted: Attribute[]) {+ if (!note) {+ return;+ }++ // The edit in flight is wrapped up first, so the paste folds into a settled list.+ commit();+ commitValueEdit();+ commitCreation();++ const { attributes, added, replaced } = mergePastedAttributes(+ owned.current,+ pasted,+ (attribute) => isMultiValued(note, attribute)+ );++ owned.current = attributes;+ rerender();+ await save();++ toast.showMessage(t("attribute_list_panel.pasted", { count: added + replaced }));+ }++ /**+ * The menu a row is right-pressed for, over the rows picked out — which a press on a row that is+ * not among them narrows down to that row alone, as a file manager does. Copying is offered for+ * any row and deleting only where every picked row is the note's own: an inherited attribute is+ * the source note's to delete.+ */+ function showRowMenu(attribute: Attribute, e: MouseEvent) {+ e.preventDefault();+ e.stopPropagation();++ const attributeId = attribute.attributeId;+ let picked = selectedAttributes();++ if (!attributeId || !selection.has(attributeId)) {+ picked = [ attribute ];++ // The narrowing is only a correction, so it is only made where there is something to+ // correct: with rows already picked out, a menu about a row outside them would leave+ // the panel offering to copy three rows while the menu deleted a fourth. With none+ // picked out there is no such contradiction — and picking this one out to make the+ // point would turn the whole panel over to a standing it was never asked for, every row+ // grown a checkbox and stripped of its own buttons, the bar up at the foot, all for a+ // menu about the one row under the pointer. A press asking what can be done to a row is+ // not a press picking it out.+ if (isSelecting) {+ selectionAnchor.current = attributeId ?? null;+ setSelection(attributeId ? new Set([ attributeId ]) : EMPTY_SELECTION);+ }+ }++ const items: MenuItem<never>[] = [+ {+ title: t("attribute_list_panel.copy", { count: picked.length }),+ uiIcon: "bx bx-copy",+ handler: () => void copyPickedAttributes(picked)+ },+ ...pasteMenuItems()+ ];++ if (picked.every((candidate) => owned.current.includes(candidate))) {+ items.push({ kind: "separator" });+ items.push({+ title: t("attribute_list_panel.delete_selection", { count: picked.length }),+ uiIcon: "bx bx-trash",+ handler: () => void deleteSelection(picked)+ });+ }++ void contextMenu.show({ x: e.pageX, y: e.pageY, items, selectMenuItemHandler: () => {} });+ }++ /**+ * The menu the card itself is right-pressed for, beside the rows — which is where a note with no+ * attributes at all is pasted onto, there being no row to press. Nothing is shown where there is+ * nothing to paste: the browser's own menu is the better answer then.+ */+ function showPanelMenu(e: MouseEvent) {+ const items = pasteMenuItems();+ if (items.length === 0) {+ return;+ }++ e.preventDefault();+ void contextMenu.show({ x: e.pageX, y: e.pageY, items, selectMenuItemHandler: () => {} });+ }++ /**+ * Pasting as a menu offers it, which is what Trilium last copied rather than what the system+ * clipboard holds — a menu cannot read that one (see the clipboard service), and the note tree's+ * own paste works from the same kind of store. The paste key is the way in to everything else,+ * the attributes editor's text included.+ */+ function pasteMenuItems(): MenuItem<never>[] {+ const heldAttributes = getHeldAttributes();+ if (heldAttributes.length === 0 || !note) {+ return [];+ }++ return [ {+ title: t("attribute_list_panel.paste", { count: heldAttributes.length }),+ uiIcon: "bx bx-paste",+ handler: () => void applyPaste(heldAttributes)+ } ];+ }++ /** Deletes the rows picked out, confirmed once for the lot as a single row's press is for the one. */+ async function deleteSelection(picked: Attribute[]) {+ if (picked.length === 1) {+ await deleteAttribute(picked[0]);+ return;+ }++ if (!await dialog.confirm(t("attribute_list_panel.delete_selection_confirm", { count: picked.length }))) {+ return;+ }++ owned.current = owned.current.filter((candidate) => !picked.includes(candidate));+ clearSelection();+ setDetail(null);+ rerender();++ await save();+ }++ /**+ * What every card carries so that the copy and paste keys reach the panel rather than the note+ * behind it: a clipboard event goes to whatever holds the focus, so a press anywhere in a card+ * takes it. Presses inside an open editor are left alone — taking the focus off a field would+ * commit the very edit the press is part of.+ */+ const clipboardProps = {+ tabIndex: -1,+ onCopy: copySelection,+ onPaste: (e: ClipboardEvent) => void pasteAttributes(e),+ onKeyDown: (e: KeyboardEvent) => {+ if (e.key === "Escape" && selection.size > 0) {+ e.stopPropagation();+ clearSelection();+ }+ },+ onMouseDownCapture: (e: MouseEvent) => {+ if (e.target instanceof Element && e.target.closest(".attribute-editor-overlay")) {+ return;+ }++ if (e.currentTarget instanceof HTMLElement) {+ e.currentTarget.focus({ preventScroll: true });+ }+ }+ };+ //#endregion+// Not built for an attribute the list no longer holds: a reload can rebuild the rows out from// under the editor within this very render, before the state has caught up (see above).const activeValueEdit = valueEdit && owned.current.includes(valueEdit.attribute) ? valueEdit : null;@@@ -647,11 -338,8 +653,12 @@@note,activeAttribute: detail?.attribute,valueEditor,+ selection,+ selecting: isSelecting,+ locked: !canEdit,onOpen: openDetail,+ onSelect: selectRow,+ onShowMenu: showRowMenu,onEditValue: startValueEdit,onDelete: (attribute: Attribute) => void deleteAttribute(attribute)};@@@ -674,215 -367,97 +681,229 @@@onSaveAndClose: detail?.isOwned ? commit : undefined,onDelete: detail?.isOwned ? () => void deleteAttribute(detail.attribute) : undefined};- const sectionList = (+ // The runs the panel is made of, in the order it draws them — the same runs either way it is+ // drawn (see below), so what a run is and what it holds is settled in one place.+ const runs: AttributeRun[] = [ {+ id: "attributes-owned",+ title: t("attribute_list_panel.section_owned"),+ count: sections.owned.length,+ // The note's own values read from the trailing edge, as the inherited ones' do — the two+ // runs of plain attributes reading as one ledger. Nothing stands in for the run holding+ // nothing: its count says it is empty and its way in says what there is to do about it.- rows: <AttributeRowList rows={sections.owned} alignValuesEnd {...rowProps} />,- add: { kind: "label", text: t("attribute_list_panel.add_attribute") }++ // The draft under creation is listed last, outside the split between the note's own names and++ // Trilium's (see `creationRow`).++ rows: (++ <>++ <AttributeRowList rows={ownedRows} alignValuesEnd {...rowProps} />++ {creationRow && <AttributeRowList rows={[ creationRow ]} alignValuesEnd {...rowProps} />}++ </>++ ),++ add: canEdit ? { kind: "label", text: t("attribute_list_panel.add_attribute") } : undefined+ } ];++ if (sections.inherited.length > 0) {+ runs.push({+ id: "attributes-inherited",+ title: t("attribute_list_panel.section_inherited"),+ count: sections.inherited.length,++ help: "attributes-inherited",+ rows: <AttributeRowList rows={sections.inherited} alignValuesEnd {...rowProps} />+ });+ }++ if (sections.definitions.length > 0) {+ runs.push({+ id: "attributes-definitions",+ title: t("attribute_list_panel.section_definitions"),+ count: sections.definitions.length,++ help: "attributes-definitions",+ // The definitions keep prose order: their "value" is a summary of settings rather than a+ // value, so there is no column of values for it to line up in.+ rows: <AttributeRowList rows={sections.definitions} {...rowProps} />,- add: { kind: "label-definition", text: t("attribute_list_panel.add_definition") }++ add: canEdit ? { kind: "label-definition", text: t("attribute_list_panel.add_definition") } : undefined+ });+ }++ if (internalRows.length > 0) {+ runs.push({+ id: "attributes-internal",+ title: t("attribute_list_panel.section_internal"),+ count: internalRows.length,+ rows: <AttributeRowList rows={internalRows} readOnly {...rowProps} />+ });+ }++ // What Trilium last copied, which is what there is to paste (see the clipboard service). Read+ // here rather than at each use so that one render offers the same thing everywhere in itself.+ const heldAttributes = getHeldAttributes();++ // At the foot of the runs, the rows it acts on being picked out anywhere among them. It holds+ // there while they are scrolled (see the stylesheet), so it is the one thing both ways of+ // drawing them share: a phone picks rows out by holding one down, a pointer by the checkbox or+ // a modifier, and either way what can be done about it is said in the one place.+ const selectionBar = note && isSelecting && (+ <AttributeSelectionBar+ count={selection.size}+ canDelete={selectedAttributes().every((candidate) => owned.current.includes(candidate))}+ canPaste={heldAttributes.length > 0}+ onCopy={() => void copyPickedAttributes(selectedAttributes())}+ onPaste={() => void applyPaste(heldAttributes)}+ onDelete={() => void deleteSelection(selectedAttributes())}+ onClear={clearSelection}+ />+ );++ // Presses inside a run do not dismiss the popup (see `parent` above), which leaves closing on a+ // press next to a row up to this handler. A run is also what the note's own attributes are pasted+ // onto, so it offers pasting beside its rows as well as on them.+ const panelProps = {+ onClick: commit,+ onContextMenu: showPanelMenu,+ ...clipboardProps+ };++ const sectionList = IS_MOBILE ? (+ // A card each, as the panel had before its runs became headings of one card. What made them+ // headings was a pane a hand wide, where four card headers were a great deal of it to spend+ // on saying which run is which — and the tree that gathered them was drawn for a pointer, in+ // hairlines and hover. A phone has neither: the panel is a sheet the width of the screen,+ // which has the room, and the card is already how everything else on it says that things+ // belong together (see the settings pages). So the runs are cards again here, and the tree+ // is left to the pane that needed it.<>- {/* A card each, so a section is collapsed on its own and the inherited attributes — which a- template can run to dozens of — can be put away without taking the note's own with them.- Which is also why the collapsing is offered here rather than left to the tab: the tab- counts this whole panel as one widget (see RightPanelContainer), being one entry in its- list. Down to a single card, collapsing it away is not on offer. */}- <CollapsibleWidgets.Provider value={shownCards > 1}>+ {runs.map((run, index) => (<AttributeSection- id="attributes"- title={t("attribute_list_panel.owned", { count: sections.owned.length })}- grow- buttons={note && (+ key={run.id}+ id={run.id}+ title={run.title}+ count={run.count}+ buttons={note && (index === 0 ? (+ // The panel's own two ride on the first card: there is no header above the+ // cards to put them in, and the note's own attributes are what the panel is+ // opened for. The menu is also the only way to a relation on a phone, whose+ // rows are pressed rather than typed into — hence every kind, not just this+ // run's.<>- <HelpButton helpPage={ATTRIBUTE_HELP_PAGE} />+ <SidebarHelp section="attributes" />++ {/* The only way to paste a phone has. A pointer has three — the key,+ a right press on a row, a right press beside them — and all three+ are a pointer's: there is no paste key to press, a row that is held+ down is being picked out instead, and the list a press beside the+ rows would land on is nothing at all on the note that most wants+ pasting into, having no rows to give it a height. The header is the+ one part of a run that stands whatever the run holds. */}+ {heldAttributes.length > 0 && (+ <ActionButton+ icon="bx bx-paste"+ text={t("attribute_list_panel.paste", { count: heldAttributes.length })}+ onClick={(e) => {+ e.stopPropagation();+ void applyPaste(heldAttributes);+ }}+ />+ )}+- <AddAttributeButton+ {canEdit && <AddAttributeButtontext={t("attribute_editor.add_a_new_attribute")}attrTypes={ALL_ATTRIBUTE_KINDS}onSelect={addAttribute}- />+ />}+ </>- )}++ ) : (++ <>++ {run.help && <SidebarHelp section={run.help} />}++ {run.add && (++ // A run that can be added to says so in its own header, which is where a++ // card keeps what is done to it. The ghost row a pointer gets is a hover++ // affordance, so it stays on the desktop.++ <ActionButton++ icon="bx bx-plus"++ text={run.add.text}++ onClick={(e) => {++ e.stopPropagation();++ addAttribute(run.add?.kind ?? "label", e);++ }}++ />++ )}+ </>- ) : run.add && (- // A run that can be added to says so in its own header, which is where a- // card keeps what is done to it. The ghost row a pointer gets is a hover- // affordance, so it stays on the desktop.- <ActionButton- icon="bx bx-plus"- text={run.add.text}- onClick={(e) => {- e.stopPropagation();- addAttribute(run.add?.kind ?? "label", e);- }}- />+ ))}>- {/* Presses inside the sections do not dismiss the popup (see `parent` above), which- leaves closing on a press next to a row up to this handler. */}- {/* The values read from the trailing edge here and in the inherited card below,- the two lists of plain attributes reading as one ledger. The definitions keep- prose order: their "value" is a summary of settings, not a value. */}- <div class="attribute-list-panel align-values-end" ref={containerRef} onClick={commit}>- {ownedRows.length > 0 ? (- <AttributeRowList rows={ownedRows} {...rowProps} />- ) : !creationRow && (+ <div+ class={clsx("attribute-list-panel", isSelecting && "selecting")}+ // The popup anchors to the panel, and the first card is the one it is+ // opened over: the note's own attributes are what it edits.+ ref={index === 0 ? containerRef : undefined}+ {...panelProps}+ >+ {run.rows}++ {/* A run holding nothing says so here, where a pointer's does not: there,+ the count says the run is empty and the add row beneath it says what+ there is to do about it, so a third telling would be one too many. A+ phone has no add row — a card keeps what is done to it in its header —+ which leaves an empty run as an empty card, saying nothing at all. Only+ the note's own attributes can be shown empty; every other run is left+ out entirely when it holds nothing. */}+ {run.count === 0 && (<NoItems icon="bx bx-hash" text={t("attribute_list_panel.no_attributes")} />)}-- {/* The draft under creation, kept last (see above) and so out of the split the- list above draws between the note's own names and Trilium's. */}- {creationRow && <AttributeRowList rows={[ creationRow ]} {...rowProps} />}-- {/* Only on a desktop: a phone adds from the header, page flow and all. */}- {!IS_MOBILE && canEdit && (- <AddAttributeRow onAdd={(e) => addAttribute("label", e)} />- )}</div></AttributeSection>+ ))}- {sections.inherited.length > 0 && (- <AttributeSection- id="attributes-inherited"- title={t("attribute_list_panel.inherited", { count: sections.inherited.length })}- buttons={<SidebarHelp section="attributes-inherited" />}- >- <div class="attribute-list-panel align-values-end" onClick={commit}>- <AttributeRowList rows={sections.inherited} {...rowProps} />- </div>- </AttributeSection>+ {selectionBar}+ </>+ ) : (+ // One card holding the lot, the runs being headings within it rather than cards of their+ // own: they are one list to the eye and one list to a selection — a range runs from any row+ // to any other — and four headers is a great deal of a hand-wide pane to spend on saying+ // which run is which. It also leaves the selection's own bar somewhere to belong: a bar at+ // the foot of one card among several belonged to a card the picked rows need not have been+ // in at all.+ //+ // Collapsing moves to the headings with it. The card cannot be collapsed away, being all its+ // tab has (see RightPanelWidget), which is what the context below says.+ <CollapsibleWidgets.Provider value={false}>+ <AttributeSection+ id="attributes"+ title={t("attributes_panel.title")}+ grow+ buttons={note && (+ <>- <HelpButton helpPage={ATTRIBUTE_HELP_PAGE} />- <AddAttributeButton++ <SidebarHelp section="attributes" />++ {canEdit && <AddAttributeButton+ text={t("attribute_editor.add_a_new_attribute")}+ attrTypes={ALL_ATTRIBUTE_KINDS}+ onSelect={addAttribute}- />++ />}+ </>)}-- {sections.definitions.length > 0 && (- <AttributeSection- id="attributes-definitions"- title={t("attribute_list_panel.definitions", { count: sections.definitions.length })}- buttons={<>- <SidebarHelp section="attributes-definitions" />- {canEdit && (- <AddAttributeButton- text={t("attribute_list_panel.add_definition")}- attrTypes={DEFINITION_KINDS}- onSelect={addAttribute}+ >+ <div+ class={clsx("attribute-list-panel", isSelecting && "selecting")}+ ref={containerRef}+ {...panelProps}+ >+ {runs.map((run) => (+ <AttributeGroup key={run.id} id={run.id} title={run.title} count={run.count}>+ {run.rows}++ {/* Inside the run it adds to rather than at the foot of everything, and+ put away with it. */}+ {run.add && note && (+ <AddAttributeRow+ text={run.add.text}+ onAdd={(e) => addAttribute(run.add?.kind ?? "label", e)}/>)}- </>}- >- <div class="attribute-list-panel" onClick={commit}>- <AttributeRowList rows={sections.definitions} {...rowProps} />- </div>- </AttributeSection>- )}+ </AttributeGroup>+ ))}- {internalRows.length > 0 && (- <AttributeSection- id="attributes-internal"- title={t("attribute_list_panel.internal", { count: internalRows.length })}- >- <div class="attribute-list-panel" onClick={commit}>- <AttributeRowList rows={internalRows} readOnly {...rowProps} />- </div>- </AttributeSection>- )}- </CollapsibleWidgets.Provider>- </>+ {selectionBar}+ </div>+ </AttributeSection>+ </CollapsibleWidgets.Provider>);// Inside a master-detail host the list and the form are its two panes, which it slides over each@@@ -924,21 -499,6 +945,23 @@@);}+/**+ * One run of the panel — a heading with its rows on a desktop, a card of its own on a phone. Held+ * apart from either so that what the runs are, and which of them the note has at all, is settled+ * once rather than twice over.+ */+interface AttributeRun {+ /** What the run is known by: a class on it, and what a collapsed run is remembered under. */+ id: string;+ title: string;+ count: number;+ rows: ComponentChildren;++ /** The `?` of the run, shown in its card header on a phone. */++ help?: SidebarSectionId;+ /** How the run is added to, for the runs that can be — the kind, and what to call adding it. */+ add?: { kind: AttributeKind; text: string };+}+interface AttributeSectionProps {/** What the right pane remembers the section by, collapsed state and all. */id: string;@@@ -1072,15 -539,13 +1095,17 @@@ interface AttributeRowListProps/*** 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.+ * always the current one's), 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 — and nothing to be picked+ * out for, being rewritten from the note's content rather than carried anywhere.*/readOnly?: boolean;+ /** Shows the rows as usual, but with no way to change them, for a note that cannot be edited. */+ locked?: boolean;onOpen: (attribute: Attribute, isOwned: boolean, anchor: HTMLElement | null, e: MouseEvent) => void;+ /** Picks the row out, or takes it back out of the selection; `range` is what shift asks for. */+ onSelect: (attributeId: string, range?: boolean) => void;+ onShowMenu: (attribute: Attribute, e: MouseEvent) => void;/** Asks for the in-place editor over the attribute's value; wired to editable labels alone. */onEditValue: (attribute: Attribute) => void;onDelete: (attribute: Attribute) => void;@@@ -1091,7 -556,9 +1116,9 @@@* 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, note, activeAttribute, valueEditor, selection, selecting, readOnly, alignValuesEnd, onOpen, onSelect, onShowMenu, onEditValue, onDelete }: AttributeRowListProps) {-function AttributeRowList({ rows, note, activeAttribute, valueEditor, readOnly, locked, onOpen, onEditValue, onDelete }: AttributeRowListProps) {++function AttributeRowList({ rows, note, activeAttribute, valueEditor, selection, selecting, readOnly, locked, alignValuesEnd, onOpen, onSelect, onShowMenu, onEditValue, onDelete }: AttributeRowListProps) {+ const canChange = !readOnly && !locked;+function renderRows(group: AttributeEntry[]) {return (// The rows are menu items on a phone (see AttributeRow), and the theme dresses a menu item@@@ -1176,91 -624,13 +1203,91 @@@ interface AttributeRowPropsonDelete?: () => void;}-function AttributeRow({ attribute, note, active, valueEditor, isSystem, showOwner, onOpen, onEditValue, onDelete }: AttributeRowProps) {+function AttributeRow({ attribute, note, active, valueEditor, isSystem, selected, selecting, showOwner, onOpen, onSelect, onShowMenu, onEditValue, onDelete }: AttributeRowProps) {const rowRef = useRef<HTMLLIElement>(null);+ // Set by a press held long enough to pick the row out, and read by the press's own release, which+ // would otherwise open the form behind the selection it just made.+ const heldDown = useRef(false);const attrType = getAttributeKind(attribute);const markerClass = getKindMarkerClass(attribute, attrType, isSystem);- const kindIcon = getKindIcon(attribute, attrType);+ const kindIcon = attributeKindIcon(attribute.type, attribute.name, attribute.value ?? "");const kindTooltip = getKindTooltip(attribute, attrType, isSystem);- const rowClass = clsx("attribute-row", active && "active", valueEditor && "editing");+ const rowClass = clsx("attribute-row", active && "active", valueEditor && "editing", selected && "selected");+ /** Whether the whole row picks, which is what it does once rows are being picked out. */+ const selectsWholeRow = !!selecting && !!onSelect;++ /**+ * A phone has no modifier to hold down, so it has the press itself held instead: held long enough,+ * it picks the row out rather than opening it, which is how a phone's lists are picked through.+ * Once rows are being picked out a plain tap picks too — there being no checkbox to aim a thumb at+ * on a row that is a menu item — which is the turn those lists take as well.+ */+ useEffect(() => {+ const row = rowRef.current;+ if (!IS_MOBILE || !row || !onSelect) return;++ let timer: ReturnType<typeof setTimeout> | undefined;+ const start = () => {+ heldDown.current = false;+ timer = setTimeout(() => {+ heldDown.current = true;+ onSelect();+ }, LONG_PRESS_DURATION);+ };+ // A press that travels is the list being scrolled, and is no longer a press on the row.+ const cancel = () => clearTimeout(timer);++ row.addEventListener("touchstart", start, { passive: true });+ row.addEventListener("touchmove", cancel, { passive: true });+ row.addEventListener("touchend", cancel);+ row.addEventListener("touchcancel", cancel);++ return () => {+ clearTimeout(timer);+ row.removeEventListener("touchstart", start);+ row.removeEventListener("touchmove", cancel);+ row.removeEventListener("touchend", cancel);+ row.removeEventListener("touchcancel", cancel);+ };+ }, [ onSelect ]);++ /**+ * Once rows are being picked out, the whole row is what picks: a checkbox is a small thing to+ * aim at, and the press that missed it would otherwise open the form and let the selection go.+ * Taken in the capture phase and kept there, so that nothing the row holds acts on the press+ * instead — a value that would open its editor, a relation's target that would be navigated to.+ */+ function selectFromRow(e: MouseEvent) {+ // The release of the press that picked the row out, which has had its say already.+ if (heldDown.current) {+ heldDown.current = false;+ e.preventDefault();+ e.stopPropagation();+ return;+ }++ // The checkbox is left its own press: refused, its tick is put back after this has run,+ // which would leave the box a press behind the selection it is drawn from.+ if (e.target instanceof Element && e.target.closest(".attribute-kind-check")) {+ return;+ }++ e.preventDefault();+ e.stopPropagation();+ onSelect?.(e.shiftKey);+ }++ // A menu item takes no capture handler of its own, so a phone's rows are bound theirs by hand.+ useEffect(() => {+ const row = rowRef.current;+ if (!IS_MOBILE || !row || !selectsWholeRow) return;++ row.addEventListener("click", selectFromRow, true);+ return () => row.removeEventListener("click", selectFromRow, true);+ // The handler itself is left out: it is written anew on every render, where what it does+ // turns only on the two below.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [ selectsWholeRow, onSelect ]);function open(e: MouseEvent) {// Keep the container's closing handler from undoing this.@@@ -1421,37 -734,6 +1448,22 @@@ const LONG_PRESS_DURATION = 500*/const IS_MOBILE = isMobile();+/** Shared so that clearing a selection that is already empty is not a change to be redrawn for. */+const EMPTY_SELECTION: ReadonlySet<string> = new Set();++/**+ * Whether the note's definitions say the attribute's field holds a set rather than a single value,+ * which is what a paste over a name the note already carries turns on: a set takes the pasted value+ * alongside what it holds, where a single value is replaced by it.+ */+export function isMultiValued(note: FNote | null | undefined, attribute: Attribute) {+ const definition = note?.getAttributeDefinitions()+ .find((candidate) => candidate.name === `${attribute.type}:${attribute.name}`)+ ?.getDefinition();++ return definition?.multiplicity === "multi";+}+- /**- * What the attribute is, as an icon. A definition takes the icon of the field it sets up, the same one- * the popup offers that field under — it needs no marker of its own, being only ever listed in a card- * of definitions. Everything else is the icon of a label or of a relation.- */- function getKindIcon(attribute: Attribute, attrType: AttributeKind) {- if (isDefinition(attrType)) {- // A definition written by hand can name a field the popup knows nothing of, leaving the icon of- // the label it defines to stand for it.- return getDefinitionType(attribute, attrType)?.icon ?? "bx bx-hash";- }-- return attrType === "relation" ? "bx bx-transfer" : "bx bx-hash";- }-/*** The badge the kind icon carries on its corner, where there is one to carry: a cog for the names* Trilium reads for itself, and a chevron for a definition whose field is promoted — lifted, that is,diff --cc apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsxindex 7937d4a59c,098168e16c..f83d9d1cb5--- a/apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsx+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.spec.tsx@@@ -1,48 -1,27 +1,72 @@@-import { describe, expect, it } from "vitest";+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { groupIntoTabs, reduceTabSelection, RightPanelWidgetDefinition } from "./RightPanelContainer";+import FNote from "../../entities/fnote";++// The container follows whichever note is being read; the tests hand it one directly.+const shownNote = vi.hoisted(() => ({ current: null as FNote | null }));+// The tabs' names live in tooltips only; Bootstrap's own machinery is not what is under test here.+const useStaticTooltip = vi.hoisted(() => vi.fn());+vi.mock("../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../react/hooks")>()),+ useActiveNoteContext: () => ({ note: shownNote.current }),+ useStaticTooltip+}));++// The tabs' bodies are widgets with specs of their own: bare boxes stand in for them, the strip and+// the choice between the tabs being what is under test here.+vi.mock("./AttributeList", () => stubWidget("attribute-list-stub"));+vi.mock("./TableOfContents", () => stubWidget("toc-stub"));+vi.mock("./HighlightsList", () => stubWidget("highlights-stub"));++vi.mock("./NoteMap", () => stubWidget("note-map-stub"));++vi.mock("./NotePaths", () => stubWidget("note-paths-stub"));++vi.mock("./Backlinks", () => stubWidget("backlinks-stub"));++vi.mock("./BoardColumns", () => stubWidget("board-columns-stub"));+vi.mock("./ChatHighlightsList", () => stubWidget("chat-highlights-stub"));+vi.mock("./pdf/PdfPages", () => stubWidget("pdf-pages-stub"));+vi.mock("./pdf/PdfAttachments", () => stubWidget("pdf-attachments-stub"));+vi.mock("./pdf/PdfLayers", () => stubWidget("pdf-layers-stub"));+vi.mock("./pdf/PdfAnnotations", () => stubWidget("pdf-annotations-stub"));+vi.mock("./RightPanePeekButton", () => stubWidget("peek-button-stub"));+vi.mock("../../services/keyboard_actions", () => ({+ default: { getAction: vi.fn().mockResolvedValue({ effectiveShortcuts: [] }) }+}));++async function stubWidget(className: string) {+ const { h } = await import("preact");+ return { default: () => h("div", { className }) };+}++import appContext from "../../components/app_context";+import type Component from "../../components/component";+import type LoadResults from "../../services/load_results";+import options from "../../services/options";+import { buildNote } from "../../test/easy-froca";+import { ParentComponent } from "../react/react_utils";- import RightPanelContainer, { groupIntoTabs, RightPanelWidgetDefinition } from "./RightPanelContainer";++import RightPanelContainer, { groupIntoTabs, reduceTabSelection, RightPanelWidgetDefinition } from "./RightPanelContainer";+import { RIGHT_PANE_TABS } from "./RightPaneTabs";+ describe("reduceTabSelection", () => {+ it("opens a closed pane, and brings a tab that is not the one on show to the front", () => {+ expect(reduceTabSelection("closed", undefined, { tabId: "chat" })).toBe("open");+ expect(reduceTabSelection("closed", "outline", { tabId: "connections", peek: true })).toBe("open");+ expect(reduceTabSelection("docked", "outline", { tabId: "chat" })).toBe("select");+ expect(reduceTabSelection("peek", "outline", { tabId: "connections", peek: true })).toBe("select");+ });++ it("puts away what the press itself opened: its peek, or the pane an entry point docks", () => {+ expect(reduceTabSelection("peek", "connections", { tabId: "connections", peek: true })).toBe("dismiss");+ expect(reduceTabSelection("peek", "chat", { tabId: "chat" })).toBe("dismiss");+ expect(reduceTabSelection("docked", "chat", { tabId: "chat" })).toBe("close");+ });++ it("leaves a docked pane docked for a glance at the tab it is already showing", () => {+ // The dock is the user's layout; the press is left to expand the widget it is about.+ expect(reduceTabSelection("docked", "connections", { tabId: "connections", peek: true })).toBe("select");+ });+ });+describe("groupIntoTabs", () => {it("keeps the enabled widgets only, in position order, and drops the tabs left empty", () => {const toc = widget("outline");@@@ -81,117 -61,6 +106,118 @@@});});+describe("RightPanelContainer", () => {+ let container: HTMLElement;+ /** What the pane subscribed to, when rendered under a parent component that can tell it. */+ let eventHandlers: Map<string, Set<(data: unknown) => void>>;++ beforeEach(() => {+ vi.clearAllMocks();+ options.set("rightPaneVisible", "true");+ options.set("rightPaneWidth", "25");+ options.set("rightPaneSelectedTab", "attributes");+ options.set("highlightsList", "[]");+ options.set("aiEnabled", "false");+ appContext.tabManager = { getActiveContext: () => null } as typeof appContext.tabManager;+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ it("treats the tab as the window's own: a press writes the choice back, another window's is not followed", () => {+ shownNote.current = buildNote({ title: "Read" });+ renderContainer();+- // A text note offers the outline and the attributes; the pane is on the tab last chosen here.- expect(shownTabIcons()).toEqual([ icon("outline"), icon("attributes") ]);++ // A text note offers the outline, the attributes and the connections; the pane is on the tab++ // last chosen here.++ expect(shownTabIcons()).toEqual([ icon("outline"), icon("attributes"), icon("connections") ]);+ expect(activeTabIcon()).toBe(icon("attributes"));++ // A press of this window's own switches the pane and writes the choice back, which is what+ // a window opened later starts from.+ act(() => {+ tabButton(icon("outline"))?.click();+ });+ expect(activeTabIcon()).toBe(icon("outline"));+ expect(options.get("rightPaneSelectedTab")).toBe("outline");++ // Another window picking a tab of its own arrives as the shared option's change: the cache+ // is rewritten first and the reload announced after, as the sync updater delivers it.+ act(() => {+ options.set("rightPaneSelectedTab", "attributes");+ fireEntitiesReloaded([ "rightPaneSelectedTab" ]);+ });++ // The choice belongs to the window it was made in: this pane stays where it was put.+ expect(activeTabIcon()).toBe(icon("outline"));+ });++ function renderContainer() {+ eventHandlers = new Map();+ const parent = {+ componentId: "pane-cid",+ registerHandler: (name: string, callback: (data: unknown) => void) => {+ if (!eventHandlers.has(name)) {+ eventHandlers.set(name, new Set());+ }+ eventHandlers.get(name)?.add(callback);+ },+ removeHandler: (name: string, callback: (data: unknown) => void) => {+ eventHandlers.get(name)?.delete(callback);+ }+ } as unknown as Component;+ const widgetsByParent = {+ getLegacyWidgets: () => [],+ getPreactWidgets: () => []+ } as unknown as Parameters<typeof RightPanelContainer>[0]["widgetsByParent"];++ act(() => render(+ <ParentComponent.Provider value={parent}>+ <RightPanelContainer widgetsByParent={widgetsByParent} />+ </ParentComponent.Provider>,+ container+ ));+ }++ /** Hands the pane a reload naming the given options, as a change made in another window arrives. */+ function fireEntitiesReloaded(optionNames: string[]) {+ const loadResults = {+ getOptionNames: () => optionNames,+ isNoteReloaded: () => false+ } as unknown as LoadResults;+ for (const handler of eventHandlers.get("entitiesReloaded") ?? []) {+ handler({ loadResults });+ }+ }++ function tabButton(iconClass: string) {+ return [ ...container.querySelectorAll<HTMLButtonElement>("[role=tab]") ]+ .find((button) => button.querySelector("span")?.className.includes(iconClass));+ }++ /** The strip names no tab in words, so the icon is what tells them apart here. */+ function icon(tabId: string) {+ const tab = RIGHT_PANE_TABS.find((definition) => definition.id === tabId);+ expect(tab, tabId).toBeDefined();+ return tab?.icon ?? "";+ }++ function shownTabIcons() {+ return [ ...container.querySelectorAll("[role=tab] span") ]- .map((span) => span.className.replace("right-pane-tab-icon tn-icon ", ""));++ .map((span) => span.className.replace("tab-strip-tab-icon tn-icon ", ""));+ }++ function activeTabIcon() {+ const active = container.querySelector("[role=tab][aria-selected=true] span");+ expect(active).not.toBeNull();- return (active?.className ?? "").replace("right-pane-tab-icon tn-icon ", "");++ return (active?.className ?? "").replace("tab-strip-tab-icon tn-icon ", "");+ }+});+function widget(tab: RightPanelWidgetDefinition["tab"], overrides: Partial<RightPanelWidgetDefinition> = {}) {return { el: <div class={tab} />, enabled: true, tab, ...overrides };}diff --cc apps/client/src/widgets/sidebar/RightPanelContainer.tsxindex 033f06120e,72fcc3584d..31367f7ad3--- a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx@@@ -4,17 -3,16 +3,16 @@@ import "./RightPanelContainer.css"import Split from "@triliumnext/split.js";import clsx from "clsx";import { VNode } from "preact";- import { useCallback, useLayoutEffect, useRef, useState } from "preact/hooks";-import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";++import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";import appContext from "../../components/app_context";import { WidgetsByParent } from "../../services/bundle";import { t } from "../../services/i18n";import options from "../../services/options";import { DEFAULT_GUTTER_SIZE } from "../../services/resizer";- import { isStandalone } from "../../services/utils";import ActionButton from "../react/ActionButton";import Button from "../react/Button";-import { useActiveNoteContext, useGetContextData, useLegacyWidget, useNoteProperty, useTriliumEvent, useTriliumOption, useTriliumOptionBool, useTriliumOptionJson } from "../react/hooks";+import { useActiveNoteContext, useGetContextData, useLegacyWidget, useNoteProperty, useTriliumEvent, useTriliumOptionBool, useTriliumOptionJson } from "../react/hooks";import LazyComponent from "../react/LazyComponent";import NoItems from "../react/NoItems";import { PaneMode, usePaneMode, usePeekDismiss } from "../react/peek_pane";@@@ -50,14 -52,8 +52,15 @@@ export interface RightPaneTabContents eexport default function RightPanelContainer({ widgetsByParent }: { widgetsByParent: WidgetsByParent }) {const { mode, visible, mounted, togglePeek, toggleDocked, dock, close, dismiss } = usePaneMode("rightPaneVisible");const tabs = useItems(mounted, widgetsByParent);- const [ selectedTabId, setSelectedTabId ] = useTriliumOption("rightPaneSelectedTab");+ // This window's own choice, seeded from the option and written back for the next window to start+ // from — the same treatment usePaneMode gives the pane's visibility. Subscribing to the option+ // (useTriliumOption) would let a click in one window flip the strip in every other.+ const [ selectedTabId, setSelectedTabIdState ] = useState(() => options.get("rightPaneSelectedTab"));+ const setSelectedTabId = useCallback((tabId: RightPaneTabId) => {+ setSelectedTabIdState(tabId);+ void options.save("rightPaneSelectedTab", tabId);+ }, []);+ const [ expandRequest, setExpandRequest ] = useState<ExpandWidgetRequest | null>(null);useSplit(mode);// The chosen tab may have nothing to show for this note (or may have gone away entirely, e.g. the@@@ -87,9 -90,17 +97,17 @@@return;}- void setSelectedTabId(tabId);+ setSelectedTabId(tabId);- if (!visible) {- toggleDocked();+ // Raised before the pane opens, so a widget mounted for the first time already reads it.+ if (expandWidgetId) {+ setExpandRequest((prev) => ({ id: expandWidgetId, counter: (prev?.counter ?? 0) + 1 }));+ }+ if (action === "open") {+ if (peek) {+ togglePeek();+ } else {+ toggleDocked();+ }}});@@@ -117,23 -134,27 +141,27 @@@<div class="right-pane-peek-spacer" />{/* Mode class (right-pane-mode-docked / -peek) as a styling hook; none when closed. */}<div id="right-pane" class={visible ? `right-pane-mode-${mode}` : undefined}>- {visible && (- <div class="right-pane-actions">- {/* Pin only applies while peeking (it docks the pane); close shows in both modes. */}- {mode === "peek" && <ActionButton icon="bx bx-pin" text={t("right_pane.dock")} onClick={dock} />}- <ActionButton icon="bx bx-x" text={t("right_pane.close")} onClick={close} />- </div>- )}{mounted && (- tabs.length > 0 ? (- <>- <RightPaneTabs- tabs={tabs}- activeTabId={activeTab?.id}- onSelect={setSelectedTabId}- />-- {tabs.filter((tab) => openedTabs.current.has(tab.id)).map((tab) => (+ <>+ {/* One flex row holding the tab strip and the pane's own actions, so a+ narrow pane shrinks the strip instead of sliding it under the buttons+ (see RightPanelContainer.css). */}+ <div class="right-pane-header">+ {tabs.length > 0 && (+ <RightPaneTabs+ tabs={tabs}+ activeTabId={activeTab?.id}- onSelect={(tabId) => void setSelectedTabId(tabId)}++ onSelect={setSelectedTabId}+ />+ )}+ <div class="right-pane-actions">+ {/* Pin only applies while peeking (it docks the pane); close shows in both modes. */}+ {mode === "peek" && <ActionButton icon="bx bx-pin" text={t("right_pane.dock")} onClick={dock} />}+ <ActionButton icon="bx bx-x" text={t("right_pane.close")} onClick={close} />+ </div>+ </div>+ {tabs.length > 0 ? (+ tabs.filter((tab) => openedTabs.current.has(tab.id)).map((tab) => (<divkey={tab.id}role="tabpanel"