Skip to content

Build your personal knowledge base with Trilium Notes

fix(board): keep a read-only board from editing, and from loading its editing code

Elian Doran43674565766a
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index 768f01a5d5..4627b7c7e4 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -403,9 +403,9 @@ describe("BoardApi column mutations", () => {
);
let releaseSecond = () => {};
+ const second = new Promise<void>((resolve) => { releaseSecond = resolve; });
failNextRename();
- vi.mocked(executeBulkActions).mockImplementationOnce(
- () => new Promise<void>((resolve) => { releaseSecond = resolve; }));
+ vi.mocked(executeBulkActions).mockImplementationOnce(() => second);
const failing = api.renameColumn("Done", "Shipped");
const running = api.removeColumn("To Do");
@@ -478,9 +478,9 @@ describe("BoardApi column mutations", () => {
);
let releaseSecond = () => {};
+ const second = new Promise<void>((resolve) => { releaseSecond = resolve; });
vi.mocked(executeBulkActions).mockRejectedValueOnce(new Error("offline"));
- vi.mocked(executeBulkActions).mockImplementationOnce(
- () => new Promise<void>((resolve) => { releaseSecond = resolve; }));
+ vi.mocked(executeBulkActions).mockImplementationOnce(() => second);
// The same column, deleted twice over before either has answered.
const failing = api.removeColumn("Done");
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index 26b27652e1..46039e9ede 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -5,7 +5,6 @@ import type NoteContext from "../../../components/note_context";
import FNote from "../../../entities/fnote";
import attributes from "../../../services/attributes";
import branches from "../../../services/branches";
-import { executeBulkActions } from "../../../services/bulk_action";
import cssClassManager from "../../../services/css_class_manager";
import dialog from "../../../services/dialog";
import froca from "../../../services/froca";
@@ -548,8 +547,10 @@ export default class BoardApi {
: this.isRelationMode
? { name: "deleteRelation", relationName: this.statusAttribute }
: { name: "deleteLabel", labelName: this.statusAttribute };
- await this.retiredWhile(column, undefined,
- () => executeBulkActions(noteIds, [ action ], { silent: true }));
+ await this.retiredWhile(column, undefined, async () => {
+ const { executeBulkActions } = await loadBulkActions();
+ return executeBulkActions(noteIds, [ action ], { silent: true });
+ });
this.storeColumns(this.storedColumns.filter(col => col.value !== column));
}
@@ -1766,3 +1767,10 @@ export default class BoardApi {
}
+let bulkActions: Promise<typeof import("../../../services/bulk_action")> | undefined;
+
+/** Loads the bulk action service once, whose dialogs a board has no use for until it edits. */
+function loadBulkActions() {
+ bulkActions ??= import("../../../services/bulk_action");
+ return bulkActions;
+}
diff --git a/apps/client/src/widgets/collections/board/board_drag.ts b/apps/client/src/widgets/collections/board/board_drag.ts
index eaae324c61..c13eb09948 100644
--- a/apps/client/src/widgets/collections/board/board_drag.ts
+++ b/apps/client/src/widgets/collections/board/board_drag.ts
@@ -684,11 +684,6 @@ function endIndex(end: ColumnEnd | undefined, column: ColumnBox) {
return end === "first" ? 0 : column.count;
}
-/** Asks an element for its menu the way a right click does, at the place the press landed. */
-export function askForMenu(element: HTMLElement, clientX: number, clientY: number) {
- element.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, clientX, clientY }));
-}
-
/** What a press on a card starts, or nothing where the press was not on one. */
function startCard(
target: HTMLElement, carriedWith: (noteId: string) => string[]
diff --git a/apps/client/src/widgets/collections/board/card.spec.tsx b/apps/client/src/widgets/collections/board/card.spec.tsx
index 4d52a61094..479ac96b55 100644
--- a/apps/client/src/widgets/collections/board/card.spec.tsx
+++ b/apps/client/src/widgets/collections/board/card.spec.tsx
@@ -4,7 +4,7 @@
*/
import { render } from "preact";
import { act } from "preact/test-utils";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import appContext from "../../../components/app_context";
import Component from "../../../components/component";
@@ -19,7 +19,7 @@ import utils from "../../../services/utils";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
import BoardApi from "./api";
-import BoardView from ".";
+import BoardView, { loadBoardEditing } from ".";
import { OutsideFilterBadge } from "./card";
// The card menu opens with the shared link items, which reach for the active note context.
@@ -56,6 +56,9 @@ vi.mock("../../attribute_widgets/UserAttributesList", () => ({
}
}));
+// An editable board draws once its editing code has loaded, which the app fetches on demand.
+beforeAll(() => loadBoardEditing());
+
describe("Board card", () => {
let container: HTMLElement | undefined;
/** froca is module-level, so ids are kept distinct rather than reset between tests. */
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index b6456e32d8..aa07d15e32 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -8,8 +8,8 @@ import FBranch from "../../../entities/fbranch";
import FNote from "../../../entities/fnote";
import BoardApi, { CARD_REDIRECT_RELATION, CARD_REDIRECT_RELATION_LEGACY } from "./api";
import {
- BoardActionsContext, BoardHighlightTokensContext, BoardKeptCardsContext,
- BoardOverlayHostContext, BoardPromotedAttributesContext, BoardSelectionModeContext, TitleEditor
+ BoardActionsContext, BoardEditingContext, BoardHighlightTokensContext, BoardKeptCardsContext,
+ BoardOverlayHostContext, BoardPromotedAttributesContext, BoardSelectionModeContext
} from ".";
import { ContextMenuEvent } from "../../../menus/context_menu";
import { cardFollows } from "./columns";
@@ -26,9 +26,10 @@ import {
} from "../../react/hooks";
import { TooltipIcon } from "../../react/Icon";
import { HighlightedText } from "../../react/RawHtml";
-import { useIsOnScreen, useLingeringTrue } from "../../react/hooks";
+import {
+ type DragData, TREE_CLIPBOARD_TYPE, useIsOnScreen, useLingeringTrue
+} from "../../react/hooks";
import { useIsSelected, useSelection } from "../../react/selection";
-import { type DragData, TREE_CLIPBOARD_TYPE } from "../../note_tree";
import CardToolbar, { RAIL_EXIT_MS } from "./card_toolbar";
function Card({
@@ -77,6 +78,7 @@ function Card({
onNewItem: () => void
}) {
const { setBranchIdToEdit } = useContext(BoardActionsContext);
+ const editing = useContext(BoardEditingContext);
const shownAttributes = useContext(BoardPromotedAttributesContext);
const highlightedTokens = useContext(BoardHighlightTokensContext);
const isOutsideFilter = useContext(BoardKeptCardsContext).has(note.noteId);
@@ -343,8 +345,8 @@ function Card({
onClick={handleEdit}
/>}
</>
- ) : (
- <TitleEditor
+ ) : editing && (
+ <editing.TitleEditor
returnFocusTo={cardRef}
currentValue={note.title}
save={newTitle => {
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index 59543945f7..a8f00d03e7 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -14,10 +14,11 @@ import { getHue, parseColor } from "../../../services/css_class_manager";
import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
import { isMobile } from "../../../services/utils";
-import { DragData, TREE_CLIPBOARD_TYPE } from "../../note_tree";
import ActionButton from "../../react/ActionButton";
import Icon from "../../react/Icon";
-import { useIsOnScreen, useLingeringTrue, useStaticTooltip } from "../../react/hooks";
+import {
+ type DragData, TREE_CLIPBOARD_TYPE, useIsOnScreen, useLingeringTrue, useStaticTooltip
+} from "../../react/hooks";
import { useFlip } from "../../react/flip";
import { useScrollFade } from "../../react/scroll_fade";
import { useSelection } from "../../react/selection";
@@ -39,8 +40,8 @@ const MIN_CARD_HEIGHT = 32;
export const EXPAND_MS = 200;
import NoteLink from "../../react/NoteLink";
import {
- BoardActionsContext, BoardDragStateContext, BoardOverlayHostContext, BoardSelectionModeContext,
- TitleEditor
+ BoardActionsContext, BoardDragStateContext, BoardEditingContext, BoardOverlayHostContext,
+ BoardSelectionModeContext
} from ".";
import BoardApi from "./api";
import Card from "./card";
@@ -574,6 +575,7 @@ export default function Column({
setIsHeaderFocused(false);
}, []);
const isSelecting = useContext(BoardSelectionModeContext);
+ const editing = useContext(BoardEditingContext);
// Off the heading while its title is edited, since the rename it offers is under way, and in
// selection mode, where the board's own rail stands for the selection.
const isRailWanted = isMobile() && isHeaderFocused && !isEditing && !isSelecting;
@@ -814,8 +816,8 @@ export default function Column({
}}
/>
</>
- ) : (
- <TitleEditor
+ ) : editing && (
+ <editing.TitleEditor
currentValue={api.getColumnTitle(column)}
save={newTitle => api.setColumnTitle(column, newTitle)}
dismiss={() => setColumnNameToEdit(undefined)}
@@ -1037,6 +1039,7 @@ function AddNewItem({
const close = useCallback(
() => insert ? insert.close() : setIsCreating?.(false),
[ insert, setIsCreating ]);
+ const editing = useContext(BoardEditingContext);
// What the editor opens with: empty to begin with, then whatever was typed into it and left
// unsaved, so that reaching for something else and coming back does not cost the title.
const [ initialTitle, setInitialTitle ] = useState("");
@@ -1124,8 +1127,8 @@ function AddNewItem({
<Icon icon="bx bx-plus" />{" "}
{t("board_view.new-item")}
</>
- ) : (
- <TitleEditor
+ ) : editing && (
+ <editing.TitleEditor
currentValue={initialTitle}
placeholder={t("board_view.new-item-placeholder")}
save={create}
@@ -1242,7 +1245,8 @@ function useDragging({
}, [setDraggedColumn]);
const handleDragOver = useCallback((e: DragEvent) => {
- if (isEditing || draggedColumn || isDraggingRef.current) return; // Don't handle card drops when dragging columns
+ // Don't handle card drops when dragging columns
+ if (api.isReadOnly || isEditing || draggedColumn || isDraggingRef.current) return;
// Cards are carried by pointer now; what still arrives this way comes from the note tree.
if (!e.dataTransfer?.types.includes(TREE_CLIPBOARD_TYPE)) return;
@@ -1285,7 +1289,8 @@ function useDragging({
}, [setDropTarget, setDropPosition]);
const handleDrop = useCallback(async (e: DragEvent) => {
- if (draggedColumn) return; // Don't handle card drops when dragging columns
+ // Don't handle card drops when dragging columns
+ if (api.isReadOnly || draggedColumn) return;
e.preventDefault();
// Taken before the gap is closed, which is what says where the note goes.
const standing = dropState.get().position;
diff --git a/apps/client/src/widgets/collections/board/drag.spec.tsx b/apps/client/src/widgets/collections/board/drag.spec.tsx
index 61d9859199..7ff88b8487 100644
--- a/apps/client/src/widgets/collections/board/drag.spec.tsx
+++ b/apps/client/src/widgets/collections/board/drag.spec.tsx
@@ -5,15 +5,15 @@
*/
import { render } from "preact";
import { act } from "preact/test-utils";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import Component from "../../../components/component";
import branches from "../../../services/branches";
import server from "../../../services/server";
import { buildNote } from "../../../test/easy-froca";
-import { TREE_CLIPBOARD_TYPE } from "../../note_tree";
+import { TREE_CLIPBOARD_TYPE } from "../../react/hooks";
import { ParentComponent } from "../../react/react_utils";
-import BoardView, { BoardViewData } from ".";
+import BoardView, { BoardViewData, loadBoardEditing } from ".";
import { placeCard, settleCards } from "./column";
vi.mock("../../../services/branches", () => ({
@@ -34,6 +34,9 @@ vi.mock("../../../services/utils", async (importOriginal) => ({
isMobile: () => layout.onMobile
}));
+// An editable board draws once its editing code has loaded, which the app fetches on demand.
+beforeAll(() => loadBoardEditing());
+
describe("Board drag and drop", () => {
let container: HTMLElement | undefined;
diff --git a/apps/client/src/widgets/collections/board/editing.spec.tsx b/apps/client/src/widgets/collections/board/editing.spec.tsx
new file mode 100644
index 0000000000..8de068a403
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/editing.spec.tsx
@@ -0,0 +1,89 @@
+/**
+ * A board loads its editing code apart from itself, so a read-only one, such as a shared board,
+ * never fetches it.
+ */
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import Component from "../../../components/component";
+import { buildNote } from "../../../test/easy-froca";
+import { ParentComponent } from "../../react/react_utils";
+import BoardView, { loadBoardEditing } from ".";
+
+const imports = vi.hoisted(() => ({ editing: 0 }));
+vi.mock("./editing", async (importOriginal) => {
+ imports.editing++;
+ return await importOriginal();
+});
+
+// i18next is never initialised under test, so every label would read as undefined.
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string) => key,
+ translationsInitializedPromise: Promise.resolve(),
+ getCurrentLanguage: () => "en"
+}));
+
+describe("a board's editing code", () => {
+ const mounted: HTMLElement[] = [];
+
+ afterEach(() => {
+ for (const mountPoint of mounted.splice(0)) {
+ act(() => render(null, mountPoint));
+ mountPoint.remove();
+ }
+ });
+
+ it("loads only once a board that can be edited is drawn", async () => {
+ const readOnly = await renderBoard({ "#readOnly": "" });
+ expect(readOnly.querySelector(".board-note")).not.toBeNull();
+ expect(readOnly.querySelector(".board-add-column")).toBeNull();
+ expect(imports.editing).toBe(0);
+
+ const editable = await renderBoard();
+ expect(imports.editing).toBe(1);
+ // The import the board started, which the first time can take longer than any fixed wait.
+ await act(async () => { await loadBoardEditing(); });
+ await settle();
+ expect(editable.querySelector(".board-note")).not.toBeNull();
+ expect(editable.querySelector(".board-add-column")).not.toBeNull();
+ });
+
+ async function renderBoard(labels: Record<string, string> = {}) {
+ const note = buildNote({
+ title: "Board",
+ "#collection": "",
+ "#viewType": "board",
+ ...labels,
+ children: [ { title: "First", "#status": "To Do" } ]
+ });
+ const mountPoint = document.createElement("div");
+ mounted.push(mountPoint);
+ document.body.appendChild(mountPoint);
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={new Component()}>
+ <BoardView
+ note={note}
+ notePath={`root/${note.noteId}`}
+ noteIds={note.getChildNoteIds()}
+ highlightedTokens={null}
+ viewConfig={{ columns: [ { value: "To Do" } ] }}
+ saveConfig={() => {}}
+ media="screen"
+ onReady={() => {}}
+ />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ });
+ await settle();
+ return mountPoint;
+ }
+});
+
+async function settle() {
+ for (let pass = 0; pass < 5; pass++) {
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+ }
+}
diff --git a/apps/client/src/widgets/collections/board/editing.tsx b/apps/client/src/widgets/collections/board/editing.tsx
new file mode 100644
index 0000000000..879baec10c
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/editing.tsx
@@ -0,0 +1,633 @@
+import clsx from "clsx";
+import {
+ ComponentChildren, RefObject, TargetedFocusEvent, TargetedKeyboardEvent, TargetedMouseEvent,
+ TargetedPointerEvent
+} from "preact";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import { isIMEComposing } from "../../../services/shortcuts";
+import toast from "../../../services/toast";
+import { escapeHtml } from "../../../services/utils";
+import ActionButton from "../../react/ActionButton";
+import FormTextArea from "../../react/FormTextArea";
+import FormTextBox from "../../react/FormTextBox";
+import Icon from "../../react/Icon";
+import { IconPickerButton } from "../../react/IconPicker";
+import NoteAutocomplete from "../../react/NoteAutocomplete";
+import type { HoldOpen } from ".";
+import BoardApi from "./api";
+import { type BoardDragCallbacks, useBoardDrag } from "./board_drag";
+import { DEFAULT_COLUMN_ICON } from "./columns";
+import { openCreateColumnMenu } from "./context_menu";
+
+export { default as ColumnLimitDialog } from "./column_limit";
+export { default as BoardProperties } from "./properties";
+
+/**
+ * Drives the drag of cards and columns over the board's container, and measures the board again
+ * while a card is carried, since a column opened to take it moves every column after it.
+ *
+ * Only a column carried is measured among the columns as they stood when it was picked up, which
+ * is the list the place it would take is counted against.
+ */
+export function BoardDrag({
+ containerRef, callbacks, isCarryingColumn, activeColumn, shownColumns, onDraggingChange
+}: {
+ containerRef: RefObject<HTMLElement | null>;
+ callbacks: BoardDragCallbacks;
+ isCarryingColumn: boolean;
+ /** The column drawn open, which changes the board's measurements as it opens. */
+ activeColumn: string | undefined;
+ shownColumns: string[];
+ onDraggingChange: (isDragging: boolean) => void;
+}) {
+ const { isDragging, remeasure } = useBoardDrag(containerRef, callbacks);
+
+ useLayoutEffect(() => {
+ onDraggingChange(isDragging);
+ }, [ isDragging, onDraggingChange ]);
+
+ useLayoutEffect(() => {
+ if (isDragging && !isCarryingColumn) {
+ remeasure();
+ }
+ }, [ isDragging, isCarryingColumn, remeasure, activeColumn, shownColumns ]);
+
+ return null;
+}
+
+export function AddNewColumn({
+ api, isInRelationMode, columnCount, onCreated, isCreating, setIsCreating
+}: {
+ api: BoardApi,
+ isInRelationMode: boolean,
+ /** How many columns stand before this, which is what carries it past the board's edge. */
+ columnCount: number,
+ /** Names the column just made, which the board reveals as it draws it. */
+ onCreated: (column: string) => void,
+ /** Whether the editor is open. The board's own menu opens the same one this slot opens. */
+ isCreating: boolean,
+ setIsCreating: (isCreating: boolean) => void
+}) {
+ const isCreatingNewColumn = isCreating;
+ const setIsCreatingNewColumn = setIsCreating;
+ // Kept between columns, as the card editor keeps its own: a run of columns is often a run of
+ // the same kind of column.
+ const [ icon, setIcon ] = useState(DEFAULT_COLUMN_ICON);
+ const slotRef = useRef<HTMLDivElement>(null);
+
+ // Keyed on the count rather than done when the write returns: the column it makes room for is
+ // drawn by a refresh that has yet to run at that point, so the board is not yet as wide as it
+ // is about to be.
+ useLayoutEffect(() => {
+ if (!isCreatingNewColumn) {
+ return;
+ }
+
+ const board = slotRef.current?.closest<HTMLElement>(".board-view-container");
+ if (!board) {
+ return;
+ }
+
+ board.scrollLeft = board.scrollWidth;
+ }, [ columnCount, isCreatingNewColumn ]);
+
+ const addColumnCallback = useCallback(() => {
+ setIsCreatingNewColumn(true);
+ }, []);
+
+ const keydownCallback = useCallback((e: KeyboardEvent) => {
+ if (e.key === "Enter") {
+ setIsCreatingNewColumn(true);
+ }
+ }, []);
+
+ return (
+ <div
+ ref={slotRef}
+ className={`board-add-column ${isCreatingNewColumn ? "editing" : ""}`}
+ onClick={addColumnCallback}
+ onKeyDown={keydownCallback}
+ tabIndex={300}
+ >
+ {!isCreatingNewColumn
+ ? <>
+ <Icon icon="bx bx-plus" />{" "}
+ {t("board_view.add-column")}
+ </>
+ : (
+ <TitleEditor
+ placeholder={t("board_view.add-column-placeholder")}
+ save={async (columnName, atStart) => {
+ const created = await api.addNewColumn(columnName, atStart,
+ icon !== DEFAULT_COLUMN_ICON ? icon : undefined);
+ if (created) {
+ onCreated(columnName);
+ } else {
+ toast.showMessage(t("board_view.column-already-exists"), undefined, "bx bx-duplicate");
+ }
+ }}
+ dismiss={() => setIsCreatingNewColumn(false)}
+ isNewItem
+ // Columns are added in runs as a board is set up, so the editor is left
+ // standing with an empty field. A column named by a note answers for
+ // itself, since picking one is what closes that editor.
+ saveAndContinue={!isInRelationMode}
+ submitTitle={t("board_view.create-new-column")}
+ openPlacements={openCreateColumnMenu}
+ // The same picker the column's own heading carries, so a column is given
+ // its icon as it is named rather than after it stands there.
+ icon={{
+ current: icon,
+ onSelect: setIcon,
+ onReset: icon !== DEFAULT_COLUMN_ICON
+ ? () => setIcon(DEFAULT_COLUMN_ICON)
+ : undefined
+ }}
+ mode={isInRelationMode ? "relation" : "normal"}
+ />
+ )}
+ </div>
+ );
+}
+
+export function TitleEditor({
+ currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true,
+ saveAndContinue = false, handsOver = false, returnFocusTo, abandon, whenEmpty, submitTitle,
+ openPlacements, icon, footer
+}: {
+ currentValue?: string;
+ placeholder?: string;
+ /**
+ * Writes what was typed. Returns `false` to refuse it, which keeps the editor open on what it
+ * holds so the reader can correct it.
+ */
+ save: (newValue: string, atStart?: boolean) => false | void | Promise<void>;
+ dismiss: () => void;
+ isNewItem?: boolean;
+ mode?: "normal" | "multiline" | "relation";
+ /**
+ * Whether Enter saves and clears the editor rather than closing it, so a run of cards can be
+ * typed one after another. Enter is then the only thing that saves: Escape and losing focus
+ * discard what was typed and close the editor. An editor left standing between cards is walked
+ * away from often enough that saving on the way out would create cards nobody asked for.
+ */
+ saveAndContinue?: boolean;
+ /**
+ * Whether the field keeps what was typed once it has saved, and saves only once.
+ *
+ * For an editor the caller takes down as what it made takes its place: emptied instead, the
+ * field would stand where the new thing is about to be drawn without holding what it says.
+ */
+ handsOver?: boolean;
+ /** Reports what was typed and not saved, so reopening the editor can restore it. */
+ abandon?: (typed: string) => void;
+ /**
+ * What the button does while the field is empty, drawn as `bx bx-folder-open`. Without it no
+ * button is drawn at all until something is typed.
+ */
+ whenEmpty?: { title: string, onClick?: () => void };
+ /** Names what the button creates, shown in its tooltip. */
+ submitTitle?: string;
+ /**
+ * What stands at the foot of the field, inside its own box: the pill naming what a new card
+ * will be made from. The field is given room for it.
+ */
+ footer?: (hold: HoldOpen) => ComponentChildren;
+ /**
+ * The icon shown inside the field, at the leading edge, which opens the picker when pressed.
+ * The caller answers for what a pick does: a card carries it as `iconClass`, and the editor a
+ * card is made in keeps it for the next card.
+ */
+ icon?: { current: string, onSelect: (icon: string) => void, onReset?: () => void };
+ /**
+ * Opens the menu naming which end to create at, for a `save` that reads `atStart`. Passing it
+ * is what gives the button both ends: a right click or a hold opens the menu, Shift+Enter
+ * saves at the start.
+ */
+ openPlacements?: (x: number, y: number, place: (atStart: boolean) => void) => void;
+ /**
+ * Where focus goes when the editor closes, instead of back to whatever held it before. A card
+ * whose editor was opened by an insert passes its own element, so closing does not focus the
+ * card the insert was made from.
+ */
+ returnFocusTo?: RefObject<HTMLElement | null>;
+ /**
+ * Whether opening the editor selects the text already in it, which is what a rename wants. An
+ * editor opened part-typed puts the caret after the text instead, so the next key continues it.
+ */
+ selectOnFocus?: boolean;
+}) {
+ const inputRef = useRef<any>(null);
+ /**
+ * What the field holds. Kept in state because `FormTextBox` takes its value as a prop: any
+ * other render, the button changing icon included, would write a stale prop back over it.
+ */
+ const [ typed, setTyped ] = useState(currentValue ?? "");
+ const isEmpty = !typed.trim();
+ const focusElRef = useRef<Element>(null);
+ const dismissOnNextRefreshRef = useRef(false);
+ const shouldDismiss = useRef(false);
+ /**
+ * Whether something the field carries is open, during which the editor stays where it is.
+ *
+ * A menu takes focus with it, and losing focus is what closes this editor: it would take the
+ * menu down with itself, which is what the icon picker and the pill naming what a card is made
+ * from both do. Held in a ref rather than in state because the blur arrives before the render
+ * a state change would schedule; focus goes back to the field as the menu closes, the blur
+ * that would have ended the edit being spent.
+ */
+ const isHoldingOpen = useRef(false);
+ /** The box holding the field and the picker. `iconFocusOut` tests `relatedTarget` against it. */
+ const fieldRef = useRef<HTMLDivElement>(null);
+ const iconRef = useRef<HTMLSpanElement>(null);
+ /**
+ * Whether the icon picker holds focus, which Shift+Tab hands to it.
+ *
+ * Set before focus moves rather than when the picker receives it: the field blurs first, and
+ * that blur is what would close the editor.
+ */
+ const isIconFocused = useRef(false);
+ const holdOpen = useMemo<HoldOpen>(() => ({
+ onOpened: () => { isHoldingOpen.current = true; },
+ onClosed: () => {
+ isHoldingOpen.current = false;
+ inputRef.current?.focus();
+ }
+ }), []);
+ /** Whether the field has already saved, for one that keeps what it saved standing. */
+ const hasHandedOver = useRef(false);
+ const held = useRef<number | undefined>(undefined);
+ /** Where on the screen the finger went down, against which a scroll is told from a hold. */
+ const heldFrom = useRef<{ x: number, y: number } | undefined>(undefined);
+ /** Whether the menu was opened by a hold, whose press ends in a click the menu must survive. */
+ const openedByHold = useRef(false);
+
+ useEffect(() => () => window.clearTimeout(held.current), []);
+
+ // Laid out rather than deferred: with the open drawn synchronously, this puts focus on the
+ // editor inside the press that asked for it, which is what opens a phone's keyboard.
+ useLayoutEffect(() => {
+ focusElRef.current = document.activeElement !== document.body ? document.activeElement : null;
+ inputRef.current?.focus();
+
+ if (selectOnFocus) {
+ inputRef.current?.select();
+ } else {
+ const end = inputRef.current?.value.length ?? 0;
+ inputRef.current?.setSelectionRange(end, end);
+ }
+ }, [ inputRef ]);
+
+ useEffect(() => {
+ if (dismissOnNextRefreshRef.current) {
+ dismiss();
+ dismissOnNextRefreshRef.current = false;
+ }
+ });
+
+ const onKeyDown = (e: TargetedKeyboardEvent<HTMLInputElement | HTMLTextAreaElement> | KeyboardEvent) => {
+ // Skip processing during IME composition so the Enter that commits a
+ // CJK conversion does not also save the title with unconfirmed text.
+ if (isIMEComposing(e)) {
+ return;
+ }
+
+ if (e.key === "Tab" && e.shiftKey && icon) {
+ const button = iconRef.current?.querySelector("button");
+ if (button) {
+ e.preventDefault();
+ e.stopPropagation();
+ isIconFocused.current = true;
+ button.focus();
+ return;
+ }
+ }
+
+ if (e.key === "Enter" && saveAndContinue) {
+ e.preventDefault();
+ e.stopPropagation();
+ submit(!!openPlacements && e.shiftKey);
+ return;
+ }
+
+ if (e.key === "Enter" || e.key === "Escape") {
+ e.preventDefault();
+ e.stopPropagation();
+ const target = returnFocusTo?.current ?? focusElRef.current;
+ if (target instanceof HTMLElement) {
+ shouldDismiss.current = (e.key === "Escape");
+ target.focus();
+ return;
+ }
+
+ // Nothing to hand focus back to, and it is the blur of handing it back that saves. An
+ // editor opened by a press on the thing it edits, rather than from something focused,
+ // has nowhere to send it, so Enter says here what that blur would have said.
+ const typed = inputRef.current?.value ?? "";
+ if (e.key === "Enter" && typed.trim() && (typed !== currentValue || isNewItem)
+ && !commit(typed)) {
+ return;
+ }
+
+ dismiss();
+ }
+ };
+
+ /**
+ * Saves what is in the editor and empties it, leaving it open for whatever comes next.
+ *
+ * @param atStart whether to save at the near end, for an editor that offers both.
+ * @param typed what to save, for a menu that read the field when it opened rather than now.
+ */
+ function submit(atStart?: boolean, typed?: string) {
+ const input = inputRef.current;
+ const value = typed ?? input?.value ?? "";
+
+ if (value.trim()) {
+ if (hasHandedOver.current) {
+ return;
+ }
+
+ if (!commit(value, atStart)) {
+ input?.focus();
+ return;
+ }
+
+ if (handsOver) {
+ hasHandedOver.current = true;
+ input?.focus();
+ return;
+ }
+
+ if (input) {
+ input.value = "";
+ }
+ }
+
+ input?.focus();
+ setTyped("");
+ }
+
+ /** Offers both ends, saving what the field held when the menu was opened. */
+ function openPlacementMenu(e: TargetedMouseEvent<HTMLElement>) {
+ e.preventDefault();
+ e.stopPropagation();
+ cancelHold();
+
+ const typed = inputRef.current?.value ?? "";
+ openPlacements?.(e.pageX, e.pageY, (atStart) => submit(atStart, typed));
+ }
+
+ /** Opens the same menu for a finger, which has no second button to open it with. */
+ function holdToPlace(e: TargetedPointerEvent<HTMLElement>) {
+ if (e.pointerType === "mouse") {
+ return;
+ }
+
+ const { pageX, pageY, clientX, clientY } = e;
+ cancelHold();
+ heldFrom.current = { x: clientX, y: clientY };
+ held.current = window.setTimeout(() => {
+ openedByHold.current = true;
+ const typed = inputRef.current?.value ?? "";
+ openPlacements?.(pageX, pageY, (atStart) => submit(atStart, typed));
+ }, HOLD_TO_PLACE_MS);
+ }
+
+ function cancelHold() {
+ window.clearTimeout(held.current);
+ heldFrom.current = undefined;
+ }
+
+ /** Gives up on a hold the finger has walked away from, which is a scroll and not a press. */
+ function holdMoved(e: TargetedPointerEvent<HTMLElement>) {
+ const from = heldFrom.current;
+ if (from && Math.hypot(e.clientX - from.x, e.clientY - from.y) > HOLD_SLACK_PX) {
+ cancelHold();
+ }
+ }
+
+ function pressed(e: TargetedMouseEvent<HTMLElement>) {
+ cancelHold();
+
+ // A hold ends in a click, which would reach the page and close the menu it just opened.
+ if (openedByHold.current) {
+ openedByHold.current = false;
+ e.stopPropagation();
+ return;
+ }
+
+ submit(false);
+ }
+
+ const onBlur = (newValue: string) => {
+ if (isHoldingOpen.current || isIconFocused.current) {
+ return;
+ }
+
+ if (saveAndContinue) {
+ abandon?.(newValue);
+ dismiss();
+ return;
+ }
+
+ if (!shouldDismiss.current && newValue.trim() && (newValue !== currentValue || isNewItem)) {
+ if (!commit(newValue)) {
+ // The field stays open, so the focus this blur took off it has to come back.
+ inputRef.current?.focus();
+ return;
+ }
+
+ dismissOnNextRefreshRef.current = true;
+ } else {
+ dismiss();
+ }
+ };
+
+ /**
+ * Ends the edit when focus moves outside `fieldRef`. A `relatedTarget` inside it is the field
+ * itself; `isHoldingOpen` covers the picker's menu, which is drawn outside `fieldRef`.
+ */
+ function iconFocusOut(e: TargetedFocusEvent<HTMLSpanElement>) {
+ isIconFocused.current = false;
+
+ const next = e.relatedTarget;
+ if (isHoldingOpen.current || (next instanceof Node && fieldRef.current?.contains(next))) {
+ return;
+ }
+
+ onBlur(inputRef.current?.value ?? "");
+ }
+
+ /** Leaves the editor from the picker, which Escape does from the field itself. */
+ function iconKeyDown(e: TargetedKeyboardEvent<HTMLSpanElement>) {
+ if (e.key !== "Escape" || isHoldingOpen.current) {
+ return;
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+ shouldDismiss.current = true;
+
+ const target = returnFocusTo?.current ?? focusElRef.current;
+ if (target instanceof HTMLElement) {
+ target.focus();
+ return;
+ }
+
+ isIconFocused.current = false;
+ dismiss();
+ }
+
+ /**
+ * Saves what was typed and reports whether `save` accepted it.
+ *
+ * A refusal is reported by `save` itself, which is what knows why it refused. A save that
+ * fails later is reported here instead of rejecting unhandled: the editor has closed by then,
+ * and whatever could not be written has already been put back.
+ */
+ function commit(newValue: string, atStart?: boolean) {
+ const outcome = save(newValue, atStart);
+ if (outcome === false) {
+ return false;
+ }
+
+ Promise.resolve(outcome).catch((e) => {
+ console.error("Failed to save what the board editor was given:", e);
+ toast.showError(t("board_view.save-error"));
+ });
+ return true;
+ }
+
+ if (mode !== "relation") {
+ const Element = mode === "multiline" ? FormTextArea : FormTextBox;
+ const field = (
+ <Element
+ inputRef={inputRef}
+ currentValue={typed}
+ placeholder={placeholder}
+ autoComplete="trilium-title-entry" // forces the auto-fill off better than the "off" value.
+ rows={mode === "multiline" ? 4 : undefined}
+ onKeyDown={onKeyDown}
+ onBlur={onBlur}
+ onInput={(e) => setTyped(e.currentTarget.value)}
+ />
+ );
+
+ if (!saveAndContinue && !icon && !footer) {
+ return field;
+ }
+
+ // A placement applies only to the button that creates. With nothing typed there is nothing
+ // to create, so the button stands for whatever the caller offers instead, or for nothing.
+ // An editor that saves once, a card being renamed above all, makes nothing and offers none.
+ const offersPlacement = !!openPlacements && !isEmpty;
+ const madeBy = submitTitle ?? t("board_view.add-new-item");
+ const offered = isEmpty
+ ? whenEmpty && {
+ icon: "bx bx-folder-open", title: whenEmpty.title, onClick: whenEmpty.onClick
+ }
+ : saveAndContinue && {
+ icon: "bx bx-plus-circle",
+ title: offersPlacement
+ ? `<span class="action">${escapeHtml(madeBy)}</span>`
+ + `<span class="hint">${escapeHtml(t("board_view.create-hold-hint"))}</span>`
+ : madeBy,
+ onClick: pressed
+ };
+
+ return (
+ <div ref={fieldRef} className={clsx("title-editor-field", {
+ "with-submit": saveAndContinue,
+ "with-footer": !!footer
+ })}>
+ {/* The press that opens the picker must not take focus out of the field: the
+ blur arrives before the picker reports itself open, and losing focus is what
+ closes the editor. */}
+ {icon && (
+ <span
+ ref={iconRef}
+ onMouseDown={(e) => e.preventDefault()}
+ onFocusOut={iconFocusOut}
+ onKeyDown={iconKeyDown}
+ >
+ <IconPickerButton
+ className="title-editor-icon"
+ icon={icon.current}
+ title={t("board_view.change-note-icon")}
+ onSelect={icon.onSelect}
+ onReset={icon.onReset}
+ // A grid of a thousand icons and a search field is a task of its own,
+ // so the board behind it is dimmed rather than left looking pressable.
+ backdrop
+ {...holdOpen}
+ />
+ </span>
+ )}
+ {field}
+ {/* The press must not take focus out of the field first: losing it is what closes
+ the editor, and it would be gone before the click arrived. */}
+ {offered && (
+ <span
+ onMouseDown={(e) => e.preventDefault()}
+ onPointerDown={offersPlacement ? holdToPlace : undefined}
+ onPointerUp={cancelHold}
+ onPointerMove={holdMoved}
+ onPointerCancel={cancelHold}
+ onContextMenu={offersPlacement ? openPlacementMenu : undefined}
+ >
+ <ActionButton
+ className="title-editor-submit"
+ icon={offered.icon}
+ text={offered.title}
+ tooltipHtml={offersPlacement}
+ tooltipClass={
+ offersPlacement ? "title-editor-submit-tooltip" : undefined}
+ onClick={offered.onClick}
+ />
+ </span>
+ )}
+ {/* Inside the field's own box, in the room made for it below the text. The press
+ must not take focus out of the field, which is what closes the editor. */}
+ {footer && (
+ <span
+ className="title-editor-footer"
+ onMouseDown={(e) => e.preventDefault()}
+ >{footer(holdOpen)}</span>
+ )}
+ </div>
+ );
+ }
+ return (
+ <NoteAutocomplete
+ inputRef={inputRef}
+ noteId={currentValue ?? ""}
+ opts={{
+ hideAllButtons: true,
+ allowCreatingNotes: true
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ dismiss();
+ }
+ }}
+ onBlur={() => dismiss()}
+ noteIdChanged={(newValue) => {
+ if (newValue && !commit(newValue)) {
+ return;
+ }
+
+ dismiss();
+ }}
+ />
+ );
+
+}
+
+/** How long a finger stays on the create button before it offers where to put the card. */
+const HOLD_TO_PLACE_MS = 500;
+
+/** How far the pointer can move during that and still count as a hold rather than a scroll. */
+const HOLD_SLACK_PX = 10;
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index 82ad8cdaff..6fc3652a14 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -6,7 +6,7 @@ import $ from "jquery";
import { render } from "preact";
import { useCallback, useEffect, useState } from "preact/hooks";
import { act } from "preact/test-utils";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { Modal as BootstrapModal, Tooltip } from "bootstrap";
@@ -26,12 +26,13 @@ import noteAttributeCache from "../../../services/note_attribute_cache";
import searchService from "../../../services/search";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
-import BoardView, { BoardViewData } from ".";
+import BoardView, { BoardViewData, loadBoardEditing } from ".";
import { getNoteTypeOptions, type NoteTypeOption } from "../../../services/note_types";
import { collectShortcutHints } from "../../../services/shortcut_hints";
import BoardApi, { getPendingWrites } from "./api";
import { RAIL_EXIT_MS } from "./card_toolbar";
import { DEFAULT_COLUMN_ICON } from "./columns";
+import { TREE_CLIPBOARD_TYPE } from "../../react/hooks";
// Stands in for the server: by the time the bulk action resolves, the notes carry the new value,
// which is what makes the old column empty rather than merely renamed.
@@ -240,6 +241,9 @@ function columnTitles(container: HTMLElement) {
return [ ...container.querySelectorAll(".board-column h3 .title") ].map(el => el.textContent);
}
+// An editable board draws once its editing code has loaded, which the app fetches on demand.
+beforeAll(() => loadBoardEditing());
+
describe("Collapsed board columns", () => {
let container: HTMLElement | undefined;
@@ -5670,6 +5674,62 @@ describe("BoardView, read-only", () => {
expect(board.querySelectorAll(".board-note.editing, .board-new-item").length).toBe(0);
});
+ it("changes nothing from the keyboard or from a note dropped from the tree", async () => {
+ const board = await setup();
+ // Opening the board records its columns, which is not the reader's doing.
+ saved.length = 0;
+ const writes = [
+ ...([
+ "removeFromBoard", "confirmAndRemoveColumn", "insertColumn", "moveToColumnEnd",
+ "reorderColumn", "changeColumn"
+ ] as const).map((name) => vi.spyOn(BoardApi.prototype, name)),
+ ...([ "deleteNotes", "moveAfterBranch" ] as const)
+ .map((name) => vi.spyOn(branches, name).mockResolvedValue(undefined as never))
+ ];
+ const card = board.querySelector<HTMLElement>(".board-note");
+ const header = board.querySelector<HTMLElement>(".board-column h3");
+ const column = board.querySelector<HTMLElement>(".board-column");
+ expect([ card, header, column ]).not.toContain(null);
+
+ const presses: [ HTMLElement | null, KeyboardEventInit ][] = [
+ [ card, { key: "Delete" } ],
+ [ card, { key: "Delete", shiftKey: true } ],
+ [ card, { key: "ArrowRight", ctrlKey: true } ],
+ [ card, { key: "ArrowDown", ctrlKey: true } ],
+ [ header, { key: "Enter", ctrlKey: true } ],
+ [ header, { key: "ArrowRight", ctrlKey: true } ],
+ [ header, { key: "Delete" } ]
+ ];
+ for (const [ target, init ] of presses) {
+ await act(async () => {
+ target?.focus();
+ target?.dispatchEvent(
+ new KeyboardEvent("keydown", { ...init, bubbles: true, cancelable: true }));
+ await flush();
+ });
+ }
+
+ const dragged = JSON.stringify(
+ [ { noteId: "roCard2", branchId: "roBranch", title: "Second" } ]);
+ for (const type of [ "dragover", "drop" ]) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "dataTransfer", {
+ value: { types: [ TREE_CLIPBOARD_TYPE ], getData: () => dragged }
+ });
+ await act(async () => {
+ column?.dispatchEvent(event);
+ await flush();
+ });
+ }
+
+ expect({
+ saved,
+ called: writes
+ .filter((write) => write.mock.calls.length)
+ .map((write) => write.getMockName())
+ }).toEqual({ saved: [], called: [] });
+ });
+
it("keeps only the entries that change nothing in the menus, and shows none for the board", async () => {
const board = await setup();
const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 97393e0854..9ce4c92b29 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -3,13 +3,10 @@ import "./index.css";
import clsx from "clsx";
-import {
- ComponentChildren, createContext, createPortal, Fragment, RefObject, TargetedFocusEvent,
- TargetedKeyboardEvent, TargetedMouseEvent, TargetedPointerEvent
-} from "preact";
+import { createContext, createPortal, Fragment, RefObject } from "preact";
import { useSyncExternalStore } from "preact/compat";
import {
- Dispatch, StateUpdater, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState
+ Dispatch, StateUpdater, useCallback, useEffect, useMemo, useRef, useState
} from "preact/hooks";
import { type HighlightedTokenInfo, normalizeBoardGroupBy } from "@triliumnext/commons";
@@ -23,11 +20,9 @@ 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";
import type { ShortcutHintDefinition } from "../../../services/shortcut_hints";
-import toast from "../../../services/toast";
import ws from "../../../services/ws";
-import { escapeHtml, isMobile } from "../../../services/utils";
+import { isMobile } from "../../../services/utils";
import { type NoteTypeOption, resolveNoteTypeOptions } from "../../../services/note_types";
import {
type PromotedAttributeSetting, resolvePromotedAttributes, visiblePromotedAttributeNames
@@ -35,20 +30,14 @@ import {
import type { SortContext } from "../sorting";
import CollectionProperties from "../../note_bars/CollectionProperties";
import { FormListItem } from "../../react/FormList";
-import FormTextArea from "../../react/FormTextArea";
-import FormTextBox from "../../react/FormTextBox";
import {
useContextualShortcutHints, useEffectiveReadOnly, useLingeringTrue, useNoteContext, useNoteLabel,
useNoteLabelBoolean, useNoteLabelWithDefault, useNoteTypeOptions, useSetContextData,
useTrackedElement, useTriliumEvent
} from "../../react/hooks";
-import Icon from "../../react/Icon";
-import NoteAutocomplete from "../../react/NoteAutocomplete";
import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";
import { ShortcutHintOverlayButton } from "../../shortcut_hints/shortcut_hint_button";
import { onWheelHorizontalScroll } from "../../widget_utils";
-import ActionButton from "../../react/ActionButton";
-import { IconPickerButton } from "../../react/IconPicker";
import { useDragPan } from "../../react/drag_pan";
import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";
import { SelectionContext, SelectionStore } from "../../react/selection";
@@ -57,7 +46,7 @@ import { BoardRailContext, RAIL_EXIT_MS, RailStand, SelectionToolbar } from "./c
import BoardHeaderTools from "./selection_bar";
import { ViewModeProps } from "../interface";
import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api";
-import { askForMenu, useBoardDrag } from "./board_drag";
+import type { BoardDragCallbacks } from "./board_drag";
import { columnGapStandsAside, columnStandsAside, movesColumn } from "./drag_geometry";
import { forgetCardHeights } from "./drag_measure";
import { forgetWindowHeights } from "./windowing";
@@ -65,23 +54,20 @@ import { BoardDropStateContext, DropStateStore } from "./drop_state";
import BoardApi from "./api";
import { adoptLegacyColumns, readColumns } from "./column_storage";
import {
- COLUMN_WIDTH_LABEL, columnWidthClass, DEFAULT_COLUMN_ICON, DEFAULT_GROUP_BY,
- getStatusDefinition, INBOX_COLUMN
+ COLUMN_WIDTH_LABEL, columnWidthClass, DEFAULT_GROUP_BY, getStatusDefinition, INBOX_COLUMN
} from "./columns";
import Column, { clearGap, EXPAND_MS, placeCard, settleCards } from "./column";
import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";
-import ColumnLimitDialog from "./column_limit";
import BoardGroupBy, { groupingOptions } from "./group_by";
-import BoardProperties from "./properties";
import { useBoardReference } from "./reference";
-import { openBoardContextMenu, openCreateColumnMenu } from "./context_menu";
+import { openBoardContextMenu } from "./context_menu";
import { useBoardSort } from "./sort";
import {
affectsCardDefinitions, affectsSortOrder, applyCardMoves, cardNotes, ColumnMap,
definitionSources, filterColumnMap, getBoardData, resolveColumnSorts, resolveSortWatch,
sortColumnMap, unfilteredCardIndex
} from "./data";
-import { useBoardKeyboard } from "./keyboard";
+import { askForMenu, useBoardKeyboard } from "./keyboard";
/**
* What a control standing inside an editor's field calls as it opens and closes.
@@ -254,6 +240,12 @@ export const BoardActionsContext = createContext<BoardActions>({
setInsertingColumn: () => undefined
});
+/**
+ * The board's editing code, which `BoardView` loads only for a board that can be edited: `null` on
+ * a read-only board, whose cards and columns then draw no editor.
+ */
+export const BoardEditingContext = createContext<BoardEditing | null>(null);
+
/**
* Which promoted attributes a card draws, in order.
*
@@ -294,12 +286,6 @@ const NO_COLUMNS: ReadonlySet<string> = new Set();
/** Shared empty map for a filter under which no column has been opened or closed by hand. */
const NO_FILTER_COLLAPSE: ReadonlyMap<string, boolean> = new Map();
-/** How long a finger stays on the create button before it offers where to put the card. */
-const HOLD_TO_PLACE_MS = 500;
-
-/** How far the pointer can move during that and still count as a hold rather than a scroll. */
-const HOLD_SLACK_PX = 10;
-
const BOARD_HINTS: ShortcutHintDefinition = [
{
titleKey: "board_view.hints.navigation",
@@ -359,11 +345,32 @@ const BOARD_HINTS: ShortcutHintDefinition = [
}
];
-export default function BoardView({
- note: parentNote, noteIds, viewConfig: storedConfig, saveConfig, onOpenNote
-}: ViewModeProps<BoardViewData>) {
+/**
+ * Draws a board, with its editing code for a board that can be edited. A board opened editable
+ * waits for that code before it draws; one made editable while open stays read-only until it
+ * arrives, rather than being drawn again from scratch.
+ */
+export default function BoardView(props: ViewModeProps<BoardViewData>) {
+ const { noteContext } = useNoteContext();
+ const isReadOnly = useEffectiveReadOnly(props.note, noteContext);
+ const editing = useBoardEditing(!isReadOnly);
+ const [ waitsForEditing ] = useState(!isReadOnly && editing === undefined);
+ if (waitsForEditing && editing === undefined) {
+ return undefined;
+ }
+
+ const shownEditing = isReadOnly ? null : editing ?? null;
+ return (
+ <BoardEditingContext.Provider value={shownEditing}>
+ <Board {...props} isReadOnly={!shownEditing} editing={shownEditing} />
+ </BoardEditingContext.Provider>
+ );
+}
+
+function Board({
+ note: parentNote, noteIds, viewConfig: storedConfig, saveConfig, onOpenNote, isReadOnly, editing
+}: ViewModeProps<BoardViewData> & { isReadOnly: boolean, editing: BoardEditing | null }) {
const { noteContext } = useNoteContext();
- const isReadOnly = useEffectiveReadOnly(parentNote, noteContext);
const [ requestedGroupBy, setRequestedGroupBy ] = useGroupBy(parentNote, isReadOnly);
/**
* The grouping the board draws and writes for.
@@ -984,7 +991,8 @@ export default function BoardView({
// The gesture drives the same state a drag from the note tree does, so the placeholders and the
// card's own dimming are drawn from one place whichever brought the card here.
- const { isDragging: isDraggingItem, remeasure } = useBoardDrag(containerRef, {
+ const [ isDraggingItem, setIsDraggingItem ] = useState(false);
+ const dragCallbacks: BoardDragCallbacks = {
carriedWith: (noteId) => (selection.has(noteId)
? api.getCards(selection.keys).map((card) => card.note.noteId)
: [ noteId ]),
@@ -1097,17 +1105,7 @@ export default function BoardView({
setDraggedColumn(null);
setColumnDropPosition(null);
}
- });
-
- // A column opened to take the card moves every column after it, which the measurement predates.
- // Only for a card: a carried column is measured among the columns as they stood when it was
- // picked up, which is the list the place it would take is counted against, and measuring again
- // with it out of the flow would count one place fewer than the board has.
- useLayoutEffect(() => {
- if (isDraggingItem && !draggedColumn) {
- remeasure();
- }
- }, [ isDraggingItem, draggedColumn, remeasure, activeColumn, shownColumns ]);
+ };
// Only the board's own background, so a press on a column, a card or the button that adds one
// is left to whatever it belongs to. Suppressed while a card is carried: the gesture owns the
@@ -1528,7 +1526,7 @@ export default function BoardView({
</div>
- {!isReadOnly && <AddNewColumn
+ {editing && <editing.AddNewColumn
api={api}
isInRelationMode={isInRelationMode}
columnCount={shownColumns.length}
@@ -1539,17 +1537,25 @@ export default function BoardView({
{/* Where what is being carried is put. Preact draws the layer and never
its contents, so the copy is not among the children it places. */}
<div className="board-drag-layer" />
+ {editing && <editing.BoardDrag
+ containerRef={containerRef}
+ callbacks={dragCallbacks}
+ isCarryingColumn={!!draggedColumn}
+ activeColumn={activeColumn}
+ shownColumns={shownColumns}
+ onDraggingChange={setIsDraggingItem}
+ />}
{/* Out of the board and onto the page: a dialog is positioned against the
window, and Bootstrap puts its backdrop on the body, so a stacking
context above the board would trap it underneath. */}
- {createPortal(
+ {editing && createPortal(
<>
- <ColumnLimitDialog
+ <editing.ColumnLimitDialog
api={api}
column={columnLimitToEdit}
onClose={() => setColumnLimitToEdit(undefined)}
/>
- <BoardProperties
+ <editing.BoardProperties
api={api}
note={parentNote}
shown={isEditingProperties}
@@ -1594,7 +1600,7 @@ export default function BoardView({
?.querySelectorAll<HTMLElement>(".board-note") ?? [] ]
.find((element) => element.dataset.noteId === first);
if (card) {
- askForMenu(card, e.clientX, e.clientY);
+ askForMenu(card, { x: e.clientX, y: e.clientY });
}
}}
/>
@@ -1727,571 +1733,35 @@ function useGroupBy(note: FNote, isReadOnly: boolean): [ string, (groupBy: strin
return isReadOnly ? [ viewed ?? label, setViewed ] : [ label, setLabel ];
}
-function AddNewColumn({
- api, isInRelationMode, columnCount, onCreated, isCreating, setIsCreating
-}: {
- api: BoardApi,
- isInRelationMode: boolean,
- /** How many columns stand before this, which is what carries it past the board's edge. */
- columnCount: number,
- /** Names the column just made, which the board reveals as it draws it. */
- onCreated: (column: string) => void,
- /** Whether the editor is open. The board's own menu opens the same one this slot opens. */
- isCreating: boolean,
- setIsCreating: (isCreating: boolean) => void
-}) {
- const isCreatingNewColumn = isCreating;
- const setIsCreatingNewColumn = setIsCreating;
- // Kept between columns, as the card editor keeps its own: a run of columns is often a run of
- // the same kind of column.
- const [ icon, setIcon ] = useState(DEFAULT_COLUMN_ICON);
- const slotRef = useRef<HTMLDivElement>(null);
-
- // Keyed on the count rather than done when the write returns: the column it makes room for is
- // drawn by a refresh that has yet to run at that point, so the board is not yet as wide as it
- // is about to be.
- useLayoutEffect(() => {
- if (!isCreatingNewColumn) {
- return;
- }
-
- const board = slotRef.current?.closest<HTMLElement>(".board-view-container");
- if (!board) {
- return;
- }
-
- board.scrollLeft = board.scrollWidth;
- }, [ columnCount, isCreatingNewColumn ]);
+type BoardEditing = typeof import("./editing");
- const addColumnCallback = useCallback(() => {
- setIsCreatingNewColumn(true);
- }, []);
-
- const keydownCallback = useCallback((e: KeyboardEvent) => {
- if (e.key === "Enter") {
- setIsCreatingNewColumn(true);
- }
- }, []);
+let loadedEditing: BoardEditing | undefined;
+let editingLoad: Promise<BoardEditing> | undefined;
- return (
- <div
- ref={slotRef}
- className={`board-add-column ${isCreatingNewColumn ? "editing" : ""}`}
- onClick={addColumnCallback}
- onKeyDown={keydownCallback}
- tabIndex={300}
- >
- {!isCreatingNewColumn
- ? <>
- <Icon icon="bx bx-plus" />{" "}
- {t("board_view.add-column")}
- </>
- : (
- <TitleEditor
- placeholder={t("board_view.add-column-placeholder")}
- save={async (columnName, atStart) => {
- const created = await api.addNewColumn(columnName, atStart,
- icon !== DEFAULT_COLUMN_ICON ? icon : undefined);
- if (created) {
- onCreated(columnName);
- } else {
- toast.showMessage(t("board_view.column-already-exists"), undefined, "bx bx-duplicate");
- }
- }}
- dismiss={() => setIsCreatingNewColumn(false)}
- isNewItem
- // Columns are added in runs as a board is set up, so the editor is left
- // standing with an empty field. A column named by a note answers for
- // itself, since picking one is what closes that editor.
- saveAndContinue={!isInRelationMode}
- submitTitle={t("board_view.create-new-column")}
- openPlacements={openCreateColumnMenu}
- // The same picker the column's own heading carries, so a column is given
- // its icon as it is named rather than after it stands there.
- icon={{
- current: icon,
- onSelect: setIcon,
- onReset: icon !== DEFAULT_COLUMN_ICON
- ? () => setIcon(DEFAULT_COLUMN_ICON)
- : undefined
- }}
- mode={isInRelationMode ? "relation" : "normal"}
- />
- )}
- </div>
- );
+/** Loads the board's editing code once, which a spec does ahead of drawing an editable board. */
+export function loadBoardEditing() {
+ editingLoad ??= import("./editing").then((editing) => {
+ loadedEditing = editing;
+ return editing;
+ });
+ return editingLoad;
}
-export function TitleEditor({
- currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true,
- saveAndContinue = false, handsOver = false, returnFocusTo, abandon, whenEmpty, submitTitle,
- openPlacements, icon, footer
-}: {
- currentValue?: string;
- placeholder?: string;
- /**
- * Writes what was typed. Returns `false` to refuse it, which keeps the editor open on what it
- * holds so the reader can correct it.
- */
- save: (newValue: string, atStart?: boolean) => false | void | Promise<void>;
- dismiss: () => void;
- isNewItem?: boolean;
- mode?: "normal" | "multiline" | "relation";
- /**
- * Whether Enter saves and clears the editor rather than closing it, so a run of cards can be
- * typed one after another. Enter is then the only thing that saves: Escape and losing focus
- * discard what was typed and close the editor. An editor left standing between cards is walked
- * away from often enough that saving on the way out would create cards nobody asked for.
- */
- saveAndContinue?: boolean;
- /**
- * Whether the field keeps what was typed once it has saved, and saves only once.
- *
- * For an editor the caller takes down as what it made takes its place: emptied instead, the
- * field would stand where the new thing is about to be drawn without holding what it says.
- */
- handsOver?: boolean;
- /** Reports what was typed and not saved, so reopening the editor can restore it. */
- abandon?: (typed: string) => void;
- /**
- * What the button does while the field is empty, drawn as `bx bx-folder-open`. Without it no
- * button is drawn at all until something is typed.
- */
- whenEmpty?: { title: string, onClick?: () => void };
- /** Names what the button creates, shown in its tooltip. */
- submitTitle?: string;
- /**
- * What stands at the foot of the field, inside its own box: the pill naming what a new card
- * will be made from. The field is given room for it.
- */
- footer?: (hold: HoldOpen) => ComponentChildren;
- /**
- * The icon shown inside the field, at the leading edge, which opens the picker when pressed.
- * The caller answers for what a pick does: a card carries it as `iconClass`, and the editor a
- * card is made in keeps it for the next card.
- */
- icon?: { current: string, onSelect: (icon: string) => void, onReset?: () => void };
- /**
- * Opens the menu naming which end to create at, for a `save` that reads `atStart`. Passing it
- * is what gives the button both ends: a right click or a hold opens the menu, Shift+Enter
- * saves at the start.
- */
- openPlacements?: (x: number, y: number, place: (atStart: boolean) => void) => void;
- /**
- * Where focus goes when the editor closes, instead of back to whatever held it before. A card
- * whose editor was opened by an insert passes its own element, so closing does not focus the
- * card the insert was made from.
- */
- returnFocusTo?: RefObject<HTMLElement | null>;
- /**
- * Whether opening the editor selects the text already in it, which is what a rename wants. An
- * editor opened part-typed puts the caret after the text instead, so the next key continues it.
- */
- selectOnFocus?: boolean;
-}) {
- const inputRef = useRef<any>(null);
- /**
- * What the field holds. Kept in state because `FormTextBox` takes its value as a prop: any
- * other render, the button changing icon included, would write a stale prop back over it.
- */
- const [ typed, setTyped ] = useState(currentValue ?? "");
- const isEmpty = !typed.trim();
- const focusElRef = useRef<Element>(null);
- const dismissOnNextRefreshRef = useRef(false);
- const shouldDismiss = useRef(false);
- /**
- * Whether something the field carries is open, during which the editor stays where it is.
- *
- * A menu takes focus with it, and losing focus is what closes this editor: it would take the
- * menu down with itself, which is what the icon picker and the pill naming what a card is made
- * from both do. Held in a ref rather than in state because the blur arrives before the render
- * a state change would schedule; focus goes back to the field as the menu closes, the blur
- * that would have ended the edit being spent.
- */
- const isHoldingOpen = useRef(false);
- /** The box holding the field and the picker. `iconFocusOut` tests `relatedTarget` against it. */
- const fieldRef = useRef<HTMLDivElement>(null);
- const iconRef = useRef<HTMLSpanElement>(null);
- /**
- * Whether the icon picker holds focus, which Shift+Tab hands to it.
- *
- * Set before focus moves rather than when the picker receives it: the field blurs first, and
- * that blur is what would close the editor.
- */
- const isIconFocused = useRef(false);
- const holdOpen = useMemo<HoldOpen>(() => ({
- onOpened: () => { isHoldingOpen.current = true; },
- onClosed: () => {
- isHoldingOpen.current = false;
- inputRef.current?.focus();
- }
- }), []);
- /** Whether the field has already saved, for one that keeps what it saved standing. */
- const hasHandedOver = useRef(false);
- const held = useRef<number | undefined>(undefined);
- /** Where on the screen the finger went down, against which a scroll is told from a hold. */
- const heldFrom = useRef<{ x: number, y: number } | undefined>(undefined);
- /** Whether the menu was opened by a hold, whose press ends in a click the menu must survive. */
- const openedByHold = useRef(false);
-
- useEffect(() => () => window.clearTimeout(held.current), []);
-
- // Laid out rather than deferred: with the open drawn synchronously, this puts focus on the
- // editor inside the press that asked for it, which is what opens a phone's keyboard.
- useLayoutEffect(() => {
- focusElRef.current = document.activeElement !== document.body ? document.activeElement : null;
- inputRef.current?.focus();
-
- if (selectOnFocus) {
- inputRef.current?.select();
- } else {
- const end = inputRef.current?.value.length ?? 0;
- inputRef.current?.setSelectionRange(end, end);
- }
- }, [ inputRef ]);
-
+/**
+ * The board's editing code once it has loaded, loading it for an editable board: `undefined` while
+ * it loads, and `null` when it failed to, which leaves the board read-only.
+ */
+function useBoardEditing(isEditable: boolean) {
+ const [ editing, setEditing ] = useState<BoardEditing | null | undefined>(loadedEditing);
useEffect(() => {
- if (dismissOnNextRefreshRef.current) {
- dismiss();
- dismissOnNextRefreshRef.current = false;
- }
- });
-
- const onKeyDown = (e: TargetedKeyboardEvent<HTMLInputElement | HTMLTextAreaElement> | KeyboardEvent) => {
- // Skip processing during IME composition so the Enter that commits a
- // CJK conversion does not also save the title with unconfirmed text.
- if (isIMEComposing(e)) {
- return;
- }
-
- if (e.key === "Tab" && e.shiftKey && icon) {
- const button = iconRef.current?.querySelector("button");
- if (button) {
- e.preventDefault();
- e.stopPropagation();
- isIconFocused.current = true;
- button.focus();
- return;
- }
- }
-
- if (e.key === "Enter" && saveAndContinue) {
- e.preventDefault();
- e.stopPropagation();
- submit(!!openPlacements && e.shiftKey);
+ if (!isEditable || editing !== undefined) {
return;
}
- if (e.key === "Enter" || e.key === "Escape") {
- e.preventDefault();
- e.stopPropagation();
- const target = returnFocusTo?.current ?? focusElRef.current;
- if (target instanceof HTMLElement) {
- shouldDismiss.current = (e.key === "Escape");
- target.focus();
- return;
- }
-
- // Nothing to hand focus back to, and it is the blur of handing it back that saves. An
- // editor opened by a press on the thing it edits, rather than from something focused,
- // has nowhere to send it, so Enter says here what that blur would have said.
- const typed = inputRef.current?.value ?? "";
- if (e.key === "Enter" && typed.trim() && (typed !== currentValue || isNewItem)
- && !commit(typed)) {
- return;
- }
-
- dismiss();
- }
- };
-
- /**
- * Saves what is in the editor and empties it, leaving it open for whatever comes next.
- *
- * @param atStart whether to save at the near end, for an editor that offers both.
- * @param typed what to save, for a menu that read the field when it opened rather than now.
- */
- function submit(atStart?: boolean, typed?: string) {
- const input = inputRef.current;
- const value = typed ?? input?.value ?? "";
-
- if (value.trim()) {
- if (hasHandedOver.current) {
- return;
- }
-
- if (!commit(value, atStart)) {
- input?.focus();
- return;
- }
-
- if (handsOver) {
- hasHandedOver.current = true;
- input?.focus();
- return;
- }
-
- if (input) {
- input.value = "";
- }
- }
-
- input?.focus();
- setTyped("");
- }
-
- /** Offers both ends, saving what the field held when the menu was opened. */
- function openPlacementMenu(e: TargetedMouseEvent<HTMLElement>) {
- e.preventDefault();
- e.stopPropagation();
- cancelHold();
-
- const typed = inputRef.current?.value ?? "";
- openPlacements?.(e.pageX, e.pageY, (atStart) => submit(atStart, typed));
- }
-
- /** Opens the same menu for a finger, which has no second button to open it with. */
- function holdToPlace(e: TargetedPointerEvent<HTMLElement>) {
- if (e.pointerType === "mouse") {
- return;
- }
-
- const { pageX, pageY, clientX, clientY } = e;
- cancelHold();
- heldFrom.current = { x: clientX, y: clientY };
- held.current = window.setTimeout(() => {
- openedByHold.current = true;
- const typed = inputRef.current?.value ?? "";
- openPlacements?.(pageX, pageY, (atStart) => submit(atStart, typed));
- }, HOLD_TO_PLACE_MS);
- }
-
- function cancelHold() {
- window.clearTimeout(held.current);
- heldFrom.current = undefined;
- }
-
- /** Gives up on a hold the finger has walked away from, which is a scroll and not a press. */
- function holdMoved(e: TargetedPointerEvent<HTMLElement>) {
- const from = heldFrom.current;
- if (from && Math.hypot(e.clientX - from.x, e.clientY - from.y) > HOLD_SLACK_PX) {
- cancelHold();
- }
- }
-
- function pressed(e: TargetedMouseEvent<HTMLElement>) {
- cancelHold();
-
- // A hold ends in a click, which would reach the page and close the menu it just opened.
- if (openedByHold.current) {
- openedByHold.current = false;
- e.stopPropagation();
- return;
- }
-
- submit(false);
- }
-
- const onBlur = (newValue: string) => {
- if (isHoldingOpen.current || isIconFocused.current) {
- return;
- }
-
- if (saveAndContinue) {
- abandon?.(newValue);
- dismiss();
- return;
- }
-
- if (!shouldDismiss.current && newValue.trim() && (newValue !== currentValue || isNewItem)) {
- if (!commit(newValue)) {
- // The field stays open, so the focus this blur took off it has to come back.
- inputRef.current?.focus();
- return;
- }
-
- dismissOnNextRefreshRef.current = true;
- } else {
- dismiss();
- }
- };
-
- /**
- * Ends the edit when focus moves outside `fieldRef`. A `relatedTarget` inside it is the field
- * itself; `isHoldingOpen` covers the picker's menu, which is drawn outside `fieldRef`.
- */
- function iconFocusOut(e: TargetedFocusEvent<HTMLSpanElement>) {
- isIconFocused.current = false;
-
- const next = e.relatedTarget;
- if (isHoldingOpen.current || (next instanceof Node && fieldRef.current?.contains(next))) {
- return;
- }
-
- onBlur(inputRef.current?.value ?? "");
- }
-
- /** Leaves the editor from the picker, which Escape does from the field itself. */
- function iconKeyDown(e: TargetedKeyboardEvent<HTMLSpanElement>) {
- if (e.key !== "Escape" || isHoldingOpen.current) {
- return;
- }
-
- e.preventDefault();
- e.stopPropagation();
- shouldDismiss.current = true;
-
- const target = returnFocusTo?.current ?? focusElRef.current;
- if (target instanceof HTMLElement) {
- target.focus();
- return;
- }
-
- isIconFocused.current = false;
- dismiss();
- }
-
- /**
- * Saves what was typed and reports whether `save` accepted it.
- *
- * A refusal is reported by `save` itself, which is what knows why it refused. A save that
- * fails later is reported here instead of rejecting unhandled: the editor has closed by then,
- * and whatever could not be written has already been put back.
- */
- function commit(newValue: string, atStart?: boolean) {
- const outcome = save(newValue, atStart);
- if (outcome === false) {
- return false;
- }
-
- Promise.resolve(outcome).catch((e) => {
- console.error("Failed to save what the board editor was given:", e);
- toast.showError(t("board_view.save-error"));
+ loadBoardEditing().then(setEditing, (error: unknown) => {
+ console.error("Failed to load the board's editing code:", error);
+ setEditing(null);
});
- return true;
- }
-
- if (mode !== "relation") {
- const Element = mode === "multiline" ? FormTextArea : FormTextBox;
- const field = (
- <Element
- inputRef={inputRef}
- currentValue={typed}
- placeholder={placeholder}
- autoComplete="trilium-title-entry" // forces the auto-fill off better than the "off" value.
- rows={mode === "multiline" ? 4 : undefined}
- onKeyDown={onKeyDown}
- onBlur={onBlur}
- onInput={(e) => setTyped(e.currentTarget.value)}
- />
- );
-
- if (!saveAndContinue && !icon && !footer) {
- return field;
- }
-
- // A placement applies only to the button that creates. With nothing typed there is nothing
- // to create, so the button stands for whatever the caller offers instead, or for nothing.
- // An editor that saves once, a card being renamed above all, makes nothing and offers none.
- const offersPlacement = !!openPlacements && !isEmpty;
- const madeBy = submitTitle ?? t("board_view.add-new-item");
- const offered = isEmpty
- ? whenEmpty && {
- icon: "bx bx-folder-open", title: whenEmpty.title, onClick: whenEmpty.onClick
- }
- : saveAndContinue && {
- icon: "bx bx-plus-circle",
- title: offersPlacement
- ? `<span class="action">${escapeHtml(madeBy)}</span>`
- + `<span class="hint">${escapeHtml(t("board_view.create-hold-hint"))}</span>`
- : madeBy,
- onClick: pressed
- };
-
- return (
- <div ref={fieldRef} className={clsx("title-editor-field", {
- "with-submit": saveAndContinue,
- "with-footer": !!footer
- })}>
- {/* The press that opens the picker must not take focus out of the field: the
- blur arrives before the picker reports itself open, and losing focus is what
- closes the editor. */}
- {icon && (
- <span
- ref={iconRef}
- onMouseDown={(e) => e.preventDefault()}
- onFocusOut={iconFocusOut}
- onKeyDown={iconKeyDown}
- >
- <IconPickerButton
- className="title-editor-icon"
- icon={icon.current}
- title={t("board_view.change-note-icon")}
- onSelect={icon.onSelect}
- onReset={icon.onReset}
- // A grid of a thousand icons and a search field is a task of its own,
- // so the board behind it is dimmed rather than left looking pressable.
- backdrop
- {...holdOpen}
- />
- </span>
- )}
- {field}
- {/* The press must not take focus out of the field first: losing it is what closes
- the editor, and it would be gone before the click arrived. */}
- {offered && (
- <span
- onMouseDown={(e) => e.preventDefault()}
- onPointerDown={offersPlacement ? holdToPlace : undefined}
- onPointerUp={cancelHold}
- onPointerMove={holdMoved}
- onPointerCancel={cancelHold}
- onContextMenu={offersPlacement ? openPlacementMenu : undefined}
- >
- <ActionButton
- className="title-editor-submit"
- icon={offered.icon}
- text={offered.title}
- tooltipHtml={offersPlacement}
- tooltipClass={
- offersPlacement ? "title-editor-submit-tooltip" : undefined}
- onClick={offered.onClick}
- />
- </span>
- )}
- {/* Inside the field's own box, in the room made for it below the text. The press
- must not take focus out of the field, which is what closes the editor. */}
- {footer && (
- <span
- className="title-editor-footer"
- onMouseDown={(e) => e.preventDefault()}
- >{footer(holdOpen)}</span>
- )}
- </div>
- );
- }
- return (
- <NoteAutocomplete
- inputRef={inputRef}
- noteId={currentValue ?? ""}
- opts={{
- hideAllButtons: true,
- allowCreatingNotes: true
- }}
- onKeyDown={(e) => {
- if (e.key === "Escape") {
- dismiss();
- }
- }}
- onBlur={() => dismiss()}
- noteIdChanged={(newValue) => {
- if (newValue && !commit(newValue)) {
- return;
- }
-
- dismiss();
- }}
- />
- );
-
+ }, [ isEditable, editing ]);
+ return editing;
}
diff --git a/apps/client/src/widgets/collections/board/keyboard.spec.tsx b/apps/client/src/widgets/collections/board/keyboard.spec.tsx
index f565a38be2..b3672684c9 100644
--- a/apps/client/src/widgets/collections/board/keyboard.spec.tsx
+++ b/apps/client/src/widgets/collections/board/keyboard.spec.tsx
@@ -6,7 +6,7 @@
import $ from "jquery";
import { render } from "preact";
import { act } from "preact/test-utils";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import appContext from "../../../components/app_context";
import Component from "../../../components/component";
@@ -19,7 +19,7 @@ import server from "../../../services/server";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
import BoardApi from "./api";
-import BoardView, { BoardViewData } from ".";
+import BoardView, { BoardViewData, loadBoardEditing } from ".";
vi.mock("../../../services/branches", () => ({
default: {
@@ -45,6 +45,9 @@ vi.mock("../../../services/i18n", () => ({
translationsInitializedPromise: $.Deferred().resolve()
}));
+// An editable board draws once its editing code has loaded, which the app fetches on demand.
+beforeAll(() => loadBoardEditing());
+
describe("Board keyboard", () => {
let container: HTMLElement | undefined;
const saved: BoardViewData[] = [];
diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.ts
index 1123c5fdf1..b59fcca7bf 100644
--- a/apps/client/src/widgets/collections/board/keyboard.ts
+++ b/apps/client/src/widgets/collections/board/keyboard.ts
@@ -238,6 +238,9 @@ export function useBoardKeyboard({
return;
}
+ // Every key below edits the board.
+ if (api.isReadOnly) return;
+
// A column beside the one focus is in, wherever inside it focus sits. The button that
// adds a column stands beside none, and is the plain way to add one at the end anyway.
if (e.key === "Enter" && !e.altKey && spot.kind !== "add-column") {
@@ -369,6 +372,8 @@ export function useBoardKeyboard({
return;
}
+ if (api.isReadOnly) return;
+
if (e.key === "Delete" && spot.kind === "header" && !e.shiftKey) {
take(e);
@@ -445,18 +450,19 @@ function neighbourOf(
}
/**
- * Asks the focused card or header for its menu the way a right click does, rather than by opening
- * one here: both already answer for `contextmenu`, and what each menu offers is theirs to say.
+ * Asks a card or a header for its menu the way a right click does, rather than by opening one
+ * here: both already answer for `contextmenu`, and what each menu offers is theirs to say.
*
- * The press is taken first, so the browser sends no `contextmenu` of its own and the menu is not
- * opened twice. Where it opens is named here, a key press carrying no position of its own.
+ * The menu opens at `at`, else below the element's leading corner, for a key press, which carries
+ * no position of its own. A key press is taken first, so the browser sends no `contextmenu` of its
+ * own and the menu is not opened twice.
*/
-function askForMenu(element: HTMLElement) {
+export function askForMenu(element: HTMLElement, at?: { x: number, y: number }) {
const { left, bottom } = element.getBoundingClientRect();
element.dispatchEvent(new MouseEvent("contextmenu", {
bubbles: true,
- clientX: left,
- clientY: bottom
+ clientX: at?.x ?? left,
+ clientY: at?.y ?? bottom
}));
}
diff --git a/apps/client/src/widgets/collections/board/reference.spec.tsx b/apps/client/src/widgets/collections/board/reference.spec.tsx
index 47f0a3c730..b6fa111e12 100644
--- a/apps/client/src/widgets/collections/board/reference.spec.tsx
+++ b/apps/client/src/widgets/collections/board/reference.spec.tsx
@@ -4,7 +4,7 @@
*/
import { render } from "preact";
import { act } from "preact/test-utils";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import Component from "../../../components/component";
import type NoteContext from "../../../components/note_context";
@@ -13,7 +13,7 @@ import type { ViewScope } from "../../../services/link";
import toast from "../../../services/toast";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
-import BoardView, { type BoardViewData } from ".";
+import BoardView, { type BoardViewData, loadBoardEditing } from ".";
import {
cardReference, columnReference, COLUMN_ID_LENGTH, findColumnById, newColumnId, readColumnId,
waitFor
@@ -38,6 +38,9 @@ const TODO_ID = "colTodo00001";
const DONE_ID = "colDone00001";
const HIGH_ID = "colHigh00001";
+// An editable board draws once its editing code has loaded, which the app fetches on demand.
+beforeAll(() => loadBoardEditing());
+
describe("board reference links", () => {
it("names a column and a card in a note path the app can follow", () => {
const label = { title: "To Do", icon: "bx bx-star", color: "#ff8800" };
diff --git a/apps/client/src/widgets/collections/promoted_attributes.ts b/apps/client/src/widgets/collections/promoted_attributes.ts
index 5cd300384c..6388bc9897 100644
--- a/apps/client/src/widgets/collections/promoted_attributes.ts
+++ b/apps/client/src/widgets/collections/promoted_attributes.ts
@@ -2,7 +2,6 @@ import type { BulkAction } from "@triliumnext/commons";
import type FAttribute from "../../entities/fattribute";
import type FNote from "../../entities/fnote";
-import { executeBulkActions } from "../../services/bulk_action";
import { t } from "../../services/i18n";
/** How one promoted attribute is shown, as a collection's view config stores it. */
@@ -188,13 +187,14 @@ export function storedPromotedAttributes(attributes: PromotedAttribute[]): Promo
* Renames an attribute on the collection and everything under it, so the values follow the
* definition they were written against.
*/
-export function renameAttributeInSubtree(
+export async function renameAttributeInSubtree(
parentNoteId: string, type: "label" | "relation", oldName: string, newName: string
) {
const action: BulkAction = type === "label"
? { name: "renameLabel", oldLabelName: oldName, newLabelName: newName }
: { name: "renameRelation", oldRelationName: oldName, newRelationName: newName };
+ const { executeBulkActions } = await import("../../services/bulk_action");
return executeBulkActions([ parentNoteId ], [ action ], { includeDescendants: true });
}
@@ -202,13 +202,14 @@ export function renameAttributeInSubtree(
* Deletes an attribute from the collection and everything under it. Silent: the attribute leaving
* the list and the items reports it, and a toast over the dialog reads as something else.
*/
-export function deleteAttributeInSubtree(
+export async function deleteAttributeInSubtree(
parentNoteId: string, type: "label" | "relation", name: string
) {
const action: BulkAction = type === "label"
? { name: "deleteLabel", labelName: name }
: { name: "deleteRelation", relationName: name };
+ const { executeBulkActions } = await import("../../services/bulk_action");
return executeBulkActions(
[ parentNoteId ], [ action ], { includeDescendants: true, silent: true });
}
diff --git a/apps/client/src/widgets/note_tree.ts b/apps/client/src/widgets/note_tree.ts
index 0e8247d32e..d2b3485b06 100644
--- a/apps/client/src/widgets/note_tree.ts
+++ b/apps/client/src/widgets/note_tree.ts
@@ -184,17 +184,6 @@ interface RefreshContext {
noteIdsToReload: Set<string>;
}
-/**
- * The information contained within a drag event.
- */
-export interface DragData {
- noteId: string;
- branchId: string;
- title: string;
-}
-
-export const TREE_CLIPBOARD_TYPE = "application/x-fancytree-node";
-
/** Entity changes below the given threshold will be processed without batching to avoid performance degradation. */
const BATCH_UPDATE_THRESHOLD = 10;
diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx b/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx
index 38cdcd1909..6700fb74e8 100644
--- a/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx
+++ b/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx
@@ -546,10 +546,10 @@ describe("PromotedAttributesCard", () => {
});
}
+ /** Lets the card's writes run, the bulk action among them, which loads its service first. */
async function flush() {
- for (let step = 0; step < 4; step++) {
- await Promise.resolve();
- }
+ await import("../../services/bulk_action");
+ await new Promise((resolve) => setTimeout(resolve, 0));
}
function press(target: Element, key: string, options: KeyboardEventInit = {}) {
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 9b24d9dd6f..60f19185e9 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -35,7 +35,6 @@ import utils, { getErrorMessage, isShare, randomString, reloadFrontendApp } from
import ws from "../../services/ws";
import BasicWidget, { ReactWrappedWidget } from "../basic_widget";
import NoteContextAwareWidget from "../note_context_aware_widget";
-import { DragData } from "../note_tree";
import { noteSavedDataStore } from "./NoteStore";
import { findClosestNoteContext, NoteContextContext, ParentComponent, refToJQuerySelector } from "./react_utils";
import type FAttachment from "../../entities/fattachment";
@@ -1697,6 +1696,16 @@ export function useImperativeSearchHighlighlighting(
};
}
+/** A note the note tree's drag carries, as JSON under the `text` type. */
+export interface DragData {
+ noteId: string;
+ branchId: string;
+ title: string;
+}
+
+/** The type that marks a drag as holding notes from the note tree, as fancytree's `dnd5` sets. */
+export const TREE_CLIPBOARD_TYPE = "application/x-fancytree-node";
+
export function useNoteTreeDrag(containerRef: RefObject<HTMLElement | null | undefined>, { dragEnabled, dragNotEnabledMessage, callback }: {
dragEnabled: boolean,
dragNotEnabledMessage: Omit<ToastOptions, "id">;
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Kanban Board.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Kanban Board.html
index 7a94ad1806..082b48f3a8 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Kanban Board.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Kanban Board.html
@@ -707,9 +707,11 @@ class="admonition warning">
<h2>Read-only boards</h2>
<p>A board marked as <a href="#root/_help_CoFPLs3dRlXc">read-only</a> only
shows its cards. It has no buttons to add a card or a column, column and
- card titles can't be renamed, and column icons can't be changed. The context
- menus of a card or a column keep only the entries that change nothing,
- such as opening the note or <span class="tn-icon bx bx-copy"></span> <em>Copy reference</em>,
+ card titles can't be renamed, and column icons can't be changed. Cards
+ and columns can't be dragged, moved or deleted with the keyboard, and notes
+ dragged in from the note tree aren't added. The context menus of a card
+ or a column keep only the entries that change nothing, such as opening
+ the note or <span class="tn-icon bx bx-copy"></span> <em>Copy reference</em>,
and the board's own menu doesn't open. The cards can still be grouped by
another attribute, but the choice isn't saved, and no new grouping attribute
can be created.</p>
\ No newline at end of file
diff --git a/docs/User Guide/User Guide/Collections/Kanban Board.md b/docs/User Guide/User Guide/Collections/Kanban Board.md
index e95dfe32fb..24544c8ad5 100644
--- a/docs/User Guide/User Guide/Collections/Kanban Board.md
+++ b/docs/User Guide/User Guide/Collections/Kanban Board.md
@@ -452,4 +452,4 @@ In a text note, the pasted link displays the title, icon, and color of the colum
## Read-only boards
-A board marked as [read-only](../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md) only shows its cards. It has no buttons to add a card or a column, column and card titles can't be renamed, and column icons can't be changed. The context menus of a card or a column keep only the entries that change nothing, such as opening the note or <span class="tn-icon bx bx-copy"></span> _Copy reference_, and the board's own menu doesn't open. The cards can still be grouped by another attribute, but the choice isn't saved, and no new grouping attribute can be created.
\ No newline at end of file
+A board marked as [read-only](../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md) only shows its cards. It has no buttons to add a card or a column, column and card titles can't be renamed, and column icons can't be changed. Cards and columns can't be dragged, moved or deleted with the keyboard, and notes dragged in from the note tree aren't added. The context menus of a card or a column keep only the entries that change nothing, such as opening the note or <span class="tn-icon bx bx-copy"></span> _Copy reference_, and the board's own menu doesn't open. The cards can still be grouped by another attribute, but the choice isn't saved, and no new grouping attribute can be created.
\ No newline at end of file