Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: migrate Brain link buckets/chips from native HTML5 DnD to dnd-kit (#8120)

[._.]/ Adam Eivya1127de4325d
diff --git a/client/src/a11yConventions.test.js b/client/src/a11yConventions.test.js
index d84c4e019b..dd4905b91c 100644
--- a/client/src/a11yConventions.test.js
+++ b/client/src/a11yConventions.test.js
@@ -3712,6 +3712,48 @@ function B() { const sensors = useSensors(useSensor(PointerSensor)); return <Dnd
expect(offenders, `DndContext registered without a KeyboardSensor — every dnd-kit handle already announces itself as draggable and tells the user to press Space, so a pointer-only sensor list is a WCAG 2.1.1 failure. Add useSensor(KeyboardSensor, { coordinateGetter }) (sortableKeyboardCoordinates for a SortableContext, createFreeDroppableKeyboardCoordinates from lib/dndKeyboardCoordinates.js for free droppables):\n${offenders.join('\n')}`).toEqual([]);
});
+ it('never reintroduces native HTML5 drag-and-drop (#8120)', () => {
+ // A JSX `draggable` attribute means the browser's OWN drag-and-drop, which
+ // has no keyboard or assistive-technology path at all — that gap is
+ // exactly what the tree-wide dnd-kit migration (#6911, #7243, #8120)
+ // replaced. Brain → Links was the last native site (buckets and chips,
+ // both via `dataTransfer`); see `components/brain/links/bucketDnd.js` for
+ // the worked multi-container (bucket-reorder + cross-bucket chip-reorder)
+ // example this rule now guards. `draggable={false}` (or `"false"`) is the
+ // one legitimate spelling left: it suppresses the browser's default drag
+ // on an `<a>`/`<img>` nested inside a dnd-kit handle so it stops fighting
+ // the pointer sensor — see the anchors in `LinkChip.jsx`.
+ const DRAGGABLE_ATTR = /(?:^|\s)draggable(?:\s*=\s*(?:\{([^}]*)\}|"([^"]*)"|'([^']*)'))?(?=[\s/>])/;
+ const offendersIn = (file, src) => {
+ const out = [];
+ for (const node of forEachOpeningTag(src, undefined)) {
+ const m = DRAGGABLE_ATTR.exec(node.tag);
+ if (!m) continue;
+ const value = (m[1] ?? m[2] ?? m[3] ?? '').trim();
+ if (value === 'false' || value === "'false'" || value === '"false"') continue;
+ out.push(`${file}:${lineOf(src, node.index)}`);
+ }
+ return out;
+ };
+
+ // Probe first — the tree is green by construction, so nothing left in it
+ // pins what the walk rejects.
+ expect(offendersIn('probe.jsx', '<div draggable>x</div>')).toEqual(['probe.jsx:1']);
+ expect(offendersIn('probe.jsx', '<div draggable={true}>x</div>')).toEqual(['probe.jsx:1']);
+ expect(offendersIn('probe.jsx', '<div draggable="true">x</div>')).toEqual(['probe.jsx:1']);
+ expect(offendersIn('probe.jsx', '<div draggable={isDraggable}>x</div>')).toEqual(['probe.jsx:1']);
+ // …the one exempt spelling, in both a JSX-expression and a plain string:
+ expect(offendersIn('probe.jsx', '<div draggable={false}>x</div>')).toEqual([]);
+ expect(offendersIn('probe.jsx', '<a draggable="false" href="x">x</a>')).toEqual([]);
+ // A bare mention of the word (prose, an object key) is not the JSX attribute.
+ expect(offendersIn('probe.jsx', '<div>draggable</div>')).toEqual([]);
+ expect(offendersIn('probe.jsx', "const draggable = true;\n<div />")).toEqual([]);
+
+ const offenders = [];
+ for (const file of trackedJsxFiles()) offenders.push(...offendersIn(file, maskedSourceOf(file)));
+ expect(offenders, `A JSX draggable attribute other than draggable={false} — native HTML5 drag-and-drop has no keyboard path. Migrate to dnd-kit (useDraggable/useDroppable + a KeyboardSensor); components/brain/links/bucketDnd.js is a worked multi-container example:\n${offenders.join('\n')}`).toEqual([]);
+ });
+
// --- routed-page top-level heading (#7245) -------------------------------
//
// A routed page with no <h1> inverts the document outline: heading
diff --git a/client/src/components/brain/links/BucketBoard.jsx b/client/src/components/brain/links/BucketBoard.jsx
index 637048857e..b7eca1a7ea 100644
--- a/client/src/components/brain/links/BucketBoard.jsx
+++ b/client/src/components/brain/links/BucketBoard.jsx
@@ -7,12 +7,12 @@ import BucketCard from './BucketCard';
/**
* The bucket board: a responsive grid of bucket cards plus a "new bucket"
* affordance. The bucket collection + links (the single source of truth) live
- * in the parent LinksTab and flow in via props. Drag-and-drop is carried via
- * dataTransfer (link id / bucket id) so a link dragged from the list, a chip
- * dragged from another bucket, and a bucket header dragged to reorder all
- * resolve the same way regardless of which component started the drag.
+ * in the parent LinksTab and flow in via props. Drag-and-drop (reordering
+ * buckets, filing/reordering chips) is dnd-kit, driven by the ONE
+ * `DndContext` the parent `LinksTab` mounts around this board and the flat
+ * link list — see `bucketDnd.js` for the shared coordinate/collision logic.
*/
-export default function BucketBoard({ links, buckets, setBuckets, onAssignLink, onAddLinkToBucket, onBucketDeleted, onMoveLinkToIndex }) {
+export default function BucketBoard({ links, buckets, setBuckets, onAssignLink, onAddLinkToBucket, onBucketDeleted }) {
const [creating, setCreating] = useState(false);
const [newName, setNewName] = useState('');
@@ -51,39 +51,6 @@ export default function BucketBoard({ links, buckets, setBuckets, onAssignLink,
}
}, [onBucketDeleted, setBuckets]);
- // --- Drag: move a link (from the list or another bucket) into a bucket ---
- const handleDropLink = useCallback((linkId, bucketId) => {
- const link = links.find(l => l.id === linkId);
- if (link && link.bucketId !== bucketId) {
- onAssignLink?.(link, bucketId);
- }
- }, [links, onAssignLink]);
-
- // --- Drag: drop a chip at a specific position within (or into) a bucket ---
- const handleMoveLink = useCallback((linkId, bucketId, targetIndex) => {
- const link = links.find(l => l.id === linkId);
- if (link) onMoveLinkToIndex?.(link, bucketId, targetIndex);
- }, [links, onMoveLinkToIndex]);
-
- // --- Drag: reorder buckets ---
- const handleReorder = useCallback((draggedId, targetBucket) => {
- if (!draggedId || draggedId === targetBucket.id) return;
-
- setBuckets(prev => {
- const ids = prev.map(b => b.id);
- const from = ids.indexOf(draggedId);
- const to = ids.indexOf(targetBucket.id);
- if (from === -1 || to === -1) return prev;
- const next = [...prev];
- const [moved] = next.splice(from, 1);
- next.splice(to, 0, moved);
- api.reorderBrainBuckets(next.map(b => b.id), { silent: true }).catch(err => {
- toast.error(err.message || 'Failed to reorder buckets');
- });
- return next;
- });
- }, [setBuckets]);
-
const groupedLinks = useMemo(() => {
const grouped = new Map();
links.forEach(link => {
@@ -103,18 +70,16 @@ export default function BucketBoard({ links, buckets, setBuckets, onAssignLink,
return (
<div className="@container">
<div className="grid grid-cols-1 @md:grid-cols-2 @4xl:grid-cols-3 gap-4">
- {buckets.map(bucket => (
+ {buckets.map((bucket, bucketIndex) => (
<BucketCard
key={bucket.id}
bucket={bucket}
+ bucketIndex={bucketIndex}
links={groupedLinks.get(bucket.id) || []}
onUpdate={handleUpdate}
onDelete={handleDelete}
onAddLink={onAddLinkToBucket}
onRemoveLink={(link) => onAssignLink?.(link, null)}
- onDropLink={(linkId) => handleDropLink(linkId, bucket.id)}
- onReorderBucket={(draggedId) => handleReorder(draggedId, bucket)}
- onMoveLink={(linkId, index) => handleMoveLink(linkId, bucket.id, index)}
/>
))}
diff --git a/client/src/components/brain/links/BucketBoard.test.jsx b/client/src/components/brain/links/BucketBoard.test.jsx
index 0605ee1ca5..a5cc63b421 100644
--- a/client/src/components/brain/links/BucketBoard.test.jsx
+++ b/client/src/components/brain/links/BucketBoard.test.jsx
@@ -49,8 +49,7 @@ describe('BucketBoard', () => {
{ id: 'l2', url: 'https://b.com', title: 'Beta', bucketId: 'b1', bucketOrder: 1 }
];
- it('routes a positioned chip drop to onMoveLinkToIndex with the dragged link + chip index', () => {
- const onMoveLinkToIndex = vi.fn();
+ it('renders each bucket\'s chips in bucketOrder', () => {
render(
<BucketBoard
links={twoChip}
@@ -59,63 +58,10 @@ describe('BucketBoard', () => {
onAssignLink={vi.fn()}
onAddLinkToBucket={vi.fn()}
onBucketDeleted={vi.fn()}
- onMoveLinkToIndex={onMoveLinkToIndex}
/>
);
- // Drag Alpha (l1) onto Beta (index 1). jsdom reports a zero-size rect, so
- // the before/after midpoint resolves to "before" → index 1. (The exact
- // before/after split is geometry the helper test covers.)
- const dataTransfer = { getData: () => 'l1', types: ['text/x-brain-link'] };
- fireEvent.drop(screen.getByText('Beta'), { dataTransfer });
- expect(onMoveLinkToIndex).toHaveBeenCalledWith(twoChip[0], 'b1', 1);
- });
-
- it('keeps the armed marker through a bubbled dragleave and routes a gap drop to it', () => {
- const onMoveLinkToIndex = vi.fn();
- const { container } = render(
- <BucketBoard
- links={twoChip}
- buckets={buckets}
- setBuckets={vi.fn()}
- onAssignLink={vi.fn()}
- onAddLinkToBucket={vi.fn()}
- onBucketDeleted={vi.fn()}
- onMoveLinkToIndex={onMoveLinkToIndex}
- />
- );
- const linkDt = { getData: () => 'l1', types: ['text/x-brain-link'] };
- const card = container.querySelector('.flex.flex-col.bg-port-card'); // b1's card root
- const chipRow = container.querySelector('.flex.flex-wrap'); // b1's chip row
- // Hovering Beta (index 1) arms the marker at index 1.
- fireEvent.dragOver(screen.getByText('Beta'), { dataTransfer: linkDt });
- // A bubbled dragleave reaching the card (the chip→gap crossing fires one)
- // must NOT clear the armed marker — the regression was the card-level
- // onDragLeave wiping dropIndex unconditionally. (relatedTarget can't be
- // simulated in jsdom, but the card's leave no longer reads the event, so
- // this exercises the exact handler that held the bug.)
- fireEvent.dragLeave(card);
- // Releasing in the gap (the chip row, not a chip) bubbles to the card's
- // drop handler, which must honor the still-armed marker rather than append.
- fireEvent.drop(chipRow, { dataTransfer: linkDt });
- expect(onMoveLinkToIndex).toHaveBeenCalledWith(twoChip[0], 'b1', 1);
- });
-
- it('ignores a chip-level drop that carries no link payload (e.g. a bucket reorder)', () => {
- const onMoveLinkToIndex = vi.fn();
- render(
- <BucketBoard
- links={twoChip}
- buckets={buckets}
- setBuckets={vi.fn()}
- onAssignLink={vi.fn()}
- onAddLinkToBucket={vi.fn()}
- onBucketDeleted={vi.fn()}
- onMoveLinkToIndex={onMoveLinkToIndex}
- />
- );
- const dataTransfer = { getData: () => '', types: ['text/x-brain-bucket'] };
- fireEvent.drop(screen.getByText('Alpha'), { dataTransfer });
- expect(onMoveLinkToIndex).not.toHaveBeenCalled();
+ const chips = screen.getAllByText(/Alpha|Beta/).map((el) => el.textContent);
+ expect(chips).toEqual(['Alpha', 'Beta']);
});
it('creates a new bucket through the inline form', async () => {
diff --git a/client/src/components/brain/links/BucketCard.jsx b/client/src/components/brain/links/BucketCard.jsx
index c20f6f611a..ac603238a2 100644
--- a/client/src/components/brain/links/BucketCard.jsx
+++ b/client/src/components/brain/links/BucketCard.jsx
@@ -1,27 +1,33 @@
import { useState, Fragment } from 'react';
import { Plus, Edit2, Trash2, Save, X, Check, GripVertical } from 'lucide-react';
+import { useDraggable, useDroppable } from '@dnd-kit/core';
import BrailleSpinner from '../../BrailleSpinner';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import LinkChip from './LinkChip';
-import { bucketColor, BUCKET_COLORS, BUCKET_COLOR_KEYS, LINK_DND_TYPE, BUCKET_DND_TYPE } from './bucketColors';
-import { chipInsertIndex } from './bucketReorder';
+import { bucketColor, BUCKET_COLORS, BUCKET_COLOR_KEYS } from './bucketColors';
+import { bucketDropId, chipSlotId, BUCKET_KIND, LINK_KIND, LINK_SLOT_KIND } from './bucketDnd';
/**
* A single bucket (bookmark group): colored header with inline edit/delete,
- * a grid of link chips, and an inline "add URL" affordance. Acts as a drop
- * target so a link can be dragged in (from the list or another bucket) and
- * so buckets can be reordered by dragging their headers.
+ * a grid of link chips, and an inline "add URL" affordance.
+ *
+ * Drag-and-drop is dnd-kit, driven by the ONE `DndContext` in `LinksTab`
+ * (buckets and chips share it so a link can move from the flat list straight
+ * into a bucket). This card registers two independent drop targets: the
+ * whole card is a 'bucket' droppable (reordering the board), and each chip —
+ * plus the chip area as a whole, for "append to the end" — is a 'link-slot'
+ * droppable (filing/reordering a link). The two never collide because
+ * `linksCollisionDetection` only matches droppables of the dragged item's own
+ * kind.
*/
export default function BucketCard({
bucket,
+ bucketIndex,
links,
onUpdate,
onDelete,
onAddLink,
onRemoveLink,
- onDropLink,
- onReorderBucket,
- onMoveLink
}) {
const formFromBucket = () => ({ name: bucket.name, color: bucket.color, icon: bucket.icon || '' });
const [editing, setEditing] = useState(false);
@@ -29,38 +35,25 @@ export default function BucketCard({
const [form, setForm] = useState(formFromBucket);
const [addUrl, setAddUrl] = useState('');
const [adding, setAdding] = useState(false);
- const [dropActive, setDropActive] = useState(false);
- // The chip index where a dragged link would be inserted (null = no chip-level
- // drop in progress); renders a vertical insertion bar at that position.
- const [dropIndex, setDropIndex] = useState(null);
const colors = bucketColor(bucket.color);
- // Insert a chip before or after the chip at index `i` based on which half of
- // it the pointer is over (chips flow left-to-right within a wrapping row).
- const dropIndexFor = (e, i) => chipInsertIndex(e.currentTarget.getBoundingClientRect(), e.clientX, i);
-
- // While dragging a link over a chip: show a precise insertion bar instead of
- // the whole-card drop ring. Bucket-reorder drags (no link payload) fall
- // through so they bubble to the card's drop handler.
- const handleChipDragOver = (e, i) => {
- if (!e.dataTransfer.types.includes(LINK_DND_TYPE)) return;
- e.preventDefault();
- e.stopPropagation();
- setDropActive(false);
- setDropIndex(dropIndexFor(e, i));
- };
-
- const handleChipDrop = (e, i) => {
- const linkId = e.dataTransfer.getData(LINK_DND_TYPE);
- if (!linkId) return; // not a chip drag — let the card handle bucket reorder
- e.preventDefault();
- e.stopPropagation();
- const targetIndex = dropIndexFor(e, i);
- setDropIndex(null);
- setDropActive(false);
- onMoveLink?.(linkId, targetIndex);
- };
+ const { setNodeRef: setCardDropRef, isOver: isBucketOver } = useDroppable({
+ id: bucketDropId(bucket.id),
+ data: { kind: BUCKET_KIND, bucketId: bucket.id, bucketName: bucket.name, bucketIndex },
+ });
+ const {
+ attributes: bucketDragAttrs, listeners: bucketDragListeners,
+ setNodeRef: setBucketDragRef, setActivatorNodeRef: setBucketActivatorRef,
+ isDragging: isBucketDragging,
+ } = useDraggable({
+ id: `bucket-drag:${bucket.id}`,
+ data: { kind: BUCKET_KIND, bucket, bucketIndex },
+ });
+ const { setNodeRef: setEndSlotRef, isOver: isEndSlotOver } = useDroppable({
+ id: chipSlotId(bucket.id, links.length),
+ data: { kind: LINK_SLOT_KIND, bucketId: bucket.id, bucketName: bucket.name, bucketIndex, index: links.length },
+ });
const startEdit = () => {
setForm(formFromBucket());
@@ -86,32 +79,10 @@ export default function BucketCard({
return (
<div
+ ref={setCardDropRef}
className={`flex flex-col bg-port-card border rounded-lg overflow-hidden transition-colors ${
- dropActive ? 'border-port-accent ring-1 ring-port-accent' : 'border-port-border'
- }`}
- onDragOver={(e) => { e.preventDefault(); if (dropIndex === null) setDropActive(true); }}
- // Don't clear dropIndex here: native dragleave bubbles, so a chip→gap
- // crossing would fire this and wipe the armed marker before a gap/bar
- // release — defeating the guarded clear on the chips row below. The chips
- // row's own dragleave (with a relatedTarget guard) owns clearing.
- onDragLeave={() => setDropActive(false)}
- onDrop={(e) => {
- e.preventDefault();
- const insertAt = dropIndex; // capture the visible insertion point before clearing
- setDropActive(false);
- setDropIndex(null);
- const linkId = e.dataTransfer.getData(LINK_DND_TYPE);
- if (linkId) {
- // Releasing in a chip gap / on the insertion bar bubbles here rather
- // than to a chip's own handler — honor the marker that was showing
- // (land at that index) instead of silently appending.
- if (insertAt !== null) onMoveLink?.(linkId, insertAt);
- else onDropLink?.(linkId);
- return;
- }
- const draggedBucketId = e.dataTransfer.getData(BUCKET_DND_TYPE);
- if (draggedBucketId) onReorderBucket?.(draggedBucketId);
- }}
+ isBucketOver ? 'border-port-accent ring-1 ring-port-accent' : 'border-port-border'
+ } ${isBucketDragging ? 'opacity-30' : ''}`}
>
{/* Header */}
{editing ? (
@@ -171,15 +142,18 @@ export default function BucketCard({
) : (
// py-1 rather than py-2: the 44px action buttons now set the row height,
// so the larger tap targets don't also inflate the header.
- <div
- className={`flex items-center gap-2 px-3 py-1 border-b cursor-grab ${colors.header}`}
- draggable
- onDragStart={(e) => {
- e.dataTransfer.setData(BUCKET_DND_TYPE, bucket.id);
- e.dataTransfer.effectAllowed = 'move';
- }}
- >
- <GripVertical size={14} className="shrink-0 text-gray-500" />
+ <div ref={setBucketDragRef} className={`flex items-center gap-2 px-3 py-1 border-b ${colors.header}`}>
+ <button
+ type="button"
+ ref={setBucketActivatorRef}
+ {...bucketDragAttrs}
+ {...bucketDragListeners}
+ className="shrink-0 flex items-center justify-center text-gray-500 cursor-grab active:cursor-grabbing"
+ aria-label={`Reorder bucket ${bucket.name}`}
+ title="Drag to reorder buckets"
+ >
+ <GripVertical size={14} />
+ </button>
{bucket.icon && <span className="shrink-0 text-base leading-none">{bucket.icon}</span>}
<h3 className={`font-medium truncate flex-1 ${colors.text}`}>{bucket.name}</h3>
<span className="text-xs text-gray-500">{links.length}</span>
@@ -212,25 +186,19 @@ export default function BucketCard({
{/* Chips */}
<div
- className="flex flex-wrap gap-2 p-3 min-h-[2.5rem]"
- onDragLeave={(e) => {
- // Only clear when the pointer truly left the chips area — crossing
- // between chips fires its own dragleave we don't want to react to.
- if (!e.currentTarget.contains(e.relatedTarget)) setDropIndex(null);
- }}
+ ref={setEndSlotRef}
+ className={`flex flex-wrap gap-2 p-3 min-h-[2.5rem] rounded transition-colors ${
+ isEndSlotOver ? 'bg-port-accent/10 ring-1 ring-inset ring-port-accent' : ''
+ }`}
>
- {links.length === 0 && dropIndex === null && (
+ {links.length === 0 && (
<span className="text-xs text-gray-600 italic">Drop links here or add a URL below.</span>
)}
{links.map((link, i) => (
<Fragment key={link.id}>
- {dropIndex === i && <ChipInsertionBar />}
- <div className="max-w-full min-w-0" onDragOver={(e) => handleChipDragOver(e, i)} onDrop={(e) => handleChipDrop(e, i)}>
- <LinkChip link={link} onRemove={onRemoveLink} draggable />
- </div>
+ <DraggableLinkChip bucket={bucket} bucketIndex={bucketIndex} link={link} index={i} onRemove={onRemoveLink} />
</Fragment>
))}
- {dropIndex === links.length && links.length > 0 && <ChipInsertionBar />}
</div>
{/* Add URL */}
@@ -258,9 +226,31 @@ export default function BucketCard({
);
}
-/** A thin vertical accent bar marking where a dragged chip will land. */
-function ChipInsertionBar() {
- // pointer-events-none so the bar isn't itself a drag target — a release on it
- // passes through to the chips row (and bubbles to the card drop handler).
- return <div className="w-0.5 self-stretch min-h-[1.75rem] rounded-full bg-port-accent pointer-events-none" aria-hidden="true" />;
+/**
+ * A chip that is BOTH a drag source (moving itself elsewhere) and a drop
+ * target (another link dropped here is inserted before it) — the same
+ * "slot doubles as source" shape `KanbanBoard.jsx`'s `DraggableTicket` uses.
+ */
+function DraggableLinkChip({ bucket, bucketIndex, link, index, onRemove }) {
+ const { setNodeRef: setSlotRef, isOver } = useDroppable({
+ id: chipSlotId(bucket.id, index),
+ data: { kind: LINK_SLOT_KIND, bucketId: bucket.id, bucketName: bucket.name, bucketIndex, index },
+ });
+ const {
+ attributes, listeners, setNodeRef: setDragRef, setActivatorNodeRef, isDragging,
+ } = useDraggable({
+ id: `link-chip:${link.id}`,
+ data: { kind: LINK_KIND, link, bucketId: bucket.id, index },
+ });
+
+ return (
+ <div
+ ref={(node) => { setSlotRef(node); setDragRef(node); }}
+ className={`max-w-full min-w-0 rounded-md transition-[box-shadow] ${isDragging ? 'opacity-30' : ''} ${
+ isOver ? 'ring-2 ring-port-accent ring-offset-1 ring-offset-port-card' : ''
+ }`}
+ >
+ <LinkChip link={link} onRemove={onRemove} dragHandleProps={{ attributes, listeners, setActivatorNodeRef }} />
+ </div>
+ );
}
diff --git a/client/src/components/brain/links/BucketCard.test.jsx b/client/src/components/brain/links/BucketCard.test.jsx
index 98ff671772..e396609997 100644
--- a/client/src/components/brain/links/BucketCard.test.jsx
+++ b/client/src/components/brain/links/BucketCard.test.jsx
@@ -9,6 +9,7 @@ const links = [{ id: 'l1', url: 'https://example.com', title: 'Example', bucketI
const renderCard = (props = {}) => render(
<BucketCard
bucket={bucket}
+ bucketIndex={0}
links={links}
onUpdate={vi.fn()}
onDelete={vi.fn()}
@@ -52,4 +53,23 @@ describe('BucketCard', () => {
expect(onDelete).not.toHaveBeenCalled();
expect(screen.getByText(/Delete bucket\?/)).toBeTruthy();
});
+
+ // #8120: native drag-and-drop had no keyboard path. dnd-kit's `useDraggable`
+ // attributes make a button a focusable, announced drag handle, so asserting
+ // the handle carries a real accessible name is the reachable proxy for
+ // "a keyboard user can find and pick this up" in a jsdom render.
+ it('names the bucket reorder handle for the bucket it moves', () => {
+ renderCard();
+ expect(screen.getByLabelText('Reorder bucket Bookmarks')).toBeTruthy();
+ });
+
+ it('names each chip\'s drag handle for the link it moves', () => {
+ renderCard();
+ expect(screen.getByLabelText('Drag Example')).toBeTruthy();
+ });
+
+ it('renders no native draggable attribute anywhere in the card', () => {
+ const { container } = renderCard();
+ expect(container.querySelector('[draggable="true"]')).toBeNull();
+ });
});
diff --git a/client/src/components/brain/links/LinkChip.jsx b/client/src/components/brain/links/LinkChip.jsx
index 96de252b35..e859518dce 100644
--- a/client/src/components/brain/links/LinkChip.jsx
+++ b/client/src/components/brain/links/LinkChip.jsx
@@ -1,28 +1,33 @@
import { useState } from 'react';
import { Link2, X, GripVertical } from 'lucide-react';
-import { faviconUrl, LINK_DND_TYPE } from './bucketColors';
+import { faviconUrl } from './bucketColors';
/**
* A compact favicon + title button for a link inside a bucket.
* Clicking opens the link in a new tab; the hover-revealed X removes it
- * from the bucket (does not delete the underlying link). Draggable chips
- * carry their link id so they can be dropped into another bucket.
+ * from the bucket (does not delete the underlying link). `dragHandleProps`
+ * (a dnd-kit `useDraggable` handle's `attributes`/`listeners`/ref, wired by
+ * the caller so the drag id carries the chip's bucket + index) turns the
+ * grip icon into the pointer/keyboard drag activator.
*/
-export default function LinkChip({ link, onRemove, draggable }) {
+export default function LinkChip({ link, onRemove, dragHandleProps }) {
const [iconFailed, setIconFailed] = useState(false);
const favicon = faviconUrl(link.url);
return (
- <div
- className={`group flex items-center gap-2 pl-1.5 pr-1 py-1 bg-port-bg border border-port-border rounded-md hover:border-port-accent/50 transition-colors max-w-full ${draggable ? 'cursor-grab' : ''}`}
- draggable={draggable}
- onDragStart={draggable ? (e) => {
- e.dataTransfer.setData(LINK_DND_TYPE, link.id);
- e.dataTransfer.effectAllowed = 'move';
- } : undefined}
- >
- {draggable && (
- <GripVertical size={12} className="shrink-0 text-gray-600 group-hover:text-gray-400" />
+ <div className="group flex items-center gap-2 pl-1.5 pr-1 py-1 bg-port-bg border border-port-border rounded-md hover:border-port-accent/50 transition-colors max-w-full">
+ {dragHandleProps && (
+ <button
+ type="button"
+ ref={dragHandleProps.setActivatorNodeRef}
+ {...dragHandleProps.attributes}
+ {...dragHandleProps.listeners}
+ className="shrink-0 flex items-center justify-center text-gray-600 hover:text-gray-300 cursor-grab active:cursor-grabbing"
+ aria-label={`Drag ${link.title}`}
+ title="Drag to reorder or move to another bucket"
+ >
+ <GripVertical size={12} />
+ </button>
)}
<a
href={link.url}
diff --git a/client/src/components/brain/links/LinkChip.test.jsx b/client/src/components/brain/links/LinkChip.test.jsx
index b0f1461470..4f7c394e19 100644
--- a/client/src/components/brain/links/LinkChip.test.jsx
+++ b/client/src/components/brain/links/LinkChip.test.jsx
@@ -31,4 +31,15 @@ describe('LinkChip', () => {
fireEvent.click(screen.getByTitle('Remove from bucket'));
expect(onRemove).toHaveBeenCalledWith(link);
});
+
+ it('renders no drag handle when dragHandleProps is omitted', () => {
+ render(<LinkChip link={link} />);
+ expect(screen.queryByLabelText(/Drag /)).toBeNull();
+ });
+
+ it('renders a named, focusable drag handle when dragHandleProps is supplied', () => {
+ render(<LinkChip link={link} dragHandleProps={{ attributes: {}, listeners: {}, setActivatorNodeRef: () => {} }} />);
+ const handle = screen.getByLabelText('Drag Example Docs');
+ expect(handle.tagName).toBe('BUTTON');
+ });
});
diff --git a/client/src/components/brain/links/bucketColors.js b/client/src/components/brain/links/bucketColors.js
index 3844509750..548f2fd6f7 100644
--- a/client/src/components/brain/links/bucketColors.js
+++ b/client/src/components/brain/links/bucketColors.js
@@ -16,12 +16,6 @@ export const BUCKET_COLORS = {
export const BUCKET_COLOR_KEYS = Object.keys(BUCKET_COLORS);
-// Drag-and-drop payload types — shared so a link dragged from the list or
-// from another bucket, and a bucket dragged for reordering, are recognized
-// by any drop target regardless of which component initiated the drag.
-export const LINK_DND_TYPE = 'text/x-brain-link';
-export const BUCKET_DND_TYPE = 'text/x-brain-bucket';
-
export function bucketColor(key) {
return BUCKET_COLORS[key] || BUCKET_COLORS.accent;
}
diff --git a/client/src/components/brain/links/bucketDnd.js b/client/src/components/brain/links/bucketDnd.js
new file mode 100644
index 0000000000..965412bf06
--- /dev/null
+++ b/client/src/components/brain/links/bucketDnd.js
@@ -0,0 +1,156 @@
+/**
+ * dnd-kit wiring for the Links board: keyboard coordinates + collision
+ * detection shared by bucket reordering and chip (link) reordering, which
+ * both live in ONE `DndContext` (LinksTab.jsx) so a link dragged from the
+ * flat list can land inside any bucket at a specific position.
+ *
+ * Two drag "kinds" share the context, distinguished by `data.current.kind`:
+ * - 'bucket' — a bucket header handle, dropped onto another bucket's
+ * card to reorder the board.
+ * - 'link' — a link (from the flat list or a bucket chip), dropped
+ * onto a 'link-slot' droppable to file/reorder it.
+ *
+ * A 'link-slot' droppable is registered once BEFORE every chip in a bucket
+ * (data.index = that chip's index — "insert before this chip") plus one more
+ * covering the bucket's chip area as a whole (data.index = links.length —
+ * "append to the end"). The trailing slot's rect ENCLOSES the per-chip slots,
+ * so `rectIntersection` (dnd-kit's pointer default) would usually prefer the
+ * larger container over the chip actually under the pointer. `closestCenter`
+ * doesn't have that problem — a chip's center is far closer to the pointer
+ * than the container's overall center whenever the pointer is actually near
+ * that chip — so it is used for both pointer and keyboard drags here, unlike
+ * the free-droppable/kanban helpers elsewhere in this tree.
+ */
+
+import { closestCenter } from '@dnd-kit/core';
+
+export const BUCKET_KIND = 'bucket';
+export const LINK_KIND = 'link';
+export const LINK_SLOT_KIND = 'link-slot';
+
+export const bucketDropId = (bucketId) => `bucket-drop:${bucketId}`;
+export const chipSlotId = (bucketId, index) => `chip-slot:${bucketId}:${index}`;
+
+const DIRECTIONS = {
+ ArrowDown: 1,
+ ArrowRight: 1,
+ ArrowUp: -1,
+ ArrowLeft: -1,
+};
+
+/**
+ * Collision detection for the combined bucket/link `DndContext`: only
+ * droppables whose `kind` matches the item being dragged are candidates, so a
+ * bucket drag never resolves onto a chip slot (or vice versa).
+ */
+export function linksCollisionDetection(args) {
+ const activeKind = args.active?.data?.current?.kind;
+ const droppableContainers = args.droppableContainers.filter(
+ (container) => container.data?.current?.kind === activeKind,
+ );
+ return closestCenter({ ...args, droppableContainers });
+}
+
+function centerOf(target, activeRect) {
+ return {
+ x: target.rect.left + (target.rect.width - (activeRect?.width || 0)) / 2,
+ y: target.rect.top + (target.rect.height - (activeRect?.height || 0)) / 2,
+ };
+}
+
+function activeRectOf(active, context) {
+ return context?.active?.rect?.current?.translated
+ || context?.active?.rect?.current?.initial
+ || active?.rect?.current?.translated
+ || active?.rect?.current?.initial;
+}
+
+function enabledEntries(context) {
+ return (context?.droppableContainers?.getEnabled?.() || [])
+ .map((entry) => ({ entry, data: entry.data?.current || {}, rect: context.droppableRects?.get(entry.id) }))
+ .filter(({ rect }) => rect);
+}
+
+function bucketKeyboardCoordinates(direction, activeData, context) {
+ const buckets = enabledEntries(context)
+ .filter(({ data }) => data.kind === BUCKET_KIND)
+ .sort((a, b) => a.data.bucketIndex - b.data.bucketIndex);
+ if (buckets.length === 0) return undefined;
+
+ const overData = context?.over?.data?.current || {};
+ const currentBucketId = overData.bucketId ?? activeData.bucket?.id;
+ const currentIndex = buckets.findIndex(({ data }) => data.bucketId === currentBucketId);
+ const nextIndex = currentIndex === -1 ? (direction > 0 ? 0 : buckets.length - 1) : currentIndex + direction;
+ const target = buckets[nextIndex];
+ return target ? { entry: target } : undefined;
+}
+
+function linkKeyboardCoordinates(event, activeData, context) {
+ const slots = enabledEntries(context).filter(({ data }) => data.kind === LINK_SLOT_KIND);
+ if (slots.length === 0) return undefined;
+
+ const overData = context?.over?.data?.current || {};
+ const currentBucketId = overData.bucketId ?? activeData.bucketId ?? null;
+ const currentIndex = overData.kind === LINK_SLOT_KIND ? overData.index : (activeData.index ?? null);
+
+ if (event.code === 'ArrowUp' || event.code === 'ArrowDown') {
+ const direction = DIRECTIONS[event.code];
+ const withinBucket = slots
+ .filter(({ data }) => data.bucketId === currentBucketId)
+ .sort((a, b) => a.data.index - b.data.index);
+ if (withinBucket.length === 0) return undefined;
+ const idx = withinBucket.findIndex(({ data }) => data.index === currentIndex);
+ const nextIdx = idx === -1 ? (direction > 0 ? 0 : withinBucket.length - 1) : idx + direction;
+ const target = withinBucket[nextIdx];
+ return target ? { entry: target } : undefined;
+ }
+
+ if (event.code === 'ArrowLeft' || event.code === 'ArrowRight') {
+ const direction = DIRECTIONS[event.code];
+ const bucketOrder = [];
+ const seen = new Set();
+ for (const { data } of slots) {
+ if (seen.has(data.bucketId)) continue;
+ seen.add(data.bucketId);
+ bucketOrder.push({ bucketId: data.bucketId, bucketIndex: data.bucketIndex });
+ }
+ bucketOrder.sort((a, b) => a.bucketIndex - b.bucketIndex);
+ if (bucketOrder.length === 0) return undefined;
+ const curPos = bucketOrder.findIndex((b) => b.bucketId === currentBucketId);
+ const nextPos = curPos === -1 ? (direction > 0 ? 0 : bucketOrder.length - 1) : curPos + direction;
+ const nextBucket = bucketOrder[nextPos];
+ if (!nextBucket) return undefined;
+ const destSlots = slots
+ .filter(({ data }) => data.bucketId === nextBucket.bucketId)
+ .sort((a, b) => a.data.index - b.data.index);
+ if (destSlots.length === 0) return undefined;
+ const clampedIndex = Math.min(Math.max(currentIndex ?? 0, 0), destSlots.length - 1);
+ const target = destSlots[clampedIndex];
+ return target ? { entry: target } : undefined;
+ }
+
+ return undefined;
+}
+
+/**
+ * `coordinateGetter` for the combined bucket/link `KeyboardSensor`. Branches
+ * on the dragged item's `kind`: a bucket steps left/right (and up/down, since
+ * the board wraps into a responsive grid) through the other bucket cards; a
+ * link steps up/down within its current bucket's chip order and left/right
+ * into the adjacent bucket at the nearest equivalent position.
+ */
+export function linksKeyboardCoordinates(event, { active, context }) {
+ const direction = DIRECTIONS[event.code];
+ if (!direction) return undefined;
+
+ const activeData = context?.active?.data?.current || active?.data?.current || {};
+ const result = activeData.kind === BUCKET_KIND
+ ? bucketKeyboardCoordinates(direction, activeData, context)
+ : activeData.kind === LINK_KIND
+ ? linkKeyboardCoordinates(event, activeData, context)
+ : undefined;
+ if (!result) return undefined;
+
+ const activeRect = activeRectOf(active, context);
+ return centerOf(result.entry, activeRect);
+}
diff --git a/client/src/components/brain/links/bucketDnd.test.js b/client/src/components/brain/links/bucketDnd.test.js
new file mode 100644
index 0000000000..3d7abfa8d7
--- /dev/null
+++ b/client/src/components/brain/links/bucketDnd.test.js
@@ -0,0 +1,116 @@
+import { describe, it, expect } from 'vitest';
+import { linksCollisionDetection, linksKeyboardCoordinates, BUCKET_KIND, LINK_KIND, LINK_SLOT_KIND } from './bucketDnd';
+
+// Minimal fake droppable-container entries, shaped like the subset of
+// dnd-kit's internal `DroppableContainer` this module actually reads
+// (`id`, `data.current`, plus a `rect` for the keyboard coordinate math).
+const rect = (top, left, width = 100, height = 30) => ({ top, left, width, height });
+
+const bucketEntry = (id, bucketIndex, top) => ({
+ id: `bucket-drop:${id}`,
+ data: { current: { kind: BUCKET_KIND, bucketId: id, bucketName: id, bucketIndex } },
+ rect: rect(top, 0),
+});
+
+const slotEntry = (bucketId, bucketIndex, index, top) => ({
+ id: `chip-slot:${bucketId}:${index}`,
+ data: { current: { kind: LINK_SLOT_KIND, bucketId, bucketName: bucketId, bucketIndex, index } },
+ rect: rect(top, bucketIndex * 200),
+});
+
+function fakeContext(entries, overId, activeId) {
+ const rectsById = new Map(entries.map((e) => [e.id, e.rect]));
+ return {
+ droppableContainers: { getEnabled: () => entries },
+ droppableRects: rectsById,
+ over: overId ? { id: overId, data: { current: entries.find((e) => e.id === overId)?.data.current } } : null,
+ active: activeId ? { rect: { current: { initial: rect(0, 0, 40, 20) } } } : null,
+ };
+}
+
+describe('linksKeyboardCoordinates', () => {
+ it('steps a bucket drag to the next bucket in order', () => {
+ const entries = [bucketEntry('b1', 0, 0), bucketEntry('b2', 1, 40), bucketEntry('b3', 2, 80)];
+ const context = fakeContext(entries, 'bucket-drop:b1', 'bucket:b1');
+ const active = { data: { current: { kind: BUCKET_KIND, bucket: { id: 'b1' }, bucketIndex: 0 } } };
+ const coords = linksKeyboardCoordinates({ code: 'ArrowRight' }, { active, context });
+ // Centered on b2's rect (left 0, width 100, active width 40 → x = 30;
+ // top 40, height 30, active height 20 → y = 45).
+ expect(coords).toEqual({ x: 30, y: 45 });
+ });
+
+ it('anchors on the dragged bucket\'s own position when nothing is currently over', () => {
+ const entries = [bucketEntry('b1', 0, 0), bucketEntry('b2', 1, 40)];
+ const context = fakeContext(entries, null, 'bucket:b1');
+ const active = { data: { current: { kind: BUCKET_KIND, bucket: { id: 'b1' }, bucketIndex: 0 } } };
+ // Falls back to the dragged bucket's own id (b1, index 0) rather than
+ // resolving to nothing, then steps forward from there to b2.
+ expect(linksKeyboardCoordinates({ code: 'ArrowRight' }, { active, context })).toEqual({ x: 30, y: 45 });
+ });
+
+ it('returns undefined for a key the getter does not handle', () => {
+ const entries = [bucketEntry('b1', 0, 0)];
+ const context = fakeContext(entries, 'bucket-drop:b1', 'bucket:b1');
+ const active = { data: { current: { kind: BUCKET_KIND, bucket: { id: 'b1' }, bucketIndex: 0 } } };
+ expect(linksKeyboardCoordinates({ code: 'Tab' }, { active, context })).toBeUndefined();
+ });
+
+ it('steps a link drag up/down within its current bucket by chip index', () => {
+ const entries = [
+ slotEntry('b1', 0, 0, 0), slotEntry('b1', 0, 1, 30), slotEntry('b1', 0, 2, 60),
+ ];
+ const context = fakeContext(entries, 'chip-slot:b1:0', 'link:l1');
+ const active = { data: { current: { kind: LINK_KIND, link: { id: 'l1' }, bucketId: 'b1', index: 0 } } };
+ const coords = linksKeyboardCoordinates({ code: 'ArrowDown' }, { active, context });
+ expect(coords).toEqual({ x: 30, y: 35 });
+ });
+
+ it('steps a link drag left/right into the adjacent bucket at the closest equivalent index', () => {
+ const entries = [
+ slotEntry('b1', 0, 0, 0), slotEntry('b1', 0, 1, 30),
+ slotEntry('b2', 1, 0, 0), slotEntry('b2', 1, 1, 30), slotEntry('b2', 1, 2, 60),
+ ];
+ // Currently over b1's index-1 slot; ArrowRight should land on b2's index-1
+ // slot (same index carried across), not b2's first slot.
+ const context = fakeContext(entries, 'chip-slot:b1:1', 'link:l1');
+ const active = { data: { current: { kind: LINK_KIND, link: { id: 'l1' }, bucketId: 'b1', index: 1 } } };
+ const coords = linksKeyboardCoordinates({ code: 'ArrowRight' }, { active, context });
+ expect(coords).toEqual({ x: 230, y: 35 });
+ });
+
+ it('clamps the destination index when the adjacent bucket has fewer slots', () => {
+ const entries = [
+ slotEntry('b1', 0, 0, 0), slotEntry('b1', 0, 1, 30), slotEntry('b1', 0, 2, 60),
+ slotEntry('b2', 1, 0, 0),
+ ];
+ const context = fakeContext(entries, 'chip-slot:b1:2', 'link:l1');
+ const active = { data: { current: { kind: LINK_KIND, link: { id: 'l1' }, bucketId: 'b1', index: 2 } } };
+ const coords = linksKeyboardCoordinates({ code: 'ArrowRight' }, { active, context });
+ // Only one slot (index 0) exists in b2 — clamp rather than resolving to nothing.
+ expect(coords).toEqual({ x: 230, y: 5 });
+ });
+
+ it('returns undefined when the dragged item has no recognized kind', () => {
+ const entries = [bucketEntry('b1', 0, 0)];
+ const context = fakeContext(entries, null, null);
+ const active = { data: { current: { kind: 'mystery' } } };
+ expect(linksKeyboardCoordinates({ code: 'ArrowRight' }, { active, context })).toBeUndefined();
+ });
+});
+
+describe('linksCollisionDetection', () => {
+ it('only matches droppables of the dragged item\'s own kind', () => {
+ const bucketContainer = { id: 'bucket-drop:b1', data: { current: { kind: BUCKET_KIND, bucketId: 'b1' } }, rect: rect(0, 0) };
+ const slotContainer = { id: 'chip-slot:b1:0', data: { current: { kind: LINK_SLOT_KIND, bucketId: 'b1', index: 0 } }, rect: rect(0, 0) };
+ const args = {
+ active: { id: 'bucket:b1', data: { current: { kind: BUCKET_KIND } }, rect: { current: { initial: rect(0, 0) } } },
+ collisionRect: rect(0, 0),
+ droppableRects: new Map([[bucketContainer.id, bucketContainer.rect], [slotContainer.id, slotContainer.rect]]),
+ droppableContainers: [bucketContainer, slotContainer],
+ pointerCoordinates: null,
+ };
+ const collisions = linksCollisionDetection(args);
+ expect(collisions.every((c) => c.id === bucketContainer.id)).toBe(true);
+ expect(collisions.some((c) => c.id === slotContainer.id)).toBe(false);
+ });
+});
diff --git a/client/src/components/brain/links/bucketReorder.js b/client/src/components/brain/links/bucketReorder.js
index b46e8707d0..e232ec2f79 100644
--- a/client/src/components/brain/links/bucketReorder.js
+++ b/client/src/components/brain/links/bucketReorder.js
@@ -1,13 +1,3 @@
-/**
- * Map a pointer position over a chip to an insertion index: before the chip
- * (its own index) when the pointer is in its left half, after it (index + 1)
- * when in the right half. Pure so the before/after boundary is unit-testable
- * (jsdom can't supply a real rect or clientX to a drag event).
- */
-export function chipInsertIndex(rect, clientX, i) {
- return clientX > rect.left + rect.width / 2 ? i + 1 : i;
-}
-
/**
* Pure helper for intra-bucket (and cross-bucket) positioned chip drops.
*
diff --git a/client/src/components/brain/links/bucketReorder.test.js b/client/src/components/brain/links/bucketReorder.test.js
index c6ce80868d..0489419451 100644
--- a/client/src/components/brain/links/bucketReorder.test.js
+++ b/client/src/components/brain/links/bucketReorder.test.js
@@ -1,24 +1,8 @@
import { describe, it, expect } from 'vitest';
-import { reorderLinksInBucket, chipInsertIndex } from './bucketReorder';
+import { reorderLinksInBucket } from './bucketReorder';
const mk = (id, bucketId, bucketOrder) => ({ id, bucketId, bucketOrder });
-describe('chipInsertIndex', () => {
- const rect = { left: 100, width: 40 }; // midpoint at 120
-
- it('inserts before the chip when the pointer is in its left half', () => {
- expect(chipInsertIndex(rect, 110, 3)).toBe(3);
- });
-
- it('inserts after the chip when the pointer is in its right half', () => {
- expect(chipInsertIndex(rect, 130, 3)).toBe(4);
- });
-
- it('treats the exact midpoint as "before" (not strictly greater)', () => {
- expect(chipInsertIndex(rect, 120, 3)).toBe(3);
- });
-});
-
describe('reorderLinksInBucket', () => {
it('moves a chip later within its bucket, accounting for its own removal', () => {
const links = [mk('a', 'b1', 0), mk('b', 'b1', 1), mk('c', 'b1', 2), mk('d', 'b1', 3)];
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsx
index fd4c5090ce..80e04622b2 100644
--- a/client/src/components/brain/tabs/LinksTab.jsx
+++ b/client/src/components/brain/tabs/LinksTab.jsx
@@ -1,5 +1,9 @@
-import { useState, useEffect, useCallback, useRef } from 'react';
+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { Link } from 'react-router';
+import {
+ DndContext, DragOverlay, KeyboardSensor, PointerSensor,
+ useDraggable, useSensor, useSensors,
+} from '@dnd-kit/core';
import * as api from '../../../services/api';
import {
Link2,
@@ -33,8 +37,12 @@ import { timeAgo } from '../../../utils/formatters';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
import BucketBoard from '../links/BucketBoard';
import RepoRestudyPanel from '../RepoRestudyPanel';
-import { LINK_DND_TYPE } from '../links/bucketColors';
+import LinkChip from '../links/LinkChip';
import { reorderLinksInBucket } from '../links/bucketReorder';
+import {
+ linksCollisionDetection, linksKeyboardCoordinates,
+ BUCKET_KIND, LINK_KIND, LINK_SLOT_KIND,
+} from '../links/bucketDnd';
import { normalizeUrl as normalizeUrlShared } from '../../../utils/urlNormalize';
/**
@@ -465,6 +473,102 @@ export default function LinksTab({ onRefresh }) {
}
};
+ // --- Drag-and-drop: buckets (reorder) and links (file/reorder into a
+ // bucket, from the flat list or from another chip) share ONE DndContext so
+ // a link picked up in the list can be dropped straight into a bucket at a
+ // specific position. See bucketDnd.js for the coordinate/collision logic.
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: linksKeyboardCoordinates }),
+ );
+ const [activeDrag, setActiveDrag] = useState(null);
+
+ const handleReorderBuckets = useCallback((draggedId, targetId) => {
+ if (!draggedId || draggedId === targetId) return;
+ setBuckets(prev => {
+ const ids = prev.map(b => b.id);
+ const from = ids.indexOf(draggedId);
+ const to = ids.indexOf(targetId);
+ if (from === -1 || to === -1) return prev;
+ const next = [...prev];
+ const [moved] = next.splice(from, 1);
+ next.splice(to, 0, moved);
+ api.reorderBrainBuckets(next.map(b => b.id), { silent: true }).catch(err => {
+ toast.error(err.message || 'Failed to reorder buckets');
+ });
+ return next;
+ });
+ }, []);
+
+ const handleDragStart = useCallback((event) => {
+ setActiveDrag(event.active.data.current || null);
+ }, []);
+
+ const handleDragEnd = useCallback((event) => {
+ const { active, over } = event;
+ setActiveDrag(null);
+ if (!over || !active) return;
+ const activeData = active.data.current || {};
+ const overData = over.data.current || {};
+ if (activeData.kind === BUCKET_KIND && overData.kind === BUCKET_KIND) {
+ handleReorderBuckets(activeData.bucket?.id, overData.bucketId);
+ return;
+ }
+ if (activeData.kind === LINK_KIND && overData.kind === LINK_SLOT_KIND && activeData.link) {
+ handleMoveLinkToIndex(activeData.link, overData.bucketId, overData.index);
+ }
+ }, [handleReorderBuckets, handleMoveLinkToIndex]);
+
+ const handleDragCancel = useCallback(() => setActiveDrag(null), []);
+
+ // dnd-kit's stock announcements only say "draggable item N" (an id). Name
+ // the bucket/link and its destination instead, using the live counts so
+ // "position 2 of 5" stays accurate as buckets fill up.
+ const dndAccessibility = useMemo(() => {
+ const bucketName = (id) => buckets.find(b => b.id === id)?.name || 'Unfiled';
+ const describeBucketTarget = (over) => {
+ const bucketId = over?.data?.current?.bucketId;
+ if (!bucketId) return null;
+ const idx = buckets.findIndex(b => b.id === bucketId);
+ return idx === -1 ? null : `position ${idx + 1} of ${buckets.length}`;
+ };
+ const describeLinkTarget = (active, over) => {
+ const data = over?.data?.current;
+ if (!data || data.kind !== LINK_SLOT_KIND) return null;
+ const link = active?.data?.current?.link;
+ const alreadyThere = !!link && link.bucketId === data.bucketId;
+ const bucketSize = links.filter(l => l.bucketId === data.bucketId).length + (alreadyThere ? 0 : 1);
+ return `position ${data.index + 1} of ${bucketSize} in ${bucketName(data.bucketId)}`;
+ };
+ const itemLabel = (active) => {
+ const data = active?.data?.current;
+ if (!data) return 'item';
+ return data.kind === BUCKET_KIND ? `bucket ${data.bucket?.name || ''}`.trim() : (data.link?.title || 'link');
+ };
+ const destinationFor = (active, over) => (active?.data?.current?.kind === BUCKET_KIND
+ ? describeBucketTarget(over)
+ : describeLinkTarget(active, over));
+ return {
+ announcements: {
+ onDragStart: ({ active }) => (active?.data?.current?.kind === BUCKET_KIND
+ ? `Picked up ${itemLabel(active)}. Use the arrow keys to choose a new position, Space to drop it there, or Escape to cancel.`
+ : `Picked up ${itemLabel(active)}. Use the arrow keys to choose a bucket and position, Space to file it there, or Escape to cancel.`),
+ onDragOver: ({ active, over }) => {
+ const dest = destinationFor(active, over);
+ return dest ? `${itemLabel(active)} is over ${dest}.` : `${itemLabel(active)} is not over a valid destination.`;
+ },
+ onDragEnd: ({ active, over }) => {
+ const dest = destinationFor(active, over);
+ return dest ? `Moved ${itemLabel(active)} to ${dest}.` : `${itemLabel(active)} was dropped outside a valid destination and did not move.`;
+ },
+ onDragCancel: ({ active }) => `Cancelled moving ${itemLabel(active)}. It stayed where it was.`,
+ },
+ screenReaderInstructions: {
+ draggable: 'To move this item, press Space or Enter. While dragging, use the arrow keys to choose a destination, then press Space to drop it there, or Escape to cancel.',
+ },
+ };
+ }, [links, buckets]);
+
if (loading) {
return (
<div className="flex items-center justify-center h-64">
@@ -475,6 +579,14 @@ export default function LinksTab({ onRefresh }) {
return (
<div className="flex flex-col h-full">
+ <DndContext
+ sensors={sensors}
+ collisionDetection={linksCollisionDetection}
+ accessibility={dndAccessibility}
+ onDragStart={handleDragStart}
+ onDragEnd={handleDragEnd}
+ onDragCancel={handleDragCancel}
+ >
<div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(340px,440px)] gap-6 items-start">
{/* Left column: entry form, filters, and the full link list */}
<div className="min-w-0 flex flex-col">
@@ -627,17 +739,12 @@ export default function LinksTab({ onRefresh }) {
return (
<div
key={link.id}
- draggable={!isEditing}
- onDragStart={!isEditing ? (e) => {
- e.dataTransfer.setData(LINK_DND_TYPE, link.id);
- e.dataTransfer.effectAllowed = 'move';
- } : undefined}
- className={`p-4 bg-port-card border border-port-border rounded-lg ${isEditing ? '' : 'cursor-grab'}`}
+ className="p-4 bg-port-card border border-port-border rounded-lg"
>
{/* Header row */}
<div className="flex items-start justify-between gap-3 mb-2">
{!isEditing && (
- <GripVertical size={16} className="shrink-0 mt-0.5 text-gray-600" title="Drag to a bucket" />
+ <LinkDragHandle link={link} />
)}
{editingId === link.id ? (
<div className="flex-1 space-y-2">
@@ -1041,7 +1148,7 @@ export default function LinksTab({ onRefresh }) {
<div className="flex items-center gap-2 mb-3 flex-wrap">
<FolderClosed size={16} className="text-port-accent shrink-0" />
<h2 className="text-sm font-semibold text-gray-300">Buckets</h2>
- <span className="text-xs text-gray-500">Group links — drag chips between buckets.</span>
+ <span className="text-xs text-gray-500">Group links — drag chips (or use a chip/bucket's grip handle with the keyboard) to reorder or move between buckets.</span>
</div>
<BucketBoard
links={links}
@@ -1049,11 +1156,58 @@ export default function LinksTab({ onRefresh }) {
setBuckets={setBuckets}
onAssignLink={handleAssignLink}
onAddLinkToBucket={handleAddLinkToBucket}
- onMoveLinkToIndex={handleMoveLinkToIndex}
onBucketDeleted={(bucketId) => setLinks(prev => prev.map(l => (l.bucketId === bucketId ? { ...l, bucketId: null } : l)))}
/>
</aside>
</div>
+ <DragOverlay>
+ {activeDrag?.kind === LINK_KIND && activeDrag.link && (
+ <div className="rotate-1 shadow-lg">
+ <LinkChip link={activeDrag.link} />
+ </div>
+ )}
+ {activeDrag?.kind === BUCKET_KIND && activeDrag.bucket && (
+ <div className="flex items-center gap-2 px-3 py-1.5 rounded bg-port-card border border-port-accent text-sm text-port-accent shadow-lg">
+ {activeDrag.bucket.icon && <span className="text-base leading-none">{activeDrag.bucket.icon}</span>}
+ {activeDrag.bucket.name}
+ </div>
+ )}
+ </DragOverlay>
+ </DndContext>
</div>
);
}
+
+/**
+ * Drag source for a link-list row: dnd-kit's `attributes`/`listeners` must be
+ * spread on a real focusable element (not the whole row, which also hosts
+ * click targets like Edit/Delete/Open), so the grip icon becomes a dedicated
+ * handle — the same shape as `LibraryPane.jsx`'s `WorkRow` and
+ * `KanbanBoard.jsx`'s `DraggableTicket`. Its `data.bucketId`/`index` are
+ * always null: a list row isn't rendered inside any one bucket's order, so a
+ * keyboard pickup here always enters bucket order fresh (see
+ * `bucketDnd.js`'s fallback for "no current position").
+ */
+function LinkDragHandle({ link, disabled }) {
+ const { attributes, listeners, setNodeRef, setActivatorNodeRef, isDragging } = useDraggable({
+ id: `link-list:${link.id}`,
+ data: { kind: LINK_KIND, link, bucketId: null, index: null },
+ disabled,
+ });
+ return (
+ <button
+ type="button"
+ ref={(node) => { setNodeRef(node); setActivatorNodeRef(node); }}
+ {...attributes}
+ {...listeners}
+ disabled={disabled}
+ className={`shrink-0 mt-0.5 flex items-center justify-center text-gray-600 hover:text-gray-400 ${
+ disabled ? 'cursor-not-allowed opacity-50' : 'cursor-grab active:cursor-grabbing'
+ } ${isDragging ? 'opacity-30' : ''}`}
+ aria-label={`Drag ${link.title} to a bucket`}
+ title="Drag to a bucket"
+ >
+ <GripVertical size={16} />
+ </button>
+ );
+}
diff --git a/client/src/components/brain/tabs/LinksTab.test.jsx b/client/src/components/brain/tabs/LinksTab.test.jsx
index 14594e395e..c48f9c2d65 100644
--- a/client/src/components/brain/tabs/LinksTab.test.jsx
+++ b/client/src/components/brain/tabs/LinksTab.test.jsx
@@ -10,6 +10,7 @@ vi.mock('../../../services/api', () => ({
updateBrainLink: vi.fn(),
deleteBrainLink: vi.fn(),
reorderBrainLinks: vi.fn(),
+ reorderBrainBuckets: vi.fn(),
cloneBrainLink: vi.fn(),
pullBrainLink: vi.fn(),
scanBrainLink: vi.fn(),
@@ -34,8 +35,35 @@ vi.mock('../links/BucketBoard', () => ({
},
}));
-import { createBrainLink, getBrainLink, getBrainLinks, getBrainBuckets, studyBrainLink } from '../../../services/api';
+// LinksTab mounts its own `DndContext` (buckets + the flat link list share
+// one). Capturing its props — the same shape KanbanBoard.test.jsx uses — lets
+// the drag-end routing and the live announcement text be exercised directly,
+// since jsdom cannot supply real pointer geometry to drive an actual drag.
+const dndState = vi.hoisted(() => ({ context: null }));
+vi.mock('@dnd-kit/core', () => ({
+ DndContext: ({ children, ...props }) => {
+ dndState.context = props;
+ return <>{children}</>;
+ },
+ DragOverlay: ({ children }) => <>{children}</>,
+ closestCenter: vi.fn(() => []),
+ KeyboardSensor: function KeyboardSensorStub() {},
+ PointerSensor: function PointerSensorStub() {},
+ useDraggable: () => ({
+ attributes: {},
+ listeners: {},
+ setNodeRef: () => {},
+ setActivatorNodeRef: () => {},
+ isDragging: false,
+ }),
+ useSensor: (sensor, options) => ({ sensor, options }),
+ useSensors: (...sensors) => sensors,
+}));
+
+import { createBrainLink, getBrainLink, getBrainLinks, getBrainBuckets, studyBrainLink, reorderBrainBuckets, reorderBrainLinks } from '../../../services/api';
import toast from '../../ui/Toast';
+import { KeyboardSensor } from '@dnd-kit/core';
+import { BUCKET_KIND, LINK_KIND, LINK_SLOT_KIND, linksKeyboardCoordinates } from '../links/bucketDnd';
import LinksTab from './LinksTab';
const link = (id, cloneStatus, overrides = {}) => ({
@@ -64,6 +92,7 @@ const tick = (ms = 3000) => act(async () => { await vi.advanceTimersByTimeAsync(
beforeEach(() => {
vi.clearAllMocks();
bucketBoardRenders = 0;
+ dndState.context = null;
vi.useFakeTimers();
getBrainBuckets.mockResolvedValue({ buckets: [] });
});
@@ -371,3 +400,119 @@ describe('LinksTab on-demand repo re-study', () => {
expect(toast.success).not.toHaveBeenCalled();
});
});
+
+// #8120: buckets and chips could only be reordered with a mouse (native HTML5
+// drag, no keyboard path). This suite exercises the ONE DndContext LinksTab
+// mounts around the flat list + the bucket board — sensors, drag-end routing,
+// and the live announcement text — the same "capture DndContext's props"
+// shape KanbanBoard.test.jsx uses, since jsdom cannot drive a real drag.
+describe('LinksTab drag-and-drop wiring', () => {
+ const buckets = [
+ { id: 'b1', name: 'Reading', color: 'accent', order: 0 },
+ { id: 'b2', name: 'Tools', color: 'purple', order: 1 },
+ ];
+
+ beforeEach(() => {
+ getBrainBuckets.mockResolvedValue({ buckets });
+ });
+
+ it('registers a KeyboardSensor with the shared coordinate getter', async () => {
+ getBrainLinks.mockResolvedValue({ links: [] });
+ await renderTab();
+
+ const keyboardSensor = dndState.context.sensors.find(({ sensor }) => sensor === KeyboardSensor);
+ expect(keyboardSensor).toBeDefined();
+ expect(keyboardSensor.options.coordinateGetter).toBe(linksKeyboardCoordinates);
+ });
+
+ it('reorders buckets when a bucket is dropped on another bucket', async () => {
+ getBrainLinks.mockResolvedValue({ links: [] });
+ reorderBrainBuckets.mockResolvedValue(true);
+ await renderTab();
+
+ const active = { data: { current: { kind: BUCKET_KIND, bucket: { id: 'b1' }, bucketIndex: 0 } } };
+ const over = { data: { current: { kind: BUCKET_KIND, bucketId: 'b2', bucketIndex: 1 } } };
+ await act(async () => { dndState.context.onDragEnd({ active, over }); });
+
+ expect(reorderBrainBuckets).toHaveBeenCalledWith(['b2', 'b1'], { silent: true });
+ });
+
+ it('does nothing when a bucket is dropped back on itself', async () => {
+ getBrainLinks.mockResolvedValue({ links: [] });
+ await renderTab();
+
+ const active = { data: { current: { kind: BUCKET_KIND, bucket: { id: 'b1' }, bucketIndex: 0 } } };
+ const over = { data: { current: { kind: BUCKET_KIND, bucketId: 'b1', bucketIndex: 0 } } };
+ await act(async () => { dndState.context.onDragEnd({ active, over }); });
+
+ expect(reorderBrainBuckets).not.toHaveBeenCalled();
+ });
+
+ it('reorders a link to a specific chip slot when dropped on a link-slot droppable', async () => {
+ const twoInBucket = [
+ link('a', 'none', { bucketId: 'b1', bucketOrder: 0, title: 'Alpha' }),
+ link('c', 'none', { bucketId: 'b1', bucketOrder: 1, title: 'Charlie' }),
+ ];
+ getBrainLinks.mockResolvedValue({ links: twoInBucket });
+ reorderBrainLinks.mockResolvedValue(true);
+ await renderTab();
+
+ // Drag Alpha (currently index 0) to index 2 — after Charlie.
+ const active = { data: { current: { kind: LINK_KIND, link: twoInBucket[0], bucketId: 'b1', index: 0 } } };
+ const over = { data: { current: { kind: LINK_SLOT_KIND, bucketId: 'b1', bucketName: 'Reading', index: 2 } } };
+ await act(async () => { dndState.context.onDragEnd({ active, over }); });
+
+ expect(reorderBrainLinks).toHaveBeenCalledWith(
+ [{ id: 'c', bucketId: 'b1', bucketOrder: 0 }, { id: 'a', bucketId: 'b1', bucketOrder: 1 }],
+ { silent: true },
+ );
+ });
+
+ it('ignores a drop with no destination, and a drop whose kinds do not match', async () => {
+ getBrainLinks.mockResolvedValue({ links: [] });
+ await renderTab();
+
+ await act(async () => { dndState.context.onDragEnd({ active: { data: { current: { kind: BUCKET_KIND } } }, over: null }); });
+ const mismatched = {
+ active: { data: { current: { kind: LINK_KIND, link: { id: 'a' } } } },
+ over: { data: { current: { kind: BUCKET_KIND, bucketId: 'b1' } } },
+ };
+ await act(async () => { dndState.context.onDragEnd(mismatched); });
+
+ expect(reorderBrainBuckets).not.toHaveBeenCalled();
+ expect(reorderBrainLinks).not.toHaveBeenCalled();
+ });
+
+ it('announces the destination bucket and position when a link drag ends', async () => {
+ const twoInBucket = [
+ link('a', 'none', { bucketId: 'b1', bucketOrder: 0, title: 'Alpha' }),
+ link('c', 'none', { bucketId: 'b1', bucketOrder: 1, title: 'Charlie' }),
+ ];
+ getBrainLinks.mockResolvedValue({ links: twoInBucket });
+ await renderTab();
+
+ const active = { data: { current: { kind: LINK_KIND, link: twoInBucket[0], bucketId: 'b1', index: 0 } } };
+ const over = { data: { current: { kind: LINK_SLOT_KIND, bucketId: 'b1', index: 1 } } };
+ const message = dndState.context.accessibility.announcements.onDragEnd({ active, over });
+ expect(message).toBe('Moved Alpha to position 2 of 2 in Reading.');
+ });
+
+ it('announces the destination position when a bucket drag ends', async () => {
+ getBrainLinks.mockResolvedValue({ links: [] });
+ await renderTab();
+
+ const active = { data: { current: { kind: BUCKET_KIND, bucket: { id: 'b1', name: 'Reading' } } } };
+ const over = { data: { current: { kind: BUCKET_KIND, bucketId: 'b2' } } };
+ const message = dndState.context.accessibility.announcements.onDragEnd({ active, over });
+ expect(message).toBe('Moved bucket Reading to position 2 of 2.');
+ });
+
+ it('announces a drop outside a valid destination did not move anything', async () => {
+ getBrainLinks.mockResolvedValue({ links: [] });
+ await renderTab();
+
+ const active = { data: { current: { kind: LINK_KIND, link: { id: 'a', title: 'Alpha' } } } };
+ const message = dndState.context.accessibility.announcements.onDragEnd({ active, over: null });
+ expect(message).toBe('Alpha was dropped outside a valid destination and did not move.');
+ });
+});