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
client: fix several issues
Adorian Doranf0be5a2a9134
diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.tsindex 5a66d0ace6..659165e66e 100644--- a/apps/client/src/widgets/collections/board/data.spec.ts+++ b/apps/client/src/widgets/collections/board/data.spec.ts@@ -85,6 +85,32 @@ describe("Board data", () => {const noteIds = [...data.byColumn.values()].flat().map(item => item.note.noteId);expect(noteIds.length).toBe(3);});+ /**+ * A template is what a card is made from, not a card. One made from the board's own properties+ * is filed under the board with no grouping value, which the inbox would otherwise collect.+ */+ it("leaves a template under the board out of the cards", async () => {+ const board = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { title: "Card", "#status": "To Do" },+ { title: "A template", "#template": "" },+ { title: "Unassigned" }+ ]+ });++ const data = await getBoardData(+ board, "status", { columns: [ { value: "To Do" } ] }, false, [], new Map(), true);++ const titles = (column: string) =>+ (data.byColumn.get(column) ?? []).map((item) => item.note.title);+ expect(titles("To Do")).toEqual([ "Card" ]);+ // The one with no value is collected; the template is not.+ expect(titles("")).toEqual([ "Unassigned" ]);+ });+/*** A column inserted or dragged is written to the attachment at once and to the definition a* round trip later. The refresh in between must not put it back where the definition says.diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex a8106582fe..633305324a 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -170,6 +170,10 @@ async function recursiveGroupBy(const note = await branch.getNote();if (!note || (!includeArchived && note.isArchived)) continue;+ // A template is what a card is made from, not a card. One made from the board's own+ // properties is filed under it, and the inbox would otherwise collect it as one.+ const isTemplate = note.hasLabel("template");+if (note.type !== "search" && note.hasChildren()) {await recursiveGroupBy(note.getChildBranches(), byColumn, groupByColumn, includeArchived,@@ -180,7 +184,7 @@ async function recursiveGroupBy(// Anything below the board's own children is a card's child, collected only when nested.const value = note.getLabelOrRelation(groupByColumn);const group = value || (inbox && (depth === 0 || inbox.nested) ? INBOX_COLUMN : undefined);- if (group === undefined || seenNoteIds.has(note.noteId)) {+ if (group === undefined || isTemplate || seenNoteIds.has(note.noteId)) {continue;}diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex 90be6daa27..470f84d5af 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -259,7 +259,7 @@ body.mobile .board-view-container .board-add-column {padding: 0.5em 0.5em 0;}-/* A field standing among the cards is spaced as one of them, which is what it stands for. */+/* A field between the cards is spaced like one. */.board-view-container .board-column-content > .board-new-item {margin-block: 0 0.65em;}diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsxindex ce99747ad8..a0450f9bce 100644--- a/apps/client/src/widgets/collections/board/properties.tsx+++ b/apps/client/src/widgets/collections/board/properties.tsx@@ -7,14 +7,14 @@ import TemplateSelectionCard from "../../react/TemplateSelectionCard";import BoardApi from "./api";/**- * What the board is set up with, apart from the columns and the cards themselves.+ * The board's own settings, apart from its columns and cards.*- * One card for now, the templates a new card is made from; the dialog is the place the rest of the- * board's own settings will be put as they arrive.+ * One card for now, the templates a new card is created from; the rest of the board's settings go+ * here as they arrive.*/export default function BoardProperties({ api, note, shown, onClose }: {api: BoardApi,- /** The board itself, which is what a template made here is filed under. */+ /** The board itself, and the parent of any template created here. */note: FNote,shown: boolean,onClose: () => voiddiff --git a/apps/client/src/widgets/dialogs/item_picker.css b/apps/client/src/widgets/dialogs/item_picker.cssindex 782e58cb5d..d10b655b54 100644--- a/apps/client/src/widgets/dialogs/item_picker.css+++ b/apps/client/src/widgets/dialogs/item_picker.css@@ -2,21 +2,21 @@/* The colour the quick search marks its terms in, which is what a marked term reads as here. */--item-picker-mark-color: var(--quick-search-result-highlight-color);--item-picker-inline-padding: 40px;- /* One line of caption in the card's own padding: an exact height, which is what lets an item- fold and unfold rather than jumping once a max-height has come down to meet it. */+ /* One line of caption plus the card's padding: an exact height, which is what lets an item+ collapse and expand smoothly rather than appearing to jump. */--item-picker-item-height: calc(1.4em + 2 * var(--card-padding-block));--item-picker-fold-duration: 0.15s;}.modal.item-picker-dialog {.modal-body {- /* A column, so that what stands where the list was can take the room the list is not using. */+ /* A column, so the empty state can take the space the list is not using. */display: flex;flex-direction: column;padding-inline: var(--item-picker-inline-padding);}- /* The room the list stands in, which is also what the placeholder is laid over. */+ /* The area holding the list, which the empty state is laid over. */.item-picker-results {position: relative;flex: 1 0 auto;@@ -36,8 +36,8 @@flex-direction: column;}- /* The room between groups is each card's own, so it closes with the card rather than holding a- stripe open where one used to stand. */+ /* The space between groups belongs to each card, so it closes with the card rather than leaving+ a stripe where one was. */.item-picker-groups > .tn-card {margin-block-end: 1em;transition: margin var(--item-picker-fold-duration) ease;@@ -48,11 +48,10 @@}/*- * A group whose items have all folded goes as well, but by folding: the heading closes over the- * same moment the items do.+ * A group whose items have all collapsed collapses too, its heading closing on the same beat.*- * The filter's own rule takes an empty group away outright, which would cut the folding short.- * Answered in kind, since that rule is `!important` for reasons of its own.+ * The filter primitive removes an empty group outright, which would cut the animation short. It+ * is overridden here in kind, that rule being `!important` for reasons of its own.*/.tn-card.tn-filter-scope:not(:has(.tn-filter-match)) {display: block !important;@@ -81,12 +80,12 @@display: flex;align-items: center;gap: 0.4em;- /* Folding: what the item takes up, and what it is painted with, both go to nothing. Its own- height rather than a ceiling to come down from, so the whole of the transition is spent- moving: a max-height above the real one is over before it has visibly begun. */+ /* Collapsing: the space it takes and what paints it both go to nothing. An exact height rather+ than a max-height ceiling, which would spend most of the transition above the real height and+ so appear instant. */height: var(--item-picker-item-height);- /* The gap between segments is the item's own, so it folds away with the item. A card's flex- gap would hold a stripe open for every item the filter took out. */+ /* The gap belongs to the item, so it collapses with it. A flex gap on the card would leave a+ stripe for every item the filter removed. */margin-block-end: var(--card-section-gap);transition: height var(--item-picker-fold-duration) ease,margin var(--item-picker-fold-duration) ease,@@ -109,15 +108,15 @@opacity: 0;}- /* Marked by its colour alone, as the quick search marks what it found. */+ /* Marked by colour alone, as the quick search marks its results. */.item-picker-caption {overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}- /* Bootstrap gives a mark padding of its own, which would part the term from the rest of the- caption it stands in the middle of. */+ /* Bootstrap's Reboot gives `mark` padding, which would space a matched term away from the rest+ of the caption. */.item-picker-caption mark {margin: 0;padding: 0;@@ -127,9 +126,8 @@}/*- * Laid over the room the list stands in rather than following it, so it holds still while the- * list folds away under it. Out of the way of the field above and of what is still standing:- * it is faded rather than taken down, and takes no presses meant for either.+ * Laid over the list rather than following it, so it stays put while the list collapses beneath.+ * Faded rather than unmounted, and it takes no presses meant for the field or the items.*/.item-picker-empty {position: absolute;@@ -141,17 +139,17 @@visibility 0s linear var(--item-picker-fold-duration);}- /* Nothing left standing anywhere, which is the only time there is anything to say. */+ /* Shown only when the filter has left nothing. */.item-picker-groups:not(:has(.item-picker-item:not(.item-picker-folded))) + .item-picker-empty {opacity: 1;visibility: visible;transition: opacity var(--item-picker-fold-duration) ease;}- /* The groups arrive with the dialog rather than into it: one rise as it opens, which is also- one animation however many items are being shown. */+ /* The groups animate with the dialog rather than into it: one animation however many items are+ shown. */.item-picker-groups {- /* Long enough to be read as its own: the dialog's opening covers the first moments of it. */+ /* Long enough to read as its own animation, the dialog's opening covering its first moments. */animation: item-picker-rise 0.4s ease-out;}}@@ -166,13 +164,13 @@}/*- * One height whatever it holds, so a list of three opens the same box as a list of a hundred and- * the list scrolls inside it.+ * One height whatever it holds, so three items open the same box as a hundred and the list scrolls+ * inside it.*- * The height is the content box's rather than the dialog's: a scrollable modal only caps that box,- * which is otherwise sized by what it holds and closes over the list as the filter narrows it. The- * dialog is then given the whole screen and centres the box in it, which is how Bootstrap centres- * one of its own; a margin of half the room left over would rest on that room being what it looks.+ * The height belongs to `.modal-content` rather than `.modal-dialog`: a scrollable modal only caps+ * the content box, which is otherwise sized by its contents and would shrink as the filter narrows+ * the list. The dialog then fills the viewport and centres the box, which is how Bootstrap centres+ * `.modal-dialog-centered`.*/body:not(.mobile) .modal.item-picker-dialog {.modal-dialog {diff --git a/apps/client/src/widgets/dialogs/item_picker.tsx b/apps/client/src/widgets/dialogs/item_picker.tsxindex d9177e7acb..c38dbc7719 100644--- a/apps/client/src/widgets/dialogs/item_picker.tsx+++ b/apps/client/src/widgets/dialogs/item_picker.tsx@@ -13,7 +13,7 @@ import Icon from "../react/Icon";import Modal from "../react/Modal";import NoItems from "../react/NoItems";-/** One thing that can be picked. */+/** One entry the dialog offers. */export interface PickerItem {key: string;caption: string;@@ -21,7 +21,7 @@ export interface PickerItem {icon?: string;}-/** A run of items under a heading of their own. */+/** A set of items under a heading. */export interface PickerItemGroup {key: string;groupHeader: string;@@ -31,34 +31,34 @@ export interface PickerItemGroup {export interface ItemPickerDialogOptions {title?: string;/**- * What can be picked: either the items themselves or groups of them, never the two mixed.+ * What can be picked: either the items themselves or groups of them, never mixed.*- * They are read as they are given, so whatever it takes to work them out is done before the- * dialog is opened rather than while the reader waits.+ * Used as given, so the caller works them out before opening the dialog rather than making the+ * user wait for it.*/items: PickerItem[] | PickerItemGroup[];- /** What the search field reads while it is empty. */+ /** Placeholder for the search field. */placeholder?: string;- /** Said with what was picked, or with nothing where the reader backed out. */+ /** Called with the item picked, or with null when the dialog was dismissed. */callback?: (item: PickerItem | null) => void;}-/** How long the typing settles before the list answers it. Matches the settings search. */+/** How long typing is debounced before the list is filtered. Matches the settings search. */const DEBOUNCE_MS = 150;/**- * Picks one thing out of many, grouped, searchable, and closed by the picking.+ * Picks one item out of many, grouped and searchable, and closes on the pick.*- * The list is narrowed by {@link FilterProvider}, the same filter the settings search runs on: each- * item asks whether it matches and is left standing or folded away, so nothing is mounted or torn- * down as the query changes and the folding can be drawn.+ * The list is narrowed by {@link FilterProvider}, the filter the settings search uses: each item+ * asks whether it matches and is shown or collapsed, so nothing is mounted or unmounted as the+ * query changes and the collapse can be animated.*- * Summoned through `dialog.pickSingleItem()`, which is named for the one thing it does now: picking- * several at once is the same dialog with a different answer.+ * Opened through `dialog.pickSingleItem()`, named for the single pick: picking several at once will+ * be the same dialog with a different result.*/export default function ItemPickerDialog() {const opts = useRef<ItemPickerDialogOptions>();- /** What was picked, said once the dialog has closed rather than while it is closing. */+ /** The item picked, reported once the dialog has closed rather than while it is closing. */const picked = useRef<PickerItem | null>(null);const searchRef = useRef<HTMLInputElement>(null);const [ shown, setShown ] = useState(false);@@ -96,8 +96,8 @@ export default function ItemPickerDialog() {opts.current = undefined;}}>- {/* The field the settings are looked through, which stands over the lists of the- dialogs they open as well. */}+ {/* The settings search field, which is also used over the lists of the dialogs the+ settings open. */}<SettingsSearchinputRef={searchRef}query={query}@@ -106,11 +106,11 @@ export default function ItemPickerDialog() {/><FilterProvider query={settled}>- {/* What stands where the list was is laid over this rather than after it, so it- holds still while the list folds away under it. */}+ {/* The empty state is laid over this rather than following it, so it stays put+ while the list collapses underneath. */}<div className="item-picker-results">- {/* Drawn once the dialog has opened, which is what the rise comes from: the- items are the dialog's content rather than something arriving into it. */}+ {/* Animated as the dialog opens: the items are its content rather than+ something arriving into it. */}<div className="item-picker-groups">{groups.map((group) => (<Card key={group.key} heading={group.groupHeader || undefined}>@@ -133,16 +133,16 @@ export default function ItemPickerDialog() {}/**- * One item, standing whether or not it matches: folded away rather than taken down, so the list- * closes over what was filtered out instead of blinking from one set to the next.+ * One item, rendered whether or not it matches: collapsed rather than unmounted, so the list closes+ * over what was filtered out instead of jumping from one set to the next.*/function PickerRow({ item, onPick }: { item: PickerItem, onPick: (item: PickerItem) => void }) {const matched = useFilterMatch(item.caption);return (<section- // Marked as a match for the card holding it, which is what keeps a group standing- // while anything in it is still being shown.+ // Marked as a match for the card, which is what keeps a group rendered while any of its+ // items is still shown.className={clsx("tn-card-section tn-card-highlight-on-hover item-picker-item",filterRoleClass(matched ? "match" : undefined),{ "item-picker-folded": !matched })}@@ -162,7 +162,7 @@ function PickerRow({ item, onPick }: { item: PickerItem, onPick: (item: PickerIt);}-/** What the reader typed, marked wherever it stands in the caption. */+/** The caption with the search terms marked wherever they occur. */function Marked({ text }: { text: string }) {const filter = useFilterState();const parts = useMemo(() => split(text, filter?.tokens), [ text, filter ]);@@ -176,15 +176,15 @@ function Marked({ text }: { text: string }) {);}-/** Whether what was given is groups of items rather than the items themselves. */+/** Whether `items` holds groups rather than items. */function isGroup(entry: PickerItem | PickerItemGroup): entry is PickerItemGroup {return "items" in entry;}/**- * The items as groups, whichever of the two the caller gave.+ * The items as groups, whichever form the caller gave.*- * A plain list becomes one group with no heading, so the dialog draws one shape rather than two.+ * A plain list becomes one group with no heading, so the dialog renders one shape rather than two.*/function asGroups(items: PickerItem[] | PickerItemGroup[]): PickerItemGroup[] {const [ first ] = items;@@ -198,18 +198,17 @@ function asGroups(items: PickerItem[] | PickerItemGroup[]): PickerItemGroup[] {}/**- * The caption cut into the parts that were typed and the parts that were not.+ * The caption split into matched and unmatched parts.*- * Marked against the text as it stands, so a term matched by its shape alone, an accent dropped for- * instance, is left unmarked rather than marked in the wrong place.+ * Matched against the raw text, so a term that matched only after normalisation, an accent dropped+ * for instance, is left unmarked rather than marked in the wrong place.*/function split(text: string, tokens?: string[]) {if (!tokens?.length) {return [ { text, marked: false } ];}- // Split on a capturing group, so what was typed comes back among the parts: at the odd- // places, whatever the terms matched.+ // A capturing group puts the matches among the parts, at the odd indices.const terms = new RegExp(`(${tokens.map(escapeRegExp).join("|")})`, "gi");return text.split(terms).map((part, index) => ({ text: part, marked: index % 2 === 1 }))diff --git a/apps/client/src/widgets/react/SortableCard.css b/apps/client/src/widgets/react/SortableCard.cssindex 3a4ae15678..d1f74f35f5 100644--- a/apps/client/src/widgets/react/SortableCard.css+++ b/apps/client/src/widgets/react/SortableCard.css@@ -2,18 +2,18 @@--sortable-grip-color: var(--muted-text-color);--sortable-grip-hover-color: var(--main-text-color);--sortable-selected-color: var(--main-text-color);- /* Above and below both, so the segment reads as raised over the ones it is passing rather than- as lit from one corner. The lower one is the heavier, as it would be under a light overhead. */+ /* Above and below, so a dragged segment reads as raised over the ones it passes. The lower+ shadow is heavier, as under an overhead light. */--sortable-dragging-shadow: 0 -3px 8px rgba(0, 0, 0, 0.3),0 5px 8px rgba(0, 0, 0, 0.3);- /* Enough to read as held rather than filed, without losing what it says. */+ /* Enough to read as lifted without losing the text. */--sortable-dragging-opacity: 0.90;}.tn-card.tn-sortable-card {.tn-sortable-list {display: flex;- /* The carried segment is placed against this, so it must be what `offsetTop` is read from. */+ /* The dragged segment is positioned against this, so it must be its offsetParent. */position: relative;flex-direction: column;gap: var(--card-section-gap);@@ -23,14 +23,14 @@display: flex;align-items: center;gap: 0.5em;- /* What `useFlip` turns into a slide: it puts a segment back where it was for one frame and- lets this carry it to where it now stands. 200ms matches FLIP_DURATION_MS. */+ /* What useFlip animates: it transforms a segment back to its old position for one frame and+ lets this transition carry it to the new one. 200ms matches FLIP_DURATION_MS. */transition: transform 200ms ease;}- /* A finger takes hold of a segment by resting anywhere on it, and a rest that long is what- raises the callout and the text magnifier on iOS. A mouse is left alone: it carries a segment- by the grip, and a caption is still text to read and select. */+ /* A touch drags a segment by resting anywhere on it, and a press that long raises the callout+ and the text magnifier on iOS. Left alone for a mouse, which drags by the grip and can still+ select the caption text. */@media (pointer: coarse) {.tn-sortable-segment {-webkit-touch-callout: none;@@ -43,9 +43,8 @@outline-offset: -2px;}- /* Painted inside the segment's own box, so a selected segment takes no more room than the rest.- Only while the reader is standing among the entries: they are somewhere else once they have- left the card, and the segment that adds is a place of its own rather than one of them. */+ /* Inset, so a selected segment takes no more room than the rest. Painted only while the focus is+ on an entry: not when it has left the card, and not on the creation row. */.tn-sortable-list:has(.tn-sortable-segment:focus-within) .tn-sortable-selected {box-shadow: inset 0 0 0 1px var(--sortable-selected-color);}@@ -71,8 +70,8 @@padding: 0.2em 0.1em;color: var(--sortable-grip-color);cursor: grab;- /* The page scrolls from here as it does anywhere else. What stops it once a segment is being- carried is the move being refused, which leaves the gesture with the card. */+ /* The page still scrolls from here. What stops it during a drag is preventDefault on+ touchmove, which hands the gesture to the card. */touch-action: pan-y;-webkit-touch-callout: none;user-select: none;@@ -90,8 +89,8 @@}}- /* A thumb reaches for more than the mark it aims at. What the padding adds here the margin takes- back, so the grip is easier to land on without the segments standing any taller. */+ /* A touch target wider than the mark it aims at. The negative margin takes back what the padding+ adds, so the segments keep their height. */@media (pointer: coarse) {.tn-sortable-grip {margin-block: -0.5em;@@ -99,15 +98,15 @@padding: 0.7em calc(var(--card-padding-inline) / 2);}- /* Standing first, it reaches for the leading edge instead. */+ /* Placed first, it extends into the leading padding instead. */.tn-sortable-grip:first-child {margin-inline-start: calc(var(--card-padding-inline) / -2);margin-inline-end: 0;}}- /* Under the pointer rather than in the flow: it follows the finger, and the transition the other- segments slide by would drag it a frame behind. */+ /* Follows the pointer directly: the transition the other segments slide by would leave it a+ frame behind. */.tn-sortable-dragging {z-index: 1;box-shadow: var(--sortable-dragging-shadow);@@ -119,8 +118,8 @@}}- /* The row itself is painted with nothing: the gaps between the buttons are the card's parent- showing through, and each button carries what a segment is painted with. */+ /* Transparent: the gaps between the buttons show the card's parent through, and each button+ paints itself like a segment. */.tn-sortable-adders {display: flex;gap: var(--card-section-gap);@@ -129,41 +128,50 @@background: transparent;}- /* All of one width, however many there are. */- .tn-sortable-adder {+ /* Painted as a segment rather than as a button, and all of one width however many there are.+ What Bootstrap and the theme give a button is undone here. */+ button.tn-sortable-adder.btn {display: flex;flex: 1 1 0;justify-content: center;align-items: center;gap: 0.3em;min-width: 0;+ box-shadow: none;border: 1px solid var(--card-border-color, var(--main-border-color));+ border-radius: 0;padding: var(--card-padding-block) var(--card-padding-inline);background: var(--card-background-color);color: var(--muted-text-color);font: inherit;+ letter-spacing: normal;+ text-transform: none;cursor: pointer;&:hover {background-color: var(--card-background-hover-color);color: var(--main-text-color);}++ &:active {+ background-color: var(--card-background-hover-color);+ }}- /* The card's own corners are the row's to keep, and it is the buttons that are painted. */- .tn-sortable-adders:first-of-type .tn-sortable-adder:first-child {+ /* The card's corners belong to the buttons, the row being transparent. */+ .tn-sortable-adders:first-of-type button.tn-sortable-adder:first-child {border-start-start-radius: var(--card-border-radius);}- .tn-sortable-adders:first-of-type .tn-sortable-adder:last-child {+ .tn-sortable-adders:first-of-type button.tn-sortable-adder:last-child {border-start-end-radius: var(--card-border-radius);}- .tn-sortable-adders:last-of-type .tn-sortable-adder:first-child {+ .tn-sortable-adders:last-of-type button.tn-sortable-adder:first-child {border-end-start-radius: var(--card-border-radius);}- .tn-sortable-adders:last-of-type .tn-sortable-adder:last-child {+ .tn-sortable-adders:last-of-type button.tn-sortable-adder:last-child {border-end-end-radius: var(--card-border-radius);}diff --git a/apps/client/src/widgets/react/SortableCard.spec.tsx b/apps/client/src/widgets/react/SortableCard.spec.tsxindex f5193b7679..1746de4c89 100644--- a/apps/client/src/widgets/react/SortableCard.spec.tsx+++ b/apps/client/src/widgets/react/SortableCard.spec.tsx@@ -476,7 +476,7 @@ describe("SortableCard", () => {makes("f", "Zeta", "Add a folder")] });- expect(adders().map((button) => button.textContent))+ expect(adders().map((button) => button.textContent?.trim())).toEqual([ "Add a note", "Add a link", "Add a folder" ]);// Of one width, however many there are, which the row shares out between them.expect(adders().every((button) => button.style.flex === "")).toBe(true);diff --git a/apps/client/src/widgets/react/SortableCard.tsx b/apps/client/src/widgets/react/SortableCard.tsxindex 0bb0d52c48..af7500362c 100644--- a/apps/client/src/widgets/react/SortableCard.tsx+++ b/apps/client/src/widgets/react/SortableCard.tsx@@ -8,6 +8,7 @@ import {} from "preact/hooks";import { t } from "../../services/i18n";+import Button from "./Button";import { Card, type CardProps } from "./Card";import { createEdgeScroller, type Insets, type ScrollTarget } from "./edge_scroll";import { useFlip } from "./flip";@@ -17,15 +18,14 @@ import Icon from "./Icon";const MAX_CREATION_BUTTONS = 3;/**- * How long a finger rests on the grip before the segment follows it.+ * How long a touch must stay still before the drag starts.*- * A finger on a grip is as likely to be scrolling the page as carrying a segment, and resting is- * what tells the two apart: one that moves on scrolls as it would anywhere else, and one that- * stays takes the segment up. Matches the board's own cards.+ * A touch on a segment can mean a page scroll or a drag. Waiting distinguishes them: a touch that+ * moves first scrolls, one that stays picks the segment up. Matches the board's cards.*/const TOUCH_HOLD_MS = 400;-/** How far it may stray in that time and still be resting rather than scrolling. */+/** How far the touch can move in that time and still count as still. */const TOUCH_SLACK_PX = 8;/**@@ -37,23 +37,28 @@ const TOUCH_SLACK_PX = 8;const SCROLL_MARGIN = 60;const TOUCH_SCROLL_MARGIN = 100;-/** What a press belongs to rather than to the segment holding it. */-const CONTROLS = "button, a, input, select, textarea, label";+/**+ * Elements that answer a press themselves, so a press starting on one is theirs rather than the+ * segment's. `renderItem` draws what it likes, so the roles and `contenteditable` count as well as+ * the native controls.+ */+const CONTROLS = "button, a, input, select, textarea, label, [contenteditable]:not([contenteditable=false]), "+ + "[role=button], [role=link], [role=checkbox], [role=switch], [role=textbox], [role=menuitem]";-/** One entry of a {@link SortableCard}, named by a key that outlives the order it stands in. */+/** One entry of a {@link SortableCard}, identified by a `key` independent of its position. */export interface SortableItem {key: string;- /** What the segment reads, for a card that draws its entries itself. */+ /** Text of the segment, used when `renderItem` is not given. */caption?: ComponentChildren;/** An icon class, `bx` prefix included, drawn before the caption. */icon?: string;}/**- * One way of making an entry, drawn as a button at the foot of the card.+ * One way of creating an entry, rendered as a button at the foot of the card.*- * What an entry is is the caller's: the button can ask with a dialog or a picker of its own, and- * answering with nothing makes none.+ * `onCreateItem` decides what the entry is, and may open a dialog or a picker first. Returning+ * nothing creates no entry.*/export interface ItemCreationButton<T extends SortableItem> {label: string;@@ -63,43 +68,41 @@ export interface ItemCreationButton<T extends SortableItem> {}export interface SortableCardProps<T extends SortableItem> extends CardProps {- /** The entries, in the order they stand. */+ /** The entries, in display order. */items: T[];- /** Said with the whole list in its new order, whenever the reader changes it. */+ /** Called with the whole list in its new order after every change. */onChange: (items: T[]) => void;/**- * Draws what stands inside a segment, for a card that shows more than a name. Without it the- * segment reads the item's own caption and icon.+ * Renders the contents of a segment, for a card showing more than a name. Without it, the+ * segment shows the item's `caption` and `icon`.*/renderItem?: (item: T, index: number) => ComponentChildren;/**- * The ways an entry can be made, drawn as a row of buttons at the foot of the card and left out- * where there are none. Up to three, past which they are too narrow to read.+ * The ways to create an entry, rendered as a row of buttons at the foot of the card and omitted+ * when empty. Up to three; more than that makes each button too narrow to read.*- * The first of them is what Enter beside an entry makes, that being the one a card leads with.+ * Enter on a segment uses the first of them.*/itemCreationButtons?: ItemCreationButton<T>[];/**- * Which edge of a segment the grip stands on. The trailing one by default, where it is out of- * the way of what the segment reads; the leading one suits a card whose entries carry controls- * of their own on that side.+ * Which edge of a segment holds the grip. Defaults to the trailing edge; use the leading one+ * when the entries carry their own controls on the trailing side.*/gripPlacement?: "start" | "end";- /** The entry the reader is on, for a card whose selection the caller keeps. */+ /** The selected entry, for a caller that keeps the selection itself. */selectedKey?: string;onSelect?: (key: string) => void;}/**- * A card whose segments the reader can put in any order.+ * A card whose segments can be reordered.*- * Each entry is one segment, carried by the grip on its trailing edge or moved with the keyboard,- * and the segments slide out of each other's way as it goes. A segment travels up and down only,- * and no further than the ends of the card it stands in.+ * Each entry renders as one segment, dragged by its grip or moved with the keyboard, and the other+ * segments slide out of the way. A drag moves vertically only and is clamped to the card.*- * The order is the caller's: every change is reported through `onChange`, and the card draws- * whatever it is handed back. It knows nothing of what the entries mean, so the same card sorts a- * list of preferences, of columns, or of anything else named by a key.+ * The caller owns the order: `onChange` reports every change, and the card renders whatever it is+ * given back. It does not interpret the entries, so it sorts preferences, columns, or anything+ * else identified by a key.*/export function SortableCard<T extends SortableItem>({items, onChange, renderItem, itemCreationButtons, gripPlacement = "end", selectedKey, onSelect,@@ -112,68 +115,74 @@ export function SortableCard<T extends SortableItem>({const listRef = useRef<HTMLDivElement>(null);const adderRef = useRef<HTMLElement>(null);const dragRef = useRef<Drag<T>>();- /** A finger resting on a grip, which becomes a carry once it has rested long enough. */+ /** A touch waiting out `TOUCH_HOLD_MS`, after which it becomes a drag. */const holdRef = useRef<Hold>();- /** Where the pointer was last seen, for a carry the scrolling moves the list under. */+ /** The last pointer position, needed when scrolling moves the list under a still pointer. */const pointerRef = useRef({ x: 0, y: 0 });- /** The carry as it now stands, for the scrolling to place the segment again by. */+ /** The current `dragTo`, so the scroller can reposition the segment without a stale closure. */const dragToRef = useRef<(clientY: number) => void>(() => {});/** What stands over the edges of the screen while a segment is carried, measured as it starts. */const reachRef = useRef<Insets>({ top: 0, bottom: 0, left: 0, right: 0 });/**- * Walks whatever the card is scrolled inside while a segment is carried to an edge of it.+ * Scrolls whatever contains the card while a segment is dragged to its edge.*- * A card taller than the screen, or one hanging off the end of it, has places the pointer- * cannot otherwise reach: the first and last segments of it above all. Made once and kept, so- * the frames it asks for outlive the render that started them.+ * A card taller than the viewport, or partly outside it, has positions the pointer cannot+ * otherwise reach, the first and last segments above all. Created once so its animation frames+ * outlive the render that started them.*/const scroller = useMemo(() => createEdgeScroller({margin: matchMedia("(pointer: coarse)").matches? TOUCH_SCROLL_MARGIN: SCROLL_MARGIN,reach: () => reachRef.current,- // The pointer has not moved, but the card has moved under it.+ // The pointer has not moved, but the card has.onScroll: () => dragToRef.current(pointerRef.current.y)}), []);useEffect(() => () => scroller.stop(), [ scroller ]);/**- * The order while a segment is being carried, which the caller is told of once it lands.+ * The order during a drag, reported to the caller when it ends.*- * Kept until the caller answers with an order of its own, so the segments stay where they were- * put rather than springing back for the frames in between.+ * Kept until the caller renders an order of its own, so the segments do not spring back for the+ * frames in between.*/const [ draft, setDraft ] = useState<T[] | null>(null);const [ draggedKey, setDraggedKey ] = useState<string>();const [ ownSelection, setOwnSelection ] = useState<string>();- /** The entry just added, which opens out and fades in where it lands. */+ /** The entry just added, which grows and fades in. */const [ addedKey, setAddedKey ] = useState<string>();- /** Which segment takes focus once the card has been drawn again, a move having moved it. */+ /** The segment to focus after the next render, since moving an element drops its focus. */const pendingFocus = useRef<string>();const shown = draft ?? items;+ /** The list as it now stands, for a callback that answers after an await. */+ const shownRef = useRef(shown);+ shownRef.current = shown;const selected = selectedKey ?? ownSelection;useEffect(() => {- // The caller has answered, so the draft has served its purpose. Not while a segment is- // being carried: that order is still being decided.+ // The caller has rendered its own order, so the draft is no longer needed. Not during a+ // drag, where the order is still changing.if (!dragRef.current) {setDraft(null);}}, [ items ]);- const segmentOf = useCallback(- (key: string) => listRef.current?.querySelector<HTMLElement>(`[data-key="${key}"]`), []);+ const segmentOf = useCallback((key: string) => {+ // Compared rather than put into a selector: a key is the caller's own string, and one+ // holding a quote or a backslash would throw or match the wrong segment.+ const segments = listRef.current?.querySelectorAll<HTMLElement>(".tn-sortable-segment");+ return [ ...segments ?? [] ].find((segment) => segment.dataset.key === key);+ }, []);- // The carried segment is left out: it stands where the pointer holds it, and would otherwise be- // slid back to the place the list has made for it.+ // The dragged segment is excluded: it follows the pointer, and useFlip would slide it back to+ // the slot the list has opened for it.useFlip(listRef, {selector: ".tn-sortable-segment:not(.tn-sortable-dragging)",grow: (segment) => segment.dataset.key === addedKey});- useEffect(() => () => window.clearTimeout(holdRef.current?.timer), []);useLayoutEffect(() => {const key = pendingFocus.current;@@ -190,7 +199,7 @@ export function SortableCard<T extends SortableItem>({onSelect?.(key);}, [ onSelect ]);- /** Stands the reader on an entry, wherever they were before it. */+ /** Moves focus and selection to the entry at `index`. */const focusEntry = useCallback((index: number) => {const key = shown[index]?.key;if (!key) {@@ -202,7 +211,7 @@ export function SortableCard<T extends SortableItem>({segmentOf(key)?.focus();}, [ segmentOf, select, shown ]);- /** Puts the entry at `from` where `to` is, and leaves the reader standing on it. */+ /** Moves the entry at `from` to `to`, keeping the focus on it. */const moveItem = useCallback((from: number, to: number) => {const order = moved(shown, from, to);if (!order) {@@ -214,7 +223,7 @@ export function SortableCard<T extends SortableItem>({onChange(order);}, [ onChange, shown ]);- /** Ends the carry, keeping where the segment was put or putting the order back as it was. */+ /** Ends the drag, keeping the new order or restoring the one the drag started from. */const endDrag = useCallback((keep: boolean) => {const drag = dragRef.current;if (!drag) {@@ -243,7 +252,7 @@ export function SortableCard<T extends SortableItem>({}}, [ onChange, scroller, segmentOf ]);- /** Takes up the segment, which is where the carry begins and where it is drawn as held. */+ /** Starts the drag: records what is being moved and marks the segment as dragging. */const startDrag = useCallback((key: string, pointerId: number, clientY: number) => {const segment = segmentOf(key);if (!segment) {@@ -252,12 +261,12 @@ export function SortableCard<T extends SortableItem>({reachRef.current = fixedChrome(segment);- // Refused where the pointer is already gone, a finger lifted during the rest above all.- // Touch captures to the segment of its own accord, so the carry stands without it.+ // Throws when the pointer is no longer active, a touch lifted during the hold above all.+ // Touch captures to the segment implicitly, so the drag works without this.try {listRef.current?.setPointerCapture?.(pointerId);} catch {- // Nothing to do: the moves reach the list either way.+ // Nothing to do: pointermove reaches the list either way.}dragRef.current = {@@ -277,10 +286,18 @@ export function SortableCard<T extends SortableItem>({}, [ segmentOf, select, shown ]);const cancelHold = useCallback(() => {- window.clearTimeout(holdRef.current?.timer);+ const held = holdRef.current;holdRef.current = undefined;+ if (!held) {+ return;+ }++ window.clearTimeout(held.timer);+ held.stopWatching();}, []);+ useEffect(() => () => cancelHold(), [ cancelHold ]);+const beginDrag = useCallback((event: PointerEvent, key: string) => {if (!listRef.current || !segmentOf(key)) {return;@@ -304,23 +321,43 @@ export function SortableCard<T extends SortableItem>({return;}- // A press that began on a control is the control's, whatever it does with it.- if (!onGrip && target?.closest(CONTROLS)) {+ // A press that began on a control is the control's, whatever it does with it. The segment+ // itself is not a control, though it handles keys and carries a tabindex.+ const control = target?.closest(CONTROLS);+ if (!onGrip && control && control !== segmentOf(key)) {return;}cancelHold();++ // The list holds the pointer only once the carry begins, so a finger lifted before then,+ // and outside the list, reports to the page instead. Without this the timer would take up+ // a segment for a pointer that is no longer down, and nothing would put it back.+ const dropped = (ended: PointerEvent) => {+ if (ended.pointerId === holdRef.current?.pointerId) {+ cancelHold();+ }+ };++ document.addEventListener("pointerup", dropped);+ document.addEventListener("pointercancel", dropped);+holdRef.current = {pointerId: event.pointerId,from: { x: event.clientX, y: event.clientY },// Where the finger is when the rest is over, so a hand that settles by a pixel or two// does not carry the segment off by as much.at: event.clientY,+ stopWatching: () => {+ document.removeEventListener("pointerup", dropped);+ document.removeEventListener("pointercancel", dropped);+ },timer: window.setTimeout(() => {const held = holdRef.current;holdRef.current = undefined;if (held) {+ held.stopWatching();startDrag(key, held.pointerId, held.at);}}, TOUCH_HOLD_MS)@@ -335,20 +372,19 @@ export function SortableCard<T extends SortableItem>({return;}- // Where the pointer has carried it, less however far the list has been scrolled out from- // under it: the segment answers to the place in the card the finger is over, not to the- // place on screen it was taken from.+ // How far the pointer has moved, less how far the list has scrolled under it: the segment+ // follows the position in the card, not the position on screen it started from.const carried = clientY - drag.grabbedAt - (list.getBoundingClientRect().top - drag.at);- // Held inside the card: the segment goes no higher than the first place and no lower than- // the last, whatever the pointer does past them.+ // Clamped to the card: the segment cannot pass the first or last position, whatever the+ // pointer does.const room = Math.max(0, list.clientHeight - drag.height);const top = Math.min(Math.max(drag.from + carried, 0), room);const order = orderFor(drag, segment, top, segmentOf);if (order) {drag.order = order;- // Drawn before the segment is placed, so it is placed against the room the list has- // just made for it rather than against the place it is leaving.+ // Rendered before the segment is positioned, so it is measured against the slot the+ // list has just opened rather than the one it is leaving.flushSync(() => setDraft(order));}@@ -358,10 +394,10 @@ export function SortableCard<T extends SortableItem>({dragToRef.current = dragTo;/**- * Makes an entry and puts it at `at`, or at the foot of the card where it is given no place.+ * Creates an entry at `at`, or appends it when no index is given.*- * The reader is left standing on an entry made among the others, that being where they asked- * for it; one made at the foot leaves them on the button that made it, so another can follow.+ * An entry created among the others takes the focus, since that is where it was asked for. An+ * appended one leaves the focus on the button, so several can be created in a row.*/const add = useCallback(async (create: ItemCreationButton<T>["onCreateItem"], at?: number) => {const created = await create();@@ -369,7 +405,9 @@ export function SortableCard<T extends SortableItem>({return;}- const order = [ ...shown ];+ // Read again rather than closed over: `create` may open a dialog, and a reorder or another+ // entry made meanwhile would be undone by an order built from the stale list.+ const order = [ ...shownRef.current ];order.splice(at ?? order.length, 0, created);setAddedKey(created.key);setDraft(order);@@ -378,7 +416,22 @@ export function SortableCard<T extends SortableItem>({}onChange(order);- }, [ onChange, shown ]);+ }, [ onChange ]);++ /**+ * Ends what the given pointer was doing, and only that: a second finger going down and up+ * inside the list would otherwise drop or commit the first one's carry.+ */+ const finish = useCallback((event: PointerEvent, keep: boolean) => {+ if (holdRef.current?.pointerId === event.pointerId) {+ cancelHold();+ return;+ }++ if (dragRef.current?.pointerId === event.pointerId) {+ endDrag(keep);+ }+ }, [ cancelHold, endDrag ]);const onSegmentKeyDown = useCallback((event: KeyboardEvent, index: number) => {if (event.key === "Escape" && dragRef.current) {@@ -387,9 +440,8 @@ export function SortableCard<T extends SortableItem>({return;}- // An entry is made beside the one the reader is standing on, the way a spreadsheet adds a- // row: below it, or above it with Shift. Made the way the card leads with, there being no- // button under the reader's hand to say which of them was meant.+ // Creates an entry beside the focused one, the way a spreadsheet adds a row: below it, or+ // above it with Shift. Uses the first creation button, since no button was pressed.const leading = itemCreationButtons?.[0];if (event.key === "Enter" && leading && !event.ctrlKey && !event.metaKey) {event.preventDefault();@@ -402,8 +454,8 @@ export function SortableCard<T extends SortableItem>({const to = placeFor(event, index, last);if (to === undefined) {- // Below the last entry stands the segment that adds another, which the reader steps- // onto rather than past. It holds no entry, so there is nothing to move onto it.+ // Below the last entry is the creation row, which Down moves onto. It holds no entry,+ // so Ctrl+Down moves nothing there.if (!control && event.key === "ArrowDown" && index === last) {event.preventDefault();adderRef.current?.querySelector<HTMLElement>(".tn-sortable-adder")?.focus();@@ -421,8 +473,8 @@ export function SortableCard<T extends SortableItem>({}, [ add, endDrag, focusEntry, itemCreationButtons, moveItem, shown ]);const onAddKeyDown = useCallback((event: KeyboardEvent) => {- // Back up into the entries. Home and End name the first and last of them here as they do- // on an entry itself, this segment being one the reader stands on rather than one of them.+ // Moves back into the entries. Home and End address the first and last entry here as they+ // do on an entry itself: the creation row is a focus stop, not an entry.const control = event.ctrlKey || event.metaKey;const to = control || !shown.length ? undefined : lastPlaceFor(event, shown.length - 1);if (to === undefined) {@@ -434,10 +486,10 @@ export function SortableCard<T extends SortableItem>({}, [ focusEntry, shown ]);/**- * What a segment is carried by, drawn on whichever edge the caller asked for.+ * The drag handle, drawn on whichever edge `gripPlacement` names.*- * A mark rather than the gesture's own: the segment answers for the press, so a finger takes- * hold anywhere on it and only a mouse has to find the grip.+ * An affordance rather than the hit area: the segment handles the press, so a touch may start+ * anywhere on it and only a mouse has to aim at the grip.*/const grip = () => (<span@@ -478,22 +530,15 @@ export function SortableCard<T extends SortableItem>({dragTo(event.clientY);}}}- // Refused only while a segment is being carried, which is what keeps the page- // still under it. Until then the gesture is the page's, so a finger that came to- // scroll scrolls, grip or no grip.+ // Prevented only during a drag, which is what stops the page scrolling under it.+ // Until then the gesture belongs to the page, so a touch meant to scroll scrolls.onTouchMove={(event) => {if (dragRef.current) {event.preventDefault();}}}- onPointerUp={() => {- cancelHold();- endDrag(true);- }}- onPointerCancel={() => {- cancelHold();- endDrag(false);- }}+ onPointerUp={(event) => finish(event, true)}+ onPointerCancel={(event) => finish(event, false)}>{shown.map((item, index) => (<section@@ -527,9 +572,8 @@ export function SortableCard<T extends SortableItem>({</section>))}- {/* Painted with nothing of its own: the gaps between the buttons are the card's- parent showing through, and each button carries what a segment is painted- with. */}+ {/* Transparent: the gaps between the buttons show the card's parent through, and+ each button paints itself like a segment. */}{!!itemCreationButtons?.length && (<sectionref={adderRef}@@ -537,17 +581,20 @@ export function SortableCard<T extends SortableItem>({onKeyDown={onAddKeyDown}>{itemCreationButtons.map((button, index) => (- <button+ <Button// The place in the row, which is the only thing that tells two// buttons apart: a label is the caller's to repeat.key={index}- type="button"+ // Not a command button: the theme paints those with a background,+ // a shadow and a minimum width, none of which a segment has.+ kind="lowProfile"className="tn-sortable-adder"+ text={<>+ {button.icon && <Icon icon={button.icon} />}+ <span>{button.label}</span>+ </>}onClick={() => add(button.onCreateItem)}- >- {button.icon && <Icon icon={button.icon} />}- <span>{button.label}</span>- </button>+ />))}</section>)}@@ -557,12 +604,12 @@ export function SortableCard<T extends SortableItem>({}/**- * How much of each edge of the screen is under something fixed, a toolbar or a bar of tabs.+ * How much of the viewport's top and bottom edges is covered by fixed chrome, a toolbar or a tab+ * bar.*- * A finger cannot be carried under a toolbar, so an edge behind one is an edge the card would- * never be walked from. Read from what stands at the middle of each edge, which is where a bar- * spanning the screen is found, and measured once per carry: chrome does not come and go during- * one.+ * A pointer cannot reach under a toolbar, so an edge behind one would never trigger the edge+ * scroll. Measured at the middle of each edge, where a full-width bar is found, and read once per+ * drag, since chrome does not come and go during one.*/function fixedChrome(carried: HTMLElement): Insets {const insets = { top: 0, bottom: 0, left: 0, right: 0 };@@ -572,8 +619,7 @@ function fixedChrome(carried: HTMLElement): Insets {const y = edge === "top" ? 1 : window.innerHeight - 1;for (const element of document.elementsFromPoint?.(middle, y) ?? []) {- // Whatever the segment is drawn inside stands over nothing: it is what is being- // carried, and the pointer is on it.+ // Whatever contains the dragged segment covers nothing: the pointer is on it.if (element.contains(carried) || getComputedStyle(element).position !== "fixed") {continue;}@@ -590,8 +636,8 @@ function fixedChrome(carried: HTMLElement): Insets {/*** What the card is scrolled inside, nearest first, which is what a carry to an edge walks along.*- * Every scroller above the card counts: one standing in a pane that scrolls, inside a page that- * scrolls as well, is reached by walking both.+ * Every scroller above the card counts: a card in a scrolling pane inside a scrolling page needs+ * both.*/function scrolledBy(list: HTMLElement | null): ScrollTarget[] {const targets: ScrollTarget[] = [];@@ -612,43 +658,45 @@ function scrolledBy(list: HTMLElement | null): ScrollTarget[] {return targets;}-/** A finger resting on a grip, until it has rested long enough to carry the segment. */+/** A touch waiting out `TOUCH_HOLD_MS` before it becomes a drag. */interface Hold {pointerId: number;- /** Where it went down, against which a stray is measured. */+ /** Where it went down, against which movement is measured. */from: { x: number, y: number };- /** Where it is now, which is where the carry begins from. */+ /** Where it is now, which is where the drag starts from. */at: number;timer: number;+ /** Drops the page-wide watch for the finger being lifted outside the list. */+ stopWatching: () => void;}-/** A segment being carried: where it was taken from, and the order it has reached. */+/** A drag in progress: where the segment started, and the order it has reached. */interface Drag<T extends SortableItem> {key: string;pointerId: number;/** Where the pointer went down, against which everything after it is measured. */grabbedAt: number;- /** Where the list stood on screen when it was taken, against which a scroll is measured. */+ /** The list's position on screen when the drag started, against which scrolling is measured. */at: number;- /** Where the segment stood in the list when it was taken. */+ /** The segment's offsetTop when the drag started. */from: number;height: number;- /** The order as it now stands, which is what the caller is told of. */+ /** The current order, which is what `onChange` reports. */order: T[];- /** The order it was taken from, against which a carry that changed nothing is told. */+ /** The order the drag started from, for telling whether it changed anything. */was: T[];}/**- * Where the carried segment now belongs: after every segment it has covered the middle of.+ * The index the dragged segment now belongs at.*- * The others are measured where the list has them now rather than where they started, a segment- * sliding out of the way already being reported at the place it is sliding to.+ * The others are measured where the list has them now: one sliding out of the way already reports+ * the position it is sliding to.*- * A segment gives way as the carried one's near edge passes its middle: the foot of the carried- * segment for one below, its head for one above. Measured by the middles alone, the carried- * segment would have to reach the very middle of the last place to take it, which is the one place- * it cannot be carried past, and the last place could not be reached at all.+ * A segment gives way once the dragged one's near edge passes its middle, its bottom edge for a+ * segment below and its top edge for one above. Comparing middles instead, the dragged segment+ * would have to reach the middle of the last slot to take it, and the clamp stops it exactly+ * there, so the last position would be unreachable.*/function orderFor<T extends SortableItem>(drag: Drag<T>, carried: HTMLElement, top: number,@@ -673,7 +721,7 @@ function orderFor<T extends SortableItem>(return from === to ? undefined : moved(drag.order, from, to);}-/** The list with one entry put elsewhere, or nothing where that would leave it as it stands. */+/** The list with one entry moved, or nothing when the move would leave the order unchanged. */function moved<T>(items: T[], from: number, to: number) {const place = Math.min(Math.max(to, 0), items.length - 1);if (from < 0 || from >= items.length || place === from) {@@ -685,7 +733,7 @@ function moved<T>(items: T[], from: number, to: number) {return order;}-/** Which entry a key asks for from the segment standing below them all. */+/** Which entry a key addresses from the creation row below them. */function lastPlaceFor(event: KeyboardEvent, last: number) {switch (event.key) {case "ArrowUp":@@ -699,10 +747,10 @@ function lastPlaceFor(event: KeyboardEvent, last: number) {}/**- * Which place a key asks for, or nothing for a key the card leaves alone.+ * Which index a key addresses, or nothing for a key the card ignores.*- * The same keys move a segment and step between them, the difference being Control: the board's- * cards are moved this way too, so a reader who knows one knows the other.+ * The same keys move a segment and step between them, Control telling them apart. The board's cards+ * use the same set.*/function placeFor(event: KeyboardEvent, index: number, last: number) {switch (event.key) {diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx b/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsxindex 268f7bd75f..5a73738e51 100644--- a/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx+++ b/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx@@ -148,7 +148,7 @@ describe("TemplateSelectionCard", () => {} as unknown as FNote);await draw();- expect(adders().map((button) => button.textContent)).toEqual([+ expect(adders().map((button) => button.textContent?.trim())).toEqual(["template_selection.add-existing", "template_selection.create"]);@@ -223,7 +223,7 @@ describe("TemplateSelectionCard", () => {}async function add(label: string) {- const button = adders().find((element) => element.textContent === label);+ const button = adders().find((element) => element.textContent?.trim() === label);await act(async () => {button?.click();await Promise.resolve();diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.tsx b/apps/client/src/widgets/react/TemplateSelectionCard.tsxindex 0f63229c67..f928268381 100644--- a/apps/client/src/widgets/react/TemplateSelectionCard.tsx+++ b/apps/client/src/widgets/react/TemplateSelectionCard.tsx@@ -17,45 +17,45 @@ import { type SortableItem, SortableCard } from "./SortableCard";export interface TemplateSelectionCardProps {heading: string;- /** The sentence saying what the templates are for, shown under the heading. */+ /** A sentence explaining what the templates are for, shown under the heading. */instruction: string;- /** The note the templates belong to, which is what one made here is filed under. */+ /** The note the templates belong to, and the parent of any created here. */note: FNote;- /** What a template made here is called, for a caller whose templates are of one kind. */+ /** The title given to a template created here. */newTemplateName?: string;- /** What is offered now, as note type ids, in the order they are offered in. */+ /** The templates on offer, as note type ids, in display order. */templates: string[];- /** Said with the whole list whenever the reader changes it. */+ /** Called with the whole list after every change. */onChange: (templates: string[]) => void;}/**- * The templates something is made from, in the order they are offered in.+ * The templates a note can be created from, in the order they are offered.*- * The order is the reader's to change, since the first of them is what is made until another is- * picked. Entries are added from what the app can already make, or made here and written straight- * away; the caller keeps the list and decides what it means.+ * The order is editable, the first template being the default until another is picked. Entries are+ * added from what the app can already create, or created here; the caller owns the list and decides+ * what it means.*- * Everything a note can be made from is read by the card itself, so a caller has only to say what- * it holds now and where a new one belongs.+ * The card reads everything a note can be created from itself, so a caller only supplies the+ * current list and where new templates belong.*/export default function TemplateSelectionCard({heading, instruction, note, newTemplateName, templates, onChange}: TemplateSelectionCardProps) {/**- * The list as it stands here, which is what the card is drawn from.+ * The current list, which the card renders from.*- * Held rather than read from the caller on every draw: a change is written straight through,- * and a caller that has nothing to redraw for would otherwise leave the list as it was found.+ * Held rather than read from the prop on every render: a change is written through at once, and+ * a caller with nothing to re-render for would otherwise leave the list unchanged.*/const [ ids, setIds ] = useState(templates);- /** Everything a note can be made from, read once the card is drawn. */+ /** Everything a note can be created from, read once when the card mounts. */const [ available, setAvailable ] = useState<NoteTypeOption[]>([]);/**- * What was made here, which the app has yet to read back.+ * Templates created here, which the app has yet to report back.*- * A template is a note, and it is known from the change that files it: until that arrives there- * is nothing to draw the entry from, and it would stand in the stored list without being shown.+ * A template is a note, and it becomes known through the entity change that creates it: until+ * that arrives there is nothing to render the entry from, so it would be stored but not shown.*/const [ made, setMade ] = useState<NoteTypeOption[]>([]);@@ -90,7 +90,7 @@ export default function TemplateSelectionCard({onChange(next);}, [ onChange ]);- /** Asks which of the ones not already offered to add, and answers with it as an entry. */+ /** Asks which of the templates not already offered to add, and returns it as an entry. */const addExisting = useCallback(async () => {const taken = new Set(offered.map((option) => option.id));const picked = await dialog.pickSingleItem({@@ -103,7 +103,7 @@ export default function TemplateSelectionCard({: undefined;}, [ available, offered ]);- /** Makes one and opens it, the reader writing what a note made from it holds. */+ /** Creates a template and opens it for editing. */const create = useCallback(async () => {const template = await note_create.createTemplateNote(note.noteId, newTemplateName ?? t("template_selection.new-name"));@@ -136,8 +136,8 @@ export default function TemplateSelectionCard({{item.icon && <Icon icon={item.icon} />}<span className="template-selection-name">{item.caption}</span>- {/* The last one left is not removable: nothing offered is nothing that could be- made, so the caller has none to fall back on. */}+ {/* The last template is not removable: with none offered, nothing could be+ created. */}{items.length > 1 && (<ActionButtonclassName="template-selection-remove"@@ -170,8 +170,8 @@ export default function TemplateSelectionCard({/*** What can still be added, as groups for the picker.*- * The templates the app ships are left out: they are a starting point for a note of one's own- * rather than something to be made from over and over.+ * The templates the app ships are excluded: they are a starting point for a template of one's own+ * rather than something to create from repeatedly.*/function pickable(available: NoteTypeOption[], taken: Set<string>): PickerItemGroup[] {const groups = new Map<string, PickerItemGroup>();diff --git a/apps/script-deployer/src/trilium-env.d.ts b/apps/script-deployer/src/trilium-env.d.tsindex d0078780c8..a804df6c20 100644--- a/apps/script-deployer/src/trilium-env.d.ts+++ b/apps/script-deployer/src/trilium-env.d.ts@@ -38,6 +38,7 @@ declare module "trilium:api" {getNoteContexts, getMainNoteContexts, getActiveContextTextEditor, getActiveContextCodeEditor,getActiveNoteDetailWidget, getActiveContextNotePath, getComponentByEl,showMessage, showError, showInfoDialog, showConfirmDialog, showPromptDialog,+ pickSingleItem,createLink, createNoteLink, triggerCommand, triggerEvent, setupElementTooltip,protectNote, protectSubTree,getTodayNote, getDayNote, getWeekFirstDayNote, getWeekNote, getMonthNote, getQuarterNote, getYearNote,diff --git a/packages/codemirror/src/type_completion/preact_types.ts b/packages/codemirror/src/type_completion/preact_types.tsindex 6d5f329bdb..3e53270434 100644--- a/packages/codemirror/src/type_completion/preact_types.ts+++ b/packages/codemirror/src/type_completion/preact_types.ts@@ -84,6 +84,7 @@ declare module "trilium:api" {getNoteContexts, getMainNoteContexts, getActiveContextTextEditor, getActiveContextCodeEditor,getActiveNoteDetailWidget, getActiveContextNotePath, getComponentByEl,showMessage, showError, showInfoDialog, showConfirmDialog, showPromptDialog,+ pickSingleItem,createLink, createNoteLink, triggerCommand, triggerEvent, setupElementTooltip,protectNote, protectSubTree,getTodayNote, getDayNote, getWeekFirstDayNote, getWeekNote, getMonthNote, getQuarterNote, getYearNote,diff --git a/packages/commons/src/lib/script_api_preact.ts b/packages/commons/src/lib/script_api_preact.tsindex b818f3761e..2b08679698 100644--- a/packages/commons/src/lib/script_api_preact.ts+++ b/packages/commons/src/lib/script_api_preact.ts@@ -416,6 +416,9 @@ interface ItemCreationButton<T extends SortableItem> {onCreateItem: () => T | undefined | Promise<T | undefined>;}interface SortableCardProps<T extends SortableItem> {+ /** See `CardProps`: the words a filter finds the card by, and whether it is filter-only. */+ filterExtraKeywords?: string;+ filterOnly?: boolean;items: T[];onChange: (items: T[]) => void;renderItem?: (item: T, index: number) => ComponentChildren;