Skip to content

Build your personal knowledge base with Trilium Notes

perf(board): split the drag state out of the board context

Elian Doran84cd9309ffdf
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index 0b35aa92f8..765807ca8d 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -2,7 +2,7 @@ import { useCallback, useContext, useEffect, useRef, useState } from "preact/hoo
import FBranch from "../../../entities/fbranch";
import FNote from "../../../entities/fnote";
import BoardApi from "./api";
-import { BoardViewContext, TitleEditor } from ".";
+import { BoardActionsContext, TitleEditor } from ".";
import { ContextMenuEvent } from "../../../menus/context_menu";
import { openNoteContextMenu } from "./context_menu";
import { perfCount } from "../../../services/debug_perf";
@@ -25,19 +25,24 @@ export default function Card({
branch,
column,
index,
- isDragging
+ isDragging,
+ isEditing
}: {
api: BoardApi,
note: FNote,
branch: FBranch,
column: string,
index: number,
- isDragging: boolean
+ isDragging: boolean,
+ /**
+ * Passed down rather than derived here from the drag state's `branchIdToEdit`, so that a card
+ * subscribes only to the board's stable context and a drag leaves it off the render path.
+ */
+ isEditing: boolean
}) {
perfCount("board.card.render");
- const { branchIdToEdit, setBranchIdToEdit, setDraggedCard } = useContext(BoardViewContext)!;
- const isEditing = branch.branchId === branchIdToEdit;
+ const { setBranchIdToEdit, setDraggedCard } = useContext(BoardActionsContext);
const colorClass = note.getColorClass() || '';
const editorRef = useRef<HTMLInputElement>(null);
const isArchived = note.isArchived;
@@ -72,14 +77,14 @@ export default function Card({
const handleEdit = useCallback((e: MouseEvent) => {
e.stopPropagation(); // don't also open the note
- setBranchIdToEdit?.(branch.branchId);
+ setBranchIdToEdit(branch.branchId);
}, [ setBranchIdToEdit, branch ]);
const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.key === "Enter") {
api.openNote(note.noteId);
} else if (e.key === "F2") {
- setBranchIdToEdit?.(branch.branchId);
+ setBranchIdToEdit(branch.branchId);
}
}, [ setBranchIdToEdit, note ]);
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index 4ef37574f1..b89c45bfa0 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -11,7 +11,7 @@ import { t } from "../../../services/i18n";
import { DragData, TREE_CLIPBOARD_TYPE } from "../../note_tree";
import Icon from "../../react/Icon";
import NoteLink from "../../react/NoteLink";
-import { BoardViewContext, TitleEditor } from ".";
+import { BoardActionsContext, BoardDragStateContext, TitleEditor } from ".";
import BoardApi from "./api";
import Card, { CARD_CLIPBOARD_TYPE, CardDragData } from "./card";
import { openColumnContextMenu } from "./context_menu";
@@ -28,6 +28,7 @@ export default function Column({
isDraggingColumn,
columnItems,
api,
+ parentNote,
onColumnHover,
isAnyColumnDragging,
isInRelationMode
@@ -35,20 +36,22 @@ export default function Column({
columnItems?: { note: FNote, branch: FBranch }[];
isDraggingColumn: boolean,
api: BoardApi,
+ parentNote: FNote,
onColumnHover?: (index: number, mouseX: number, rect: DOMRect) => void,
isAnyColumnDragging?: boolean,
isInRelationMode: boolean
} & DragContext) {
const [ isVisible, setVisible ] = useState(true);
- const { columnNameToEdit, setColumnNameToEdit, dropTarget, draggedCard, dropPosition } = useContext(BoardViewContext)!;
+ const { setColumnNameToEdit } = useContext(BoardActionsContext);
+ const { branchIdToEdit, columnNameToEdit, dropTarget, draggedCard, dropPosition } = useContext(BoardDragStateContext);
const isEditing = (columnNameToEdit === column);
const editorRef = useRef<HTMLInputElement>(null);
const { handleColumnDragStart, handleColumnDragEnd, handleDragOver, handleDragLeave, handleDrop } = useDragging({
- column, columnIndex, columnItems, isEditing
+ column, columnIndex, columnItems, isEditing, api, parentNote
});
const handleEdit = useCallback(() => {
- setColumnNameToEdit?.(column);
+ setColumnNameToEdit(column);
}, [column]);
const handleContextMenu = useCallback((e: ContextMenuEvent) => {
@@ -57,7 +60,7 @@ export default function Column({
const handleTitleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.key === "F2") {
- setColumnNameToEdit?.(column);
+ setColumnNameToEdit(column);
}
}, [ column ]);
@@ -125,7 +128,7 @@ export default function Column({
<TitleEditor
currentValue={column}
save={newTitle => api.renameColumn(column, newTitle)}
- dismiss={() => setColumnNameToEdit?.(undefined)}
+ dismiss={() => setColumnNameToEdit(undefined)}
mode={isInRelationMode ? "relation" : "normal"}
/>
)}
@@ -151,6 +154,7 @@ export default function Column({
column={column}
index={index}
isDragging={draggedCard?.noteId === note.noteId}
+ isEditing={branch.branchId === branchIdToEdit}
/>
</Fragment>
);
@@ -198,8 +202,9 @@ function AddNewItem({ column, api }: { column: string, api: BoardApi }) {
);
}
-function useDragging({ column, columnIndex, columnItems, isEditing }: DragContext & { isEditing: boolean }) {
- const { api, parentNote, draggedColumn, setDraggedColumn, setDropTarget, setDropPosition, dropPosition } = useContext(BoardViewContext)!;
+function useDragging({ column, columnIndex, columnItems, isEditing, api, parentNote }: DragContext & { isEditing: boolean, api: BoardApi, parentNote: FNote }) {
+ const { setDraggedColumn, setDropTarget, setDropPosition } = useContext(BoardActionsContext);
+ const { draggedColumn, dropPosition } = useContext(BoardDragStateContext);
/** Needed to track if current column is dragged in real-time, since {@link draggedColumn} is populated one render cycle later. */
const isDraggingRef = useRef(false);
@@ -276,14 +281,14 @@ function useDragging({ column, columnIndex, columnItems, isEditing }: DragContex
// From note tree.
const { noteId, branchId } = draggedCard[0];
const targetNote = await froca.getNote(noteId, true);
- const parentNoteId = parentNote?.noteId;
- if (!parentNoteId || !dropPosition) return;
+ const parentNoteId = parentNote.noteId;
+ if (!dropPosition) return;
const targetIndex = dropPosition.index - 1;
const targetItems = columnItems || [];
const targetBranch = targetIndex >= 0 ? targetItems[targetIndex].branch : null;
- await api?.changeColumn(noteId, column);
+ await api.changeColumn(noteId, column);
const parents = targetNote?.getParentNoteIds();
if (!parents?.includes(parentNoteId)) {
@@ -297,7 +302,7 @@ function useDragging({ column, columnIndex, columnItems, isEditing }: DragContex
await branches.moveAfterBranch([ branchId ], targetBranch.branchId);
}
} else if (draggedCard && dropPosition) {
- api?.moveWithinBoard(draggedCard.noteId, draggedCard.branchId, draggedCard.index, dropPosition.index, draggedCard.fromColumn, column);
+ api.moveWithinBoard(draggedCard.noteId, draggedCard.branchId, draggedCard.index, dropPosition.index, draggedCard.fromColumn, column);
}
}, [ api, draggedColumn, dropPosition, columnItems, column, setDropTarget, setDropPosition ]);
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 99727ff2a5..f2ba2da6ec 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -31,24 +31,68 @@ export interface BoardColumnData {
value: string;
}
-interface BoardViewContextData {
- api?: BoardApi;
- parentNote?: FNote;
+interface CardDrag {
+ noteId: string;
+ branchId: string;
+ fromColumn: string;
+ index: number;
+}
+
+interface ColumnDrag {
+ column: string;
+ index: number;
+}
+
+/**
+ * The board's setters, which `useState` gives a fixed identity, so this context never changes value
+ * at all.
+ *
+ * Kept apart from the drag state below because Preact re-renders every consumer of a context whose
+ * value changed, memo boundaries included. Merged into one value, as they used to be, a card could
+ * not be kept off the render path at all: it needs two of these setters, so it would subscribe to a
+ * value that changes several times per drag and re-render each time, all 949 of them.
+ *
+ * The board's `api` deliberately stays out. Every component that used to read it from here is also
+ * passed it as a prop, so having it in both places was duplication -- and being un-defaultable, it
+ * was the only reason this context had to be nullable.
+ */
+interface BoardActions {
+ setBranchIdToEdit: Dispatch<StateUpdater<string | undefined>>;
+ setColumnNameToEdit: Dispatch<StateUpdater<string | undefined>>;
+ setDraggedCard: Dispatch<StateUpdater<CardDrag | null>>;
+ setDraggedColumn: (column: ColumnDrag | null) => void;
+ setDropPosition: (position: ColumnDrag | null) => void;
+ setDropTarget: (target: string | null) => void;
+}
+
+/** The half that changes repeatedly while a card or column is dragged, or a title is being edited. */
+interface BoardDragState {
branchIdToEdit?: string;
columnNameToEdit?: string;
- setColumnNameToEdit?: Dispatch<StateUpdater<string | undefined>>;
- setBranchIdToEdit?: Dispatch<StateUpdater<string | undefined>>;
- draggedColumn: { column: string, index: number } | null;
- setDraggedColumn: (column: { column: string, index: number } | null) => void;
- dropPosition: { column: string, index: number } | null;
- setDropPosition: (position: { column: string, index: number } | null) => void;
- setDropTarget: (target: string | null) => void,
+ draggedCard: CardDrag | null;
+ draggedColumn: ColumnDrag | null;
+ dropPosition: ColumnDrag | null;
dropTarget: string | null;
- draggedCard: { noteId: string, branchId: string, fromColumn: string, index: number } | null;
- setDraggedCard: Dispatch<StateUpdater<{ noteId: string; branchId: string; fromColumn: string; index: number; } | null>>;
}
-export const BoardViewContext = createContext<BoardViewContextData | undefined>(undefined);
+// Both defaults are the honest identity value rather than a stand-in, which is what lets consumers
+// read these with a plain useContext(): no non-null assertion, and no guard for a provider that is
+// structurally always there. Nothing is being dragged, and the setters have nothing to set.
+export const BoardActionsContext = createContext<BoardActions>({
+ setBranchIdToEdit: () => undefined,
+ setColumnNameToEdit: () => undefined,
+ setDraggedCard: () => undefined,
+ setDraggedColumn: () => undefined,
+ setDropPosition: () => undefined,
+ setDropTarget: () => undefined
+});
+
+export const BoardDragStateContext = createContext<BoardDragState>({
+ draggedCard: null,
+ draggedColumn: null,
+ dropPosition: null,
+ dropTarget: null
+});
export default function BoardView({ note: parentNote, noteIds, viewConfig, saveConfig }: ViewModeProps<BoardViewData>) {
const [ statusAttributeWithPrefix ] = useNoteLabelWithDefault(parentNote, "board:groupBy", DEFAULT_GROUP_BY);
@@ -72,26 +116,29 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
const api = useMemo(() => {
return new Api(byColumn, columns ?? [], parentNote, statusAttributeWithPrefix, viewConfig ?? {}, saveConfig, setBranchIdToEdit, statusDefinition );
}, [ byColumn, columns, parentNote, statusAttributeWithPrefix, viewConfig, saveConfig, setBranchIdToEdit, statusDefinition ]);
- const boardViewContext = useMemo<BoardViewContextData>(() => ({
- api,
- parentNote,
- branchIdToEdit, setBranchIdToEdit,
- columnNameToEdit, setColumnNameToEdit,
- draggedColumn, setDraggedColumn,
- dropPosition, setDropPosition,
- draggedCard, setDraggedCard,
- dropTarget, setDropTarget
+ // Every member is one of useState's own setters, so this value is built once and never changes
+ // identity -- a drag cannot reach anything that reads only this.
+ const boardActions = useMemo<BoardActions>(() => ({
+ setBranchIdToEdit,
+ setColumnNameToEdit,
+ setDraggedCard,
+ setDraggedColumn,
+ setDropPosition,
+ setDropTarget
}), [
- api,
- parentNote,
- branchIdToEdit, setBranchIdToEdit,
- columnNameToEdit, setColumnNameToEdit,
- draggedColumn, setDraggedColumn,
- dropPosition, setDropPosition,
- draggedCard, setDraggedCard,
- dropTarget, setDropTarget
+ setBranchIdToEdit, setColumnNameToEdit, setDraggedCard,
+ setDraggedColumn, setDropPosition, setDropTarget
]);
+ const boardDragState = useMemo<BoardDragState>(() => ({
+ branchIdToEdit,
+ columnNameToEdit,
+ draggedCard,
+ draggedColumn,
+ dropPosition,
+ dropTarget
+ }), [ branchIdToEdit, columnNameToEdit, draggedCard, draggedColumn, dropPosition, dropTarget ]);
+
/**
* Closed by the layout effect below rather than at the end of `refresh()`, so the span covers
* the commit the refresh causes and not just the state write, which Preact defers.
@@ -197,37 +244,40 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
return (
<div className="board-view">
<CollectionProperties note={parentNote} />
- <BoardViewContext.Provider value={boardViewContext}>
- {byColumn && columns && <div
- className="board-view-container"
- onDragOver={handleColumnDragOver}
- onDrop={handleContainerDrop}
- onWheel={onWheelHorizontalScroll}
- >
- {columns.map((column, index) => (
- <>
- {columnDropPosition === index && (
- <div className="column-drop-placeholder show" />
- )}
- <Column
- isInRelationMode={isInRelationMode}
- api={api}
- column={column}
- columnIndex={index}
- columnItems={byColumn.get(column)}
- isDraggingColumn={draggedColumn?.column === column}
- onColumnHover={handleColumnHover}
- isAnyColumnDragging={!!draggedColumn}
- />
- </>
- ))}
- {columnDropPosition === columns?.length && draggedColumn && (
- <div className="column-drop-placeholder show" />
- )}
-
- <AddNewColumn api={api} isInRelationMode={isInRelationMode} />
- </div>}
- </BoardViewContext.Provider>
+ <BoardActionsContext.Provider value={boardActions}>
+ <BoardDragStateContext.Provider value={boardDragState}>
+ {byColumn && columns && <div
+ className="board-view-container"
+ onDragOver={handleColumnDragOver}
+ onDrop={handleContainerDrop}
+ onWheel={onWheelHorizontalScroll}
+ >
+ {columns.map((column, index) => (
+ <>
+ {columnDropPosition === index && (
+ <div className="column-drop-placeholder show" />
+ )}
+ <Column
+ isInRelationMode={isInRelationMode}
+ api={api}
+ parentNote={parentNote}
+ column={column}
+ columnIndex={index}
+ columnItems={byColumn.get(column)}
+ isDraggingColumn={draggedColumn?.column === column}
+ onColumnHover={handleColumnHover}
+ isAnyColumnDragging={!!draggedColumn}
+ />
+ </>
+ ))}
+ {columnDropPosition === columns?.length && draggedColumn && (
+ <div className="column-drop-placeholder show" />
+ )}
+
+ <AddNewColumn api={api} isInRelationMode={isInRelationMode} />
+ </div>}
+ </BoardDragStateContext.Provider>
+ </BoardActionsContext.Provider>
</div>
);
}