Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: allow creating a column at the top of the board, while using the new column button

Adorian Doran642069250ffd
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 6273a677a0..28ce6c1b82 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3394,13 +3394,14 @@
"add-existing-item": "Add existing note...",
"add-existing-item-title": "Add an existing note to the board",
"add-existing-item-ok": "Add to column",
- "add-existing-column": "Add existing column",
"add-new-column": "Add new column",
"create-new-note": "Create note",
"create-new-column": "Create column",
"create-hold-hint": "Right click or hold for more options.",
"create-at-top": "Create at top",
"create-at-bottom": "Create at bottom",
+ "create-column-at-start": "Create column at the start",
+ "create-column-at-end": "Create column at the end",
"add-column-before": "Before",
"add-column-after": "After",
"new-column": "New column",
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index 62856f7d08..2072ed0ecb 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -276,7 +276,12 @@ export default class BoardApi {
return this.removeFromBoard(noteId);
}
- async addNewColumn(columnName: string) {
+ /**
+ * Adds a column at one end of the board.
+ *
+ * @param atStart whether it goes at the head of the board rather than after the last column.
+ */
+ async addNewColumn(columnName: string, atStart = false) {
if (!columnName.trim()) {
return;
}
@@ -286,7 +291,26 @@ export default class BoardApi {
// Add the new column to persisted data if it doesn't exist
if (columns.some(col => col.value === columnName)) return false;
settleColumn(this.pending, columnName);
- this.storeColumns([ ...columns, { value: columnName } ]);
+
+ if (!atStart) {
+ this.storeColumns([ ...columns, { value: columnName } ]);
+ return true;
+ }
+
+ // The whole order has to be written for the column to stand before the others: the stored
+ // list is what the board reads first, and a column missing from it keeps its derived place
+ // at the end whatever is put in front. The inbox holds the head where it has one.
+ const order = columns.map(col => col.value);
+ for (const derived of this.columns) {
+ if (!order.includes(derived)) {
+ order.push(derived);
+ }
+ }
+
+ const byValue = new Map(columns.map(col => [ col.value, col ]));
+ const placed: BoardColumnData[] = order.map(value => byValue.get(value) ?? { value });
+ placed.splice(order[0] === INBOX_COLUMN ? 1 : 0, 0, { value: columnName });
+ this.storeColumns(placed);
return true;
}
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index e72fe3000b..b778bc233d 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -29,7 +29,7 @@ import { BoardActionsContext, BoardDragStateContext, TitleEditor } from ".";
import BoardApi from "./api";
import Card from "./card";
import { DEFAULT_COLUMN_ICON, INBOX_COLUMN } from "./columns";
-import { openColumnContextMenu } from "./context_menu";
+import { openColumnContextMenu, openCreateCardMenu } from "./context_menu";
interface DragContext {
column: string;
@@ -450,9 +450,10 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreat
<TitleEditor
currentValue={initialTitle}
placeholder={t("board_view.new-item-placeholder")}
- save={async (title, placement) => {
+ save={async (title, atStart) => {
onCreating();
- onCreated(await api.createNewItem(column, title, placement));
+ onCreated(await api.createNewItem(
+ column, title, atStart ? "top" : "bottom"));
}}
dismiss={() => setIsCreating(false)}
mode="multiline" isNewItem
@@ -464,7 +465,7 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreat
onClick: addExistingItem
}}
submitTitle={t("board_view.create-new-note")}
- canPlace
+ openPlacements={openCreateCardMenu}
/>
)}
</div>
diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.ts
index 581ba38222..94dbaf02e7 100644
--- a/apps/client/src/widgets/collections/board/context_menu.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.ts
@@ -11,7 +11,7 @@ import { getArchiveMenuItem } from "../../../menus/context_menu_utils";
import { t } from "../../../services/i18n";
import { escapeHtml } from "../../../services/utils";
import ColorPicker from "../../react/ColorPicker";
-import Api, { CardPlacement } from "./api";
+import Api from "./api";
import { INBOX_COLUMN } from "./columns";
/** What the column menu is opened for: the column itself, and what it can be asked to do. */
@@ -153,9 +153,7 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:
}
/** Offers both ends of a column for the card the button below it is about to create. */
-export function openCreateCardMenu(
- x: number, y: number, create: (placement: CardPlacement) => void
-) {
+export function openCreateCardMenu(x: number, y: number, create: (atStart: boolean) => void) {
contextMenu.show({
x,
y,
@@ -164,13 +162,42 @@ export function openCreateCardMenu(
title: t("board_view.create-at-top"),
uiIcon: "bx bx-vertical-top",
shortcut: "Shift+Enter",
- handler: () => create("top")
+ handler: () => create(true)
},
{
title: t("board_view.create-at-bottom"),
uiIcon: "bx bx-vertical-bottom",
shortcut: "Enter",
- handler: () => create("bottom")
+ handler: () => create(false)
+ }
+ ],
+ selectMenuItemHandler() {}
+ });
+}
+
+/**
+ * Offers both ends of the board for the column the button beside the field is about to create.
+ *
+ * Opened leftwards: the button stands at the end of the board, hard against the window's edge,
+ * where a menu drawn from the pointer would be pushed back over the button it came from.
+ */
+export function openCreateColumnMenu(x: number, y: number, create: (atStart: boolean) => void) {
+ contextMenu.show({
+ x,
+ y,
+ orientation: "left",
+ items: [
+ {
+ title: t("board_view.create-column-at-start"),
+ uiIcon: "bx bx-horizontal-left",
+ shortcut: "Shift+Enter",
+ handler: () => create(true)
+ },
+ {
+ title: t("board_view.create-column-at-end"),
+ uiIcon: "bx bx-horizontal-right",
+ shortcut: "Enter",
+ handler: () => create(false)
}
],
selectMenuItemHandler() {}
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index 6127f8c673..b4fac8889f 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -1495,7 +1495,7 @@ describe("Board column rename", () => {
await flush();
});
- expect(added).toHaveBeenCalledWith("Blocked");
+ expect(added).toHaveBeenCalledWith("Blocked", false);
expect(slot?.querySelector("input")).toBe(editor);
expect(editor.value).toBe("");
expect(document.activeElement).toBe(editor);
@@ -1514,6 +1514,83 @@ describe("Board column rename", () => {
expect(slot?.classList.contains("editing")).toBe(false);
});
+ /**
+ * The button beside the field changes face as the field is typed into, and the field takes its
+ * value from a prop: a render that fed the old one back took the first character with it.
+ */
+ it("keeps what is typed into the add-column field", async () => {
+ const { container } = await setup();
+ const slot = container.querySelector<HTMLElement>(".board-add-column");
+
+ await act(async () => {
+ slot?.click();
+ await flush();
+ });
+
+ const editor = slot?.querySelector<HTMLInputElement>("input");
+ if (!editor) throw new Error("expected the add-column editor to be open");
+
+ await type(editor, "B");
+ expect(editor.value).toBe("B");
+
+ await type(editor, "Blocked");
+ expect(editor.value).toBe("Blocked");
+ });
+
+ /** The same two ends a card's button offers, named for a board that runs across. */
+ it("offers both ends of the board from the add-column button", async () => {
+ const { container } = await setup();
+ const added = vi.spyOn(BoardApi.prototype, "addNewColumn").mockResolvedValue(true);
+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
+ const slot = container.querySelector<HTMLElement>(".board-add-column");
+
+ await act(async () => {
+ slot?.click();
+ await flush();
+ });
+
+ const editor = slot?.querySelector<HTMLInputElement>("input");
+ const button = slot?.querySelector<HTMLElement>(".title-editor-submit");
+ if (!editor || !button) throw new Error("expected the editor and its button");
+
+ await type(editor, "Blocked");
+ button.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+
+ const opened = show.mock.calls.at(-1)?.[0];
+ const entries = (opened?.items ?? []).flatMap(item =>
+ item && "title" in item && "handler" in item
+ ? [ { title: item.title, icon: "uiIcon" in item ? item.uiIcon : undefined,
+ shortcut: "shortcut" in item ? item.shortcut : undefined,
+ handler: item.handler } ]
+ : []);
+ expect(entries.map(entry => [ entry.title, entry.icon, entry.shortcut ])).toEqual([
+ [ "board_view.create-column-at-start", "bx bx-horizontal-left", "Shift+Enter" ],
+ [ "board_view.create-column-at-end", "bx bx-horizontal-right", "Enter" ]
+ ]);
+ // The button stands at the board's right edge, where a menu drawn rightwards is pushed
+ // back over it.
+ expect(opened?.orientation).toBe("left");
+
+ await act(async () => {
+ entries[0]?.handler?.({} as never, {} as never);
+ await flush();
+ });
+ expect(added).toHaveBeenCalledWith("Blocked", true);
+ expect(editor.value).toBe("");
+
+ // Shift+Enter says the same thing from the field itself.
+ added.mockClear();
+ await type(editor, "Also first");
+ await act(async () => {
+ editor.dispatchEvent(new KeyboardEvent("keydown",
+ { key: "Enter", shiftKey: true, bubbles: true }));
+ await flush();
+ });
+ expect(added).toHaveBeenCalledWith("Also first", true);
+
+ show.mockRestore();
+ });
+
/**
* The same as Enter, for a reader who would rather press something: pressing it must not take
* focus out of the field first, since losing focus is what closes the editor.
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 422c1d1b7c..faf4273afb 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -31,14 +31,14 @@ import ActionButton from "../../react/ActionButton";
import { useDragPan } from "../../react/drag_pan";
import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";
import { ViewModeProps } from "../interface";
-import Api, { CardPlacement, getPendingWrites, PendingColumnWrites, settleColumn } from "./api";
+import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api";
import { useBoardDrag } from "./board_drag";
import { movesColumn } from "./drag_geometry";
import BoardApi from "./api";
import { DEFAULT_GROUP_BY, getStatusDefinition, INBOX_COLUMN } from "./columns";
import Column from "./column";
import ColumnLimitDialog from "./column_limit";
-import { openCreateCardMenu } from "./context_menu";
+import { openCreateColumnMenu } from "./context_menu";
import { applyCardMove, ColumnMap, getBoardData } from "./data";
import { useBoardKeyboard } from "./keyboard";
@@ -782,8 +782,8 @@ function AddNewColumn({ api, isInRelationMode, columnCount, onCreated }: {
: (
<TitleEditor
placeholder={t("board_view.add-column-placeholder")}
- save={async (columnName) => {
- const created = await api.addNewColumn(columnName);
+ save={async (columnName, atStart) => {
+ const created = await api.addNewColumn(columnName, atStart);
if (created) {
onCreated(columnName);
} else {
@@ -796,8 +796,8 @@ function AddNewColumn({ api, isInRelationMode, columnCount, onCreated }: {
// standing with an empty field. A column named by a note answers for
// itself, since picking one is what closes that editor.
saveAndContinue={!isInRelationMode}
- whenEmpty={{ title: t("board_view.add-existing-column") }}
submitTitle={t("board_view.create-new-column")}
+ openPlacements={openCreateColumnMenu}
mode={isInRelationMode ? "relation" : "normal"}
/>
)}
@@ -807,11 +807,11 @@ function AddNewColumn({ api, isInRelationMode, columnCount, onCreated }: {
export function TitleEditor({
currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true,
- saveAndContinue = false, returnFocusTo, abandon, whenEmpty, submitTitle, canPlace
+ saveAndContinue = false, returnFocusTo, abandon, whenEmpty, submitTitle, openPlacements
}: {
currentValue?: string;
placeholder?: string;
- save: (newValue: string, placement?: CardPlacement) => void | Promise<void>;
+ save: (newValue: string, atStart?: boolean) => void | Promise<void>;
dismiss: () => void;
isNewItem?: boolean;
mode?: "normal" | "multiline" | "relation";
@@ -834,10 +834,11 @@ export function TitleEditor({
/** What the button beside the field makes, for the reader hovering over it. */
submitTitle?: string;
/**
- * Whether the button also offers which end of the column to make it at: a menu on a right
- * click or a hold, and Shift+Enter for the top. Only for a `save` that reads the placement.
+ * Opens the menu of which end to make the item at, for a `save` that reads that end. Its
+ * presence is what puts the two ends on the button: a right click or a hold opens the menu,
+ * and Shift+Enter saves at the start without it.
*/
- canPlace?: boolean;
+ 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 for it rather than by it names itself, so that closing does not light
@@ -852,8 +853,13 @@ export function TitleEditor({
selectOnFocus?: boolean;
}) {
const inputRef = useRef<any>(null);
- /** Whether the field holds anything, which is what the button beside it offers to do. */
- const [ isEmpty, setIsEmpty ] = useState(!currentValue?.trim());
+ /**
+ * What the field holds, kept here rather than read off the field alone: `FormTextBox` takes its
+ * value as a prop, so a render for anything else, the button beside it changing face included,
+ * writes that prop back over what has been typed.
+ */
+ const [ typed, setTyped ] = useState(currentValue ?? "");
+ const isEmpty = !typed.trim();
const focusElRef = useRef<Element>(null);
const dismissOnNextRefreshRef = useRef(false);
const shouldDismiss = useRef(false);
@@ -896,7 +902,7 @@ export function TitleEditor({
if (e.key === "Enter" && saveAndContinue) {
e.preventDefault();
e.stopPropagation();
- submit(canPlace && e.shiftKey ? "top" : "bottom");
+ submit(!!openPlacements && e.shiftKey);
return;
}
@@ -925,31 +931,31 @@ export function TitleEditor({
/**
* Saves what is in the editor and empties it, leaving it open for whatever comes next.
*
- * @param placement which end of the column to save at, for an editor that offers both.
+ * @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(placement?: CardPlacement, typed?: string) {
+ function submit(atStart?: boolean, typed?: string) {
const input = inputRef.current;
const value = typed ?? input?.value ?? "";
if (value.trim()) {
- commit(value, placement);
+ commit(value, atStart);
if (input) {
input.value = "";
}
}
input?.focus();
- setIsEmpty(true);
+ setTyped("");
}
- /** Offers both ends of the column, saving what the field held when the menu was opened. */
+ /** Offers both ends, saving what the field held when the menu was opened. */
function openPlacementMenu(e: JSX.TargetedMouseEvent<HTMLElement>) {
e.preventDefault();
e.stopPropagation();
cancelHold();
const typed = inputRef.current?.value ?? "";
- openCreateCardMenu(e.pageX, e.pageY, (placement) => submit(placement, typed));
+ 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. */
@@ -964,7 +970,7 @@ export function TitleEditor({
held.current = window.setTimeout(() => {
openedByHold.current = true;
const typed = inputRef.current?.value ?? "";
- openCreateCardMenu(pageX, pageY, (placement) => submit(placement, typed));
+ openPlacements?.(pageX, pageY, (atStart) => submit(atStart, typed));
}, HOLD_TO_PLACE_MS);
}
@@ -991,7 +997,7 @@ export function TitleEditor({
return;
}
- submit("bottom");
+ submit(false);
}
const onBlur = (newValue: string) => {
@@ -1012,8 +1018,8 @@ export function TitleEditor({
// The editor is closing either way, and what a save writes has already been put back by
// whatever could not write it; all that is left is to say so rather than to reject unhandled,
// which is what a save reaching nobody used to do.
- function commit(newValue: string, placement?: CardPlacement) {
- Promise.resolve(save(newValue, placement)).catch((e) => {
+ function commit(newValue: string, atStart?: boolean) {
+ Promise.resolve(save(newValue, atStart)).catch((e) => {
console.error("Failed to save what the board editor was given:", e);
toast.showError(t("board_view.save-error"));
});
@@ -1024,13 +1030,13 @@ export function TitleEditor({
const field = (
<Element
inputRef={inputRef}
- currentValue={currentValue ?? ""}
+ 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) => setIsEmpty(!e.currentTarget.value.trim())}
+ onInput={(e) => setTyped(e.currentTarget.value)}
/>
);
@@ -1040,7 +1046,7 @@ export function TitleEditor({
// A placement applies only to the button that creates. With nothing typed, the button
// stands for whatever the caller offers instead.
- const offersPlacement = !!canPlace && !isEmpty;
+ 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 }