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/collections/board: some issues
Adorian Doran80541f2aaea4
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 8a0d6c14ff..e729624d2b 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -629,7 +629,7 @@ export default class BoardApi {};}- /** Sets what a column sorts by. Pass `undefined` for the order the user arranges by hand. */+ /** Sets what a column sorts by. Pass `undefined` for the manual order. */async setColumnSort(column: string, orderBy: SortKey | undefined) {await this.updateColumn(column, { orderBy });}@@ -1166,14 +1166,14 @@ export default class BoardApi {return attributes.removeOwnedLabelByName(note, this.statusAttribute);}- /** Whether a column orders its own cards, which leaves no place for a move to name. */+ /** Whether a column orders its own cards rather than keeping the order the user set. */isColumnSorted(column: string) {return !!this.getColumnSort(column).orderBy;}/** Moves a card to the end of another column, where a card sent by the keyboard belongs. */async moveToColumnEnd(noteId: string, branchId: string, targetColumn: string) {- // A sorted column places the card itself, so only the value it carries is written.+ // Only the grouping value is written: `sortColumnMap` decides where the card is drawn.if (this.isColumnSorted(targetColumn)) {await this.changeColumn(noteId, targetColumn);return;@@ -1246,9 +1246,8 @@ export default class BoardApi {const note = froca.getNoteFromCache(noteId);if (!note) return;- // A sorted column places its own cards, so a move into or inside one writes the value- // alone. The branch order is left as it stands, which is the order the reader arranged- // and the one the column goes back to when it is sorted by hand again.+ // A move into or inside a sorted column writes the grouping value and no branch+ // position. Clearing `orderBy` then restores the arrangement the user made.const isSortedTarget = this.isColumnSorted(targetColumn);if (sourceColumn !== targetColumn) {diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 7dc2623a21..4df6ae4ed7 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -116,12 +116,11 @@ export default function Column({/** The note limit, absent if disabled. */limit?: number,/**- * How the column orders its own cards, absent while the reader arranges them. A sorted column- * places a dropped card itself, so it opens no gap for a carried one and offers nothing that- * would put a card in a chosen place.+ * How the column orders its cards, absent for the manual order. A sorted column opens no drop+ * gap and offers no control that puts a card at a chosen index.*/sort?: ColumnSort,- /** The card just dropped here, which is revealed where the sort put it. */+ /** The card just dropped here, drawn with the `appearing` reveal. */landedNoteId?: string,/*** How many cards the column really holds, when an active filter leaves `columnItems` with@@ -162,7 +161,7 @@ export default function Column({isSortedRef.current = isSorted;/** Opens the field at a place among the cards, which is the index the card it makes takes. */const beginInsert = useCallback((index: number) => {- // A sorted column decides where a card goes, so there is no place to open a field at.+ // A sorted column has no index to insert at.if (isSortedRef.current) {return;}@@ -192,10 +191,9 @@ export default function Column({// Asked about this column alone: where the gap stands changes on every step of a drag, and a// column that the answer does not concern is left as it is rather than drawn again.const standingDropIndex = useDropIndex(column);- // A sorted column shows only its border, since the card lands where the sort puts it. The- // column the card was picked up from keeps the hole it left, which the cards below would- // otherwise close up for the length of the gesture. The gap stands before the card whose- // place it names, so the carried card's own place is the one after it.+ // A sorted column draws only its border, since `sortColumnMap` decides where the card lands.+ // The source column keeps the gap at the lifted card's own index, or the cards below close up+ // for the length of the gesture. A gap stands before the card it indexes, hence the `+ 1`.const dropIndex = !isSorted? standingDropIndex: (draggedCard?.fromColumn === column ? draggedCard.index + 1 : null);@@ -248,8 +246,8 @@ export default function Column({// Read before anything is written, and `offsetTop` is no business of a transform anyway.if (dropIndex !== null) {const standing = cards[dropIndex];- // The carried card is taken out of the flow, so a gap past the last one is measured- // against the last card still laid out.+ // `lift()` sets `display: none` on the carried card, so a gap past the last one+ // measures against the last card still laid out.const drawn = [ ...cards ].filter(card => card.style.display !== "none");const last = drawn[drawn.length - 1];const top = standing@@ -396,21 +394,20 @@ export default function Column({setActiveColumn(isPeeked ? column : undefined);}, [ column, isActive, isPeeked, setActiveColumn ]);- // Shown only while the column sorts itself, so its absence is what says the order is the- // reader's own. The arrow says which way the order runs.+ // Only for a sorted column. The arrow shows which way the order runs.const sortButton = sort && (<ActionButtonclassName="column-sort"icon={sort.isDescending ? "bx bx-sort-down" : "bx bx-sort-up"}text={t("board_view.sort")}- // A strip has room to say which way the order runs but not to be worked in: the menu- // it would open stands where the column is about to widen.+ // Disabled on a strip: the menu would open over the space the column is about to+ // take as it widens.disabled={isCollapsed}onClick={(e) => {// The heading is the column's drag handle and opens its own menu on a right// click; neither should also fire from the button.e.stopPropagation();- openColumnSortMenu(api, e.pageX, e.pageY, column);+ openColumnSortMenu(api, ...menuOrigin(e), column);}}/>);@@ -684,9 +681,8 @@ export default function Column({{/* Both stand here for the length of the board's life: an element appearingamong the cards, or leaving them, is what a drag cannot afford. */}<div ref={gapRef} className="board-drop-placeholder">- {/* The gap a sorted column holds open is the one the card came out of, and it- stays there: nothing the reader does moves the card to another place in- this column. */}+ {/* The gap is the one the lifted card left, and it does not follow the+ pointer. */}{isSorted && (<span className="sorted-no-reorder">{t("board_view.sorted-no-reorder")}@@ -718,6 +714,19 @@ export default function Column({* @param transform what to write, or `null` to put the card back where the column draws it.* @param atOnce whether the card is already standing where it is being put, as at a lift or a drop.*/+/**+ * Where a menu opened from a button belongs: at the pointer, or against the button itself when a+ * keyboard press opened it and carries no pointer position.+ */+function menuOrigin(e: JSX.TargetedMouseEvent<HTMLElement>): [ number, number ] {+ if (e.detail) {+ return [ e.pageX, e.pageY ];+ }++ const box = e.currentTarget.getBoundingClientRect();+ return [ box.right + window.scrollX, box.bottom + window.scrollY ];+}+export function placeCard(card: HTMLElement, transform: string | null, atOnce: boolean) {if (atOnce) {card.style.transition = "none";@@ -965,7 +974,7 @@ function useDragging({isEditing: boolean,api: BoardApi,parentNote: FNote,- /** Names a card a sorted column has just placed, which is revealed where it went. */+ /** Reports a card a sorted column placed, for the `appearing` reveal. */onLanded: (noteId: string) => void}) {const { setDraggedColumn, setDropTarget, setDropPosition, setActiveColumn } =@@ -1090,8 +1099,7 @@ function useDragging({await branches.moveAfterBranch([ branchId ], targetBranch.branchId);}- // The reader dropped the card on the column rather than at a place in it, so the- // reveal is what says where the sort put it.+ // The drop named a column, not an index, so the reveal shows where it landed.if (isSorted) {onLanded(noteId);}diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex 1332066565..c901dabbbd 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -98,8 +98,8 @@ export function resolveColumnSorts(columns: BoardColumnData[] | undefined) {/*** The columns with each sorted one in its own order.*- * The map and every column array are handed back unchanged where nothing moves, so a board with- * no sorted column costs one lookup per column and a card that has not moved is not drawn again.+ * Returns the same map, and the same array per column, where nothing moves. `Column` reads a fresh+ * array as its cards having moved and re-measures every one of them, so the identities matter.*/export function sortColumnMap(byColumn: ColumnMap, sorts: ReadonlyMap<string, ColumnSort>, context: SortContext@@ -159,9 +159,9 @@ export function resolveSortWatch(/*** Whether a change can move a card in a sorted column.*- * Answered broadly: a card whose content was saved reports a note row like a renamed one does, and- * {@link sortColumnMap} hands back the same arrays when the sort finds nothing to move, so a- * needless re-sort draws nothing.+ * Deliberately broad: an autosave reports a note row just as a rename does, and+ * {@link sortColumnMap} returns the same arrays when nothing moves, so a needless re-sort renders+ * nothing.*/export function affectsSortOrder(loadResults: LoadResults, watch: SortWatch) {if (!watch.noteIds.size) {diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex a76cad4781..5033784680 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -3629,6 +3629,22 @@ describe("a column that sorts its cards", () => {expect(board.querySelector(".board-column h3 .column-sort")).toBeNull();});+ /** A keyboard press carries no pointer position, which would put the menu at the origin. */+ it("opens the menu against the button when a keyboard presses it", async () => {+ const { board } = await renderSortedBoard({ orderBy: "title" });+ const button = sortButton(board);+ if (!button) throw new Error("expected a sort button");+ button.getBoundingClientRect = () =>+ ({ right: 320, bottom: 48 }) as DOMRect;++ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});+ // `detail` is 0 for the click a keyboard synthesises, and the coordinates are 0 with it.+ button.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 0 }));++ expect(show.mock.calls.at(-1)?.[0]).toMatchObject({ x: 320, y: 48 });+ show.mockRestore();+ });+/** A strip is too narrow to work in, and the menu would stand where it is about to widen. */it("shows the button on a strip, with nothing to be done to it", async () => {const { board } = await renderSortedBoard({ orderBy: "title", collapsed: true });diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 24017d8b43..7039546a6a 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -298,10 +298,9 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC/** The column just added, which is revealed once the board has drawn it. */const [ createdColumn, setCreatedColumn ] = useState<string>();/**- * The card just dropped on a sorted column, which is shown the way a new one is.+ * The card just dropped on a sorted column, drawn with the same reveal a new card gets.*- * The column places it rather than the reader, so it can land anywhere among the cards, and- * the reveal is what says where it went.+ * `sortColumnMap` can put it anywhere among the cards, so the reveal is how the user finds it.*/const [ landedNoteId, setLandedNoteId ] = useState<string>();/**@@ -518,9 +517,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC/** Until when a column move can still be settling, which is when `useFlip` slides columns. */const columnMovedUntil = useRef(0);- // Neither the creation dates the tie-break reads nor the notes a sorted relation points at- // are loaded with the board. Both are fetched here, and the board is drawn again once they- // arrive.+ // Neither the creation dates the tie-break needs nor the targets of a sorted relation come+ // with the board. Both are fetched here, and `sortRevision` redraws it once they land.useEffect(() => {if (!sortWatch.noteIds.size) {return;@@ -696,7 +694,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCcloseGaps(containerRef.current);const branchId = byColumn?.get(card.fromColumn)?.[card.index]?.branch.branchId;const isSortedTarget = !!position && columnSorts.has(position.column);- // A card let go of over its own sorted column stands where the sort already puts it.+ // A drop inside a sorted column changes nothing: `sortColumnMap` already placed it.if (isSortedTarget && position?.column === card.fromColumn) {setDraggedCard(null);dropState.set({ position: null, target: null });@@ -707,8 +705,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCif (position && branchId && byColumn && allByColumn) {// Drawn at once, into `allByColumn` since that is what `byColumn` derives from, at// the index `unfilteredCardIndex` translates rather than the visible drop index.- // A sorted column takes the card at any index: `sortColumnMap` runs afterwards and- // places it.+ // The index does not matter for a sorted column: `sortColumnMap` reorders the+ // map afterwards.setAllByColumn(applyCardMove(allByColumn, card.noteId, card.fromColumn, position.column,unfilteredCardIndex(@@ -927,7 +925,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC}// `findRefreshReason` ignores a note row, since a card keeps its own title in step. A- // column sorting by title still has to reorder, which this does without a full refresh.+ // column sorting by title still has to reorder, and this does it without a refresh.if (affectsSortOrder(loadResults, sortWatch)) {setSortRevision(revision => revision + 1);}diff --git a/apps/client/src/widgets/collections/sort_menu.ts b/apps/client/src/widgets/collections/sort_menu.tsindex f6d5d7417d..8f3c4c22f1 100644--- a/apps/client/src/widgets/collections/sort_menu.ts+++ b/apps/client/src/widgets/collections/sort_menu.ts@@ -24,8 +24,8 @@ export interface SortMenuOptions {/*** The entries a collection offers for how it orders its items.*- * Built as a submenu for the caller to hang wherever it belongs. The direction sits at the foot,- * disabled while nothing is sorted.+ * A submenu for the caller to hang wherever it belongs. The direction sits at the foot, disabled+ * while nothing is sorted.*/export function buildSortMenuItems<T>({orderBy, isDescending, attributes, noneTitle, onSelect, onDirectionChange@@ -52,8 +52,8 @@ export function buildSortMenuItems<T>({handler: () => onSelect("creationDate")},...attributes.map<MenuItem<T>>((attribute) => ({- // The menu reads a title as markup, and an alias is the user's own text. The box is- // what clips a long one rather than letting it widen the menu.+ // The menu reads a title as markup, and an alias is the user's own text. The box+ // clips a long one instead of widening the menu.title: `<span class="sort-menu-name">${escapeHtml(attribute.title)}</span>`,className: "sort-menu-item",uiIcon: promotedAttributeType(attribute).icon,diff --git a/apps/client/src/widgets/collections/sorting.spec.ts b/apps/client/src/widgets/collections/sorting.spec.tsindex ddadf8d4c3..f2c3fdd42a 100644--- a/apps/client/src/widgets/collections/sorting.spec.ts+++ b/apps/client/src/widgets/collections/sorting.spec.ts@@ -67,9 +67,13 @@ describe("sortItems", () => {const numbers = build([{ title: "A", "#field": "10" },{ title: "B", "#field": "9" },- { title: "C", "#field": "-3.5" }+ { title: "C", "#field": "-3.5" },+ // Imported values are not always what the field would have written. A value that is+ // only partly a number is no number at all.+ { title: "D", "#field": "1-2" }]);- expect(titles(sort(numbers, "attr:field", false, "number"))).toEqual([ "C", "B", "A" ]);+ expect(titles(sort(numbers, "attr:field", false, "number")))+ .toEqual([ "C", "B", "A", "D" ]);});it("sorts dates, date-times and times by the instant they name", () => {diff --git a/apps/client/src/widgets/collections/sorting.ts b/apps/client/src/widgets/collections/sorting.tsindex d51b8c5b61..3b3a4c1e09 100644--- a/apps/client/src/widgets/collections/sorting.ts+++ b/apps/client/src/widgets/collections/sorting.ts@@ -46,8 +46,8 @@ export function sortedAttributeName(key: SortKey) {/*** Orders items by one key, breaking ties on the creation date and then on the given order.*- * An item with no value for the key sorts last in both directions. Returns the same array when- * the items are already in order, so a caller can compare identities.+ * An item with no value for the key sorts last in both directions. Returns the same array when the+ * items are already in order, so a caller can compare identities.*/export function sortItems<T extends { note: FNote }>(items: T[], key: SortKey, isDescending: boolean, context: SortContext@@ -108,7 +108,7 @@ function sortValueOf(note: FNote, key: SortKey, context: SortContext): SortValuereturn targetId ? context.noteTitle(targetId) ?? targetId : undefined;}- // Uses the first value of a multi-value attribute, which is the one a card draws.+ // The first value of a multi-value attribute, which is the one an item draws.const label = note.getLabel(name);if (!label) {return undefined;@@ -125,7 +125,9 @@ function sortValueOf(note: FNote, key: SortKey, context: SortContext): SortValuefunction labelValueOf(value: string, definition: PromotedAttribute | undefined): SortValue {switch (definition?.labelType) {case "number":- return toNumber(parseFloat(value));+ // `Number` rather than `parseFloat`, which would read "1-2" as 1 and sort it among+ // the valid numbers.+ return toNumber(Number(value));case "date":case "datetime":return toNumber(Date.parse(value));@@ -141,18 +143,18 @@ function labelValueOf(value: string, definition: PromotedAttribute | undefined):}/**- * Where a value stands among the options a select offers, so the field is read in the order it was- * defined in rather than alphabetically: `options=Low;Medium;High;Urgent` sorts by rank.+ * Where a value stands among the options a select offers, so `options=Low;Medium;High;Urgent`+ * sorts by rank rather than alphabetically.*/function optionIndex(value: string, options: string[] | undefined): SortValue {if (!options?.length) {- // A select that offers nothing has no order of its own, so the values compare as text.+ // With no options declared there is no order to follow, so the values compare as text.return value;}const at = options.indexOf(value);// A value the definition no longer offers sorts after every option it does, rather than with- // the cards that carry no value at all.+ // the items that have no value.return at >= 0 ? at : options.length;}