Skip to content

Build your personal knowledge base with Trilium Notes

client: fix some issues

Adorian Dorand8c3c51254c4
diff --git a/apps/client/src/services/dialog.ts b/apps/client/src/services/dialog.ts
index 769c0222ac..d9b5118e5d 100644
--- a/apps/client/src/services/dialog.ts
+++ b/apps/client/src/services/dialog.ts
@@ -149,32 +149,22 @@ export function closeActiveDialog() {
}
}
-/** The layer a dialog stands on with nothing said about it, which is Bootstrap's own. */
+/** Bootstrap's own modal layer, used by a dialog that declares no z-index. */
const STANDARD_MODAL_LAYER = 1055;
/** Self-managing popups (quick-edit, tree popup) set their own z-index via CSS; never lift them. */
const SELF_MANAGED_POPUP_SELECTOR = ".popup-editor-dialog, .tree-popup-editor-dialog";
/**
- * Puts a dialog opened over something else above it.
+ * Raises a dialog above every modal already open, and returns the z-index it was given.
*
- * Two cases, and one answer for both. A quick-edit / tree popup stacked on another modal sits at
- * z-index 1100, above the standard dialog layer (1055), so a dialog opened from within it would
- * render behind the popup. And a dialog opened from another dialog — a picker reached from a
- * settings dialog, say — declares the same layer as the one it was opened from, which leaves the
- * two tied: whichever stands later in the page wins, and that is not the one just opened.
+ * Two cases need this. A quick-edit or tree popup stacked on a modal sits at 1100, above the
+ * standard 1055, so a dialog opened from it renders behind. Two dialogs that declare the same
+ * layer tie, and DOM order decides, which is not the dialog just opened.
*
- * The incoming dialog is given an inline z-index just above the top-most modal, so it clears both.
- * Its backdrop follows it (see the caller), which is what keeps the dialog underneath from being
- * pressed while this one is up.
- *
- * The dialog's inline z-index is rewritten from scratch on every open, so a lift never outlives the
- * context that warranted it. `declaredZIndex` is the layer the dialog defines for itself (`Modal`'s
- * `zIndex` prop, e.g. 1100 for the note type chooser or 2000 for confirm/prompt) and is what it
- * falls back to — clearing the property outright would strip that.
- *
- * Returns the assigned z-index (for the caller to match the backdrop), or `null` when no lift was
- * applied.
+ * The z-index is rewritten on every open so a lift does not outlive it, and `declaredZIndex`
+ * (`Modal`'s `zIndex` prop) is what an unlifted dialog falls back to. The caller matches the
+ * backdrop to the result. Returns `null` when no lift is needed.
*/
function raiseAboveWhatIsOpen(dialogEl: HTMLElement, declaredZIndex?: number): number | null {
const others = Array.from(document.querySelectorAll<HTMLElement>(".modal.show"))
@@ -183,8 +173,7 @@ function raiseAboveWhatIsOpen(dialogEl: HTMLElement, declaredZIndex?: number): n
const hasStackedPopup = document.body.classList.contains("popup-editor-stacked")
|| document.body.classList.contains("tree-popup-stacked");
- // The layer this dialog would stand on of its own accord, which is what says whether anything
- // already open would cover it.
+ // The layer this dialog uses on its own, which decides whether anything open covers it.
const own = declaredZIndex ?? STANDARD_MODAL_LAYER;
const isCovered = hasStackedPopup || maxZIndex >= own;
@@ -193,7 +182,7 @@ function raiseAboveWhatIsOpen(dialogEl: HTMLElement, declaredZIndex?: number): n
return null;
}
- // A dialog that already declares a layer above everything open keeps it; lifting only raises.
+ // A dialog declaring a layer above everything open keeps it: the lift only raises.
const zIndex = Math.max(maxZIndex + 10, own);
dialogEl.style.zIndex = String(zIndex);
return zIndex;
diff --git a/apps/client/src/services/note_create.ts b/apps/client/src/services/note_create.ts
index e1a7d9d547..599c3f2255 100644
--- a/apps/client/src/services/note_create.ts
+++ b/apps/client/src/services/note_create.ts
@@ -237,17 +237,12 @@ async function duplicateSubtree(noteId: string, parentNotePath: string) {
}
/**
- * Makes a template under the given note and opens it for the reader to write.
+ * Creates a template under `parentNoteId` and opens it in the popup editor.
*
- * A template is a note carrying `#template`, which is what makes it something other notes can be
- * made from. Written here rather than in the view that asked for one, since a collection of any
- * kind may want the same: a board makes the templates its cards are made from, and the next one to
- * offer templates makes them the same way.
+ * A template is a note carrying `#template`. The popup editor keeps the dialog that asked for the
+ * template open, which a tab switch would not.
*
- * Opened in a popup rather than in the tab: what asked for it is usually a dialog, which the reader
- * is still standing in and expects to come back to.
- *
- * @returns the note that was made, or nothing where it could not be.
+ * @returns the new note, or `undefined` when it could not be created.
*/
async function createTemplateNote(parentNoteId: string, title: string) {
const { note } = await createNote(parentNoteId, {
diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsx
index ce46a8087f..52e1106e07 100644
--- a/apps/client/src/widgets/collections/board/properties.tsx
+++ b/apps/client/src/widgets/collections/board/properties.tsx
@@ -6,15 +6,10 @@ import Modal from "../../react/Modal";
import TemplateSelectionCard from "../../react/TemplateSelectionCard";
import BoardApi from "./api";
-/**
- * The board's own settings, apart from its columns and cards.
- *
- * One card for now, the templates a new card is created from; the rest of the board's settings go
- * here as they arrive.
- */
+/** The board's settings, other than its columns and cards. */
export default function BoardProperties({ api, note, shown, onClose }: {
api: BoardApi,
- /** The board itself, and the parent of any template created here. */
+ /** The board note, which is the parent of any template created here. */
note: FNote,
shown: boolean,
onClose: () => void
diff --git a/apps/client/src/widgets/dialogs/item_picker.css b/apps/client/src/widgets/dialogs/item_picker.css
index d10b655b54..f6aea6a94d 100644
--- a/apps/client/src/widgets/dialogs/item_picker.css
+++ b/apps/client/src/widgets/dialogs/item_picker.css
@@ -1,29 +1,28 @@
:where(:root) {
- /* The colour the quick search marks its terms in, which is what a marked term reads as here. */
+ /* The colour the quick search marks its terms in. */
--item-picker-mark-color: var(--quick-search-result-highlight-color);
--item-picker-inline-padding: 40px;
- /* 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. */
+ /* One line of caption plus the card's padding. Exact, so the collapse animates. */
--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 the empty state can take the space the list is not using. */
+ /* A column, so the empty state can take the space the list leaves. */
display: flex;
flex-direction: column;
padding-inline: var(--item-picker-inline-padding);
}
- /* The area holding the list, which the empty state is laid over. */
+ /* Holds the list. The empty state is positioned over it. */
.item-picker-results {
position: relative;
flex: 1 0 auto;
}
.modal-dialog {
- /* Half again as wide as a small dialog, which is narrow but not cramped by the padding. */
+ /* Half again as wide as a small dialog, to fit the inline padding. */
max-width: 405px;
}
@@ -36,8 +35,7 @@
flex-direction: column;
}
- /* The space between groups belongs to each card, so it closes with the card rather than leaving
- a stripe where one was. */
+ /* The gap between groups sits on each card, so it collapses with the card. */
.item-picker-groups > .tn-card {
margin-block-end: 1em;
transition: margin var(--item-picker-fold-duration) ease;
@@ -47,12 +45,8 @@
margin-block-end: 0;
}
- /*
- * A group whose items have all collapsed collapses too, its heading closing on the same beat.
- *
- * 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.
- */
+ /* The filter primitive hides an emptied group outright, which cuts the collapse short.
+ Overridden in kind, its own rule being `!important`. */
.tn-card.tn-filter-scope:not(:has(.tn-filter-match)) {
display: block !important;
}
@@ -80,12 +74,10 @@
display: flex;
align-items: center;
gap: 0.4em;
- /* 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. */
+ /* An exact height, not a max-height ceiling: a ceiling above the real height spends most of
+ the transition invisible. */
height: var(--item-picker-item-height);
- /* 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. */
+ /* The gap sits on the item, so it collapses with it. A flex gap would leave a stripe. */
margin-block-end: var(--card-section-gap);
transition: height var(--item-picker-fold-duration) ease,
margin var(--item-picker-fold-duration) ease,
@@ -115,8 +107,7 @@
white-space: nowrap;
}
- /* Bootstrap's Reboot gives `mark` padding, which would space a matched term away from the rest
- of the caption. */
+ /* Bootstrap's Reboot pads `mark`, which would part a matched term from the caption. */
.item-picker-caption mark {
margin: 0;
padding: 0;
@@ -125,10 +116,7 @@
font-weight: 600;
}
- /*
- * 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.
- */
+ /* Laid over the list so it holds still while the list collapses. Faded, not unmounted. */
.item-picker-empty {
position: absolute;
inset: 0;
@@ -139,17 +127,16 @@
visibility 0s linear var(--item-picker-fold-duration);
}
- /* Shown only when the filter has left nothing. */
+ /* Shown only when the filter leaves 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 animate with the dialog rather than into it: one animation however many items are
- shown. */
+ /* One animation for the whole list, however many items it holds. */
.item-picker-groups {
- /* Long enough to read as its own animation, the dialog's opening covering its first moments. */
+ /* Long enough to read as its own animation under the dialog's opening. */
animation: item-picker-rise 0.4s ease-out;
}
}
@@ -163,15 +150,11 @@
gap: 0;
}
-/*
- * One height whatever it holds, so three items open the same box as a hundred and the list scrolls
- * inside it.
- *
- * 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`.
- */
+/* One height whatever it holds, the list scrolling inside it.
+
+ The height goes on `.modal-content`: a scrollable modal only caps that box, which is otherwise
+ sized by its contents and shrinks as the filter narrows the list. `.modal-dialog` then fills the
+ viewport and centres it, as `.modal-dialog-centered` does. */
body:not(.mobile) .modal.item-picker-dialog {
.modal-dialog {
display: flex;
@@ -186,7 +169,7 @@ body:not(.mobile) .modal.item-picker-dialog {
}
}
-/* A phone fills the screen instead, which `isFullPageOnMobile` answers for. */
+/* A phone fills the screen instead, together with `isFullPageOnMobile`. */
body.mobile .modal.item-picker-dialog .modal-content {
height: 100%;
}
diff --git a/apps/client/src/widgets/dialogs/item_picker.spec.tsx b/apps/client/src/widgets/dialogs/item_picker.spec.tsx
index 682f3422a3..8bd910fe44 100644
--- a/apps/client/src/widgets/dialogs/item_picker.spec.tsx
+++ b/apps/client/src/widgets/dialogs/item_picker.spec.tsx
@@ -6,7 +6,7 @@ import Component from "../../components/component";
import { ParentComponent } from "../react/react_utils";
import ItemPickerDialog, { type ItemPickerDialogOptions, type PickerItem } from "./item_picker";
-// i18next is never initialised under test, so the stock title and placeholder would be undefined.
+// i18next is never initialised under test, so the built-in title and placeholder are undefined.
vi.mock("../../services/i18n", () => ({
t: (key: string) => key
}));
@@ -63,11 +63,11 @@ describe("ItemPickerDialog", () => {
expect(headings()).toEqual([ "Fruit", "Tools" ]);
expect(captions()).toEqual([ "Apple", "Apricot", "Hammer", "Plane" ]);
expect(dialog()?.querySelector(".modal-title")?.textContent).toContain("Pick one");
- // The icon an entry carries, for the entries that carry one.
+ // Only some entries carry an icon.
expect(item("Apple")?.querySelector(".bx-leaf")).not.toBeNull();
});
- /** A plain list is one group with nothing written above it. */
+ /** A plain list becomes one group with no heading. */
it("takes a list of items as readily as groups of them", async () => {
await open({ items: [ { key: "one", caption: "One" }, { key: "two", caption: "Two" } ] });
@@ -104,10 +104,7 @@ describe("ItemPickerDialog", () => {
});
describe("searching", () => {
- /**
- * Folded away rather than taken down, so the list closes over what was filtered out. What
- * is left standing is what a press can still reach.
- */
+ /** Folded rather than unmounted, so the list collapses over what was filtered out. */
it("folds away everything that does not match", async () => {
await open({ items: GROUPS });
@@ -115,7 +112,7 @@ describe("ItemPickerDialog", () => {
expect(standing()).toEqual([ "Apple" ]);
expect(item("Hammer")?.className).toContain("item-picker-folded");
- // Still drawn, so the folding can be drawn as well.
+ // Still rendered, so the collapse can be animated.
expect(captions()).toEqual([ "Apple", "Apricot", "Hammer", "Plane" ]);
});
@@ -126,7 +123,7 @@ describe("ItemPickerDialog", () => {
const marked = item("Hammer")?.querySelectorAll("mark");
expect([ ...marked ?? [] ].map((mark) => mark.textContent)).toEqual([ "mm" ]);
- // What was not typed is left as it was.
+ // What the query does not match keeps its plain caption.
expect(item("Hammer")?.textContent).toBe("Hammer");
});
@@ -149,7 +146,7 @@ describe("ItemPickerDialog", () => {
expect(item("Apple")?.querySelectorAll("mark").length).toBe(0);
});
- /** The field the settings are looked through, clear button and all. */
+ /** The settings search field, clear button and all. */
it("is searched through the app's own search field", async () => {
await open({ items: GROUPS });
@@ -168,8 +165,8 @@ describe("ItemPickerDialog", () => {
});
/**
- * Nothing left standing is what shows the placeholder, which is laid over the list rather
- * than following it: whether it is painted is CSS's to say from the same condition.
+ * The empty state is rendered over the list and shown by CSS once every item is folded,
+ * which is the condition asserted here.
*/
it("leaves nothing standing when nothing matches at all", async () => {
await open({ items: GROUPS });
@@ -194,7 +191,7 @@ describe("ItemPickerDialog", () => {
});
}
- /** Bootstrap tells the dialog it has gone; under test the event is the test's to send. */
+ /** Bootstrap fires this when the dialog closes; the test sends it instead. */
async function close() {
await act(async () => {
dialog()?.dispatchEvent(new Event("hidden.bs.modal", { bubbles: true }));
@@ -212,7 +209,7 @@ describe("ItemPickerDialog", () => {
await Promise.resolve();
});
- // The typing settles before the list answers it.
+ // The debounce settles before the list is filtered.
await act(async () => { vi.advanceTimersByTime(300); await Promise.resolve(); });
}
@@ -228,7 +225,7 @@ describe("ItemPickerDialog", () => {
return items().map((element) => element.textContent);
}
- /** What is left standing, which is what the reader can still pick. */
+ /** The items still unfolded, which are the ones that can be picked. */
function standing() {
return items()
.filter((element) => !element.className.includes("item-picker-folded"))
diff --git a/apps/client/src/widgets/dialogs/item_picker.tsx b/apps/client/src/widgets/dialogs/item_picker.tsx
index c38dbc7719..19aaba4bea 100644
--- a/apps/client/src/widgets/dialogs/item_picker.tsx
+++ b/apps/client/src/widgets/dialogs/item_picker.tsx
@@ -31,10 +31,8 @@ export interface PickerItemGroup {
export interface ItemPickerDialogOptions {
title?: string;
/**
- * What can be picked: either the items themselves or groups of them, never mixed.
- *
- * Used as given, so the caller works them out before opening the dialog rather than making the
- * user wait for it.
+ * What can be picked: either items or groups of them, never mixed. Used as given, so the
+ * caller assembles them before opening the dialog.
*/
items: PickerItem[] | PickerItemGroup[];
/** Placeholder for the search field. */
@@ -49,16 +47,13 @@ const DEBOUNCE_MS = 150;
/**
* Picks one item out of many, grouped and searchable, and closes on the pick.
*
- * 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.
- *
- * Opened through `dialog.pickSingleItem()`, named for the single pick: picking several at once will
- * be the same dialog with a different result.
+ * {@link FilterProvider} narrows the list, as it does in the settings search. Each item collapses
+ * instead of unmounting, which keeps the change animatable. Opened through
+ * `dialog.pickSingleItem()`.
*/
export default function ItemPickerDialog() {
const opts = useRef<ItemPickerDialogOptions>();
- /** The item picked, reported once the dialog has closed rather than while it is closing. */
+ /** The item picked, reported in `onHidden` rather than while the dialog is closing. */
const picked = useRef<PickerItem | null>(null);
const searchRef = useRef<HTMLInputElement>(null);
const [ shown, setShown ] = useState(false);
@@ -96,8 +91,7 @@ export default function ItemPickerDialog() {
opts.current = undefined;
}}
>
- {/* The settings search field, which is also used over the lists of the dialogs the
- settings open. */}
+ {/* The same search field the settings pages use over their own lists. */}
<SettingsSearch
inputRef={searchRef}
query={query}
@@ -106,11 +100,9 @@ export default function ItemPickerDialog() {
/>
<FilterProvider query={settled}>
- {/* The empty state is laid over this rather than following it, so it stays put
- while the list collapses underneath. */}
+ {/* The empty state is laid over this, so it holds still as the list collapses. */}
<div className="item-picker-results">
- {/* Animated as the dialog opens: the items are its content rather than
- something arriving into it. */}
+ {/* Animated once with the dialog, not per item. */}
<div className="item-picker-groups">
{groups.map((group) => (
<Card key={group.key} heading={group.groupHeader || undefined}>
@@ -132,17 +124,13 @@ export default function ItemPickerDialog() {
);
}
-/**
- * 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.
- */
+/** One item. Rendered whether or not it matches, collapsing when it does not. */
function PickerRow({ item, onPick }: { item: PickerItem, onPick: (item: PickerItem) => void }) {
const matched = useFilterMatch(item.caption);
return (
<section
- // Marked as a match for the card, which is what keeps a group rendered while any of its
- // items is still shown.
+ // Marks the card as matching, which keeps the group rendered while an item shows.
className={clsx("tn-card-section tn-card-highlight-on-hover item-picker-item",
filterRoleClass(matched ? "match" : undefined),
{ "item-picker-folded": !matched })}
@@ -162,7 +150,7 @@ function PickerRow({ item, onPick }: { item: PickerItem, onPick: (item: PickerIt
);
}
-/** The caption with the search terms marked wherever they occur. */
+/** The caption with every occurrence of the search terms marked. */
function Marked({ text }: { text: string }) {
const filter = useFilterState();
const parts = useMemo(() => split(text, filter?.tokens), [ text, filter ]);
@@ -181,11 +169,7 @@ function isGroup(entry: PickerItem | PickerItemGroup): entry is PickerItemGroup
return "items" in entry;
}
-/**
- * The items as groups, whichever form the caller gave.
- *
- * A plain list becomes one group with no heading, so the dialog renders one shape rather than two.
- */
+/** The items as groups. A plain list becomes one group with no heading, so there is one shape. */
function asGroups(items: PickerItem[] | PickerItemGroup[]): PickerItemGroup[] {
const [ first ] = items;
if (!first) {
@@ -198,17 +182,15 @@ function asGroups(items: PickerItem[] | PickerItemGroup[]): PickerItemGroup[] {
}
/**
- * The caption split into matched and unmatched parts.
- *
- * 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.
+ * The caption split into matched and unmatched parts. Matched against the raw text, so a term that
+ * only matches after normalisation, a dropped accent for instance, stays unmarked.
*/
function split(text: string, tokens?: string[]) {
if (!tokens?.length) {
return [ { text, marked: false } ];
}
- // A capturing group puts the matches among the parts, at the odd indices.
+ // A capturing group puts the matches at the odd indices of the result.
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.css
index d1f74f35f5..4ea9db209c 100644
--- a/apps/client/src/widgets/react/SortableCard.css
+++ b/apps/client/src/widgets/react/SortableCard.css
@@ -2,18 +2,17 @@
--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, so a dragged segment reads as raised over the ones it passes. The lower
- shadow is heavier, as under an overhead light. */
+ /* Above and below, so a dragged segment reads as raised. The lower one is heavier. */
--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 lifted without losing the text. */
+ /* Enough to read as lifted without washing out the text. */
--sortable-dragging-opacity: 0.90;
}
.tn-card.tn-sortable-card {
.tn-sortable-list {
display: flex;
- /* The dragged segment is positioned against this, so it must be its offsetParent. */
+ /* Must be the dragged segment's offsetParent: it is positioned against this. */
position: relative;
flex-direction: column;
gap: var(--card-section-gap);
@@ -23,14 +22,13 @@
display: flex;
align-items: center;
gap: 0.5em;
- /* 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. */
+ /* useFlip transforms a segment back for one frame and lets this transition carry it to its
+ new position. Must match FLIP_DURATION_MS. */
transition: transform 200ms ease;
}
- /* 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. */
+ /* A touch drags from anywhere on the segment, and a press that long raises the iOS callout and
+ magnifier. Not applied to a mouse, which drags by the grip and can select the caption. */
@media (pointer: coarse) {
.tn-sortable-segment {
-webkit-touch-callout: none;
@@ -43,8 +41,8 @@
outline-offset: -2px;
}
- /* 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. */
+ /* Inset, so a selected segment takes no more room than the rest. Painted only while an entry
+ has the focus, not the creation row and not once the focus leaves the card. */
.tn-sortable-list:has(.tn-sortable-segment:focus-within) .tn-sortable-selected {
box-shadow: inset 0 0 0 1px var(--sortable-selected-color);
}
@@ -70,8 +68,7 @@
padding: 0.2em 0.1em;
color: var(--sortable-grip-color);
cursor: grab;
- /* The page still scrolls from here. What stops it during a drag is preventDefault on
- touchmove, which hands the gesture to the card. */
+ /* The page still scrolls from here. A drag is what calls preventDefault on touchmove. */
touch-action: pan-y;
-webkit-touch-callout: none;
user-select: none;
@@ -89,8 +86,8 @@
}
}
- /* 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. */
+ /* A touch target wider than the icon. The negative margin cancels the padding, so the segment
+ keeps its height. */
@media (pointer: coarse) {
.tn-sortable-grip {
margin-block: -0.5em;
@@ -98,15 +95,14 @@
padding: 0.7em calc(var(--card-padding-inline) / 2);
}
- /* Placed first, it extends into the leading padding instead. */
+ /* Placed first, the grip extends into the leading padding instead. */
.tn-sortable-grip:first-child {
margin-inline-start: calc(var(--card-padding-inline) / -2);
margin-inline-end: 0;
}
}
- /* Follows the pointer directly: the transition the other segments slide by would leave it a
- frame behind. */
+ /* Follows the pointer directly: the sliding transition would leave it a frame behind. */
.tn-sortable-dragging {
z-index: 1;
box-shadow: var(--sortable-dragging-shadow);
@@ -118,8 +114,7 @@
}
}
- /* Transparent: the gaps between the buttons show the card's parent through, and each button
- paints itself like a segment. */
+ /* Transparent: each button paints itself, and the gaps show the card through. */
.tn-sortable-adders {
display: flex;
gap: var(--card-section-gap);
@@ -128,8 +123,8 @@
background: transparent;
}
- /* 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. */
+ /* Painted as a segment rather than a button, all of one width, undoing what Bootstrap and the
+ theme give a button. */
button.tn-sortable-adder.btn {
display: flex;
flex: 1 1 0;
@@ -158,7 +153,7 @@
}
}
- /* The card's corners belong to the buttons, the row being transparent. */
+ /* The row is transparent, so its buttons carry the card's corners. */
.tn-sortable-adders:first-of-type button.tn-sortable-adder:first-child {
border-start-start-radius: var(--card-border-radius);
}
diff --git a/apps/client/src/widgets/react/SortableCard.spec.tsx b/apps/client/src/widgets/react/SortableCard.spec.tsx
index 1746de4c89..f28f173bef 100644
--- a/apps/client/src/widgets/react/SortableCard.spec.tsx
+++ b/apps/client/src/widgets/react/SortableCard.spec.tsx
@@ -4,17 +4,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SortableCard, type SortableItem } from "./SortableCard";
-// i18next is never initialised under test, so a stock label would be undefined and the segment it
-// stands in would read nothing at all.
+// i18next is never initialised under test, so every built-in label would read as undefined.
vi.mock("../../services/i18n", () => ({
t: (key: string) => key
}));
-/** How tall every segment stands, and the gap between two of them, as the card is laid out. */
+/** The height every segment is given here, and the gap between two of them. */
const SEGMENT_HEIGHT = 40;
const SEGMENT_GAP = 4;
-/** What the card asks of a finger before it carries a segment: how long, and how still. */
+/** What a touch must do before a drag starts: how long to wait, and how still to stay. */
const TOUCH_HOLD = 400;
const TOUCH_SLACK = 8;
@@ -24,7 +23,7 @@ describe("SortableCard", () => {
let changed: SortableItem[][];
beforeEach(() => {
- // The rest a finger keeps is waited out rather than lived through.
+ // The hold is advanced with fake timers rather than waited out.
vi.useFakeTimers();
items = [
{ key: "a", caption: "Alpha" },
@@ -47,11 +46,11 @@ describe("SortableCard", () => {
expect(container.querySelector(".tn-card-description")?.textContent)
.toBe("Put them as you like.");
expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
- // Every segment answers for itself, so any of them can be reached and moved by keyboard.
+ // Every segment is focusable, so any of them can be reached and moved by keyboard.
expect(segments().every((segment) => segment.tabIndex === 0)).toBe(true);
});
- /** The slot, for a card that shows more of an entry than its name. */
+ /** The render slot, for a card showing more than an entry's name. */
it("draws each entry with what the caller gives it", () => {
draw({ renderItem: (item, index) => <b>{`${index}:${item.key}`}</b> });
@@ -67,7 +66,7 @@ describe("SortableCard", () => {
expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "b", "a", "c" ]);
expect(captions()).toEqual([ "Beta", "Alpha", "Gamma" ]);
- // The reader is left standing on the entry they moved, not on the place it left.
+ // The focus follows the entry that moved, not the position it left.
expect(document.activeElement).toBe(segmentOf("a"));
});
@@ -81,7 +80,7 @@ describe("SortableCard", () => {
expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c" ]);
});
- /** There is nowhere past the ends, and a key that changes nothing is left to the page. */
+ /** There is nothing past either end, and an unused key is left to the page. */
it("leaves an entry at the end where it is", () => {
draw();
const atTop = segments()[0];
@@ -98,7 +97,7 @@ describe("SortableCard", () => {
it("steps between entries without Control, moving nothing", () => {
draw();
- // Nothing stands below the last entry on a card that cannot be added to.
+ // A card with no creation row has nothing below its last entry.
focus(segments()[2]);
press(segments()[2], "ArrowDown");
expect(document.activeElement).toBe(segmentOf("c"));
@@ -134,7 +133,7 @@ describe("SortableCard", () => {
expect(segmentOf("c")?.className).toContain("tn-sortable-selected");
- // What the reader does is reported; what is drawn stays the caller's to decide.
+ // The change is reported, and the caller decides what is drawn.
focus(segmentOf("a"));
expect(segmentOf("c")?.className).toContain("tn-sortable-selected");
expect(segmentOf("a")?.className).not.toContain("tn-sortable-selected");
@@ -158,12 +157,11 @@ describe("SortableCard", () => {
draw();
grab(segmentOf("a"));
- // Past the middle of the second segment, which is what it changes places with.
+ // Past the middle of the second segment, which it swaps with.
moveTo(SEGMENT_HEIGHT + SEGMENT_GAP + 1);
expect(captions()).toEqual([ "Beta", "Alpha", "Gamma" ]);
- // Nothing is reported until it lands: a carry across the card is one change, not one
- // for every segment it passes.
+ // Nothing is reported until the drop: one change per drag, not per segment passed.
expect(changed).toEqual([]);
drop();
@@ -172,23 +170,21 @@ describe("SortableCard", () => {
});
/**
- * A segment gives way as the carried one's foot passes its middle, which is what puts the
- * last place within reach: the carried segment can be held no lower than that place, so
- * middle against middle it would have to reach a place it cannot be carried to.
+ * A segment gives way as the dragged one's bottom edge passes its middle, which is what
+ * makes the last position reachable: the clamp stops the drag exactly at that middle.
*/
it("takes the last place as its foot passes the middle of the last segment", () => {
draw();
const last = SEGMENT_HEIGHT * 2 + SEGMENT_GAP * 2;
grab(segmentOf("a"));
- // Short of the last place by half a segment, and just past the middle of the one
- // standing in it.
+ // Half a segment short of the last position, just past the middle of the one in it.
moveTo(last - SEGMENT_HEIGHT / 2 + 1);
expect(captions()).toEqual([ "Beta", "Gamma", "Alpha" ]);
});
- /** And the other way about: the head passing a middle is what sends a segment above it. */
+ /** The same upwards: the top edge passing a middle moves the segment above it. */
it("takes the first place as its head passes the middle of the first segment", () => {
draw();
@@ -209,11 +205,11 @@ describe("SortableCard", () => {
expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
drop();
- // Back where it started, so there is nothing to report.
+ // Back at its starting position, so there is nothing to report.
expect(changed).toEqual([]);
});
- /** The segment is held inside the card, whatever the pointer does past its ends. */
+ /** The segment is clamped to the card, however far the pointer goes past it. */
it("carries it no further than the ends of the card", () => {
draw();
const carried = segmentOf("c");
@@ -225,16 +221,14 @@ describe("SortableCard", () => {
const [ first ] = segments();
grab(first, 0);
moveTo(500);
- // The last place a segment can stand in: the room the list has, less its own height.
+ // The last position: the list's height less the segment's own.
expect(shift(first)).toBe(listHeight() - SEGMENT_HEIGHT);
drop();
});
/**
- * A card taller than the screen is scrolled while a segment is carried to an edge of it,
- * which moves the list out from under a pointer that has not itself moved. The segment
- * answers to the place in the card the pointer is over, not to the place on screen it was
- * taken from, or it would be left behind by everything the scrolling brought into view.
+ * Scrolling moves the list under a pointer that has not moved, so the segment follows the
+ * position in the card rather than the position on screen it started from.
*/
it("keeps the segment under the pointer while the card is scrolled", () => {
draw();
@@ -244,7 +238,7 @@ describe("SortableCard", () => {
moveTo(SEGMENT_HEIGHT / 2);
expect(shift(carried)).toBe(SEGMENT_HEIGHT / 2);
- // The card scrolls up by a segment, the pointer staying where it is.
+ // The card scrolls up by one segment while the pointer stays put.
standAt(-SEGMENT_HEIGHT);
moveTo(SEGMENT_HEIGHT / 2);
@@ -276,20 +270,16 @@ describe("SortableCard", () => {
expect(changed).toEqual([]);
});
- /**
- * A finger carries it the same way a mouse does, once it has rested on the grip. The grip
- * answers for the gesture as soon as it is touched, so a finger that meant to scroll the
- * page scrolls nothing wherever it lands on one: resting first is what tells them apart.
- */
+ /** A touch drags as a mouse does, once it has held still for TOUCH_HOLD_MS. */
it("is carried by a finger, once it has rested on the grip", () => {
draw();
touch(segmentOf("a"));
- // Nothing is taken up by the press itself, however long the finger is there for.
+ // The press alone starts no drag, however long the finger stays down.
expect(segmentOf("a")?.className).not.toContain("tn-sortable-dragging");
rest();
- // Held now, which the segment says for itself before it has gone anywhere.
+ // Dragging now, which the segment reports before it has moved.
expect(segmentOf("a")?.className).toContain("tn-sortable-dragging");
moveTo(SEGMENT_HEIGHT + SEGMENT_GAP + 1, { pointerType: "touch" });
@@ -300,9 +290,8 @@ describe("SortableCard", () => {
});
/**
- * The page is the gesture's until a segment is taken up: a finger that came to scroll
- * scrolls, wherever on the card it landed. Once one is being carried the move is refused,
- * which is what holds the page still under it.
+ * The page scrolls until the drag starts, wherever on the card the touch landed. From
+ * then on touchmove is prevented, which holds the page still.
*/
it("leaves the page to scroll until a segment is being carried", () => {
draw();
@@ -318,8 +307,8 @@ describe("SortableCard", () => {
});
/**
- * A thumb reaching across a phone lands on the near edge of a row far more easily than on
- * one particular end of it, so the rest is kept wherever the finger fell.
+ * A touch drags from anywhere on the segment, which a thumb reaches far more easily than
+ * one particular end of it.
*/
it("is carried by a finger resting anywhere on the segment", () => {
draw();
@@ -333,7 +322,7 @@ describe("SortableCard", () => {
expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "b", "a", "c" ]);
});
- /** A mouse has no trouble reaching a mark, and a press elsewhere is for reading. */
+ /** A mouse can aim at the grip, so a press elsewhere selects text instead. */
it("is not carried by a mouse pressed anywhere but the grip", () => {
draw();
@@ -346,7 +335,7 @@ describe("SortableCard", () => {
expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
});
- /** Whatever a control does with a press, carrying the row off is not it. */
+ /** A press on a control belongs to that control, and starts no drag. */
it("leaves a press that began on a control to the control", () => {
draw({ renderItem: (item) => <button type="button">{item.caption}</button> });
@@ -372,7 +361,7 @@ describe("SortableCard", () => {
expect(changed).toEqual([]);
});
- /** A finger settling by a pixel or two is still resting, and carries nothing off by it. */
+ /** A drift within TOUCH_SLACK_PX still counts as still, and does not offset the drag. */
it("takes it up for a finger that barely moves, from where the finger now is", () => {
draw();
@@ -407,7 +396,7 @@ describe("SortableCard", () => {
expect(changed).toEqual([]);
});
- /** A press that is not the primary button is somebody else's: a menu, most likely. */
+ /** A press with any other button opens a menu, and starts no drag. */
it("is not carried by a right click", () => {
draw();
@@ -436,10 +425,10 @@ describe("SortableCard", () => {
expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "d" ]);
expect(captions()).toEqual([ "Alpha", "Beta", "Gamma", "Delta" ]);
expect(segmentOf("d")?.className).toContain("tn-sortable-appearing");
- // The reader is left on the segment that adds, so another entry can follow.
+ // The focus stays on the creation button, so another entry can follow.
expect(document.activeElement).not.toBe(segmentOf("d"));
- // Shown once: the entry stays the one just made, and a redraw must not play it again.
+ // Played once: a redraw must not repeat the entry animation.
act(() => {
segmentOf("d")?.dispatchEvent(
new AnimationEvent("animationend", { bubbles: true }));
@@ -478,7 +467,7 @@ describe("SortableCard", () => {
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.
+ // All of one width, the row sharing its space between them.
expect(adders().every((button) => button.style.flex === "")).toBe(true);
await click(adders()[1]);
@@ -488,7 +477,7 @@ describe("SortableCard", () => {
expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "e", "f" ]);
});
- /** A label says what a button does, and two of them can say the same thing. */
+ /** Two buttons can carry the same label, so the position tells them apart. */
it("keeps two buttons that read alike apart", async () => {
draw({ itemCreationButtons: [ makes("d", "Delta"), makes("e", "Epsilon") ] });
@@ -498,7 +487,7 @@ describe("SortableCard", () => {
expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "e" ]);
});
- /** Three is as many as the foot of a card can read; a fourth is the caller's mistake. */
+ /** Three is the most the card renders; a fourth is a caller error. */
it("refuses more than three ways of making an entry", () => {
const buttons = [ makes("d", "D"), makes("e", "E"), makes("f", "F"), makes("g", "G") ];
@@ -507,7 +496,7 @@ describe("SortableCard", () => {
expect(() => draw({ itemCreationButtons: buttons.slice(0, 3) })).not.toThrow();
});
- /** Beside the entry the reader stands on, the way a spreadsheet adds a row. */
+ /** Beside the focused entry, the way a spreadsheet adds a row. */
it("makes an entry below the focused one for Enter, and above it for Shift and Enter",
async () => {
let made = 0;
@@ -558,8 +547,8 @@ describe("SortableCard", () => {
});
/**
- * It is one of the places the reader stands, even though it holds no entry: stepping down
- * from the last entry reaches it, and the keys that name an entry lead back into them.
+ * The creation row is a focus stop although it holds no entry: Down from the last entry
+ * reaches it, and the movement keys lead back into the entries.
*/
it("is stepped onto and off again, like the entries above it", () => {
draw({ itemCreationButtons: [ makes("d", "Delta") ] });
@@ -579,7 +568,7 @@ describe("SortableCard", () => {
expect(document.activeElement).toBe(segmentOf("c"));
});
- /** Nothing stands below it, and a card of no entries has nowhere to lead back to. */
+ /** Nothing is below it, and an empty card has no entry to lead back to. */
it("goes nowhere from the segment that adds", () => {
draw({ itemCreationButtons: [ makes("d", "Delta") ] });
@@ -594,7 +583,7 @@ describe("SortableCard", () => {
expect(document.activeElement).toBe(adder());
});
- /** It stands at the foot of the card to be pressed, not to be put in order with the rest. */
+ /** The creation row is a focus stop, not an entry, so it cannot be reordered. */
it("leaves the segment for adding where it is", () => {
draw({ itemCreationButtons: [ makes("d", "Delta") ] });
expect(adder()?.querySelector(".tn-sortable-grip")).toBeNull();
@@ -602,7 +591,7 @@ describe("SortableCard", () => {
press(adder(), "ArrowUp", { ctrlKey: true });
expect(changed).toEqual([]);
- // Nor does a key meant for the entries carry the reader off it while Control is held.
+ // Control plus a movement key does not move the focus off it either.
expect(document.activeElement).not.toBe(segmentOf("c"));
});
});
@@ -613,11 +602,11 @@ describe("SortableCard", () => {
expect(first.lastElementChild?.className).toContain("tn-sortable-grip");
expect(first.querySelector(".tn-sortable-grip svg line")).not.toBeNull();
- // The keyboard answers for what the grip does, so it is not read out a second time.
+ // The keyboard covers what the grip does, so it is hidden from screen readers.
expect(first.querySelector(".tn-sortable-grip")?.getAttribute("aria-hidden")).toBe("true");
});
- /** The other edge, for a card whose entries carry something of their own on the trailing one. */
+ /** The leading edge, for a card whose entries carry their own buttons on the trailing one. */
it("carries it on the leading edge where the caller asks for it there", () => {
draw({ gripPlacement: "start" });
const [ first ] = segments();
diff --git a/apps/client/src/widgets/react/SortableCard.tsx b/apps/client/src/widgets/react/SortableCard.tsx
index f6d17df96b..76418b0b0a 100644
--- a/apps/client/src/widgets/react/SortableCard.tsx
+++ b/apps/client/src/widgets/react/SortableCard.tsx
@@ -14,33 +14,29 @@ import { createEdgeScroller, type Insets, type ScrollTarget } from "./edge_scrol
import { useFlip } from "./flip";
import Icon from "./Icon";
-/** How many buttons the foot of a card holds before they are too narrow to read. */
+/** How many creation buttons fit at the foot of a card before each is too narrow to read. */
const MAX_CREATION_BUTTONS = 3;
/**
- * How long a touch must stay still before the drag starts.
- *
- * 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.
+ * How long a touch must stay still before the drag starts. A touch that moves first scrolls the
+ * page instead. Matches the board's cards.
*/
const TOUCH_HOLD_MS = 400;
-/** How far the touch can move in that time and still count as still. */
+/** How far the touch can move within `TOUCH_HOLD_MS` and still count as still. */
const TOUCH_SLACK_PX = 8;
/**
- * How near an edge the pointer comes before the card starts to walk, in pixels.
- *
- * Wider under a finger than the 60 a mouse is given: a thumb covers what it is pointing at, and
- * the strip it has to find is the strip it cannot see.
+ * How near an edge the pointer must come, in pixels, before the card scrolls. Wider for touch: a
+ * finger covers the strip it has to reach.
*/
const SCROLL_MARGIN = 60;
const TOUCH_SCROLL_MARGIN = 100;
/**
- * 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.
+ * Elements that handle a press themselves, so a press starting on one never drags the segment.
+ * `renderItem` can draw anything, so ARIA 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]";
@@ -64,6 +60,8 @@ export interface ItemCreationButton<T extends SortableItem> {
label: string;
/** An icon class, `bx` prefix included. */
icon?: string;
+ /** Turns the button off, for a caller that cannot make an entry yet. */
+ disabled?: boolean;
onCreateItem: () => T | undefined | Promise<T | undefined>;
}
@@ -100,14 +98,11 @@ export interface SortableCardProps<T extends SortableItem> extends CardProps {
}
/**
- * A card whose segments can be reordered.
- *
- * 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.
+ * A card whose segments can be reordered by dragging the grip or with the keyboard. A drag moves
+ * vertically only and is clamped to the card.
*
- * 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.
+ * The caller owns the order: `onChange` reports every change and the card renders what it is given
+ * back. Entries are not interpreted, so anything identified by a key can be sorted.
*/
export function SortableCard<T extends SortableItem>({
items, onChange, renderItem, itemCreationButtons, gripPlacement = "end", onItemKeyDown,
@@ -126,63 +121,57 @@ export function SortableCard<T extends SortableItem>({
const pointerRef = useRef({ x: 0, y: 0 });
/** 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. */
+ /** Fixed chrome covering the screen edges, measured when a drag starts. */
const reachRef = useRef<Insets>({ top: 0, bottom: 0, left: 0, right: 0 });
/**
- * Scrolls whatever contains the card while a segment is dragged to its edge.
- *
- * 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.
+ * Scrolls the card's containers while a segment is dragged to an edge, so a card taller than
+ * the viewport can be reordered end to end. Created once, so its frames outlive the render.
*/
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.
+ // The pointer has not moved, but the content under it has.
onScroll: () => dragToRef.current(pointerRef.current.y)
}), []);
useEffect(() => () => scroller.stop(), [ scroller ]);
/**
- * The order during a drag, reported to the caller when it ends.
- *
- * Kept until the caller renders an order of its own, so the segments do not spring back for the
- * frames in between.
+ * The order during a drag, reported to the caller when it ends. Kept until the caller renders
+ * its own order, so the segments do not spring back in between.
*/
const [ draft, setDraft ] = useState<T[] | null>(null);
const [ draggedKey, setDraggedKey ] = useState<string>();
const [ ownSelection, setOwnSelection ] = useState<string>();
/** The entry just added, which grows and fades in. */
const [ addedKey, setAddedKey ] = useState<string>();
- /** The segment to focus after the next render, since moving an element drops its focus. */
+ /** The segment to focus after the next render: 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. */
+ /** The current list, for a callback that resumes after an await. */
const shownRef = useRef(shown);
shownRef.current = shown;
const selected = selectedKey ?? ownSelection;
useEffect(() => {
- // The caller has rendered its own order, so the draft is no longer needed. Not during a
- // drag, where the order is still changing.
+ // The caller rendered its own order, so the draft can go. Not during a drag, where the
+ // order is still changing.
if (!dragRef.current) {
setDraft(null);
}
}, [ items ]);
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.
+ // Compared instead of interpolated into a selector: a key 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 dragged segment is excluded: it follows the pointer, and useFlip would slide it back to
- // the slot the list has opened for it.
+ // The dragged segment is excluded: it follows the pointer, and useFlip would slide it back.
useFlip(listRef, {
selector: ".tn-sortable-segment:not(.tn-sortable-dragging)",
grow: (segment) => segment.dataset.key === addedKey
@@ -266,7 +255,7 @@ export function SortableCard<T extends SortableItem>({
reachRef.current = fixedChrome(segment);
- // Throws when the pointer is no longer active, a touch lifted during the hold above all.
+ // Throws when the pointer is no longer active, usually a touch lifted during the hold.
// Touch captures to the segment implicitly, so the drag works without this.
try {
listRef.current?.setPointerCapture?.(pointerId);
@@ -311,23 +300,21 @@ export function SortableCard<T extends SortableItem>({
const target = event.target as HTMLElement | null;
const onGrip = !!target?.closest(".tn-sortable-grip");
- // A mouse takes hold of the grip and nothing else: a press anywhere on a segment is for
- // reading what it says or working a control the caller drew, and a mouse has no trouble
- // reaching a mark. A finger rests wherever it lands, a thumb across a phone reaching the
- // near edge of a row far more easily than one particular end of it.
+ // A mouse drags from the grip only, since it can aim at one. A touch drags from anywhere
+ // on the segment, which a thumb reaches far more easily.
if (event.pointerType === "mouse") {
if (!onGrip || event.button !== 0) {
return;
}
- // Stops the press from starting a selection instead.
+ // Stops the press from starting a text selection.
event.preventDefault();
startDrag(key, event.pointerId, event.clientY);
return;
}
- // 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.
+ // A press starting on a control belongs to that control. The segment is not one, although
+ // it handles keys and carries a tabindex.
const control = target?.closest(CONTROLS);
if (!onGrip && control && control !== segmentOf(key)) {
return;
@@ -336,9 +323,9 @@ export function SortableCard<T extends SortableItem>({
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.
+ // The list captures the pointer only once the drag begins, so a finger lifted before that
+ // and outside the list reports to the page. Without this the timer drags a pointer that is
+ // no longer down.
const dropped = (ended: PointerEvent) => {
if (ended.pointerId === holdRef.current?.pointerId) {
cancelHold();
@@ -351,8 +338,7 @@ export function SortableCard<T extends SortableItem>({
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.
+ // Where the finger is once the hold ends, so a small drift does not offset the drag.
at: event.clientY,
stopWatching: () => {
document.removeEventListener("pointerup", dropped);
@@ -388,8 +374,7 @@ export function SortableCard<T extends SortableItem>({
const order = orderFor(drag, segment, top, segmentOf);
if (order) {
drag.order = order;
- // 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.
+ // Rendered before the segment is positioned, so it is measured against its new slot.
flushSync(() => setDraft(order));
}
@@ -399,10 +384,8 @@ export function SortableCard<T extends SortableItem>({
dragToRef.current = dragTo;
/**
- * Creates an entry at `at`, or appends it when no index is given.
- *
- * 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.
+ * Creates an entry at `at`, or appends it when no index is given. An entry created among the
+ * others takes the focus; an appended one leaves it on the button, so several can be made.
*/
const add = useCallback(async (create: ItemCreationButton<T>["onCreateItem"], at?: number) => {
const created = await create();
@@ -410,8 +393,8 @@ export function SortableCard<T extends SortableItem>({
return;
}
- // 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.
+ // Read again instead of closed over: `create` can open a dialog, and an order built from
+ // the stale list would undo a reorder made meanwhile.
const order = [ ...shownRef.current ];
order.splice(at ?? order.length, 0, created);
setAddedKey(created.key);
@@ -424,8 +407,8 @@ export function SortableCard<T extends SortableItem>({
}, [ 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.
+ * Ends what `event.pointerId` was doing, and nothing else: a second finger pressed and lifted
+ * in the list would otherwise cancel or commit the first one's drag.
*/
const finish = useCallback((event: PointerEvent, keep: boolean) => {
if (holdRef.current?.pointerId === event.pointerId) {
@@ -445,10 +428,11 @@ export function SortableCard<T extends SortableItem>({
return;
}
- // 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.
+ // Creates an entry below the focused one, or above it with Shift, the way a spreadsheet
+ // adds a row. Uses the first creation button, since no button was pressed.
const leading = itemCreationButtons?.[0];
- if (event.key === "Enter" && leading && !event.ctrlKey && !event.metaKey) {
+ if (event.key === "Enter" && leading && !leading.disabled
+ && !event.ctrlKey && !event.metaKey) {
event.preventDefault();
add(leading.onCreateItem, event.shiftKey ? index : index + 1);
return;
@@ -459,13 +443,13 @@ export function SortableCard<T extends SortableItem>({
const to = placeFor(event, index, last);
if (to === undefined) {
- // Left to the caller, whose entries may answer keys of their own.
+ // Left to the caller, whose entries can handle keys of their own.
if (!control) {
onItemKeyDown?.(shown[index], event);
}
- // Below the last entry is the creation row, which Down moves onto. It holds no entry,
- // so Ctrl+Down moves nothing there.
+ // Down from the last entry moves onto the creation row. 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();
@@ -483,8 +467,8 @@ export function SortableCard<T extends SortableItem>({
}, [ add, endDrag, focusEntry, itemCreationButtons, moveItem, onItemKeyDown, shown ]);
const onAddKeyDown = useCallback((event: KeyboardEvent) => {
- // 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.
+ // Moves back into the entries. Home and End address the first and last entry, as they do
+ // on an entry: 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) {
@@ -496,10 +480,8 @@ export function SortableCard<T extends SortableItem>({
}, [ focusEntry, shown ]);
/**
- * The drag handle, drawn on whichever edge `gripPlacement` names.
- *
- * 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.
+ * The drag handle, drawn on the edge `gripPlacement` names. An affordance rather than the hit
+ * area: the segment handles the press, so only a mouse has to aim at the grip.
*/
const grip = () => (
<span
@@ -540,8 +522,7 @@ export function SortableCard<T extends SortableItem>({
dragTo(event.clientY);
}
}}
- // 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.
+ // Prevented during a drag only, so a touch meant to scroll still scrolls.
onTouchMove={(event) => {
if (dragRef.current) {
event.preventDefault();
@@ -582,8 +563,7 @@ export function SortableCard<T extends SortableItem>({
</section>
))}
- {/* Transparent: the gaps between the buttons show the card's parent through, and
- each button paints itself like a segment. */}
+ {/* Transparent: each button paints itself, and the gaps show the card through. */}
{!!itemCreationButtons?.length && (
<section
ref={adderRef}
@@ -592,17 +572,17 @@ export function SortableCard<T extends SortableItem>({
>
{itemCreationButtons.map((button, index) => (
<Button
- // The place in the row, which is the only thing that tells two
- // buttons apart: a label is the caller's to repeat.
+ // The position in the row: two buttons can share a label.
key={index}
- // Not a command button: the theme paints those with a background,
- // a shadow and a minimum width, none of which a segment has.
+ // Not a command button: the theme gives those a background, a
+ // shadow and a minimum width, none of which suit a segment.
kind="lowProfile"
className="tn-sortable-adder"
text={<>
{button.icon && <Icon icon={button.icon} />}
<span>{button.label}</span>
</>}
+ disabled={button.disabled}
onClick={() => add(button.onCreateItem)}
/>
))}
@@ -614,12 +594,10 @@ export function SortableCard<T extends SortableItem>({
}
/**
- * How much of the viewport's top and bottom edges is covered by fixed chrome, a toolbar or a tab
- * bar.
+ * How much of the viewport's top and bottom edges fixed chrome covers, a toolbar or a tab bar.
*
- * 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.
+ * A pointer cannot reach under a toolbar, so an edge behind one never triggers the edge scroll.
+ * Measured at the middle of each edge and read once per drag.
*/
function fixedChrome(carried: HTMLElement): Insets {
const insets = { top: 0, bottom: 0, left: 0, right: 0 };
@@ -644,10 +622,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: a card in a scrolling pane inside a scrolling page needs
- * both.
+ * The scrollable ancestors of the card, nearest first, which the edge scroller walks. A card in a
+ * scrolling pane inside a scrolling page needs both.
*/
function scrolledBy(list: HTMLElement | null): ScrollTarget[] {
const targets: ScrollTarget[] = [];
@@ -671,12 +647,12 @@ function scrolledBy(list: HTMLElement | null): ScrollTarget[] {
/** A touch waiting out `TOUCH_HOLD_MS` before it becomes a drag. */
interface Hold {
pointerId: number;
- /** Where it went down, against which movement is measured. */
+ /** Where the pointer went down, which movement is measured against. */
from: { x: number, y: number };
- /** Where it is now, which is where the drag starts from. */
+ /** Where the pointer is now, which the drag starts from. */
at: number;
timer: number;
- /** Drops the page-wide watch for the finger being lifted outside the list. */
+ /** Removes the document listeners watching for a lift outside the list. */
stopWatching: () => void;
}
@@ -698,15 +674,12 @@ interface Drag<T extends SortableItem> {
}
/**
- * The index the dragged segment now belongs at.
+ * The index the dragged segment now belongs at. The others are measured at their current
+ * positions, which for one already sliding is the position it slides 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 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.
+ * A segment gives way once the dragged one's near edge passes its middle: the bottom edge for a
+ * segment below, the top edge for one above. Comparing middles would put the last slot exactly at
+ * the clamp, leaving the last position unreachable.
*/
function orderFor<T extends SortableItem>(
drag: Drag<T>, carried: HTMLElement, top: number,
@@ -731,7 +704,7 @@ function orderFor<T extends SortableItem>(
return from === to ? undefined : moved(drag.order, from, to);
}
-/** The list with one entry moved, or nothing when the move would leave the order unchanged. */
+/** The list with one entry moved, or `undefined` when the order would not change. */
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) {
@@ -743,7 +716,7 @@ function moved<T>(items: T[], from: number, to: number) {
return order;
}
-/** Which entry a key addresses from the creation row below them. */
+/** Which entry a key addresses from the creation row. */
function lastPlaceFor(event: KeyboardEvent, last: number) {
switch (event.key) {
case "ArrowUp":
@@ -757,10 +730,8 @@ function lastPlaceFor(event: KeyboardEvent, last: number) {
}
/**
- * Which index a key addresses, or nothing for a key the card ignores.
- *
- * The same keys move a segment and step between them, Control telling them apart. The board's cards
- * use the same set.
+ * Which index a key addresses, or `undefined` for a key the card ignores. The same keys move a
+ * segment and step between them, Control telling them apart, as the board's cards do.
*/
function placeFor(event: KeyboardEvent, index: number, last: number) {
switch (event.key) {
diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.css b/apps/client/src/widgets/react/TemplateSelectionCard.css
index 046d2401c2..71ad9dd4a0 100644
--- a/apps/client/src/widgets/react/TemplateSelectionCard.css
+++ b/apps/client/src/widgets/react/TemplateSelectionCard.css
@@ -1,4 +1,4 @@
-/* The name takes what room there is, so the way to remove an entry stands at its trailing edge. */
+/* The name takes the free space, pushing the buttons to the trailing edge. */
.template-selection-name {
flex-grow: 1;
overflow: hidden;
diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx b/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx
index df98d4ca8c..afed120a8d 100644
--- a/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx
+++ b/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx
@@ -21,14 +21,14 @@ vi.mock("../../services/i18n", () => ({
t: (key: string) => key
}));
-// The listing is the app's and is tested there; the card is handed a short one of each kind.
+// The listing is tested where it lives; the card is given a short one of each kind.
vi.mock("../../services/note_types", async () => {
const actual = await vi.importActual<typeof import("../../services/note_types")>(
"../../services/note_types");
return { ...actual, getNoteTypeOptions: vi.fn(async () => AVAILABLE) };
});
-/** Everything the app could make, as `getNoteTypeOptions` answers with it. */
+/** Everything the app can create, as `getNoteTypeOptions` reports it. */
const AVAILABLE = [
[ "type:text:text/html", "Text", "type" ],
[ "type:code:text/x-markdown", "Markdown", "type" ],
@@ -43,7 +43,7 @@ const AVAILABLE = [
options: { type: "text", templateNoteId: id.split(":")[1] }
}) as NoteTypeOption);
-/** The note a template made here is filed under. */
+/** The parent note a template created here is filed under. */
const OWNER = { noteId: "owner1" } as FNote;
describe("TemplateSelectionCard", () => {
@@ -74,13 +74,13 @@ describe("TemplateSelectionCard", () => {
.toBe("Pick what a new one is made from.");
});
- /** The grip leads, so the trailing edge is left to what each entry carries there. */
+ /** The grip leads, leaving the trailing edge to the entry's own buttons. */
it("carries the grip at the start of an entry and the way to remove it at the end", async () => {
await draw();
const [ first ] = segments();
expect(first.firstElementChild?.className).toContain("tn-sortable-grip");
- // Inside what the card draws for an entry, which is the rest of the segment.
+ // Inside the segment's content, which is what renderItem draws.
expect(first.querySelector(".tn-sortable-content")?.lastElementChild?.className)
.toContain("template-selection-remove");
});
@@ -99,21 +99,16 @@ describe("TemplateSelectionCard", () => {
act(() => { segments()[0].querySelector<HTMLElement>(".template-selection-remove")?.click(); });
expect(stored).toEqual([ [ "type:code:text/x-markdown" ] ]);
- // And gone from the card, which is drawn from the list this dialog holds rather than from
- // the board it wrote to.
+ // Gone from the card too, which renders from its own state rather than the caller's.
expect(captions()).toEqual([ "Markdown" ]);
- // Nothing to make a card from is nothing the board could make one with, so the way to
- // take the last one away is not offered at all.
+ // An empty list creates nothing, so the last entry offers no way to remove it.
offered = [ "type:text:text/html" ];
await draw();
expect(segments()[0].querySelector(".template-selection-remove")).toBeNull();
});
- /**
- * A template is a note, so it carries the commands a note has. A note type is not, and carries
- * none.
- */
+ /** A template has a note behind it and so carries note commands; a note type does not. */
describe("the commands on a template", () => {
beforeEach(() => {
offered = [ "type:text:text/html", "template:mine" ];
@@ -144,7 +139,7 @@ describe("TemplateSelectionCard", () => {
"bx bx-edit", "bx bx-window-open", "bx bx-outline", "---",
"bx bx-trash destructive-action-icon"
]);
- // The last one deletes the note itself rather than taking it off the list, and says so.
+ // The last entry deletes the note rather than removing it from the list.
expect(items.map((item) => item && "title" in item ? item.title : "---")).toEqual([
"tree-context-menu.open-in-popup", "tree-context-menu.open-in-a-new-window",
"tree-context-menu.duplicate", "---", "note_actions.delete_note"
@@ -167,7 +162,7 @@ describe("TemplateSelectionCard", () => {
press(segments()[1], "Delete");
await act(async () => { await Promise.resolve(); await Promise.resolve(); });
expect(deleted).toHaveBeenCalledWith([ "b_mine" ], false, false);
- // Gone from the list once the note itself is gone.
+ // Taken off the list once the note is deleted.
expect(stored.at(-1)).toEqual([ "type:text:text/html" ]);
});
@@ -203,9 +198,9 @@ describe("TemplateSelectionCard", () => {
.toEqual([ "Text", "My template", "My template (copy)", "Canvas" ]);
});
- /** A note type answers none of those keys, having no note behind it. */
+ /** A note type has no note behind it, so it handles none of those keys. */
it("leaves the keys alone on a note type", async () => {
- // Cleared rather than made: a spy already standing comes back with its calls.
+ // Cleared rather than created: an existing spy is returned with its calls.
const command = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);
command.mockClear();
await draw();
@@ -227,7 +222,7 @@ describe("TemplateSelectionCard", () => {
key: string, items: { key: string }[]
}[];
expect(groups.map((group) => group.key)).toEqual([ "type", "user" ]);
- // What the board already offers is left out, as is everything the app ships.
+ // What the caller already offers is left out, as is everything the app ships.
expect(groups.flatMap((group) => group.items.map((item) => item.key)))
.toEqual([ "type:canvas:application/json", "template:mine" ]);
});
@@ -255,8 +250,31 @@ describe("TemplateSelectionCard", () => {
});
/**
- * The second way in makes a template of its own: a note under the board carrying
- * `#template`, opened for the reader to write, and offered by the board from then on.
+ * Until the read answers, `templates` cannot be resolved, and a creation would be stored
+ * as the whole list.
+ */
+ it("offers no way to create one until it knows what exists", async () => {
+ let answer: (options: NoteTypeOption[]) => void = () => {};
+ vi.mocked(getNoteTypeOptions)
+ .mockReturnValueOnce(new Promise((resolve) => { answer = resolve; }));
+ await draw();
+
+ expect(adders().map((button) => (button as HTMLButtonElement).disabled))
+ .toEqual([ true, true ]);
+
+ await act(async () => {
+ answer(AVAILABLE);
+ await Promise.resolve();
+ });
+
+ expect(adders().map((button) => (button as HTMLButtonElement).disabled))
+ .toEqual([ false, false ]);
+ expect(stored).toEqual([]);
+ });
+
+ /**
+ * The second button creates a template of its own: a note carrying `#template`, opened for
+ * editing and offered from then on.
*/
it("makes a template under the board, and offers it from then on", async () => {
const made = vi.spyOn(note_create, "createTemplateNote").mockResolvedValue({
diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.tsx b/apps/client/src/widgets/react/TemplateSelectionCard.tsx
index 7801031af1..b301ec985d 100644
--- a/apps/client/src/widgets/react/TemplateSelectionCard.tsx
+++ b/apps/client/src/widgets/react/TemplateSelectionCard.tsx
@@ -21,50 +21,49 @@ import {
export interface TemplateSelectionCardProps {
heading: string;
- /** A sentence explaining what the templates are for, shown under the heading. */
+ /** Explains what the templates are for. Shown under the heading. */
instruction: string;
/** The note the templates belong to, and the parent of any created here. */
note: FNote;
/** The title given to a template created here. */
newTemplateName?: string;
- /** The templates on offer, as note type ids, in display order. */
+ /** The templates offered, as note type IDs, in display order. */
templates: string[];
/** Called with the whole list after every change. */
onChange: (templates: string[]) => void;
}
/**
- * The templates a note can be created from, in the order they are offered.
+ * Lists the templates a note can be created from, in the order they are offered.
*
- * 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.
- *
- * The card reads everything a note can be created from itself, so a caller only supplies the
- * current list and where new templates belong.
+ * The reader reorders the list, adds a template the app already offers, or creates one. The caller
+ * supplies the current list through `templates` and stores what `onChange` reports; the card reads
+ * the available templates itself.
*/
export default function TemplateSelectionCard({
heading, instruction, note, newTemplateName, templates, onChange
}: TemplateSelectionCardProps) {
/**
- * The current list, which the card renders from.
- *
- * 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.
+ * The current list, which the card renders from. Held in state because `onChange` writes
+ * through at once and a caller that does not re-render would leave `templates` unchanged.
*/
const [ ids, setIds ] = useState(templates);
/** Everything a note can be created from, kept current as templates are edited. */
const available = useNoteTypeOptions();
/**
- * Templates created here, which the app has yet to report back.
- *
- * 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.
+ * Templates created here that `getNoteTypeOptions()` has not reported yet. Without them a new
+ * template is stored but has nothing to render its entry from.
*/
const [ made, setMade ] = useState<NoteTypeOption[]>([]);
useEffect(() => setIds(templates), [ templates ]);
+ /**
+ * Whether `useNoteTypeOptions()` has answered. The note types alone make it non-empty, so an
+ * empty list means `templates` cannot be resolved and a creation would replace the whole list.
+ */
+ const isRead = available.length > 0;
+
const known = useMemo(
() => [ ...available, ...made.filter((option) => !available.some((a) => a.id === option.id)) ],
[ available, made ]);
@@ -87,7 +86,7 @@ export default function TemplateSelectionCard({
onChange(next);
}, [ ids, onChange ]);
- /** What the menu on a template does to the list, the rest acting on the note alone. */
+ /** How the template menu changes the list. Its other commands act on the note alone. */
const commands = useMemo<TemplateCommands>(() => ({
onDuplicated: (sourceNoteId, copy) => {
const source = offered.find(
@@ -101,7 +100,7 @@ export default function TemplateSelectionCard({
};
setMade((was) => [ ...was, option ]);
- // Beside what it was copied from, which is where a copy is looked for.
+ // Directly after the template it was copied from.
const at = source ? ids.indexOf(source.id) : -1;
const next = [ ...ids ];
next.splice(at < 0 ? ids.length : at + 1, 0, option.id);
@@ -111,7 +110,7 @@ export default function TemplateSelectionCard({
onDeleted: (noteId) => drop(buildTemplateId(noteId))
}), [ drop, ids, offered, onChange ]);
- /** Asks which of the templates not already offered to add, and returns it as an entry. */
+ /** Asks which template 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({
@@ -150,7 +149,7 @@ export default function TemplateSelectionCard({
description={instruction}
items={items}
onChange={store}
- // The grip leads, so the trailing edge is left to what each entry carries there.
+ // The grip leads, leaving the trailing edge to the menu and remove buttons.
gripPlacement="start"
onItemKeyDown={(item, event) => {
const noteId = templateNoteId(item.key);
@@ -171,7 +170,7 @@ export default function TemplateSelectionCard({
{item.icon && <Icon icon={item.icon} />}
<span className="template-selection-name">{item.caption}</span>
- {/* Only a template is a note, and only a note has commands of its own. */}
+ {/* Only a template has a note behind it, so only it carries note commands. */}
{templateNoteId(item.key) && (
<ActionButton
className="template-selection-menu"
@@ -187,8 +186,7 @@ export default function TemplateSelectionCard({
/>
)}
- {/* The last template is not removable: with none offered, nothing could be
- created. */}
+ {/* The last template cannot be removed: an empty list creates nothing. */}
{items.length > 1 && (
<ActionButton
className="template-selection-remove"
@@ -206,11 +204,13 @@ export default function TemplateSelectionCard({
{
label: t("template_selection.add-existing"),
icon: "bx bx-list-plus",
+ disabled: !isRead,
onCreateItem: addExisting
},
{
label: t("template_selection.create"),
icon: "bx bx-plus",
+ disabled: !isRead,
onCreateItem: create
}
]}
@@ -219,10 +219,8 @@ export default function TemplateSelectionCard({
}
/**
- * What can still be added, as groups for the picker.
- *
- * 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.
+ * Groups what can still be added for the picker. Templates the app ships are left out: they are a
+ * starting point for a template of your 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/packages/commons/src/lib/script_api_preact.ts b/packages/commons/src/lib/script_api_preact.ts
index 2b08679698..b797aa93a8 100644
--- a/packages/commons/src/lib/script_api_preact.ts
+++ b/packages/commons/src/lib/script_api_preact.ts
@@ -413,6 +413,8 @@ interface SortableItem {
interface ItemCreationButton<T extends SortableItem> {
label: string;
icon?: string;
+ /** Turns the button off, for a caller that cannot make an entry yet. */
+ disabled?: boolean;
onCreateItem: () => T | undefined | Promise<T | undefined>;
}
interface SortableCardProps<T extends SortableItem> {
@@ -426,6 +428,8 @@ interface SortableCardProps<T extends SortableItem> {
itemCreationButtons?: ItemCreationButton<T>[];
/** Which edge of a segment the grip stands on. The trailing one by default. */
gripPlacement?: "start" | "end";
+ /** Called with the focused entry for a key the card does not handle itself. */
+ onItemKeyDown?: (item: T, event: KeyboardEvent) => void;
selectedKey?: string;
onSelect?: (key: string) => void;
heading?: string;