Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+164
@@ -0,0 +1,164 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { SortableKanbanBoard } from "./SortableKanbanBoard";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("@dnd-kit/core", () => ({
|
||||
DndContext: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
DragOverlay: () => null,
|
||||
KeyboardSensor: class KeyboardSensor {},
|
||||
PointerSensor: class PointerSensor {},
|
||||
closestCorners: vi.fn(),
|
||||
useDroppable: () => ({ setNodeRef: vi.fn(), isOver: false }),
|
||||
useSensor: vi.fn(() => ({})),
|
||||
useSensors: vi.fn(() => []),
|
||||
}));
|
||||
|
||||
vi.mock("@dnd-kit/sortable", () => ({
|
||||
SortableContext: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
sortableKeyboardCoordinates: vi.fn(),
|
||||
useSortable: () => ({
|
||||
attributes: {},
|
||||
listeners: {},
|
||||
setNodeRef: vi.fn(),
|
||||
setActivatorNodeRef: vi.fn(),
|
||||
transform: null,
|
||||
transition: undefined,
|
||||
isDragging: false,
|
||||
}),
|
||||
verticalListSortingStrategy: {},
|
||||
}));
|
||||
|
||||
vi.mock("@dnd-kit/utilities", () => ({
|
||||
CSS: { Transform: { toString: () => undefined } },
|
||||
}));
|
||||
|
||||
type Card = { id: string; name: string; href: string };
|
||||
|
||||
const card: Card = { id: "p1", name: "Dach Nord", href: "/acme/projects/p1" };
|
||||
|
||||
function renderBoard(options: { placement?: "above" | "inline"; onTitleClick?: () => void } = {}) {
|
||||
const onCardMove = vi.fn();
|
||||
render(
|
||||
<SortableKanbanBoard<Card>
|
||||
columns={[{ id: "new", name: "Neu", cards: [card] }]}
|
||||
renderCard={(item, dragHandle) => (
|
||||
<div data-testid={`card-${item.id}`}>
|
||||
{dragHandle}
|
||||
<a
|
||||
href={item.href}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
options.onTitleClick?.();
|
||||
}}
|
||||
>
|
||||
{item.name}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
getCardLabel={(item) => item.name}
|
||||
onCardMove={onCardMove}
|
||||
dragHandlePlacement={options.placement}
|
||||
/>,
|
||||
);
|
||||
return onCardMove;
|
||||
}
|
||||
|
||||
describe("SortableKanbanBoard drag handle", () => {
|
||||
it("puts a visible keyboard handle inside the card without intercepting its title link", () => {
|
||||
const onTitleClick = vi.fn();
|
||||
const onCardMove = renderBoard({ placement: "inline", onTitleClick });
|
||||
|
||||
// The handle used to be an invisible strip — the only place a pointer drag
|
||||
// could start, which made the cards look undraggable. Pointer dragging now
|
||||
// works on the whole tile; the handle stays as the keyboard activator and is
|
||||
// visible so it can be found and focused.
|
||||
const handle = screen.getByRole("button", { name: "kanban.dnd.reorderAria" });
|
||||
expect(screen.getByTestId("card-p1").contains(handle)).toBe(true);
|
||||
expect(handle.textContent).toBe("⋮⋮");
|
||||
|
||||
const title = screen.getByRole("link", { name: "Dach Nord" });
|
||||
expect(title.getAttribute("href")).toBe("/acme/projects/p1");
|
||||
fireEvent.click(title);
|
||||
expect(onTitleClick).toHaveBeenCalledTimes(1);
|
||||
expect(onCardMove).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("makes the whole card the pointer drag surface, not just the handle", () => {
|
||||
renderBoard({ placement: "inline" });
|
||||
const card = screen.getByTestId("card-p1");
|
||||
// The wrapper carrying the dnd-kit pointer listeners is the card's own box.
|
||||
const surface = card.closest("[data-card-id]")?.querySelector(".cursor-grab");
|
||||
expect(surface).toBeTruthy();
|
||||
expect(surface?.contains(card)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the existing visible handle above cards unless inline placement is requested", () => {
|
||||
renderBoard();
|
||||
|
||||
const handle = screen.getByRole("button", { name: "kanban.dnd.reorderAria" });
|
||||
expect(screen.getByTestId("card-p1").contains(handle)).toBe(false);
|
||||
expect(screen.getByText("⋮⋮")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("SortableKanbanBoard column forwarding", () => {
|
||||
function renderColumns(column: { sumMode?: "visible" | "locked" | "hidden"; twoColumn?: boolean; wrapAfter?: number; accentColor?: string }) {
|
||||
render(
|
||||
<SortableKanbanBoard<Card>
|
||||
columns={[{ id: "new", name: "Neu", price: "10.000,00 €", lockedSumSlot: "projects.board.sumLocked", cards: [card], ...column }]}
|
||||
renderCard={(item) => <div data-testid={`card-${item.id}`}>{item.name}</div>}
|
||||
getCardLabel={(item) => item.name}
|
||||
onCardMove={vi.fn()}
|
||||
data-ui-id="board"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
it("forwards visible sum mode so the column shows its sum", () => {
|
||||
renderColumns({ sumMode: "visible" });
|
||||
expect(screen.getByText("10.000,00 €").className.split(" ")).toContain("inline");
|
||||
expect(screen.getByText("10.000,00 €").className.split(" ")).not.toContain("hidden");
|
||||
expect(screen.queryByText("projects.board.sumLocked")).toBeNull();
|
||||
});
|
||||
|
||||
it("renders caller-provided locked copy only in locked mode", () => {
|
||||
renderColumns({ sumMode: "locked" });
|
||||
expect(screen.getByText("10.000,00 €").className.split(" ")).toContain("hidden");
|
||||
expect(screen.getByText("projects.board.sumLocked")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows neither sum nor lock hint in hidden mode", () => {
|
||||
renderColumns({ sumMode: "hidden" });
|
||||
expect(screen.getByText("10.000,00 €").className.split(" ")).toContain("hidden");
|
||||
expect(screen.queryByText("projects.board.sumLocked")).toBeNull();
|
||||
});
|
||||
|
||||
it("forwards twoColumn/wrapAfter so the column widens into the two-column grid", () => {
|
||||
renderColumns({ twoColumn: true, wrapAfter: 6 });
|
||||
const column = document.querySelector("[data-ui-id='kanban.column.new']") as HTMLElement;
|
||||
expect(column.className).toContain("w-[680px]");
|
||||
});
|
||||
|
||||
it("keeps the single-column width without twoColumn", () => {
|
||||
renderColumns({});
|
||||
const column = document.querySelector("[data-ui-id='kanban.column.new']") as HTMLElement;
|
||||
expect(column.className).not.toContain("w-[680px]");
|
||||
});
|
||||
|
||||
it("tints the column with the stage accent color at low alpha", () => {
|
||||
renderColumns({ accentColor: "#3b82f6" });
|
||||
const column = document.querySelector("[data-ui-id='kanban.column.new']") as HTMLElement;
|
||||
expect(column.style.backgroundColor).toBe("rgba(59, 130, 246, 0.1)");
|
||||
});
|
||||
|
||||
it("keeps the neutral column background without an accent color", () => {
|
||||
renderColumns({});
|
||||
const column = document.querySelector("[data-ui-id='kanban.column.new']") as HTMLElement;
|
||||
expect(column.style.backgroundColor).toBe("");
|
||||
});
|
||||
});
|
||||
+427
@@ -0,0 +1,427 @@
|
||||
// Shared app-UI Kanban board with real drag & drop (dnd-kit). App-UI layer —
|
||||
// NOT subframe-synced. It only encapsulates the dnd-kit mechanics and renders
|
||||
// the existing ~/ui KanbanColumn shell plus a caller-supplied `renderCard` slot,
|
||||
// so all boards reuse one implementation.
|
||||
//
|
||||
// Layer rules: this component is pure/presentational — it never imports the DB
|
||||
// or ~/db, never calls useLoaderData/useFetcher. It receives VM-shaped columns
|
||||
// as props and emits moves via the `onCardMove` callback; the route/screen owns
|
||||
// the server submit and revalidation.
|
||||
//
|
||||
// dnd-kit wiring follows apps/web/app/modules/formWidget/builder/{Canvas,
|
||||
// SortableField}.tsx: PointerSensor + KeyboardSensor(sortableKeyboardCoordinates)
|
||||
// and CSS.Transform.toString on each sortable node.
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
DndContext,
|
||||
DragOverlay,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
closestCorners,
|
||||
pointerWithin,
|
||||
useDroppable,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type Announcements,
|
||||
type CollisionDetection,
|
||||
type DragEndEvent,
|
||||
type DragStartEvent,
|
||||
} from "@dnd-kit/core";
|
||||
import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import { KanbanColumn } from "~/ui/components/KanbanColumn";
|
||||
import { columnDroppableId, computeKanbanMove } from "./kanbanMove";
|
||||
|
||||
/** Pointer hits are both cheaper and more intuitive than comparing every
|
||||
* rectangle corner. Keyboard dragging has no pointer coordinates, so it keeps
|
||||
* the established closest-corners fallback. */
|
||||
const pointerFirstCollision: CollisionDetection = (args) => {
|
||||
const pointerCollisions = pointerWithin(args);
|
||||
return pointerCollisions.length > 0 ? pointerCollisions : closestCorners(args);
|
||||
};
|
||||
|
||||
export interface SortableKanbanColumn<TCard extends { readonly id: string }> {
|
||||
readonly id: string;
|
||||
/** Plain-text column label used for aria/announcements (falls back to id). */
|
||||
readonly label?: string;
|
||||
readonly name?: ReactNode;
|
||||
readonly price?: ReactNode;
|
||||
readonly badge?: ReactNode;
|
||||
/** Explicit aggregate presentation; domain copy is supplied by the caller. */
|
||||
readonly sumMode?: "visible" | "locked" | "hidden";
|
||||
readonly lockedSumSlot?: ReactNode;
|
||||
/** Domain-specific empty state rendered inside an otherwise empty column. */
|
||||
readonly emptyContent?: ReactNode;
|
||||
/** Wrap the column into a two-column card grid (wide column) — see ~/ui KanbanColumn. */
|
||||
readonly twoColumn?: boolean;
|
||||
/** Row count after which the two-column grid wraps (forwarded to ~/ui KanbanColumn). */
|
||||
readonly wrapAfter?: number;
|
||||
/** Stage color (hex) — tints the column background subtly, matching the detail view's stage palette. */
|
||||
readonly accentColor?: string;
|
||||
readonly cards: readonly TCard[];
|
||||
}
|
||||
|
||||
export interface SortableKanbanBoardProps<TCard extends { readonly id: string }> {
|
||||
readonly columns: readonly SortableKanbanColumn<TCard>[];
|
||||
/** Render slot for a single card body (e.g. the ~/ui KanbanCard). */
|
||||
readonly renderCard: (card: TCard, dragHandle?: ReactNode) => ReactNode;
|
||||
/**
|
||||
* Menu of the column head — Davids export draws a kebab there. What it opens is
|
||||
* the caller's business, so the board hands over the collapse state it owns and
|
||||
* renders whatever comes back.
|
||||
*/
|
||||
readonly renderColumnMenu?: (column: SortableKanbanColumn<TCard>, api: { collapsed: boolean; toggleCollapse: () => void }) => ReactNode;
|
||||
/** Plain-text label for a card, used for aria/announcements. */
|
||||
readonly getCardLabel: (card: TCard) => string;
|
||||
/**
|
||||
* Fired when a card is dropped into a DIFFERENT column. `toIndex` is provided
|
||||
* for completeness but same-column reordering is intentionally NOT reported
|
||||
* (see intra-column note below).
|
||||
*/
|
||||
readonly onCardMove: (cardId: string, toColumnId: string, toIndex: number) => void;
|
||||
/** When true, cards render read-only (no drag handles / no DnD). */
|
||||
readonly disabled?: boolean;
|
||||
/**
|
||||
* Per-card veto. A column may hold entries that are not real cards — an empty
|
||||
* column's placeholder, for instance. Those must not be draggable: the whole
|
||||
* tile is the drag surface, so without this they would be picked up like any
|
||||
* card and land in another column.
|
||||
*/
|
||||
readonly isCardDraggable?: (card: TCard) => boolean;
|
||||
/**
|
||||
* Rollback trigger. When this flips truthy (a failed server move surfaced by
|
||||
* the host), the local optimistic state resyncs to `columns` (server truth).
|
||||
*/
|
||||
readonly errorKey?: string | null;
|
||||
/**
|
||||
* Explicit revert trigger. Bump this to force a resync to `columns` even when
|
||||
* `columns` did not change — e.g. the host cancelled a confirm dialog after an
|
||||
* optimistic drop, so the card must snap back.
|
||||
*/
|
||||
readonly resetToken?: string | number;
|
||||
/** Keep the default visible handle above the card, or place an invisible handle in the caller's card layout. */
|
||||
readonly dragHandlePlacement?: "above" | "inline";
|
||||
readonly className?: string;
|
||||
readonly "data-ui-id"?: string;
|
||||
}
|
||||
|
||||
/** Structural fingerprint (column + ordered card ids). Changes only when the
|
||||
* server truth reorders/moves a card — used to resync optimistic state without
|
||||
* clobbering it on every parent re-render. */
|
||||
function columnsSignature<TCard extends { readonly id: string }>(columns: readonly SortableKanbanColumn<TCard>[]): string {
|
||||
return columns.map((column) => `${column.id}:${column.cards.map((card) => card.id).join(",")}`).join("|");
|
||||
}
|
||||
|
||||
function cloneColumns<TCard extends { readonly id: string }>(
|
||||
columns: readonly SortableKanbanColumn<TCard>[],
|
||||
): SortableKanbanColumn<TCard>[] {
|
||||
return columns.map((column) => ({ ...column, cards: [...column.cards] }));
|
||||
}
|
||||
|
||||
interface SortableCardProps<TCard extends { readonly id: string }> {
|
||||
readonly card: TCard;
|
||||
readonly renderCard: (card: TCard, dragHandle?: ReactNode) => ReactNode;
|
||||
readonly label: string;
|
||||
readonly disabled: boolean;
|
||||
readonly dragHandlePlacement: "above" | "inline";
|
||||
}
|
||||
|
||||
function SortableCard<TCard extends { readonly id: string }>({ card, renderCard, label, disabled, dragHandlePlacement }: SortableCardProps<TCard>) {
|
||||
const { t } = useTranslation();
|
||||
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: card.id,
|
||||
disabled,
|
||||
});
|
||||
const style: CSSProperties = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
willChange: transform ? "transform" : undefined,
|
||||
// The card itself is the drag surface, so the pointer gesture must not be
|
||||
// claimed by touch scrolling before the sensor's distance threshold is met.
|
||||
touchAction: disabled ? undefined : "manipulation",
|
||||
// While a card is dragged the DragOverlay carries the visual; the original
|
||||
// stays as a faint placeholder marking where it came from.
|
||||
opacity: isDragging ? 0.4 : 1,
|
||||
};
|
||||
// Keyboard activator. Pointer dragging works anywhere on the card (the
|
||||
// listeners sit on the wrapper below), but a keyboard user needs one focusable
|
||||
// element to start the move from — that is this handle.
|
||||
const dragHandle = disabled ? null : (
|
||||
<button
|
||||
type="button"
|
||||
ref={setActivatorNodeRef}
|
||||
className={
|
||||
dragHandlePlacement === "inline"
|
||||
? "inline-flex h-6 w-6 flex-none cursor-grab items-center justify-center rounded text-icon-neutral-tertiary hover:text-icon-neutral-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-200 active:cursor-grabbing"
|
||||
: "inline-flex h-6 w-full cursor-grab items-center justify-center rounded text-icon-neutral-tertiary hover:text-icon-neutral-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-200"
|
||||
}
|
||||
aria-label={t("kanban.dnd.reorderAria", { name: label })}
|
||||
data-ui-id={`kanban.dragHandle.${card.id}`}
|
||||
{...listeners}
|
||||
{...attributes}
|
||||
>
|
||||
<span aria-hidden="true" className="text-body-small-semibold-0 leading-none tracking-widest select-none">
|
||||
{"⋮⋮"}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<div ref={setNodeRef} style={style} className="flex w-full flex-col items-center" data-card-id={card.id}>
|
||||
{/* Pointer listeners on the whole card: the tile is what a user grabs, not
|
||||
a strip inside it. A plain click still reaches the link, the checkbox
|
||||
and the context menu — the sensor only takes over past its distance
|
||||
threshold, so a press without movement is never swallowed. */}
|
||||
<div
|
||||
className={disabled ? "flex w-72 flex-col items-stretch gap-1" : "flex w-72 cursor-grab flex-col items-stretch gap-1 active:cursor-grabbing"}
|
||||
{...(disabled ? {} : listeners)}
|
||||
>
|
||||
{dragHandlePlacement === "above" ? dragHandle : null}
|
||||
{renderCard(card, dragHandlePlacement === "inline" ? dragHandle : undefined)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ColumnDropZoneProps<TCard extends { readonly id: string }> {
|
||||
readonly column: SortableKanbanColumn<TCard>;
|
||||
readonly children: ReactNode;
|
||||
readonly collapsed: boolean;
|
||||
readonly menu?: ReactNode;
|
||||
/** Expands the column again: collapsed, its head is the only control left. */
|
||||
readonly onToggleCollapse: () => void;
|
||||
readonly expandLabel: string;
|
||||
readonly "data-ui-id"?: string;
|
||||
}
|
||||
|
||||
function ColumnDropZone<TCard extends { readonly id: string }>({
|
||||
column,
|
||||
children,
|
||||
collapsed,
|
||||
menu,
|
||||
onToggleCollapse,
|
||||
expandLabel,
|
||||
...rest
|
||||
}: ColumnDropZoneProps<TCard>) {
|
||||
const { setNodeRef, isOver } = useDroppable({ id: columnDroppableId(column.id) });
|
||||
return (
|
||||
<KanbanColumn
|
||||
ref={setNodeRef}
|
||||
onToggleCollapse={onToggleCollapse}
|
||||
expandLabel={expandLabel}
|
||||
name={column.name}
|
||||
price={column.price}
|
||||
badge={column.badge}
|
||||
sumMode={column.sumMode}
|
||||
lockedSumSlot={column.lockedSumSlot}
|
||||
twoColumn={column.twoColumn}
|
||||
wrapAfter={column.wrapAfter}
|
||||
collapsed={collapsed}
|
||||
icon={menu}
|
||||
className={isOver ? "border-border-brand" : undefined}
|
||||
// 6-digit hex + alpha suffix: ~10% background tint. Border stays class-driven
|
||||
// so the drag-over highlight keeps winning.
|
||||
style={column.accentColor ? { backgroundColor: `${column.accentColor}1a` } : undefined}
|
||||
cards={children}
|
||||
data-ui-id={rest["data-ui-id"]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function SortableKanbanBoard<TCard extends { readonly id: string }>(props: SortableKanbanBoardProps<TCard>) {
|
||||
const {
|
||||
columns,
|
||||
renderCard,
|
||||
renderColumnMenu,
|
||||
getCardLabel,
|
||||
onCardMove,
|
||||
disabled = false,
|
||||
errorKey,
|
||||
resetToken,
|
||||
dragHandlePlacement = "above",
|
||||
} = props;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [localColumns, setLocalColumns] = useState<SortableKanbanColumn<TCard>[]>(() => cloneColumns(columns));
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
// Collapsed columns are a view state of this session, not server truth: it says
|
||||
// what this person wants to look at right now.
|
||||
const [collapsedIds, setCollapsedIds] = useState<ReadonlySet<string>>(() => new Set());
|
||||
|
||||
// Resync to server truth on structural change, on error (rollback) and on an
|
||||
// explicit reset bump. A ref avoids depending on the `columns` array identity,
|
||||
// which the parent recreates every render (that would clobber optimistic UI).
|
||||
const signature = columnsSignature(columns);
|
||||
const columnsRef = useRef(columns);
|
||||
columnsRef.current = columns;
|
||||
useEffect(() => {
|
||||
setLocalColumns(cloneColumns(columnsRef.current));
|
||||
}, [signature, errorKey, resetToken]);
|
||||
|
||||
// Drag-over announcements and overlay lookup run for every pointer movement.
|
||||
// Build them once per actual board shape instead of scanning every card on
|
||||
// every movement (the route currently permits up to 50 cards per column).
|
||||
const cardById = useMemo(() => {
|
||||
const cards = new Map<string, TCard>();
|
||||
const columnLabels = new Map<string, string>();
|
||||
for (const column of localColumns) {
|
||||
for (const card of column.cards) {
|
||||
cards.set(card.id, card);
|
||||
columnLabels.set(card.id, column.label ?? column.id);
|
||||
}
|
||||
}
|
||||
return { cards, columnLabels };
|
||||
}, [localColumns]);
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
);
|
||||
|
||||
// Grabbing cursor for as long as a card is in hand. It has to live on <html>
|
||||
// rather than on the card: the pointer spends the drag over other columns and
|
||||
// over the overlay, where a class on the source tile no longer applies. The
|
||||
// cleanup also runs when the component unmounts mid-drag, so the fist can
|
||||
// never get stuck on the page.
|
||||
useEffect(() => {
|
||||
if (activeId === null) return;
|
||||
const root = document.documentElement;
|
||||
root.classList.add("hg-kanban-dragging");
|
||||
return () => root.classList.remove("hg-kanban-dragging");
|
||||
}, [activeId]);
|
||||
|
||||
const findCard = useCallback(
|
||||
(cardId: string | null): TCard | null => (cardId ? cardById.cards.get(cardId) ?? null : null),
|
||||
[cardById],
|
||||
);
|
||||
|
||||
const cardLabelForId = useCallback(
|
||||
(cardId: string): string => {
|
||||
const card = findCard(cardId);
|
||||
return card ? getCardLabel(card) : cardId;
|
||||
},
|
||||
[findCard, getCardLabel],
|
||||
);
|
||||
|
||||
const columnLabelForOverId = useCallback(
|
||||
(overId: string): string => {
|
||||
const columnId = overId.replace(/^kanban-col:/, "");
|
||||
const byColumn = localColumns.find((candidate) => candidate.id === columnId);
|
||||
if (byColumn) return byColumn.label ?? byColumn.id;
|
||||
// `over` may be a card id — resolve it to its owning column.
|
||||
return cardById.columnLabels.get(overId) ?? columnId;
|
||||
},
|
||||
[localColumns, cardById],
|
||||
);
|
||||
|
||||
function handleDragStart(event: DragStartEvent) {
|
||||
setActiveId(String(event.active.id));
|
||||
}
|
||||
|
||||
function handleDragCancel() {
|
||||
setActiveId(null);
|
||||
}
|
||||
|
||||
function handleDragEnd(event: DragEndEvent) {
|
||||
setActiveId(null);
|
||||
const { active, over } = event;
|
||||
if (!over) return;
|
||||
const result = computeKanbanMove(localColumns, String(active.id), String(over.id));
|
||||
if (!result) return;
|
||||
setLocalColumns(result.columns); // optimistic
|
||||
if (result.crossColumn) {
|
||||
onCardMove(result.cardId, result.to.columnId, result.to.index);
|
||||
}
|
||||
// Intra-column reorder is visual-only and intentionally NOT persisted:
|
||||
// Projekt has no position field, so same-column order is not stored. The
|
||||
// next revalidation resyncs the server order. See kanbanMove.ts.
|
||||
}
|
||||
|
||||
const announcements: Announcements = useMemo(
|
||||
() => ({
|
||||
onDragStart: ({ active }) => t("kanban.dnd.announceStart", { name: cardLabelForId(String(active.id)) }),
|
||||
onDragOver: ({ active, over }) =>
|
||||
over ? t("kanban.dnd.announceOver", { name: cardLabelForId(String(active.id)), column: columnLabelForOverId(String(over.id)) }) : "",
|
||||
onDragEnd: ({ active, over }) =>
|
||||
over
|
||||
? t("kanban.dnd.announceEnd", { name: cardLabelForId(String(active.id)), column: columnLabelForOverId(String(over.id)) })
|
||||
: t("kanban.dnd.announceCancel"),
|
||||
onDragCancel: () => t("kanban.dnd.announceCancel"),
|
||||
}),
|
||||
[t, cardLabelForId, columnLabelForOverId],
|
||||
);
|
||||
|
||||
const activeCard = findCard(activeId);
|
||||
|
||||
return (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={pointerFirstCollision}
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragCancel={handleDragCancel}
|
||||
accessibility={{ announcements, screenReaderInstructions: { draggable: t("kanban.dnd.instructions") } }}
|
||||
>
|
||||
<div className={props.className ?? "flex w-full gap-4 overflow-x-auto pb-2"} data-ui-id={props["data-ui-id"]}>
|
||||
{localColumns.map((column) => {
|
||||
const toggleCollapse = () =>
|
||||
setCollapsedIds((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(column.id)) next.delete(column.id);
|
||||
else next.add(column.id);
|
||||
return next;
|
||||
});
|
||||
return (
|
||||
<ColumnDropZone
|
||||
key={column.id}
|
||||
column={column}
|
||||
collapsed={collapsedIds.has(column.id)}
|
||||
onToggleCollapse={toggleCollapse}
|
||||
expandLabel={t("kanban.column.expandAria", { name: column.label ?? column.id })}
|
||||
menu={renderColumnMenu?.(column, {
|
||||
collapsed: collapsedIds.has(column.id),
|
||||
toggleCollapse,
|
||||
})}
|
||||
data-ui-id={`kanban.column.${column.id}`}
|
||||
>
|
||||
<SortableContext id={column.id} items={column.cards.map((card) => card.id)} strategy={verticalListSortingStrategy}>
|
||||
{column.cards.length === 0 ? (
|
||||
column.emptyContent ?? (disabled ? null : (
|
||||
<div className="flex min-h-16 w-72 items-center justify-center rounded-md border border-dashed border-border-default text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
|
||||
{t("kanban.dnd.emptyColumn")}
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
column.cards.map((card) => (
|
||||
<SortableCard
|
||||
key={card.id}
|
||||
card={card}
|
||||
renderCard={renderCard}
|
||||
label={getCardLabel(card)}
|
||||
disabled={disabled || !(props.isCardDraggable?.(card) ?? true)}
|
||||
dragHandlePlacement={dragHandlePlacement}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</SortableContext>
|
||||
</ColumnDropZone>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{/* The dragged card rides with the cursor: `dropAnimation={null}` keeps it
|
||||
from flying back to its origin before the new order renders, and the
|
||||
lift makes clear which tile is in hand. */}
|
||||
<DragOverlay dropAnimation={null}>
|
||||
{activeCard ? (
|
||||
<div className="w-72 rotate-1 cursor-grabbing opacity-95 shadow-lg" data-ui-id="kanban.dragOverlay">
|
||||
{renderCard(activeCard)}
|
||||
</div>
|
||||
) : null}
|
||||
</DragOverlay>
|
||||
</DndContext>
|
||||
);
|
||||
}
|
||||
|
||||
export default SortableKanbanBoard;
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
// Unit tests for the pure SortableKanbanBoard move reducer. No React / dnd-kit.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { columnDroppableId, computeKanbanMove, locateCard } from "./kanbanMove";
|
||||
|
||||
interface Card {
|
||||
readonly id: string;
|
||||
}
|
||||
|
||||
interface Col {
|
||||
readonly id: string;
|
||||
readonly title: string; // extra field: must be preserved across moves
|
||||
readonly cards: readonly Card[];
|
||||
}
|
||||
|
||||
function board(): Col[] {
|
||||
return [
|
||||
{ id: "todo", title: "To do", cards: [{ id: "a" }, { id: "b" }, { id: "c" }] },
|
||||
{ id: "doing", title: "Doing", cards: [{ id: "d" }] },
|
||||
{ id: "done", title: "Done", cards: [] },
|
||||
];
|
||||
}
|
||||
|
||||
const ids = (cols: Col[]) => cols.map((c) => `${c.id}:${c.cards.map((x) => x.id).join(",")}`).join("|");
|
||||
|
||||
describe("locateCard", () => {
|
||||
it("finds the column and index of a card", () => {
|
||||
expect(locateCard(board(), "b")).toEqual({ columnId: "todo", index: 1 });
|
||||
expect(locateCard(board(), "d")).toEqual({ columnId: "doing", index: 0 });
|
||||
});
|
||||
|
||||
it("returns null for an unknown card", () => {
|
||||
expect(locateCard(board(), "zzz")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeKanbanMove", () => {
|
||||
it("moves a card into another column over a target card and flags crossColumn", () => {
|
||||
const result = computeKanbanMove(board(), "a", "d");
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.crossColumn).toBe(true);
|
||||
expect(result!.cardId).toBe("a");
|
||||
expect(result!.to).toEqual({ columnId: "doing", index: 0 });
|
||||
expect(ids(result!.columns)).toBe("todo:b,c|doing:a,d|done:");
|
||||
});
|
||||
|
||||
it("appends to an empty column when dropped on the column droppable sentinel", () => {
|
||||
const result = computeKanbanMove(board(), "b", columnDroppableId("done"));
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.crossColumn).toBe(true);
|
||||
expect(result!.to).toEqual({ columnId: "done", index: 0 });
|
||||
expect(ids(result!.columns)).toBe("todo:a,c|doing:d|done:b");
|
||||
});
|
||||
|
||||
it("preserves extra column fields (title) when moving", () => {
|
||||
const result = computeKanbanMove(board(), "a", "d");
|
||||
expect(result!.columns.map((c) => c.title)).toEqual(["To do", "Doing", "Done"]);
|
||||
});
|
||||
|
||||
it("reorders within a column (arrayMove semantics) without crossColumn", () => {
|
||||
const result = computeKanbanMove(board(), "a", "c");
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.crossColumn).toBe(false);
|
||||
expect(ids(result!.columns)).toBe("todo:b,c,a|doing:d|done:");
|
||||
});
|
||||
|
||||
it("returns null when dropped on itself", () => {
|
||||
expect(computeKanbanMove(board(), "a", "a")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for an unknown active card", () => {
|
||||
expect(computeKanbanMove(board(), "zzz", "d")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for an unknown drop target", () => {
|
||||
expect(computeKanbanMove(board(), "a", "nope")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not mutate the input columns", () => {
|
||||
const input = board();
|
||||
const before = ids(input);
|
||||
computeKanbanMove(input, "a", "d");
|
||||
expect(ids(input)).toBe(before);
|
||||
});
|
||||
});
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
// Pure move/reorder logic for the shared SortableKanbanBoard. Kept free of React
|
||||
// and dnd-kit so it can be unit-tested directly (the board only wires dnd-kit
|
||||
// events into `computeKanbanMove`). The reducer mirrors dnd-kit's arrayMove
|
||||
// insertion semantics: dropping a card "over" another card inserts it at that
|
||||
// card's slot (post-removal splice), and dropping over an (empty) column
|
||||
// appends to the end.
|
||||
|
||||
/** Sentinel prefix for a column-level droppable id (see SortableKanbanBoard).
|
||||
* Column drop-zones use this so an empty column is still a valid drop target and
|
||||
* `over.id` can be told apart from a card id. */
|
||||
export const COLUMN_DROPPABLE_PREFIX = "kanban-col:";
|
||||
|
||||
export function columnDroppableId(columnId: string): string {
|
||||
return `${COLUMN_DROPPABLE_PREFIX}${columnId}`;
|
||||
}
|
||||
|
||||
export interface KanbanMoveColumn<TCard extends { readonly id: string }> {
|
||||
readonly id: string;
|
||||
readonly cards: readonly TCard[];
|
||||
}
|
||||
|
||||
export interface KanbanCardLocation {
|
||||
readonly columnId: string;
|
||||
readonly index: number;
|
||||
}
|
||||
|
||||
export interface KanbanMoveResult<Col> {
|
||||
/** New columns array with the card moved (extra column fields preserved). */
|
||||
readonly columns: Col[];
|
||||
readonly cardId: string;
|
||||
readonly from: KanbanCardLocation;
|
||||
readonly to: KanbanCardLocation;
|
||||
/** True when the card changed column (the only case that is persisted). */
|
||||
readonly crossColumn: boolean;
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
/** Find which column a card currently lives in, and at which index. */
|
||||
export function locateCard<TCard extends { readonly id: string }>(
|
||||
columns: readonly KanbanMoveColumn<TCard>[],
|
||||
cardId: string,
|
||||
): KanbanCardLocation | null {
|
||||
for (const column of columns) {
|
||||
const index = column.cards.findIndex((card) => card.id === cardId);
|
||||
if (index >= 0) return { columnId: column.id, index };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Resolve a dnd-kit `over.id` (either a card id or a `kanban-col:<id>` sentinel)
|
||||
* to a concrete drop target column + insert index. */
|
||||
function resolveDropTarget<TCard extends { readonly id: string }>(
|
||||
columns: readonly KanbanMoveColumn<TCard>[],
|
||||
overId: string,
|
||||
): KanbanCardLocation | null {
|
||||
if (overId.startsWith(COLUMN_DROPPABLE_PREFIX)) {
|
||||
const columnId = overId.slice(COLUMN_DROPPABLE_PREFIX.length);
|
||||
const column = columns.find((candidate) => candidate.id === columnId);
|
||||
if (!column) return null;
|
||||
// Dropping onto the column background appends to the end.
|
||||
return { columnId, index: column.cards.length };
|
||||
}
|
||||
return locateCard(columns, overId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the next board state for a drag from `activeId` dropped over `overId`.
|
||||
* Returns `null` for no-ops (dropped on itself / unresolvable / same slot).
|
||||
* Column identity and any extra column fields (name/price/badge) are preserved.
|
||||
*/
|
||||
export function computeKanbanMove<
|
||||
TCard extends { readonly id: string },
|
||||
Col extends KanbanMoveColumn<TCard>,
|
||||
>(columns: readonly Col[], activeId: string, overId: string): KanbanMoveResult<Col> | null {
|
||||
if (activeId === overId) return null;
|
||||
|
||||
const from = locateCard(columns, activeId);
|
||||
if (!from) return null;
|
||||
|
||||
const target = resolveDropTarget(columns, overId);
|
||||
if (!target) return null;
|
||||
|
||||
// Clone with mutable card arrays; keep every other column field by reference.
|
||||
const next = columns.map((column) => ({ ...column, cards: [...column.cards] as TCard[] }));
|
||||
const fromColumn = next.find((column) => column.id === from.columnId)!;
|
||||
const toColumn = from.columnId === target.columnId ? fromColumn : next.find((column) => column.id === target.columnId)!;
|
||||
|
||||
const [moved] = fromColumn.cards.splice(from.index, 1);
|
||||
const insertAt = clamp(target.index, 0, toColumn.cards.length);
|
||||
toColumn.cards.splice(insertAt, 0, moved);
|
||||
|
||||
const crossColumn = from.columnId !== target.columnId;
|
||||
if (!crossColumn && insertAt === from.index) return null; // same column, same slot
|
||||
|
||||
return {
|
||||
columns: next as unknown as Col[],
|
||||
cardId: activeId,
|
||||
from,
|
||||
to: { columnId: toColumn.id, index: insertAt },
|
||||
crossColumn,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user