# Kanban board

> Work items in lanes such as Now, Next and Later. Cards can be dragged, or moved by keyboard, between and within lanes.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/kanban-board`
- File: `src/components/haze/ui/kanban-board.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/tag, @haze/utils
- Docs page: https://hazeui.com/ui/kanban-board

## Use when
- A dashboard shows what is being worked on now and what comes after
- A small team or a solo maker plans a few dozen items across stages

## Avoid when
- Items need sorting, filtering or many columns of data. Use table.
- The order of events in time is the point. Use timeline.

## Alternatives
- [table](https://hazeui.com/ui/table.md)
- [timeline](https://hazeui.com/ui/timeline.md)
- [sortable-list](https://hazeui.com/ui/sortable-list.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| label | `string` | "Work board" | no | Accessible name of the board. |
| lanes | `{ title: string; cards: { title: string; meta?: string; tag?: { label: string; variant?: Tone }; href?: string }[] }[]` |  | no | Lanes in display order, each with its cards. |
| emptyLabel | `string` | "Nothing here." | no | Text shown in a lane that has no cards. |
| moveLabel | `string` | "Move card" | no | Accessible name prefix of each card's move handle, shown once scripts run. |
| headingLevel | `2 \| 3 \| 4` | 3 | no | Heading level of the lane titles. |
| class | `string` |  | no | Additional classes on the board. |

## Accessibility
- Each lane title is a heading with its item count, so screen reader users can jump between lanes.
- Priority tags carry their meaning in text (P0, P1); the color only repeats it.
- With scripts on, each card gets a move handle button. Moves and drops are announced politely, for example "Moved 'X' to Next, position 2 of 3." Without scripts the board is a static list.
- Key Tab: Move between linked cards and move handles.
- Key Space or Enter on a handle: Pick up the card, then drop it where it is.
- Key Arrow keys (picked up): Left and Right move the card to the neighboring lane, Up and Down reorder it within the lane.
- Key Escape (picked up): Cancel the move and put the card back.

## Agent prompts

### Install and use

Install the Haze UI component "Kanban board" with `npx shadcn@latest add @haze/kanban-board`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import KanbanBoard from "@/components/haze/ui/kanban-board.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/kanban-board.md

### Customize with real content

Adapt the Haze kanban-board ui for our product. Replace the demo values of these props with our real content: label, lanes, emptyLabel, moveLabel, headingLevel, class. Keep the layout, the heading level rules and these accessibility details: Each lane title is a heading with its item count, so screen reader users can jump between lanes. Priority tags carry their meaning in text (P0, P1); the color only repeats it. With scripts on, each card gets a move handle button. Moves and drops are announced politely, for example "Moved 'X' to Next, position 2 of 3." Without scripts the board is a static list. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using kanban-board, check it fits: use it when a dashboard shows what is being worked on now and what comes after; a small team or a solo maker plans a few dozen items across stages. Avoid it when items need sorting, filtering or many columns of data. use table.; the order of events in time is the point. use timeline.. Alternatives: @haze/table, @haze/timeline, @haze/sortable-list.

## Example requests that should lead here
- Add a Now, Next, Later board to the project dashboard with P0 and P1 tags on urgent cards.

## Source

```astro
---
import { GripVertical } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Tag from "./tag.astro";

type Tone = "default" | "info" | "success" | "warning" | "destructive";

interface Card {
  title: string;
  /** Secondary line under the title, such as the project and the source. */
  meta?: string;
  /** Short label such as a priority. Its text carries the meaning; the color only repeats it. */
  tag?: { label: string; variant?: Tone };
  href?: string;
}

interface Lane {
  title: string;
  cards: Card[];
}

interface Props {
  /** Accessible name of the board. */
  label?: string;
  lanes?: Lane[];
  /** Text shown in a lane with no cards. */
  emptyLabel?: string;
  /** Accessible name prefix of each card's move handle (shown once scripts run). */
  moveLabel?: string;
  headingLevel?: 2 | 3 | 4;
  class?: string;
}

const {
  label = "Work board",
  lanes = [
    {
      title: "Now",
      cards: [
        { title: "Fix double booking on overlapping slots", meta: "Bookings · from audit", tag: { label: "P0", variant: "destructive" } },
        { title: "Send receipt email after checkout", meta: "Billing", tag: { label: "P1", variant: "warning" } },
      ],
    },
    {
      title: "Next",
      cards: [
        { title: "Move invoices to the new tax rate", meta: "Billing", tag: { label: "P2", variant: "info" } },
        { title: "Add an empty state to the reports page", meta: "Reports" },
        { title: "Cache the pricing page", meta: "Marketing site" },
      ],
    },
    { title: "Later", cards: [] },
  ],
  emptyLabel = "Nothing here.",
  moveLabel = "Move card",
  headingLevel = 3,
  class: className,
} = Astro.props;
const H = `h${headingLevel}` as "h3";
---

<section data-haze-kanban aria-label={label} class={cn("grid gap-3 md:auto-cols-fr md:grid-flow-col", className)}>
  {
    lanes.map((lane) => (
      <div data-kanban-lane data-lane-title={lane.title} class="flex min-w-0 flex-col gap-2 rounded-xl border border-border bg-muted p-2">
        <H class="flex items-center justify-between gap-2 px-1.5 pt-1 text-xs/4 font-medium text-muted-foreground">
          {lane.title}
          <span data-kanban-count class="text-xs/4 tracking-normal tabular-nums normal-case" aria-label={`${lane.cards.length} items`}>
            {lane.cards.length}
          </span>
        </H>
        <ul data-kanban-list role="list" class="flex flex-col gap-2 empty:hidden">
          {lane.cards.map((card) => (
            <li data-kanban-card data-title={card.title} class="relative data-[dragging]:rounded-md data-[dragging]:shadow-float data-[picked]:rounded-md data-[picked]:outline-2 data-[picked]:outline-offset-1 data-[picked]:outline-ring">
              {card.href ? (
                <a
                  href={card.href}
                  class="block rounded-md border border-border bg-card p-3 transition-[border-color,translate,box-shadow] duration-200 ease-snappy hover:-translate-y-0.5 hover:border-border-strong hover:shadow-lift focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [[data-haze-kanban][data-enhanced]_&]:pe-10"
                >
                  <span class="flex items-start justify-between gap-2">
                    <span class="text-[0.8125rem]/5 font-medium text-foreground">{card.title}</span>
                    {card.tag && <Tag size="sm" variant={card.tag.variant ?? "default"} class="shrink-0">{card.tag.label}</Tag>}
                  </span>
                  {card.meta && <span class="mt-1 block text-[0.8125rem]/5 text-muted-foreground">{card.meta}</span>}
                </a>
              ) : (
                <div class="rounded-md border border-border bg-card p-3 [[data-haze-kanban][data-enhanced]_&]:pe-10">
                  <div class="flex items-start justify-between gap-2">
                    <p class="text-[0.8125rem]/5 font-medium text-foreground">{card.title}</p>
                    {card.tag && <Tag size="sm" variant={card.tag.variant ?? "default"} class="shrink-0">{card.tag.label}</Tag>}
                  </div>
                  {card.meta && <p class="mt-1 text-[0.8125rem]/5 text-muted-foreground">{card.meta}</p>}
                </div>
              )}
              <button
                type="button"
                hidden
                data-kanban-handle
                aria-pressed="false"
                aria-label={`${moveLabel}: ${card.title}`}
                class="absolute end-1.5 top-1/2 size-7 -translate-y-1/2 cursor-grab touch-none items-center justify-center rounded-xs text-muted-foreground transition-[color,background-color,scale] duration-150 ease-snappy active:scale-90 active:duration-100 hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring aria-pressed:bg-accent aria-pressed:text-foreground [&:not([hidden])]:inline-flex"
              >
                <GripVertical aria-hidden="true" class="size-4" />
              </button>
            </li>
          ))}
        </ul>
        <p data-kanban-empty hidden={lane.cards.length > 0} class="rounded-md border border-dashed border-border px-3 py-6 text-center text-[0.8125rem]/5 text-muted-foreground [&[hidden]]:hidden">{emptyLabel}</p>
      </div>
    ))
  }
  <p data-kanban-status role="status" aria-live="polite" class="sr-only"></p>
</section>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const lanes = Array.from(root.querySelectorAll<HTMLElement>("[data-kanban-lane]"));
    const status = root.querySelector<HTMLElement>("[data-kanban-status]")!;
    const listOf = (lane: HTMLElement) => lane.querySelector<HTMLElement>("[data-kanban-list]")!;
    const cardsOf = (lane: HTMLElement) => Array.from(listOf(lane).querySelectorAll<HTMLElement>(":scope > [data-kanban-card]"));
    const say = (text: string) => { status.textContent = text; };
    const refresh = () => lanes.forEach((lane) => {
      const n = cardsOf(lane).length;
      const count = lane.querySelector<HTMLElement>("[data-kanban-count]")!;
      count.textContent = String(n);
      count.setAttribute("aria-label", `${n} items`);
      lane.querySelector<HTMLElement>("[data-kanban-empty]")!.hidden = n > 0;
    });
    const where = (card: HTMLElement) => {
      const lane = card.closest<HTMLElement>("[data-kanban-lane]")!;
      const all = cardsOf(lane);
      return { lane, name: lane.dataset.laneTitle ?? "", position: all.indexOf(card) + 1, total: all.length };
    };
    const place = (card: HTMLElement, lane: HTMLElement, index: number) => {
      const others = cardsOf(lane).filter((c) => c !== card);
      listOf(lane).insertBefore(card, others[Math.min(index, others.length)] ?? null);
    };

    const scroller = (() => {
      for (let el: HTMLElement | null = root; el; el = el.parentElement) {
        const x = getComputedStyle(el).overflowX;
        if ((x === "auto" || x === "scroll") && el.scrollWidth > el.clientWidth) return el;
      }
      return null;
    })();
    const EDGE = 40, MAX_STEP = 18;
    const speed = (pos: number, low: number, high: number) => pos < low + EDGE ? -Math.ceil(MAX_STEP * Math.min(1, (low + EDGE - pos) / EDGE)) : pos > high - EDGE ? Math.ceil(MAX_STEP * Math.min(1, (pos - (high - EDGE)) / EDGE)) : 0;

    for (const card of root.querySelectorAll<HTMLElement>("[data-kanban-card]")) {
      const handle = card.querySelector<HTMLButtonElement>("[data-kanban-handle]")!;
      handle.hidden = false;
      const title = card.dataset.title ?? "";
      let origin: { lane: HTMLElement; index: number } | null = null;
      let drag: { id: number; x: number; y: number; started: boolean; placeholder?: HTMLElement; dx: number; dy: number; cx: number; cy: number } | null = null;
      let scrollRaf = 0;
      let moving = false;

      const report = (verb: string) => {
        const w = where(card);
        say(`${verb} '${title}' ${verb === "Dropped" ? "in" : "to"} ${w.name}, position ${w.position} of ${w.total}.`);
      };
      const clearPick = () => {
        card.removeAttribute("data-picked");
        handle.setAttribute("aria-pressed", "false");
        origin = null;
      };

      handle.addEventListener("keydown", (event) => {
        if (drag) {
          if (event.key === "Escape" && drag.started) { event.preventDefault(); finish(drag.id, true); }
          return;
        }
        const key = event.key;
        if (key === " " || key === "Enter") {
          event.preventDefault();
          if (origin) { clearPick(); report("Dropped"); return; }
          const w = where(card);
          origin = { lane: w.lane, index: w.position - 1 };
          card.setAttribute("data-picked", "");
          handle.setAttribute("aria-pressed", "true");
          say(`Picked up '${title}', position ${w.position} of ${w.total} in ${w.name}. Use the arrow keys to move, Space to drop, Escape to cancel.`);
          return;
        }
        if (!origin) return;
        if (key === "Escape") {
          event.preventDefault();
          const from = origin;
          moving = true; place(card, from.lane, from.index); handle.focus(); moving = false;
          clearPick(); refresh();
          const w = where(card);
          say(`Move canceled. '${title}' is back in ${w.name}, position ${w.position} of ${w.total}.`);
          return;
        }
        if (!["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(key)) return;
        event.preventDefault();
        const w = where(card);
        if (key === "ArrowLeft" || key === "ArrowRight") {
          const rtl = getComputedStyle(root).direction === "rtl";
          const step = (key === "ArrowRight") !== rtl ? 1 : -1;
          const next = lanes[lanes.indexOf(w.lane) + step];
          if (!next) return;
          moving = true; place(card, next, w.position - 1); handle.focus(); moving = false;
        } else {
          const index = w.position - 1 + (key === "ArrowDown" ? 1 : -1);
          if (index < 0 || index >= w.total) return;
          moving = true; place(card, w.lane, index); handle.focus(); moving = false;
        }
        refresh(); report("Moved");
      });
      handle.addEventListener("blur", () => { if (origin && !moving && !drag) clearPick(); });

      handle.addEventListener("pointerdown", (event) => {
        if (!event.isPrimary || event.button !== 0 || origin) return;
        const r = card.getBoundingClientRect();
        drag = { id: event.pointerId, x: event.clientX, y: event.clientY, started: false, dx: event.clientX - r.left, dy: event.clientY - r.top, cx: event.clientX, cy: event.clientY };
        handle.setPointerCapture(event.pointerId);
      });
      const track = () => {
        if (!drag || !drag.started) return;
        const cx = drag.cx, cy = drag.cy;
        card.style.left = `${cx - drag.dx}px`;
        card.style.top = `${cy - drag.dy}px`;
        const target = document.elementsFromPoint(cx, cy)
          .map((e) => e.closest<HTMLElement>("[data-kanban-lane]"))
          .find((l) => l && root.contains(l));
        if (!target) return;
        const ph = drag.placeholder!;
        let before: Element | null = null;
        for (const c of cardsOf(target)) {
          if (c === card) continue;
          const cr = c.getBoundingClientRect();
          if (cy <= cr.top + cr.height / 2) { before = c; break; }
        }
        // The placeholder sits among the cards, so skip over it when comparing the next sibling.
        if (ph.parentElement !== listOf(target) || (ph.nextElementSibling !== before && !(before === null && !ph.nextElementSibling))) listOf(target).insertBefore(ph, before);
      };
      const autoScroll = () => {
        scrollRaf = 0;
        if (!drag || !drag.started) return;
        let moved = false;
        if (scroller) {
          const b = scroller.getBoundingClientRect();
          const dx = speed(drag.cx, Math.max(b.left, 0), Math.min(b.right, innerWidth));
          if (dx) { const before = scroller.scrollLeft; scroller.scrollLeft += dx; moved = scroller.scrollLeft !== before; }
        }
        const dy = speed(drag.cy, 0, innerHeight);
        if (dy) { const before = scrollY; scrollBy(0, dy); moved = moved || scrollY !== before; }
        if (moved) track();
        scrollRaf = requestAnimationFrame(autoScroll);
      };
      handle.addEventListener("pointermove", (event) => {
        if (!drag || drag.id !== event.pointerId) return;
        if (!drag.started) {
          if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 5) return;
          drag.started = true;
          const w = where(card);
          origin = { lane: w.lane, index: w.position - 1 };
          const r = card.getBoundingClientRect();
          const ph = document.createElement("li");
          ph.setAttribute("aria-hidden", "true");
          ph.setAttribute("data-kanban-drop", "");
          ph.className = "rounded-md border border-dashed border-border-strong bg-muted motion-safe:animate-rise";
          ph.style.height = `${r.height}px`;
          card.before(ph);
          drag.placeholder = ph;
          card.setAttribute("data-dragging", "");
          Object.assign(card.style, { position: "fixed", width: `${r.width}px`, zIndex: "50", pointerEvents: "none", margin: "0" });
          say(`Picked up '${title}'.`);
        }
        drag.cx = event.clientX; drag.cy = event.clientY;
        track();
        if (!scrollRaf) scrollRaf = requestAnimationFrame(autoScroll);
      });
      function finish(pointerId: number, cancel: boolean) {
        if (!drag || drag.id !== pointerId) return;
        const d = drag; drag = null; cancelAnimationFrame(scrollRaf); scrollRaf = 0;
        if (handle.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId);
        if (!d.started) return;
        const from = origin!;
        card.removeAttribute("data-dragging");
        for (const p of ["position", "width", "z-index", "pointer-events", "margin", "left", "top"]) card.style.removeProperty(p);
        if (cancel) { d.placeholder!.remove(); place(card, from.lane, from.index); }
        else d.placeholder!.replaceWith(card);
        origin = null;
        refresh();
        const w = where(card);
        const place_ = `'${title}' ${cancel ? "is back in" : "to"} ${w.name}, position ${w.position} of ${w.total}.`;
        const changed = w.lane !== from.lane || w.position - 1 !== from.index;
        say(cancel ? `Move canceled. ${place_}` : changed ? `Moved ${place_}` : `Dropped '${title}' in ${w.name}, position ${w.position} of ${w.total}.`);
      }
      handle.addEventListener("pointerup", (e) => finish(e.pointerId, false));
      handle.addEventListener("pointercancel", (e) => finish(e.pointerId, true));
    }
    refresh();
    root.setAttribute("data-enhanced", "");
  }
  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-kanban]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-kanban-listener")) {
    document.documentElement.setAttribute("data-haze-kanban-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
