Ria Choi
← Blog

Draggable Cards and Dashboard

Project Orca

Draggable Cards and Dashboard

When I started building Orca, I wanted a dashboard that felt like arranging widgets on a home screen. - the kind you see on your Iphone. Cards needed to move freely, resize from their edges, and make room for one another without unexpectedly rearranging the entire page.

I implemented the interactions directly with React, TypeScript, CSS Grid, and browser Pointer Events. The project does not depend on a drag and drop grid library.

The interesting part is not moving a rectangle. It is deciding what happens to every other card when that rectangle moves or grows.

Blog image
How Orca Dashboard look like

A card is a rectangle in grid coordinates

The grid does not store card positions in pixels. Each card has a column, row, width, and height. A width of 2 means two grid tracks, regardless of the screen's pixel width.

TSX


type CardPlacement = {
  id: string;
  column: number;
  row: number;
  width: number;
  height: number;
  layoutColumns?: number;
};

The browser turns those values into CSS Grid positions:

<div
  className="board-card-slot"
  style={{
    '--c': card.column + 1,
    '--r': card.row + 1,
    '--w': card.width,
    '--h': card.height,
  } as React.CSSProperties}
>
  <SummaryCard card={card} />
</div>

.card-grid.is-positioned > .board-card-slot {
  grid-column: var(--c) / span var(--visible-w, var(--w));
  grid-row: var(--r) / span var(--h);
}

CSS Grid counts tracks from 1, while the saved model starts from 0. That is why the rendered column and row add one.

The distinction is important: pixels describe the current screen; grid coordinates describe the layout.

The number of columns responds to available width

Orca no longer assumes that every desktop dashboard has four columns. The main card grid measures its own container with ResizeObserver.

Its calculation is equivalent to:

JavaScript
const visibleColumns = Math.max(
  1,
  Math.min(
    GRID_COLUMNS,
    Math.floor((availableWidth + gap) / (175 + gap)),
  ),
);

 

On desktop, GRID_COLUMNS is a logical maximum of 12. The actual visible count can be smaller. The desktop card grid uses 180px automatic rows, and the page scrolls vertically when the content grows. This is not a permanently fixed four by three board.

On a tablet, the visible grid is capped at four tracks. On a narrow phone, the CSS shows two physical columns and cards flow in their order. A wider card spans both phone columns.

There is one more detail: if a saved layout has more columns than the current viewport, Orcha creates a temporary projected layout. It reduces spans where necessary and arranges cards for the narrower view. The saved desktop coordinates do not need to be destroyed merely because someone resized the browser.

Blog image

Dragging and resizing are different gestures

I deliberately separate the two interactions.

Dragging begins on a card's body. Resizing begins only on the dedicated controls at the right and bottom edges. A pointer event starting on a button, input, link, or other interactive control is ignored by the card drag handler.

On desktop, the resize grips fade in when the card is hovered or focused. The vertical grip on the right changes width. The horizontal grip at the bottom changes height.

CSS
.resize-arc {
  position: absolute;
  opacity: 0;
  touch-action: none;
  border-radius: 999px;
}

.summary-card:hover .resize-arc,
.resize-arc:focus-visible,
.resize-arc.is-active {
  opacity: 1;
}

.resize-width { right: 3px; top: 50%; cursor: ew-resize; }
.resize-height { bottom: 3px; left: 50%; cursor: ns-resize; }

Touch screens have no reliable hover. There, holding a card for approximately 450ms enters the editing interaction. The grips become visible in edit mode. Moving the finger too early cancels a pending long press so normal scrolling can continue.

The same distinction protects the contents of a card. Checking a task or opening a link should not accidentally move the whole widget.

Dragging: measure, snap, preview, then commit

The drag hook follows four steps.

First, measure the grid. It reads the real column count, gap, padding, card height, and bounding rectangles from the DOM. It also saves the offset between the pointer and the card's top left corner.

Second, activate the gesture. A mouse or pen must move at least 6px. On touch, the hold must complete before dragging begins. The original card becomes an empty looking placeholder, while a floating copy follows the pointer.

Third, calculate the target cell. The pointer's position is converted into grid coordinates using the original grab offset. The top left of the dragged card, not the center of the pointer, determines the target.

The core calculation looks like this:

JavaScript
const column = clamp(
  Math.round((pointerX - offsetX - gridLeft) / stepX),
  0,
  visibleColumns - card.width,
);

const row = clamp(
  Math.round((pointerY - offsetY - gridTop) / stepY),
  0,
  GRID_ROWS - card.height,
);

const preview = placeCard(cards, card.id, column, row);

Here, stepX and stepY include the cell size plus the gap. clamp means restricting a number to its minimum and maximum bounds.

Fourth, wait briefly before rearranging neighbors. Orcha uses a 150ms dwell for a newly targeted cell. Passing quickly over another card does not make the whole dashboard jump around. The active cell produces a preview, but nothing is persisted yet.

When the pointer is released, the hook recalculates the final target. This matters if the pointer is released before the dwell timer finishes. Only then is the new layout committed.

On phones, dragging follows a simpler rule. Instead of targeting fixed desktop coordinates, the card is inserted before or after another card in reading order, then the mobile grid displays the new order.

Collision handling: move as little as possible

The placement function placeCard() tries solutions in a specific order. Its goal is to preserve the positions of cards that are not involved in the move.

Priority 1: swap two cards

If the dragged card covers exactly one neighbor, Orcha first tries moving that neighbor into the dragged card's previous location. If both rectangles fit without causing another collision, the move is a simple swap.

Priority 2: move only the covered cards

If swapping fails, the dragged card stays anchored in its target cell. The algorithm temporarily removes the positions of only the covered neighbors, then finds free cells for them. Unaffected cards remain where they were.

Priority 3: reflow or search for a valid arrangement

If the minimal move cannot fit, the algorithm tries repacking the remaining cards in reading order around the anchored card. A final search can explore other valid placements, preferring nearby positions.

In simplified pseudocode:

PHP
Collision handling: move as little as possible

The placement function placeCard() tries solutions in a specific order. Its goal is to preserve the positions of cards that are not involved in the move.

Priority 1: swap two cards

If the dragged card covers exactly one neighbor, Orcha first tries moving that neighbor into the dragged card's previous location. If both rectangles fit without causing another collision, the move is a simple swap.

Priority 2: move only the covered cards

If swapping fails, the dragged card stays anchored in its target cell. The algorithm temporarily removes the positions of only the covered neighbors, then finds free cells for them. Unaffected cards remain where they were.

Priority 3: reflow or search for a valid arrangement

If the minimal move cannot fit, the algorithm tries repacking the remaining cards in reading order around the anchored card. A final search can explore other valid placements, preferring nearby positions.

In simplified pseudocode:

function placeCard(cards, draggedId, target) {
  const anchored = moveCardTo(cards, draggedId, target);
  if (!isInsideGrid(anchored)) return null;

  const covered = findOverlappingCards(anchored, cards);

  if (covered.length === 1) {
    const swap = trySwapWithOldPosition(anchored, covered[0], cards);
    if (swap) return swap;
  }

  const minimal = moveOnlyCoveredCards(anchored, covered, cards);
  if (minimal) return minimal;

  return reflowAround(anchored, cards)
    ?? searchForValidPositions(anchored, cards);
}

This block is explanatory pseudocode, not a copy of the repository function. The actual implementation uses arrangeCards() and fitAround() for validation and fallback placement.

An overlap is detected using rectangle intersection:

JavaScript
This block is explanatory pseudocode, not a copy of the repository function. The actual implementation uses arrangeCards() and fitAround() for validation and fallback placement.

An overlap is detected using rectangle intersection:

const overlaps = (a: Tile, b: Tile) =>
  a.column < b.column + b.width &&
  a.column + a.width > b.column &&
  a.row < b.row + b.height &&
  a.row + a.height > b.row;

Each rectangle is checked in grid cells, not screen pixels.

Blog image

Resizing: snap to cell units, not arbitrary pixels

The resize component records its start position, original dimension, cell step, and allowed minimum and maximum at pointer down.

The actual snap function is small:

TypeScript
function resizeTarget(
  from: number,
  delta: number,
  step: number,
  minimum: number,
  maximum: number,
) {
  const min = Math.max(1, Math.round(minimum));
  const max = Math.max(min, Math.round(maximum));

  return Math.max(
    min,
    Math.min(max, from + Math.round(delta / Math.max(1, step))),
  );
}

 

For example, suppose a card is two columns wide and one column is approximately 190px including its gap. Dragging the width grip about 190px to the right changes the target from two columns to three. Dragging it back reverses the change one cell at a time.

Most ordinary cards can shrink to one column. Orcha's recap style card has a two column minimum. Width is limited by the visible grid at the start of the gesture, while ordinary card height can reach twenty rows. The special top widgets have a separate height limit of three rows.

The most important implementation detail is that pointer movement creates a preview only:

The preview always derives from a saved snapshot of the layout, not the previously previewed frame. This avoids cumulative position drift. It also prevents a separate server request for every pixel of mouse movement.

What happens when a card expands sideways?

This is where resizeLayout() handles the difficult cases.

Case A: empty cells are available. The card expands from its existing column and row. Nothing else changes.

Case B: another card occupies the new area. The resized card keeps its origin. The overlapping neighbor is moved to a free location. If several cards block the expansion, the algorithm may move a chain of neighbors while searching for a valid arrangement.

Case C: the card reaches the right edge. Orcha does not allow the rectangle to overflow horizontally. If the new width cannot fit from its current column, the algorithm searches the following rows for a position where the wider card fits. This makes the card wrap down to another row, not spill beyond the dashboard's boundary.

Case D: no valid placement exists. The operation returns null. The UI keeps the previous committed layout and shows an explanation instead of corrupting the coordinates.

The decision order is equivalent to:

 

This is also why the dashboard can grow vertically. The model allows up to 240 logical rows, but the visible page creates rows as needed and scrolls. Separately, Orcha limits a dashboard to 12 regular cards. The plus tile is placed just after the last occupied cell in reading order, and the layout validator reserves a final logical cell for it.

Blog image

The top widgets need their own grid

There are actually two layout engines on Orcha's dashboard.

The ordinary cards use Board, useCardDrag, resizeLayout(), and placeCard().

The top widgets use FeatureGrid, placeWidget(), and projectWidgets(). These widgets include Daily Briefing and the Weekly, Monthly, and Yearly summary folders. Their grid uses 230px rows and a separate saved layout record.

Why keep them separate? A Daily Briefing can span an entire top row, while smaller folders may sit beside it. When a folder moves into the Briefing's space, placeWidget() first tries shortening the Briefing to the remaining width. Other unaffected folders stay put. If necessary, only displaced folders are placed into open cells.

The top grid also projects its saved coordinates for narrower screens. Disabled folders do not occupy phantom cells, but their saved dimensions remain available if they are enabled later.

It has its own drag preview and animation logic, implemented by useWidgetMotion. Its gestures use the same interaction lock as ordinary cards, but it does not use the ordinary card drag hook.

Smooth movement with FLIP animation

After a card moves, the browser must visually transition from its old position to its new one. Orcha uses the FLIP principle: First, Last, Invert, Play.

  1. Record each card's previous bounding rectangle.
  2. Let CSS Grid render the new coordinates.
  3. Measure the new rectangle.
  4. Animate a translation from the previous position to the new one.
PHP
element.animate(
  [
    { transform: `translate(${old.x - next.x}px, ${old.y - next.y}px)` },
    { transform: 'translate(0, 0)' },
  ],
  {
    duration: 380,
    easing: 'cubic-bezier(.22,1,.36,1)',
  },
);

The ordinary board animates position changes. The top widget grid can animate changes in both position and size. The final drop starts from the floating card's last rectangle, so it appears to settle naturally into its assigned slot. The animation is skipped when the user prefers reduced motion.

Save the layout without losing in progress interactions

Saving is not part of every pointer movement.

For ordinary cards, the current positions live in React state. When a drag or resize ends, the new layout is committed. A diff identifies changed coordinates or dimensions and sends a layout update to the server. The update includes version information so another device's edits do not silently replace the current arrangement.

An interaction lock prevents incoming server snapshots from overwriting a card while it is being dragged or resized. Server reloads are deferred until the interaction and pending writes finish. If the server reports a version conflict (409), the save flow can reload the latest version and retry the local placements.

The top widget grid saves a record shaped like this:

TypeScript
type WidgetLayout = {
  version: number;
  columns: number;
  tiles: Array<{
    id: string;
    column: number;
    row: number;
    width: number;
    height: number;
  }>;
};

It uses a widget layout API for signed in users and browser storage for local demo mode. Desktop, tablet, and installed web app surfaces can keep independent layout records.

This separation protects two things at once: the immediate feel of dragging and the reliability of a saved dashboard.

Small details that make the grid usable

Several rules matter just as much as the placement algorithm:

  • A drag starts only after a small movement threshold. Normal clicks still open cards.
  • Dragging ignores form controls and links inside cards.
  • Releasing the pointer before a dwell completes still uses the final target cell.
  • Escape, pointer cancellation, and window blur cancel unfinished gestures.
  • Resize handles use pointer capture so their gesture remains separate from dragging.
  • Alt plus the left or right arrow key can reorder an ordinary card.
  • Keyboard focus can reveal the resize grips, and Enter or Space can step a dimension.
  • The code includes regression tests for swapping, covered neighbors, edge wrapping, responsive widths, resize snapping, and interaction locks.

These are small decisions, but together they make the layout feel predictable.

 

+ Try it out yourself

Blog image

If you'd like to try out the Orca Dashboard, feel free to sign in using the credentials below and explore the cards! :)

Please avoid using the AI features for now, as I'm still developing them and trying to keep the API costs down.

Orca Dashboard - Work in progress

Blog image

 

Hope I’m able to launch this mid 2027!

Related Posts

View all