Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: add support for sorting the cards within a column

Adorian Doranfc266d74aa2f
diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.ts
index 75fe3a165e..f5df4f0284 100644
--- a/apps/client/src/widgets/collections/board/data.spec.ts
+++ b/apps/client/src/widgets/collections/board/data.spec.ts
@@ -2,9 +2,14 @@ import { describe, expect, it } from "vitest";
import FBranch from "../../../entities/fbranch";
import froca from "../../../services/froca";
+import LoadResults from "../../../services/load_results";
+import type { EntityChange } from "../../../server_types";
import { buildNote } from "../../../test/easy-froca";
+import type { PromotedAttribute } from "../promoted_attributes";
+import type { SortContext, SortKey } from "../sorting";
import {
- applyCardMove, type ColumnMap, filterColumnMap, getBoardData, unfilteredCardIndex
+ affectsSortOrder, applyCardMove, type ColumnMap, type ColumnSort, filterColumnMap,
+ getBoardData, resolveColumnSorts, resolveSortWatch, sortColumnMap, unfilteredCardIndex
} from "./data";
describe("applyCardMove", () => {
@@ -455,3 +460,210 @@ describe("the inbox column", () => {
.toEqual([ "Deep", "Unfiled" ]);
});
});
+
+describe("sorting the cards of a column", () => {
+ describe("resolveColumnSorts", () => {
+ it("reads the columns that sort, and leaves out the ones that do not", () => {
+ const sorts = resolveColumnSorts([
+ { value: "To Do", orderBy: "title" },
+ { value: "Doing" },
+ { value: "Done", orderBy: "attr:dueDate", descendingOrder: true },
+ { value: "Later", orderBy: "dateModified" }
+ ]);
+
+ expect([ ...sorts.keys() ]).toEqual([ "To Do", "Done" ]);
+ expect(sorts.get("To Do")).toEqual({ orderBy: "title", isDescending: false });
+ expect(sorts.get("Done")).toEqual({ orderBy: "attr:dueDate", isDescending: true });
+ });
+
+ it("reads a board with no stored columns as one that sorts nothing", () => {
+ expect(resolveColumnSorts(undefined).size).toBe(0);
+ });
+ });
+
+ describe("sortColumnMap", () => {
+ it("orders only the columns that ask for it, in the direction they ask for", () => {
+ const board = cards({ A: [ "Beta", "Alpha" ], B: [ "Delta", "Charlie" ] });
+ const sorted = sortColumnMap(board, sortedBy({ A: "title" }), context());
+
+ expect(titles(sorted, "A")).toEqual([ "Alpha", "Beta" ]);
+ expect(titles(sorted, "B")).toEqual([ "Delta", "Charlie" ]);
+
+ const descending = sortColumnMap(board, sortedBy({ A: "title" }, true), context());
+ expect(titles(descending, "A")).toEqual([ "Beta", "Alpha" ]);
+ });
+
+ /**
+ * The identities are what keeps a sorted board as cheap as an unsorted one: `Column` reads
+ * a fresh array as its cards having moved and measures every one of them.
+ */
+ it("hands back the same map when no column sorts", () => {
+ const board = cards({ A: [ "Beta", "Alpha" ] });
+
+ expect(sortColumnMap(board, new Map(), context())).toBe(board);
+ });
+
+ it("hands back the same map when every sorted column is already in order", () => {
+ const board = cards({ A: [ "Alpha", "Beta" ] });
+
+ expect(sortColumnMap(board, sortedBy({ A: "title" }), context())).toBe(board);
+ });
+
+ it("keeps the array of every column it does not reorder", () => {
+ const board = cards({ A: [ "Beta", "Alpha" ], B: [ "Delta", "Charlie" ] });
+ const sorted = sortColumnMap(board, sortedBy({ A: "title" }), context());
+
+ expect(sorted).not.toBe(board);
+ expect(sorted.get("A")).not.toBe(board.get("A"));
+ expect(sorted.get("B")).toBe(board.get("B"));
+ });
+
+ it("leaves a column the board no longer holds alone", () => {
+ const board = cards({ A: [ "Alpha" ] });
+
+ expect(sortColumnMap(board, sortedBy({ Gone: "title" }), context())).toBe(board);
+ });
+ });
+
+ describe("resolveSortWatch", () => {
+ it("watches the cards of the sorted columns and the attributes they sort by", () => {
+ const board = cards({ A: [ "Alpha", "Beta" ], B: [ "Charlie" ] });
+ const watch = resolveSortWatch(board, sortedBy({ A: "attr:dueDate" }), new Map());
+
+ expect(watch.noteIds).toEqual(new Set(noteIdsOf(board, "A")));
+ expect(watch.attributeNames).toEqual(new Set([ "dueDate" ]));
+ expect(watch.targetNoteIds.size).toBe(0);
+ });
+
+ it("watches the note a relation points at, whose title the sort reads", () => {
+ const owner = buildNote({ title: "Owner" });
+ const board = cards({ A: [ { title: "Alpha", "~owner": owner.noteId } ] });
+ const watch = resolveSortWatch(
+ board, sortedBy({ A: "attr:owner" }), definitions("owner", "relation"));
+
+ expect(watch.targetNoteIds).toEqual(new Set([ owner.noteId ]));
+ });
+
+ it("watches nothing while no column sorts", () => {
+ const watch = resolveSortWatch(cards({ A: [ "Alpha" ] }), new Map(), new Map());
+
+ expect(watch.noteIds.size).toBe(0);
+ expect(watch.attributeNames.size).toBe(0);
+ });
+ });
+
+ describe("affectsSortOrder", () => {
+ it("answers for a note the sort reads, and for one it does not", () => {
+ const board = cards({ A: [ "Alpha" ], B: [ "Beta" ] });
+ const watch = resolveSortWatch(board, sortedBy({ A: "title" }), new Map());
+ const [ sorted ] = noteIdsOf(board, "A");
+ const [ unsorted ] = noteIdsOf(board, "B");
+
+ expect(affectsSortOrder(changes({ notes: [ sorted ] }), watch)).toBe(true);
+ expect(affectsSortOrder(changes({ notes: [ unsorted ] }), watch)).toBe(false);
+ });
+
+ it("answers for the note a sorted relation points at", () => {
+ const owner = buildNote({ title: "Owner" });
+ const board = cards({ A: [ { title: "Alpha", "~owner": owner.noteId } ] });
+ const watch = resolveSortWatch(
+ board, sortedBy({ A: "attr:owner" }), definitions("owner", "relation"));
+
+ expect(affectsSortOrder(changes({ notes: [ owner.noteId ] }), watch)).toBe(true);
+ });
+
+ it("answers for the attribute a column sorts by, and for no other", () => {
+ const board = cards({ A: [ "Alpha" ] });
+ const watch = resolveSortWatch(board, sortedBy({ A: "attr:dueDate" }), new Map());
+ const [ card ] = noteIdsOf(board, "A");
+
+ expect(affectsSortOrder(changes({ attributes: [ [ "dueDate", card ] ] }), watch))
+ .toBe(true);
+ expect(affectsSortOrder(changes({ attributes: [ [ "owner", card ] ] }), watch))
+ .toBe(false);
+ expect(affectsSortOrder(changes({ attributes: [ [ "dueDate", "stranger" ] ] }), watch))
+ .toBe(false);
+ });
+
+ it("answers no for every change while nothing is sorted", () => {
+ const board = cards({ A: [ "Alpha" ] });
+ const watch = resolveSortWatch(board, new Map(), new Map());
+ const [ card ] = noteIdsOf(board, "A");
+
+ expect(affectsSortOrder(changes({ notes: [ card ] }), watch)).toBe(false);
+ });
+ });
+});
+
+/** One card, either by title alone or with the single attribute a test gives it. */
+type CardDraft = string | { title: string, "#field"?: string, "~owner"?: string };
+
+function cards(columns: Record<string, CardDraft[]>): ColumnMap {
+ return new Map(Object.entries(columns).map(([ column, drafts ]) => [
+ column,
+ drafts.map((draft) => {
+ const note = buildNote(typeof draft === "string" ? { title: draft } : draft);
+ return { note, branch: { branchId: `b_${note.noteId}` } as FBranch };
+ })
+ ]));
+}
+
+function sortedBy(byColumn: Record<string, string>, isDescending = false) {
+ return new Map<string, ColumnSort>(Object.entries(byColumn)
+ .map(([ column, orderBy ]) => [ column, { orderBy: orderBy as SortKey, isDescending } ]));
+}
+
+function definitions(name: string, type: "label" | "relation") {
+ return new Map<string, PromotedAttribute>([ [ name, {
+ name,
+ definitionName: `${type}:${name}`,
+ type,
+ title: name,
+ hidden: false,
+ definitionValue: "",
+ isOwned: true,
+ isInheritable: true
+ } ] ]);
+}
+
+function context(): SortContext {
+ return {
+ definitions: new Map(),
+ creationDate: () => undefined,
+ noteTitle: (noteId) => froca.notes[noteId]?.title
+ };
+}
+
+function titles(map: ColumnMap, column: string) {
+ return (map.get(column) ?? []).map(({ note }) => note.title);
+}
+
+function noteIdsOf(map: ColumnMap, column: string) {
+ return (map.get(column) ?? []).map(({ note }) => note.noteId);
+}
+
+/** Builds the `LoadResults` a websocket message would produce. See `refresh_reason.spec.ts`. */
+function changes({ notes = [], attributes = [] }: {
+ notes?: string[];
+ /** `[ name, noteId ]` pairs. */
+ attributes?: [ string, string ][];
+}) {
+ const entityChanges = attributes.map(([ name, noteId ], index) => entityChange(
+ `attr${index}`, { attributeId: `attr${index}`, name, noteId }));
+
+ const results = new LoadResults(entityChanges);
+ for (const noteId of notes) {
+ results.addNote(noteId, "componentId");
+ }
+ for (const [ index ] of attributes.entries()) {
+ results.addAttribute(`attr${index}`, "componentId");
+ }
+
+ return results;
+}
+
+function entityChange(entityId: string, entity: object): EntityChange {
+ return {
+ entityName: "attributes", entityId, entity, hash: "", isSynced: true, isErased: false
+ };
+}
diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.ts
index ec809fc910..1332066565 100644
--- a/apps/client/src/widgets/collections/board/data.ts
+++ b/apps/client/src/widgets/collections/board/data.ts
@@ -1,5 +1,10 @@
import FBranch from "../../../entities/fbranch";
import FNote from "../../../entities/fnote";
+import type LoadResults from "../../../services/load_results";
+import type { PromotedAttribute } from "../promoted_attributes";
+import {
+ parseSortKey, sortedAttributeName, sortItems, type SortContext, type SortKey
+} from "../sorting";
import { INBOX_COLUMN, resolveBoardColumns } from "./columns";
import { BoardColumnData, BoardViewData } from "./index";
@@ -60,6 +65,119 @@ export function filterColumnMap(
return filtered;
}
+/** How one column orders its cards. */
+export interface ColumnSort {
+ orderBy: SortKey;
+ isDescending: boolean;
+}
+
+/** What a sorted board reads, so it can be reloaded and watched for changes. */
+export interface SortWatch {
+ /** The cards in sorted columns, whose creation dates the tie-break reads. */
+ noteIds: Set<string>;
+ /** The relation targets whose titles a column sorts by. */
+ targetNoteIds: Set<string>;
+ /** The attribute names the columns sort by. */
+ attributeNames: Set<string>;
+}
+
+/** What each column sorts by, leaving out every column that keeps the manual order. */
+export function resolveColumnSorts(columns: BoardColumnData[] | undefined) {
+ const sorts = new Map<string, ColumnSort>();
+
+ for (const { value, orderBy, descendingOrder } of columns ?? []) {
+ const key = parseSortKey(orderBy);
+ if (key) {
+ sorts.set(value, { orderBy: key, isDescending: !!descendingOrder });
+ }
+ }
+
+ return sorts;
+}
+
+/**
+ * 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.
+ */
+export function sortColumnMap(
+ byColumn: ColumnMap, sorts: ReadonlyMap<string, ColumnSort>, context: SortContext
+): ColumnMap {
+ let sorted: ColumnMap | undefined;
+
+ for (const [ column, { orderBy, isDescending } ] of sorts) {
+ const items = byColumn.get(column);
+ if (!items) {
+ continue;
+ }
+
+ const ordered = sortItems(items, orderBy, isDescending, context);
+ if (ordered !== items) {
+ sorted ??= new Map(byColumn);
+ sorted.set(column, ordered);
+ }
+ }
+
+ return sorted ?? byColumn;
+}
+
+/**
+ * The notes a sorted board reads, and the attributes it reads off them.
+ *
+ * @param definitions the board's promoted attributes by name, which say which keys are relations.
+ */
+export function resolveSortWatch(
+ byColumn: ColumnMap | undefined,
+ sorts: ReadonlyMap<string, ColumnSort>,
+ definitions: ReadonlyMap<string, PromotedAttribute>
+): SortWatch {
+ const noteIds = new Set<string>();
+ const targetNoteIds = new Set<string>();
+ const attributeNames = new Set<string>();
+
+ for (const [ column, { orderBy } ] of sorts) {
+ const name = sortedAttributeName(orderBy);
+ const relation = name && definitions.get(name)?.type === "relation" ? name : undefined;
+ if (name) {
+ attributeNames.add(name);
+ }
+
+ for (const { note } of byColumn?.get(column) ?? []) {
+ noteIds.add(note.noteId);
+
+ const target = relation && note.getRelationValue(relation);
+ if (target) {
+ targetNoteIds.add(target);
+ }
+ }
+ }
+
+ return { noteIds, targetNoteIds, attributeNames };
+}
+
+/**
+ * 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.
+ */
+export function affectsSortOrder(loadResults: LoadResults, watch: SortWatch) {
+ if (!watch.noteIds.size) {
+ return false;
+ }
+
+ const isWatched = (noteId: string) =>
+ watch.noteIds.has(noteId) || watch.targetNoteIds.has(noteId);
+ if (loadResults.getNoteIds().some(isWatched)) {
+ return true;
+ }
+
+ return loadResults.getAttributeRows().some(attr =>
+ watch.attributeNames.has(attr.name ?? "") && watch.noteIds.has(attr.noteId ?? ""));
+}
+
/**
* Where a card dropped among the cards on screen goes in the full column.
*
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index eb66738311..2ca6355ee8 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -3502,3 +3502,139 @@ describe("Board filtering", () => {
expect(marks.map(el => el.textContent)).toEqual([ "First" ]);
});
});
+
+describe("a column that sorts its cards", () => {
+ let container: HTMLElement | undefined;
+
+ beforeEach(() => {
+ vi.spyOn(server, "post").mockImplementation(async (url) =>
+ (url === "notes/metadata" ? {} : undefined));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ it("draws the sorted column in its own order and the others in branch order", async () => {
+ const { board } = await renderSortedBoard({ orderBy: "title" });
+
+ expect(cardTitlesIn(board, 0)).toEqual([ "Alpha", "Beta", "Delta" ]);
+ expect(cardTitlesIn(board, 1)).toEqual([ "Zulu", "Yankee" ]);
+ });
+
+ it("draws it backwards when the column asks for that", async () => {
+ const { board } = await renderSortedBoard({ orderBy: "title", descendingOrder: true });
+
+ expect(cardTitlesIn(board, 0)).toEqual([ "Delta", "Beta", "Alpha" ]);
+ });
+
+ it("leaves every column in branch order while none of them sorts", async () => {
+ const { board } = await renderSortedBoard({});
+
+ expect(cardTitlesIn(board, 0)).toEqual([ "Delta", "Beta", "Alpha" ]);
+ });
+
+ it("asks for no creation dates at all while no column sorts", async () => {
+ await renderSortedBoard({});
+
+ expect(server.post).not.toHaveBeenCalledWith("notes/metadata", expect.anything());
+ });
+
+ it("draws the column again when a title it sorts by changes", async () => {
+ const { board, host, cards } = await renderSortedBoard({ orderBy: "title" });
+
+ cards.beta.title = "Omega";
+ await act(async () => {
+ await host.handleEvent("entitiesReloaded",
+ { loadResults: noteRenamed(cards.beta.noteId, "Omega") });
+ await flush();
+ });
+
+ expect(cardTitlesIn(board, 0)).toEqual([ "Alpha", "Delta", "Omega" ]);
+ });
+
+ it("sorts by a promoted attribute, keeping the cards that have no value last", async () => {
+ const { board } = await renderSortedBoard({ orderBy: "attr:priority" }, {
+ "#label:priority(inheritable)": "promoted,single,number",
+ values: { Alpha: "3", Beta: "1" }
+ });
+
+ expect(cardTitlesIn(board, 0)).toEqual([ "Beta", "Alpha", "Delta" ]);
+ });
+
+ /** The note row a rename produces, which is what the card reads its new title from. */
+ function noteRenamed(noteId: string, title: string) {
+ const results = new LoadResults([ {
+ entityName: "notes",
+ entityId: noteId,
+ entity: { noteId, title }
+ } as never ]);
+ results.addNote(noteId, "other");
+ return results;
+ }
+
+ function cardTitlesIn(board: HTMLElement, column: number) {
+ const columns = [ ...board.querySelectorAll(".board-column") ];
+ return [ ...columns[column].querySelectorAll(".board-note .title") ]
+ .map(el => el.textContent);
+ }
+
+ async function renderSortedBoard(
+ sort: { orderBy?: string, descendingOrder?: boolean },
+ promoted?: { "#label:priority(inheritable)": string, values: Record<string, string> }
+ ) {
+ const priorities = promoted?.values ?? {};
+ const note = buildNote({
+ title: "Board",
+ "#collection": "",
+ "#viewType": "board",
+ ...(promoted
+ ? { "#label:priority(inheritable)": promoted["#label:priority(inheritable)"] }
+ : {}),
+ children: [
+ { title: "Delta", "#status": "To Do", ...priorityOf("Delta") },
+ { title: "Beta", "#status": "To Do", ...priorityOf("Beta") },
+ { title: "Alpha", "#status": "To Do", ...priorityOf("Alpha") },
+ { title: "Zulu", "#status": "Done" },
+ { title: "Yankee", "#status": "Done" }
+ ]
+ });
+
+ function priorityOf(title: string): Record<string, string> {
+ return priorities[title] ? { "#priority": priorities[title] } : {};
+ }
+
+ const host = new Component();
+ const mountPoint = document.createElement("div");
+ container = mountPoint;
+ document.body.appendChild(mountPoint);
+
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={host}>
+ <Harness
+ note={note}
+ noteIds={[ ...note.getChildNoteIds() ]}
+ initialConfig={{
+ columns: [ { value: "To Do", ...sort }, { value: "Done" } ]
+ }}
+ />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ });
+ await act(async () => { await flush(); });
+ await act(async () => { await flush(); });
+
+ const byTitle = Object.fromEntries([ ...note.getChildNoteIds() ]
+ .map(noteId => froca.notes[noteId])
+ .map(child => [ child.title.toLowerCase(), child ]));
+
+ return { board: mountPoint, host, cards: byTitle };
+ }
+});
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 6fb4f1c4d5..b83bbce3cf 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -12,7 +12,9 @@ import {
import type { HighlightedTokenInfo } from "@triliumnext/commons";
import FNote from "../../../entities/fnote";
+import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
+import { getCreationDate, loadCreationDates } from "../../../services/note_dates";
import type LoadResults from "../../../services/load_results";
import { ContextMenuEvent } from "../../../menus/context_menu";
import { isIMEComposing } from "../../../services/shortcuts";
@@ -20,7 +22,8 @@ import type { ShortcutHintDefinition } from "../../../services/shortcut_hints";
import toast from "../../../services/toast";
import { escapeHtml, isMobile } from "../../../services/utils";
import { type NoteTypeOption, resolveNoteTypeOptions } from "../../../services/note_types";
-import type { PromotedAttributeSetting } from "../promoted_attributes";
+import { type PromotedAttributeSetting, resolvePromotedAttributes } from "../promoted_attributes";
+import type { SortContext } from "../sorting";
import CollectionProperties from "../../note_bars/CollectionProperties";
import FormTextArea from "../../react/FormTextArea";
import FormTextBox from "../../react/FormTextBox";
@@ -51,7 +54,8 @@ import ColumnLimitDialog from "./column_limit";
import BoardProperties from "./properties";
import { openBoardContextMenu, openCreateColumnMenu } from "./context_menu";
import {
- applyCardMove, ColumnMap, filterColumnMap, getBoardData, unfilteredCardIndex
+ affectsSortOrder, applyCardMove, ColumnMap, filterColumnMap, getBoardData, resolveColumnSorts,
+ resolveSortWatch, sortColumnMap, unfilteredCardIndex
} from "./data";
import { useBoardKeyboard } from "./keyboard";
@@ -332,6 +336,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
const movesInFlight = useRef(0);
/** Bumped when the definition changes, since it is read off the note rather than held in state. */
const [ definitionRevision, setDefinitionRevision ] = useState(0);
+ /** Bumped when the titles or dates a sort reads change, since neither is held in state. */
+ const [ sortRevision, setSortRevision ] = useState(0);
// A ref rather than state: `api` is rebuilt on every refresh, and the map has to outlive those
// instances to cover a rename (see BoardApi#retireColumn). Mutating it must not re-render.
const pendingRenamesRef = useRef<{ board: string, writes: PendingColumnWrites }>({
@@ -376,13 +382,36 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
onQueryChanged: persistFilterQuery,
collectionNoteIds: noteIds
});
+ const statusAttribute = statusAttributeWithPrefix.replace(/^[~#]/, "");
+ // Every promoted attribute the board defines, hidden ones included: a column can sort by a
+ // field its cards do not draw.
+ const promotedAttributes = useMemo(
+ () => resolvePromotedAttributes(
+ parentNote, viewConfig?.promotedAttributes, [ statusAttribute ]),
+ [ parentNote, viewConfig, statusAttribute, definitionRevision ]);
+ const columnSorts = useMemo(
+ () => resolveColumnSorts(viewConfig?.columns), [ viewConfig ]);
+ const sortContext = useMemo<SortContext>(() => ({
+ definitions: new Map(promotedAttributes.map(attribute => [ attribute.name, attribute ])),
+ creationDate: getCreationDate,
+ noteTitle: (noteId) => froca.getNoteFromCache(noteId)?.title
+ }), [ promotedAttributes ]);
+ // Sorted before the filter: `filterColumnMap` keeps the order it is given, so a card the
+ // filter hides cannot change where the others stand. `sortRevision` is a dependency because
+ // the dates and titles `sortContext` reads live outside the render.
+ const sortedByColumn = useMemo(
+ () => (allByColumn ? sortColumnMap(allByColumn, columnSorts, sortContext) : undefined),
+ [ allByColumn, columnSorts, sortContext, sortRevision ]);
// The cards as drawn. Derived rather than held, so what is shown cannot fall behind what the
// filter matches, and withheld until a query stored in `board.json` has said what it matches.
const byColumn = useMemo(
- () => (allByColumn && !filter.isResolvingStoredQuery
- ? filterColumnMap(allByColumn, filter.shownNoteIds)
+ () => (sortedByColumn && !filter.isResolvingStoredQuery
+ ? filterColumnMap(sortedByColumn, filter.shownNoteIds)
: undefined),
- [ allByColumn, filter.shownNoteIds, filter.isResolvingStoredQuery ]);
+ [ sortedByColumn, filter.shownNoteIds, filter.isResolvingStoredQuery ]);
+ const sortWatch = useMemo(
+ () => resolveSortWatch(allByColumn, columnSorts, sortContext.definitions),
+ [ allByColumn, columnSorts, sortContext ]);
if (!apiRef.current || apiRef.current.board !== boardIdentity) {
apiRef.current = {
@@ -482,6 +511,36 @@ 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.
+ useEffect(() => {
+ if (!sortWatch.noteIds.size) {
+ return;
+ }
+
+ let isCancelled = false;
+ const settle = (isLoaded: boolean) => {
+ if (isLoaded && !isCancelled) {
+ setSortRevision(revision => revision + 1);
+ }
+ };
+
+ loadCreationDates(sortWatch.noteIds)
+ .then(settle)
+ .catch((error) => console.error("Failed to load the card creation dates:", error));
+
+ const missingTargets = [ ...sortWatch.targetNoteIds ]
+ .filter(noteId => !froca.getNoteFromCache(noteId));
+ if (missingTargets.length) {
+ froca.getNotes(missingTargets, true)
+ .then(() => settle(true))
+ .catch((error) => console.error("Failed to load the sorted relations:", error));
+ }
+
+ return () => { isCancelled = true; };
+ }, [ sortWatch ]);
+
// What a card measures is kept between drags, which holds while a column is the width it was
// measured at. A phone gives a column a share of the window, so a window that changes size
// takes the heights with it.
@@ -846,6 +905,12 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
setDefinitionRevision(revision => revision + 1);
}
+ // `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.
+ if (affectsSortOrder(loadResults, sortWatch)) {
+ setSortRevision(revision => revision + 1);
+ }
+
if (findRefreshReason(loadResults, api.statusAttribute, noteIds, parentNote.noteId)) {
refresh();
}
diff --git a/apps/client/src/widgets/collections/sorting.ts b/apps/client/src/widgets/collections/sorting.ts
index 31e2d85f0b..132dddfcdd 100644
--- a/apps/client/src/widgets/collections/sorting.ts
+++ b/apps/client/src/widgets/collections/sorting.ts
@@ -38,6 +38,11 @@ export function parseSortKey(orderBy: string | null | undefined): SortKey | unde
return undefined;
}
+/** The attribute a key sorts by, or undefined when the key names something else. */
+export function sortedAttributeName(key: SortKey) {
+ return key.startsWith(ATTRIBUTE_PREFIX) ? key.substring(ATTRIBUTE_PREFIX.length) : undefined;
+}
+
/**
* Orders items by one key, breaking ties on the creation date and then on the given order.
*
@@ -95,7 +100,7 @@ function sortValueOf(note: FNote, key: SortKey, context: SortContext): SortValue
return context.creationDate(note.noteId);
}
- const name = key.substring(ATTRIBUTE_PREFIX.length);
+ const name = sortedAttributeName(key) ?? "";
const definition = context.definitions.get(name);
if (definition?.type === "relation") {