From 5bb7181d8459d2d963010dea461d12d70a17ff23 Mon Sep 17 00:00:00 2001 From: moT01 <20648924+moT01@users.noreply.github.com> Date: Fri, 11 Sep 2026 09:48:36 -0500 Subject: [PATCH 1/9] feat: add packages for drag and drop --- files/framework/astro-react/package.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/files/framework/astro-react/package.json b/files/framework/astro-react/package.json index d518e33..26d6ebd 100644 --- a/files/framework/astro-react/package.json +++ b/files/framework/astro-react/package.json @@ -18,6 +18,9 @@ }, "dependencies": { "@astrojs/react": "^6", + "@dnd-kit/core": "^6", + "@dnd-kit/sortable": "^10", + "@dnd-kit/utilities": "^3", "@nanostores/react": "^1", "astro": "^7", "mdast-util-gfm": "^3", From 2cf60ba2f0e73e0cd39ce6e7059589728083f99c Mon Sep 17 00:00:00 2001 From: moT01 <20648924+moT01@users.noreply.github.com> Date: Fri, 11 Sep 2026 09:48:59 -0500 Subject: [PATCH 2/9] fix: categorize UX, add drag and drop --- .../src/components/tasks/categorize.css | 71 ++-- .../src/components/tasks/categorize.test.tsx | 225 ++++++------ .../src/components/tasks/categorize.tsx | 331 ++++++++++++------ 3 files changed, 371 insertions(+), 256 deletions(-) diff --git a/files/framework/astro-react/src/components/tasks/categorize.css b/files/framework/astro-react/src/components/tasks/categorize.css index b5ac918..31e85be 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.css +++ b/files/framework/astro-react/src/components/tasks/categorize.css @@ -16,79 +16,62 @@ } .zone { - position: relative; border: 1px solid var(--quaternary-background); border-radius: var(--radius-md); padding: var(--space-md); } .zone-heading { - position: relative; - z-index: 1; - pointer-events: none; margin-bottom: var(--space-sm); font-size: var(--text-size-sm); } .zone-items { - position: relative; - z-index: 1; - pointer-events: none; display: flex; flex-direction: column; gap: var(--space-xs); min-height: 2.5rem; - margin-bottom: var(--space-sm); } -.item-row { - pointer-events: auto; - display: block; - width: 100%; - text-align: left; - background: none; - border: 1px solid var(--quaternary-background); - border-radius: var(--radius-sm); - padding: var(--space-xs) var(--space-sm); - font: inherit; - color: inherit; - cursor: pointer; +.zone-empty { + border-style: dashed; } -.item-row:not(:disabled):hover { - background: var(--quaternary-background); +.zone-over { + border-color: var(--highlight-color); + background: var(--selection-color); } -.item-row.selected { - background: var(--quaternary-background); - border-color: var(--highlight-color); - font-weight: 700; +.zone-placeholder { + margin: 0; + color: var(--quaternary-color); + font-size: var(--text-size-xs); + text-align: center; } -.item-row:disabled { - cursor: not-allowed; +.item-card { + background: var(--secondary-background); + border: 1px solid var(--quaternary-background); + border-radius: var(--radius-sm); + padding: var(--space-xs) var(--space-sm); + cursor: grab; + touch-action: none; } -.unshuffled .item-row { - visibility: hidden; +.item-card:focus-visible { + outline: var(--border-focus); + outline-offset: 2px; } -.zone-drop { - position: absolute; - inset: 0; - z-index: 0; - width: 100%; - height: 100%; - background: none; - border: none; - border-radius: var(--radius-md); - cursor: pointer; +.item-dragging { + opacity: 0.4; } -.zone-drop.active:not(:disabled):hover { - background: var(--quaternary-background); +.item-overlay { + cursor: grabbing; + box-shadow: 0 4px 12px var(--primary-background-translucent); } -.zone-drop:disabled { - cursor: default; +.unshuffled .item-card { + visibility: hidden; } diff --git a/files/framework/astro-react/src/components/tasks/categorize.test.tsx b/files/framework/astro-react/src/components/tasks/categorize.test.tsx index 7fd5275..f1698a6 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.test.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.test.tsx @@ -1,7 +1,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; -import { render, screen, within } from "@testing-library/react"; +import { render, screen, within, fireEvent } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { Categorize } from "./categorize"; +import { Categorize, findContainer, moveItem } from "./categorize"; import type { Task } from "../../lib/curriculum-tasks"; const task: Extract = { @@ -20,153 +20,160 @@ beforeEach(() => { function getZoneItems(zoneName: string): string[] { const zone = screen.getByRole("group", { name: zoneName }); return within(zone) - .queryAllByRole("button", { pressed: undefined }) - .filter((button) => button.getAttribute("aria-label") === null) - .map((button) => button.textContent ?? ""); + .queryAllByText((_, element) => element?.className === "item-card") + .map((element) => element.textContent ?? ""); } -describe(Categorize, () => { - it("starts with all items in the unplaced zone", () => { - render( {}} />); +// dnd-kit measures real DOM rects to decide collisions, which jsdom doesn't +// compute (everything is 0x0 by default). Stubbing getBoundingClientRect on +// the specific elements involved lets a real pointer-driven drag resolve to +// a specific drop target, the same way it would in a real layout. +function mockRect(element: Element, rect: Partial) { + vi.spyOn(element, "getBoundingClientRect").mockReturnValue({ + x: 0, + y: 0, + width: 100, + height: 40, + top: 0, + left: 0, + right: 100, + bottom: 40, + toJSON: () => {}, + ...rect, + }); +} - expect(getZoneItems("Items")).toEqual( - expect.arrayContaining(["Apple", "Banana", "Carrot"]), - ); +// Each zone gets its own, non-overlapping vertical band so the pointer +// coordinates land unambiguously in the intended target zone. +const ZONE_TOP: Record = { Items: 0, Fruit: 200, Vegetable: 400 }; + +function dragItemToZone(itemText: string, zoneName: string) { + const item = screen.getByText(itemText); + const zone = screen.getByRole("group", { name: zoneName }); + const top = ZONE_TOP[zoneName]; + const centerY = top + 75; + + mockRect(item, { top: 0, left: 0, bottom: 40, right: 100 }); + mockRect(zone, { top, left: 0, bottom: top + 150, right: 300 }); + + fireEvent.pointerDown(item, { + pointerId: 1, + isPrimary: true, + button: 0, + clientX: 50, + clientY: 20, }); + fireEvent.pointerMove(document, { pointerId: 1, clientX: 50, clientY: centerY }); + fireEvent.pointerUp(document, { pointerId: 1, clientX: 50, clientY: centerY }); +} - it("moves a selected item to a category zone", async () => { - const user = userEvent.setup(); +describe("findContainer", () => { + it("finds the container an item currently belongs to", () => { + const containers = { unplaced: ["a"], Fruit: ["b"] }; - render( {}} />); + expect(findContainer(containers, "b")).toBe("Fruit"); + }); - await user.click(screen.getByRole("button", { name: "Apple" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to fruit/i, - }), - ); + it("treats a container id as its own container", () => { + const containers = { unplaced: [], Fruit: [] }; - expect(getZoneItems("Fruit")).toContain("Apple"); - expect(getZoneItems("Items")).not.toContain("Apple"); + expect(findContainer(containers, "Fruit")).toBe("Fruit"); }); - it("moves an item back to unplaced when removed from a category", async () => { - const user = userEvent.setup(); + it("returns undefined for an id that isn't in any container", () => { + const containers = { unplaced: ["a"] }; - render( {}} />); + expect(findContainer(containers, "z")).toBeUndefined(); + }); +}); - // Place Apple in Fruit - await user.click(screen.getByRole("button", { name: "Apple" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to fruit/i, - }), - ); +describe("moveItem", () => { + it("moves an item from one container to another", () => { + const containers = { unplaced: ["a", "b"], Fruit: [] }; - // Move Apple back to unplaced - await user.click(screen.getByRole("button", { name: "Apple" })); - await user.click( - screen.getByRole("button", { - name: /move selected item back to the unplaced items/i, - }), - ); + const result = moveItem(containers, "a", "unplaced", "Fruit", "Fruit"); - expect(getZoneItems("Items")).toContain("Apple"); - expect(getZoneItems("Fruit")).not.toContain("Apple"); + expect(result.unplaced).toEqual(["b"]); + expect(result.Fruit).toEqual(["a"]); }); - it("shows correct feedback and calls onCorrect when all items are placed correctly", async () => { - const onCorrect = vi.fn<() => void>(); - const user = userEvent.setup(); + it("positions the item before overId, not just appended", () => { + const containers = { unplaced: ["a"], Fruit: ["b", "c"] }; - render(); + const result = moveItem(containers, "a", "unplaced", "Fruit", "c"); - await user.click(screen.getByRole("button", { name: "Apple" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to fruit/i, - }), - ); - await user.click(screen.getByRole("button", { name: "Banana" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to fruit/i, - }), - ); - await user.click(screen.getByRole("button", { name: "Carrot" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to vegetable/i, - }), - ); + expect(result.Fruit).toEqual(["b", "a", "c"]); + }); +}); - await user.click( - screen.getByRole("button", { name: /check answer/i }), +describe(Categorize, () => { + it("starts with all items in the unplaced zone and categories empty", () => { + render( {}} />); + + expect(getZoneItems("Items")).toEqual( + expect.arrayContaining(["Apple", "Banana", "Carrot"]), ); + expect(getZoneItems("Fruit")).toHaveLength(0); + expect(getZoneItems("Vegetable")).toHaveLength(0); + }); - expect(screen.getByRole("status")).toHaveTextContent("Correct!"); - expect(onCorrect).toHaveBeenCalledOnce(); + it("shows a drop-here placeholder for an empty zone", () => { + render( {}} />); + + expect(within(screen.getByRole("group", { name: "Fruit" })).getByText("Drop here")).toBeInTheDocument(); }); - it("shows incorrect feedback for wrong placements", async () => { + it("shows unanswered feedback when not all items are placed", async () => { const user = userEvent.setup(); - render( {}} />); - // Place all items, but Apple in wrong category - await user.click(screen.getByRole("button", { name: "Apple" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to vegetable/i, - }), - ); - await user.click(screen.getByRole("button", { name: "Banana" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to fruit/i, - }), - ); - await user.click(screen.getByRole("button", { name: "Carrot" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to vegetable/i, - }), - ); + await user.click(screen.getByRole("button", { name: /check answer/i })); - await user.click( - screen.getByRole("button", { name: /check answer/i }), - ); + expect(screen.getByText("Place all items before checking.")).toBeInTheDocument(); + }); - expect(screen.getByRole("status")).toHaveTextContent( - "Not quite. Try again.", - ); + it("moves an item into a category by dragging it", () => { + render( {}} />); + + dragItemToZone("Apple", "Fruit"); + + expect(getZoneItems("Fruit")).toContain("Apple"); + expect(getZoneItems("Items")).not.toContain("Apple"); }); - it("shows unanswered feedback when not all items are placed", async () => { + it("shows correct feedback and calls onCorrect once everything is placed correctly", async () => { + const onCorrect = vi.fn<() => void>(); const user = userEvent.setup(); + render(); - render( {}} />); + dragItemToZone("Apple", "Fruit"); + dragItemToZone("Banana", "Fruit"); + dragItemToZone("Carrot", "Vegetable"); - await user.click( - screen.getByRole("button", { name: /check answer/i }), - ); + await user.click(screen.getByRole("button", { name: /check answer/i })); - expect(screen.getByRole("status")).toHaveTextContent( - "Place all items before checking.", - ); + expect(screen.getByText("Correct!")).toBeInTheDocument(); + expect(onCorrect).toHaveBeenCalledOnce(); }); - it("resets all items to unplaced", async () => { + it("shows incorrect feedback for a wrong placement", async () => { const user = userEvent.setup(); + render( {}} />); + + dragItemToZone("Apple", "Vegetable"); + dragItemToZone("Banana", "Fruit"); + dragItemToZone("Carrot", "Fruit"); + + await user.click(screen.getByRole("button", { name: /check answer/i })); + expect(screen.getByText("Not quite. Try again.")).toBeInTheDocument(); + }); + + it("resets all items back to unplaced", async () => { + const user = userEvent.setup(); render( {}} />); - await user.click(screen.getByRole("button", { name: "Apple" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to fruit/i, - }), - ); + dragItemToZone("Apple", "Fruit"); await user.click(screen.getByRole("button", { name: /reset/i })); expect(getZoneItems("Items")).toHaveLength(3); diff --git a/files/framework/astro-react/src/components/tasks/categorize.tsx b/files/framework/astro-react/src/components/tasks/categorize.tsx index 63434cc..ecb30a3 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.tsx @@ -1,13 +1,35 @@ import './task.css'; import './categorize.css'; import { useEffect, useId, useState } from 'react'; +import { + DndContext, + DragOverlay, + KeyboardSensor, + PointerSensor, + closestCorners, + useDroppable, + useSensor, + useSensors, + type Announcements, + type DragEndEvent, + type DragOverEvent, + type DragStartEvent, +} from '@dnd-kit/core'; +import { + SortableContext, + arrayMove, + sortableKeyboardCoordinates, + useSortable, + verticalListSortingStrategy, +} from '@dnd-kit/sortable'; +import { CSS } from '@dnd-kit/utilities'; import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; -import { Button } from '../button'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; import { TaskActions, type Result } from './task-actions'; +import { Button } from '../button'; -const UNPLACED = null; +const UNPLACED = 'unplaced'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', @@ -15,10 +37,7 @@ const FEEDBACK_MESSAGES: Record = { unanswered: 'Place all items before checking.', }; -type CategorizeProps = { - task: Extract; - onCorrect: () => void; -}; +type Containers = Record; function shuffle(items: T[]): T[] { const copy = [...items]; @@ -29,114 +48,222 @@ function shuffle(items: T[]): T[] { return copy; } +function zoneLabel(id: string): string { + return id === UNPLACED ? 'Items' : id; +} + +// Which container currently holds `id` - or, if `id` is itself a container +// (e.g. an empty zone's own droppable), that container. +export function findContainer(containers: Containers, id: string): string | undefined { + if (id in containers) return id; + return Object.keys(containers).find((key) => containers[key].includes(id)); +} + +// Moves `activeId` out of `activeContainer` and into `overContainer`, +// positioned just before `overId` (or at the end, if `overId` is the +// container itself - e.g. dropping into an empty zone). +export function moveItem( + containers: Containers, + activeId: string, + activeContainer: string, + overContainer: string, + overId: string, +): Containers { + const overItems = containers[overContainer]; + const overIndex = overItems.indexOf(overId); + const newIndex = overIndex >= 0 ? overIndex : overItems.length; + + return { + ...containers, + [activeContainer]: containers[activeContainer].filter((item) => item !== activeId), + [overContainer]: [...overItems.slice(0, newIndex), activeId, ...overItems.slice(newIndex)], + }; +} + +type ItemProps = { + id: string; + disabled: boolean; +}; + +function Item({ id, disabled }: ItemProps) { + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id, + disabled, + }); + + return ( +
+ {id} +
+ ); +} + type ZoneProps = { - label: string; - dropLabel: string; + id: string; items: string[]; - selectedItem: string | null; disabled: boolean; - onSelectItem: (item: string) => void; - onDrop: () => void; }; -function Zone({ label, dropLabel, items, selectedItem, disabled, onSelectItem, onDrop }: ZoneProps) { - // A zone isn't a valid drop target for an item that's already in it. - const canDrop = selectedItem !== null && !items.includes(selectedItem); +function Zone({ id, items, disabled }: ZoneProps) { + const { setNodeRef, isOver } = useDroppable({ id, disabled }); + const label = zoneLabel(id); + + const classNames = ['zone']; + if (isOver) classNames.push('zone-over'); + if (items.length === 0) classNames.push('zone-empty'); return ( -
+

{label}

-
- {items.map((item) => ( - - ))} -
-
); } +type CategorizeProps = { + task: Extract; + onCorrect: () => void; +}; + export function Categorize({ task, onCorrect }: CategorizeProps) { const groupId = useId(); + const feedbackId = `${groupId}-feedback`; - const allItems = task.categories.flatMap((category) => - category.items.map((item) => ({ item, correctCategory: category.name })), + const allItems = task.categories.flatMap((category) => category.items); + const correctCategoryByItem = Object.fromEntries( + task.categories.flatMap((category) => category.items.map((item) => [item, category.name])), ); - const [order, setOrder] = useState(() => allItems.map((entry) => entry.item)); - const [placements, setPlacements] = useState>(() => - Object.fromEntries(allItems.map((entry) => [entry.item, UNPLACED])), - ); - const [selectedItem, setSelectedItem] = useState(null); - const [announcement, setAnnouncement] = useState(''); - const [result, setResult] = useState(null); + const [containers, setContainers] = useState(() => ({ + [UNPLACED]: allItems, + ...Object.fromEntries(task.categories.map((category) => [category.name, [] as string[]])), + })); + const [initialUnplaced, setInitialUnplaced] = useState(allItems); const [shuffled, setShuffled] = useState(false); + const [activeId, setActiveId] = useState(null); + const [result, setResult] = useState(null); useEffect(() => { - setOrder(shuffle(allItems.map((entry) => entry.item))); + const shuffledItems = shuffle(allItems); + setContainers((previous) => ({ ...previous, [UNPLACED]: shuffledItems })); + setInitialUnplaced(shuffledItems); setShuffled(true); }, []); - function handleSelectItem(item: string) { - setSelectedItem((current) => (current === item ? null : item)); + const isAnswered = result === 'correct'; + const taskRef = useFocusOnCorrect(result); + + const sensors = useSensors( + useSensor(PointerSensor), + useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), + ); + + const announcements: Announcements = { + onDragStart({ active }) { + return `Picked up ${active.id}.`; + }, + onDragOver({ active, over }) { + if (!over) return undefined; + const container = findContainer(containers, String(over.id)); + return container ? `${active.id} is over ${zoneLabel(container)}.` : undefined; + }, + onDragEnd({ active, over }) { + if (!over) return `${active.id} was dropped.`; + const container = findContainer(containers, String(over.id)); + return container + ? `${active.id} was placed in ${zoneLabel(container)}.` + : `${active.id} was dropped.`; + }, + onDragCancel({ active }) { + return `Moving ${active.id} was cancelled.`; + }, + }; + + function handleDragStart(event: DragStartEvent) { + setActiveId(String(event.active.id)); + } + + function handleDragOver(event: DragOverEvent) { + const { active, over } = event; + if (!over) return; + + const activeId = String(active.id); + const overId = String(over.id); + const activeContainer = findContainer(containers, activeId); + const overContainer = findContainer(containers, overId); + + if (!activeContainer || !overContainer || activeContainer === overContainer) return; + + setContainers((previous) => moveItem(previous, activeId, activeContainer, overContainer, overId)); } - function handlePlace(categoryName: string | null) { - if (!selectedItem) { - setAnnouncement('Select an item first.'); + function handleDragEnd(event: DragEndEvent) { + setActiveId(null); + const { active, over } = event; + if (!over) return; + + const activeId = String(active.id); + const overId = String(over.id); + const activeContainer = findContainer(containers, activeId); + const overContainer = findContainer(containers, overId); + if (!activeContainer || !overContainer || activeContainer !== overContainer) { + setResult(null); return; } - setPlacements((current) => ({ ...current, [selectedItem]: categoryName })); - setAnnouncement( - categoryName - ? `${selectedItem} moved to ${categoryName}.` - : `${selectedItem} moved back to the unplaced items.`, - ); - setSelectedItem(null); + const items = containers[activeContainer]; + const activeIndex = items.indexOf(activeId); + const overIndex = overId in containers ? items.length - 1 : items.indexOf(overId); + + if (activeIndex !== overIndex && overIndex >= 0) { + setContainers((previous) => ({ + ...previous, + [activeContainer]: arrayMove(previous[activeContainer], activeIndex, overIndex), + })); + } + setResult(null); } - function handleReset() { - setPlacements(Object.fromEntries(allItems.map((entry) => [entry.item, UNPLACED]))); - setSelectedItem(null); - setResult(null); - setAnnouncement('All items reset.'); + function handleDragCancel() { + setActiveId(null); } function handleCheck() { - const allPlaced = order.every((item) => placements[item] !== UNPLACED); - if (!allPlaced) { + if (containers[UNPLACED].length > 0) { setResult('unanswered'); return; } - const correctByItem = Object.fromEntries(allItems.map((entry) => [entry.item, entry.correctCategory])); - const allCorrect = order.every((item) => placements[item] === correctByItem[item]); + const allCorrect = task.categories.every( + (category) => + containers[category.name].length === category.items.length && + containers[category.name].every((item) => correctCategoryByItem[item] === category.name), + ); setResult(allCorrect ? 'correct' : 'incorrect'); - if (allCorrect) { - onCorrect(); - } + if (allCorrect) onCorrect(); } - const unplacedItems = order.filter((item) => placements[item] === UNPLACED); - const feedbackId = `${groupId}-feedback`; - const taskRef = useFocusOnCorrect(result); + function handleReset() { + setContainers({ + [UNPLACED]: initialUnplaced, + ...Object.fromEntries(task.categories.map((category) => [category.name, [] as string[]])), + }); + setResult(null); + } return (
@@ -144,36 +271,34 @@ export function Categorize({ task, onCorrect }: CategorizeProps) { {task.question}
-

- {announcement} -

- -
- handlePlace(UNPLACED)} - /> - -
- {task.categories.map((category) => ( - placements[item] === category.name)} - selectedItem={selectedItem} - disabled={result === 'correct'} - onSelectItem={handleSelectItem} - onDrop={() => handlePlace(category.name)} - /> - ))} + +
+ + +
+ {task.categories.map((category) => ( + + ))} +
-
+ + + {activeId ?
{activeId}
: null} +
+ Reset From ad79ef4166560b5b432129e89a0f66005a4a39ab Mon Sep 17 00:00:00 2001 From: moT01 <20648924+moT01@users.noreply.github.com> Date: Fri, 11 Sep 2026 10:25:41 -0500 Subject: [PATCH 3/9] fix: categorize drag and drop UI/UX --- .../src/components/tasks/categorize.css | 16 +++++++++---- .../src/components/tasks/categorize.tsx | 23 +++++++++++++++++-- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/files/framework/astro-react/src/components/tasks/categorize.css b/files/framework/astro-react/src/components/tasks/categorize.css index 31e85be..bf24627 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.css +++ b/files/framework/astro-react/src/components/tasks/categorize.css @@ -18,11 +18,11 @@ .zone { border: 1px solid var(--quaternary-background); border-radius: var(--radius-md); - padding: var(--space-md); + padding: var(--space-sm); } .zone-heading { - margin-bottom: var(--space-sm); + margin-bottom: var(--space-xs); font-size: var(--text-size-sm); } @@ -30,7 +30,7 @@ display: flex; flex-direction: column; gap: var(--space-xs); - min-height: 2.5rem; + min-height: 2rem; } .zone-empty { @@ -50,14 +50,22 @@ } .item-card { + display: flex; + align-items: center; + gap: var(--space-md); background: var(--secondary-background); border: 1px solid var(--quaternary-background); border-radius: var(--radius-sm); - padding: var(--space-xs) var(--space-sm); + padding: var(--space-sm) var(--space-md); cursor: grab; touch-action: none; } +.item-grip { + flex-shrink: 0; + color: var(--quaternary-color); +} + .item-card:focus-visible { outline: var(--border-focus); outline-offset: 2px; diff --git a/files/framework/astro-react/src/components/tasks/categorize.tsx b/files/framework/astro-react/src/components/tasks/categorize.tsx index ecb30a3..8b3d0bd 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.tsx @@ -80,6 +80,19 @@ export function moveItem( }; } +function DragGrip() { + return ( + + ); +} + type ItemProps = { id: string; disabled: boolean; @@ -99,7 +112,8 @@ function Item({ id, disabled }: ItemProps) { {...attributes} {...listeners} > - {id} + + {id}
); } @@ -296,7 +310,12 @@ export function Categorize({ task, onCorrect }: CategorizeProps) {
- {activeId ?
{activeId}
: null} + {activeId ? ( +
+ + {activeId} +
+ ) : null}
From 566bea372d5b5a17ea09a7b2373ce7b87735e3c6 Mon Sep 17 00:00:00 2001 From: moT01 <20648924+moT01@users.noreply.github.com> Date: Fri, 11 Sep 2026 11:04:03 -0500 Subject: [PATCH 4/9] fix: categorize UX more --- .../src/components/tasks/categorize.css | 6 +- .../src/components/tasks/categorize.test.tsx | 8 +- .../src/components/tasks/categorize.tsx | 117 +++++++++--------- 3 files changed, 61 insertions(+), 70 deletions(-) diff --git a/files/framework/astro-react/src/components/tasks/categorize.css b/files/framework/astro-react/src/components/tasks/categorize.css index bf24627..f88f39e 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.css +++ b/files/framework/astro-react/src/components/tasks/categorize.css @@ -37,15 +37,11 @@ border-style: dashed; } -.zone-over { - border-color: var(--highlight-color); - background: var(--selection-color); -} - .zone-placeholder { margin: 0; color: var(--quaternary-color); font-size: var(--text-size-xs); + font-style: italic; text-align: center; } diff --git a/files/framework/astro-react/src/components/tasks/categorize.test.tsx b/files/framework/astro-react/src/components/tasks/categorize.test.tsx index f1698a6..e7d8c43 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.test.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.test.tsx @@ -91,18 +91,18 @@ describe("moveItem", () => { it("moves an item from one container to another", () => { const containers = { unplaced: ["a", "b"], Fruit: [] }; - const result = moveItem(containers, "a", "unplaced", "Fruit", "Fruit"); + const result = moveItem(containers, "a", "unplaced", "Fruit"); expect(result.unplaced).toEqual(["b"]); expect(result.Fruit).toEqual(["a"]); }); - it("positions the item before overId, not just appended", () => { + it("appends the item, since order within a container is never scored", () => { const containers = { unplaced: ["a"], Fruit: ["b", "c"] }; - const result = moveItem(containers, "a", "unplaced", "Fruit", "c"); + const result = moveItem(containers, "a", "unplaced", "Fruit"); - expect(result.Fruit).toEqual(["b", "a", "c"]); + expect(result.Fruit).toEqual(["b", "c", "a"]); }); }); diff --git a/files/framework/astro-react/src/components/tasks/categorize.tsx b/files/framework/astro-react/src/components/tasks/categorize.tsx index 8b3d0bd..1036bc9 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.tsx @@ -7,22 +7,19 @@ import { KeyboardSensor, PointerSensor, closestCorners, + useDraggable, useDroppable, useSensor, useSensors, type Announcements, - type DragEndEvent, type DragOverEvent, type DragStartEvent, } from '@dnd-kit/core'; -import { - SortableContext, - arrayMove, - sortableKeyboardCoordinates, - useSortable, - verticalListSortingStrategy, -} from '@dnd-kit/sortable'; -import { CSS } from '@dnd-kit/utilities'; +// Only its coordinate getter is used here - it jumps to the nearest +// registered droppable in the pressed direction, which works fine for plain +// (non-sortable) droppables too, since its sortable-specific offset logic +// only kicks in when both sides actually have sortable data attached. +import { sortableKeyboardCoordinates } from '@dnd-kit/sortable'; import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; @@ -59,24 +56,19 @@ export function findContainer(containers: Containers, id: string): string | unde return Object.keys(containers).find((key) => containers[key].includes(id)); } -// Moves `activeId` out of `activeContainer` and into `overContainer`, -// positioned just before `overId` (or at the end, if `overId` is the -// container itself - e.g. dropping into an empty zone). +// Moves `activeId` out of `activeContainer` and into `overContainer`. Order +// within a container is never scored, so it's just appended - no insertion +// position to work out. export function moveItem( containers: Containers, activeId: string, activeContainer: string, overContainer: string, - overId: string, ): Containers { - const overItems = containers[overContainer]; - const overIndex = overItems.indexOf(overId); - const newIndex = overIndex >= 0 ? overIndex : overItems.length; - return { ...containers, [activeContainer]: containers[activeContainer].filter((item) => item !== activeId), - [overContainer]: [...overItems.slice(0, newIndex), activeId, ...overItems.slice(newIndex)], + [overContainer]: [...containers[overContainer], activeId], }; } @@ -99,7 +91,11 @@ type ItemProps = { }; function Item({ id, disabled }: ItemProps) { - const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + // No transform applied here: the DragOverlay is what visually follows the + // cursor. This card just sits at rest (wherever it's currently placed) and + // fades out while dragging - applying the raw pointer-delta transform on + // top of that produced a distorted, offset duplicate. + const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id, disabled, }); @@ -107,7 +103,6 @@ function Item({ id, disabled }: ItemProps) { return (
item !== activeId).length; + const classNames = ['zone']; - if (isOver) classNames.push('zone-over'); - if (items.length === 0) classNames.push('zone-empty'); + if (settledCount === 0) classNames.push('zone-empty'); return (

{label}

- -
- {items.map((item) => ( - - ))} - {items.length === 0 ?

Drop here

: null} -
-
+
+ {items.map((item) => ( + + ))} + {items.length === 0 ?

Drop here

: null} +
); } @@ -168,6 +167,7 @@ export function Categorize({ task, onCorrect }: CategorizeProps) { const [initialUnplaced, setInitialUnplaced] = useState(allItems); const [shuffled, setShuffled] = useState(false); const [activeId, setActiveId] = useState(null); + const [dragStartContainer, setDragStartContainer] = useState(null); const [result, setResult] = useState(null); useEffect(() => { @@ -207,7 +207,9 @@ export function Categorize({ task, onCorrect }: CategorizeProps) { }; function handleDragStart(event: DragStartEvent) { - setActiveId(String(event.active.id)); + const activeId = String(event.active.id); + setActiveId(activeId); + setDragStartContainer(findContainer(containers, activeId) ?? null); } function handleDragOver(event: DragOverEvent) { @@ -215,45 +217,32 @@ export function Categorize({ task, onCorrect }: CategorizeProps) { if (!over) return; const activeId = String(active.id); - const overId = String(over.id); + const overContainer = findContainer(containers, String(over.id)); const activeContainer = findContainer(containers, activeId); - const overContainer = findContainer(containers, overId); if (!activeContainer || !overContainer || activeContainer === overContainer) return; - setContainers((previous) => moveItem(previous, activeId, activeContainer, overContainer, overId)); + setContainers((previous) => moveItem(previous, activeId, activeContainer, overContainer)); } - function handleDragEnd(event: DragEndEvent) { + function handleDragEnd() { setActiveId(null); - const { active, over } = event; - if (!over) return; - - const activeId = String(active.id); - const overId = String(over.id); - const activeContainer = findContainer(containers, activeId); - const overContainer = findContainer(containers, overId); - if (!activeContainer || !overContainer || activeContainer !== overContainer) { - setResult(null); - return; - } - - const items = containers[activeContainer]; - const activeIndex = items.indexOf(activeId); - const overIndex = overId in containers ? items.length - 1 : items.indexOf(overId); - - if (activeIndex !== overIndex && overIndex >= 0) { - setContainers((previous) => ({ - ...previous, - [activeContainer]: arrayMove(previous[activeContainer], activeIndex, overIndex), - })); - } - + setDragStartContainer(null); setResult(null); } function handleDragCancel() { + // handleDragOver already moved the item as a live preview while hovering + // - cancelling has to undo that, or the item would stay wherever it last + // hovered even though the user backed out of the move. + if (activeId && dragStartContainer) { + const currentContainer = findContainer(containers, activeId); + if (currentContainer && currentContainer !== dragStartContainer) { + setContainers((previous) => moveItem(previous, activeId, currentContainer, dragStartContainer)); + } + } setActiveId(null); + setDragStartContainer(null); } function handleCheck() { @@ -295,7 +284,12 @@ export function Categorize({ task, onCorrect }: CategorizeProps) { onDragCancel={handleDragCancel} >
- +
{task.categories.map((category) => ( @@ -303,6 +297,7 @@ export function Categorize({ task, onCorrect }: CategorizeProps) { key={category.name} id={category.name} items={containers[category.name]} + activeId={activeId} disabled={isAnswered} /> ))} From cffa7163273affd34dedd2afbad2fd67a7dab3e8 Mon Sep 17 00:00:00 2001 From: moT01 <20648924+moT01@users.noreply.github.com> Date: Fri, 11 Sep 2026 11:20:40 -0500 Subject: [PATCH 5/9] fix: categories UX final --- .../src/components/tasks/categorize.css | 3 ++- .../src/components/tasks/categorize.test.tsx | 6 ------ .../src/components/tasks/categorize.tsx | 21 ------------------- 3 files changed, 2 insertions(+), 28 deletions(-) diff --git a/files/framework/astro-react/src/components/tasks/categorize.css b/files/framework/astro-react/src/components/tasks/categorize.css index f88f39e..8a5e0ef 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.css +++ b/files/framework/astro-react/src/components/tasks/categorize.css @@ -5,7 +5,8 @@ } .categorize-categories { - display: grid; + display: flex; + flex-direction: column; gap: var(--space-md); } diff --git a/files/framework/astro-react/src/components/tasks/categorize.test.tsx b/files/framework/astro-react/src/components/tasks/categorize.test.tsx index e7d8c43..834c735 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.test.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.test.tsx @@ -24,10 +24,6 @@ function getZoneItems(zoneName: string): string[] { .map((element) => element.textContent ?? ""); } -// dnd-kit measures real DOM rects to decide collisions, which jsdom doesn't -// compute (everything is 0x0 by default). Stubbing getBoundingClientRect on -// the specific elements involved lets a real pointer-driven drag resolve to -// a specific drop target, the same way it would in a real layout. function mockRect(element: Element, rect: Partial) { vi.spyOn(element, "getBoundingClientRect").mockReturnValue({ x: 0, @@ -43,8 +39,6 @@ function mockRect(element: Element, rect: Partial) { }); } -// Each zone gets its own, non-overlapping vertical band so the pointer -// coordinates land unambiguously in the intended target zone. const ZONE_TOP: Record = { Items: 0, Fruit: 200, Vegetable: 400 }; function dragItemToZone(itemText: string, zoneName: string) { diff --git a/files/framework/astro-react/src/components/tasks/categorize.tsx b/files/framework/astro-react/src/components/tasks/categorize.tsx index 1036bc9..8668a85 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.tsx @@ -15,10 +15,6 @@ import { type DragOverEvent, type DragStartEvent, } from '@dnd-kit/core'; -// Only its coordinate getter is used here - it jumps to the nearest -// registered droppable in the pressed direction, which works fine for plain -// (non-sortable) droppables too, since its sortable-specific offset logic -// only kicks in when both sides actually have sortable data attached. import { sortableKeyboardCoordinates } from '@dnd-kit/sortable'; import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; @@ -49,16 +45,11 @@ function zoneLabel(id: string): string { return id === UNPLACED ? 'Items' : id; } -// Which container currently holds `id` - or, if `id` is itself a container -// (e.g. an empty zone's own droppable), that container. export function findContainer(containers: Containers, id: string): string | undefined { if (id in containers) return id; return Object.keys(containers).find((key) => containers[key].includes(id)); } -// Moves `activeId` out of `activeContainer` and into `overContainer`. Order -// within a container is never scored, so it's just appended - no insertion -// position to work out. export function moveItem( containers: Containers, activeId: string, @@ -91,10 +82,6 @@ type ItemProps = { }; function Item({ id, disabled }: ItemProps) { - // No transform applied here: the DragOverlay is what visually follows the - // cursor. This card just sits at rest (wherever it's currently placed) and - // fades out while dragging - applying the raw pointer-delta transform on - // top of that produced a distorted, offset duplicate. const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id, disabled, @@ -123,11 +110,6 @@ type ZoneProps = { function Zone({ id, items, activeId, disabled }: ZoneProps) { const { setNodeRef } = useDroppable({ id, disabled }); const label = zoneLabel(id); - - // Dragging over a zone eagerly relocates the item here as a live preview - // (see handleDragOver), so `items` briefly includes it before anything's - // actually dropped. Excluding the active item keeps the border reflecting - // what's actually settled, not the in-progress preview. const settledCount = items.filter((item) => item !== activeId).length; const classNames = ['zone']; @@ -232,9 +214,6 @@ export function Categorize({ task, onCorrect }: CategorizeProps) { } function handleDragCancel() { - // handleDragOver already moved the item as a live preview while hovering - // - cancelling has to undo that, or the item would stay wherever it last - // hovered even though the user backed out of the move. if (activeId && dragStartContainer) { const currentContainer = findContainer(containers, activeId); if (currentContainer && currentContainer !== dragStartContainer) { From 5a09e006afd0903d1d71ab5e02dbc6764fb6c6c5 Mon Sep 17 00:00:00 2001 From: moT01 <20648924+moT01@users.noreply.github.com> Date: Fri, 11 Sep 2026 12:52:27 -0500 Subject: [PATCH 6/9] fix order task UI/UX --- .../src/components/tasks/categorize.css | 35 --- .../src/components/tasks/categorize.test.tsx | 37 +-- .../src/components/tasks/categorize.tsx | 14 +- .../src/components/tasks/drag-grip.tsx | 13 + .../src/components/tasks/order.css | 28 --- .../src/components/tasks/order.test.tsx | 115 ++++----- .../src/components/tasks/order.tsx | 226 ++++++++++-------- .../astro-react/src/components/tasks/task.css | 36 +++ .../astro-react/src/test-utils/dnd.ts | 50 ++++ 9 files changed, 270 insertions(+), 284 deletions(-) create mode 100644 files/framework/astro-react/src/components/tasks/drag-grip.tsx create mode 100644 files/framework/astro-react/src/test-utils/dnd.ts diff --git a/files/framework/astro-react/src/components/tasks/categorize.css b/files/framework/astro-react/src/components/tasks/categorize.css index 8a5e0ef..917c031 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.css +++ b/files/framework/astro-react/src/components/tasks/categorize.css @@ -45,38 +45,3 @@ font-style: italic; text-align: center; } - -.item-card { - display: flex; - align-items: center; - gap: var(--space-md); - background: var(--secondary-background); - border: 1px solid var(--quaternary-background); - border-radius: var(--radius-sm); - padding: var(--space-sm) var(--space-md); - cursor: grab; - touch-action: none; -} - -.item-grip { - flex-shrink: 0; - color: var(--quaternary-color); -} - -.item-card:focus-visible { - outline: var(--border-focus); - outline-offset: 2px; -} - -.item-dragging { - opacity: 0.4; -} - -.item-overlay { - cursor: grabbing; - box-shadow: 0 4px 12px var(--primary-background-translucent); -} - -.unshuffled .item-card { - visibility: hidden; -} diff --git a/files/framework/astro-react/src/components/tasks/categorize.test.tsx b/files/framework/astro-react/src/components/tasks/categorize.test.tsx index 834c735..4e58611 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.test.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.test.tsx @@ -1,8 +1,9 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; -import { render, screen, within, fireEvent } from "@testing-library/react"; +import { render, screen, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { Categorize, findContainer, moveItem } from "./categorize"; import type { Task } from "../../lib/curriculum-tasks"; +import { dragPointerTo, waitOutDragClickGuard } from "../../test-utils/dnd"; const task: Extract = { type: "categorize", @@ -24,41 +25,16 @@ function getZoneItems(zoneName: string): string[] { .map((element) => element.textContent ?? ""); } -function mockRect(element: Element, rect: Partial) { - vi.spyOn(element, "getBoundingClientRect").mockReturnValue({ - x: 0, - y: 0, - width: 100, - height: 40, - top: 0, - left: 0, - right: 100, - bottom: 40, - toJSON: () => {}, - ...rect, - }); -} - +// Each zone gets its own, non-overlapping vertical band so the pointer +// coordinates land unambiguously in the intended target zone. const ZONE_TOP: Record = { Items: 0, Fruit: 200, Vegetable: 400 }; function dragItemToZone(itemText: string, zoneName: string) { const item = screen.getByText(itemText); const zone = screen.getByRole("group", { name: zoneName }); const top = ZONE_TOP[zoneName]; - const centerY = top + 75; - mockRect(item, { top: 0, left: 0, bottom: 40, right: 100 }); - mockRect(zone, { top, left: 0, bottom: top + 150, right: 300 }); - - fireEvent.pointerDown(item, { - pointerId: 1, - isPrimary: true, - button: 0, - clientX: 50, - clientY: 20, - }); - fireEvent.pointerMove(document, { pointerId: 1, clientX: 50, clientY: centerY }); - fireEvent.pointerUp(document, { pointerId: 1, clientX: 50, clientY: centerY }); + dragPointerTo(item, zone, { top, left: 0, bottom: top + 150, right: 300 }); } describe("findContainer", () => { @@ -144,6 +120,7 @@ describe(Categorize, () => { dragItemToZone("Banana", "Fruit"); dragItemToZone("Carrot", "Vegetable"); + await waitOutDragClickGuard(); await user.click(screen.getByRole("button", { name: /check answer/i })); expect(screen.getByText("Correct!")).toBeInTheDocument(); @@ -158,6 +135,7 @@ describe(Categorize, () => { dragItemToZone("Banana", "Fruit"); dragItemToZone("Carrot", "Fruit"); + await waitOutDragClickGuard(); await user.click(screen.getByRole("button", { name: /check answer/i })); expect(screen.getByText("Not quite. Try again.")).toBeInTheDocument(); @@ -168,6 +146,7 @@ describe(Categorize, () => { render( {}} />); dragItemToZone("Apple", "Fruit"); + await waitOutDragClickGuard(); await user.click(screen.getByRole("button", { name: /reset/i })); expect(getZoneItems("Items")).toHaveLength(3); diff --git a/files/framework/astro-react/src/components/tasks/categorize.tsx b/files/framework/astro-react/src/components/tasks/categorize.tsx index 8668a85..da4a722 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.tsx @@ -21,6 +21,7 @@ import { Markdown } from '../markdown'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; import { TaskActions, type Result } from './task-actions'; import { Button } from '../button'; +import { DragGrip } from './drag-grip'; const UNPLACED = 'unplaced'; @@ -63,19 +64,6 @@ export function moveItem( }; } -function DragGrip() { - return ( - - ); -} - type ItemProps = { id: string; disabled: boolean; diff --git a/files/framework/astro-react/src/components/tasks/drag-grip.tsx b/files/framework/astro-react/src/components/tasks/drag-grip.tsx new file mode 100644 index 0000000..ccd0f3b --- /dev/null +++ b/files/framework/astro-react/src/components/tasks/drag-grip.tsx @@ -0,0 +1,13 @@ +// Shared drag-handle affordance for draggable task items (categorize, order). +export function DragGrip() { + return ( + + ); +} diff --git a/files/framework/astro-react/src/components/tasks/order.css b/files/framework/astro-react/src/components/tasks/order.css index c5917a3..fa4f837 100644 --- a/files/framework/astro-react/src/components/tasks/order.css +++ b/files/framework/astro-react/src/components/tasks/order.css @@ -4,35 +4,7 @@ gap: var(--space-xs); } -.unshuffled .order-row { - visibility: hidden; -} - -.order-row { - display: flex; - align-items: center; - gap: var(--space-sm); - border: 1px solid var(--quaternary-background); - border-radius: var(--radius-sm); - padding: var(--space-xs) var(--space-sm); -} - .order-position { font-weight: 700; min-width: 1.5rem; } - -.order-text { - flex: 1; - min-width: 0; -} - -.order-controls { - display: flex; - gap: var(--space-xs); -} - -.order-controls button:disabled { - cursor: not-allowed; - opacity: 0.6; -} diff --git a/files/framework/astro-react/src/components/tasks/order.test.tsx b/files/framework/astro-react/src/components/tasks/order.test.tsx index a0b0f82..423c693 100644 --- a/files/framework/astro-react/src/components/tasks/order.test.tsx +++ b/files/framework/astro-react/src/components/tasks/order.test.tsx @@ -3,6 +3,7 @@ import { render, screen, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { Order } from "./order"; import type { Task } from "../../lib/curriculum-tasks"; +import { dragPointerTo, mockRect, waitOutDragClickGuard } from "../../test-utils/dnd"; const task: Extract = { type: "order", @@ -18,117 +19,83 @@ beforeEach(() => { vi.spyOn(Math, "random").mockReturnValue(0.1); }); -const ITEM_NAMES = task.items; - function getItemOrder(): string[] { const group = screen.getByRole("group", { name: "Put these in order:" }); return within(group) - .getAllByText(new RegExp(`^(${ITEM_NAMES.join("|")})$`)) - .map((el) => el.textContent!); + .queryAllByText((_, element) => element?.className === "item-card") + .map((element) => element.textContent?.replace(/^\d+\.\s*/, "") ?? ""); } -describe(Order, () => { - it("renders items in shuffled order", () => { - render( {}} />); - - expect(getItemOrder()).toEqual(["Beta", "Gamma", "Alpha"]); - }); - - it("moves an item up when its up button is clicked", async () => { - const user = userEvent.setup(); - - render( {}} />); - - await user.click( - screen.getByRole("button", { name: "Move Gamma up" }), - ); +// Sortable collision detection compares the dragged row against every other +// row's rect, not just the drop target - so, unlike categorize's separate +// zones, every row needs a distinct, stacked rect or the drop can land on +// the wrong neighbor. +const ROW_HEIGHT = 40; - expect(getItemOrder()).toEqual(["Gamma", "Beta", "Alpha"]); +function mockRowRects(order: string[]) { + order.forEach((text, index) => { + const row = screen.getByText(text).closest(".item-card"); + if (row) mockRect(row, { top: index * ROW_HEIGHT, left: 0, bottom: (index + 1) * ROW_HEIGHT, right: 100 }); }); +} - it("moves an item down when its down button is clicked", async () => { - const user = userEvent.setup(); - - render( {}} />); - - await user.click( - screen.getByRole("button", { name: "Move Beta down" }), - ); +function dragItemToRow(itemText: string, targetText: string, currentOrder: string[]) { + mockRowRects(currentOrder); + const item = screen.getByText(itemText); + const sourceRow = item.closest(".item-card"); + const targetRow = screen.getByText(targetText).closest(".item-card"); + if (!sourceRow || !targetRow) throw new Error("Could not find row"); - expect(getItemOrder()).toEqual(["Gamma", "Beta", "Alpha"]); - }); + dragPointerTo(item, targetRow, targetRow.getBoundingClientRect(), sourceRow.getBoundingClientRect()); +} - it("disables the up button for the first item and down for the last", () => { +describe(Order, () => { + it("renders items in shuffled order", () => { render( {}} />); - expect( - screen.getByRole("button", { name: "Move Beta up" }), - ).toBeDisabled(); - expect( - screen.getByRole("button", { name: "Move Alpha down" }), - ).toBeDisabled(); + expect(getItemOrder()).toEqual(["Beta", "Gamma", "Alpha"]); }); - it("restores the initial shuffled order on reset", async () => { - const user = userEvent.setup(); - + it("moves an item into a new position by dragging it", () => { render( {}} />); - await user.click( - screen.getByRole("button", { name: "Move Alpha up" }), - ); - await user.click( - screen.getByRole("button", { name: /reset/i }), - ); + dragItemToRow("Gamma", "Beta", ["Beta", "Gamma", "Alpha"]); - expect(getItemOrder()).toEqual(["Beta", "Gamma", "Alpha"]); + expect(getItemOrder()).toEqual(["Gamma", "Beta", "Alpha"]); }); it("shows correct feedback and calls onCorrect for the right order", async () => { const onCorrect = vi.fn<() => void>(); const user = userEvent.setup(); - render(); - // Shuffled: ["Beta", "Gamma", "Alpha"] - // Move Alpha up twice to get ["Alpha", "Beta", "Gamma"] - await user.click( - screen.getByRole("button", { name: "Move Alpha up" }), - ); - await user.click( - screen.getByRole("button", { name: "Move Alpha up" }), - ); - await user.click( - screen.getByRole("button", { name: /check answer/i }), - ); - - expect(screen.getByRole("status")).toHaveTextContent("Correct!"); + // Shuffled: ["Beta", "Gamma", "Alpha"] - dragging Alpha to the front + // gives the correct order in one move. + dragItemToRow("Alpha", "Beta", ["Beta", "Gamma", "Alpha"]); + await waitOutDragClickGuard(); + await user.click(screen.getByRole("button", { name: /check answer/i })); + + expect(screen.getByText("Correct!")).toBeInTheDocument(); expect(onCorrect).toHaveBeenCalledOnce(); }); it("shows incorrect feedback for the wrong order", async () => { const user = userEvent.setup(); - render( {}} />); - await user.click( - screen.getByRole("button", { name: /check answer/i }), - ); + await user.click(screen.getByRole("button", { name: /check answer/i })); - expect(screen.getByRole("status")).toHaveTextContent( - "Not quite. Try again.", - ); + expect(screen.getByText("Not quite. Try again.")).toBeInTheDocument(); }); - it("announces item movement for screen readers", async () => { + it("restores the initial shuffled order on reset", async () => { const user = userEvent.setup(); - render( {}} />); - await user.click( - screen.getByRole("button", { name: "Move Gamma down" }), - ); + dragItemToRow("Alpha", "Beta", ["Beta", "Gamma", "Alpha"]); + await waitOutDragClickGuard(); + await user.click(screen.getByRole("button", { name: /reset/i })); - expect(screen.getByText(/Gamma moved down/)).toBeInTheDocument(); + expect(getItemOrder()).toEqual(["Beta", "Gamma", "Alpha"]); }); }); diff --git a/files/framework/astro-react/src/components/tasks/order.tsx b/files/framework/astro-react/src/components/tasks/order.tsx index 1827045..2aa1655 100644 --- a/files/framework/astro-react/src/components/tasks/order.tsx +++ b/files/framework/astro-react/src/components/tasks/order.tsx @@ -1,11 +1,32 @@ import './task.css'; import './order.css'; -import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'; +import { useEffect, useId, useState } from 'react'; +import { + DndContext, + DragOverlay, + KeyboardSensor, + PointerSensor, + closestCenter, + useSensor, + useSensors, + type Announcements, + type DragEndEvent, + type DragStartEvent, +} from '@dnd-kit/core'; +import { + SortableContext, + arrayMove, + sortableKeyboardCoordinates, + useSortable, + verticalListSortingStrategy, +} from '@dnd-kit/sortable'; +import { CSS } from '@dnd-kit/utilities'; import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; import { Button } from '../button'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; import { TaskActions, type Result } from './task-actions'; +import { DragGrip } from './drag-grip'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', @@ -18,7 +39,6 @@ type OrderProps = { onCorrect: () => void; }; -// Fisher-Yates algorithm function shuffle(items: T[]): T[] { const copy = [...items]; for (let i = copy.length - 1; i > 0; i--) { @@ -28,6 +48,36 @@ function shuffle(items: T[]): T[] { return copy; } +type RowProps = { + id: string; + disabled: boolean; +}; + +function Row({ id, disabled }: RowProps) { + // Unlike categorize's plain useDraggable, order's items need to visibly + // slide into their new slots as you drag past them - that's what applying + // transform/transition here does; DragOverlay only covers the one being held. + const { attributes, listeners, setNodeRef, transform, transition, isDragging, index } = useSortable({ + id, + disabled, + }); + const style = { transform: CSS.Transform.toString(transform), transition }; + + return ( +
+ + {index + 1}. + {id} +
+ ); +} + export function Order({ task, onCorrect }: OrderProps) { const groupId = useId(); const questionId = `${groupId}-question`; @@ -36,53 +86,9 @@ export function Order({ task, onCorrect }: OrderProps) { const [items, setItems] = useState(() => task.items); const [initialOrder, setInitialOrder] = useState(() => task.items); const [shuffled, setShuffled] = useState(false); - const [announcement, setAnnouncement] = useState(''); + const [activeId, setActiveId] = useState(null); const [result, setResult] = useState(null); - const rowRefs = useRef>({}); - const previousRects = useRef | null>(null); - - function captureRowPositions() { - const rects: Record = {}; - for (const item of items) { - const node = rowRefs.current[item]; - if (node) { - rects[item] = node.getBoundingClientRect(); - } - } - previousRects.current = rects; - } - - useLayoutEffect(() => { - const previous = previousRects.current; - if (!previous) { - return; - } - - for (const item of items) { - const node = rowRefs.current[item]; - const previousRect = previous[item]; - if (!node || !previousRect) { - continue; - } - - const deltaY = previousRect.top - node.getBoundingClientRect().top; - if (deltaY === 0) { - continue; - } - - node.style.transition = 'none'; - node.style.transform = `translateY(${deltaY}px)`; - - requestAnimationFrame(() => { - node.style.transition = 'transform 150ms ease'; - node.style.transform = ''; - }); - } - - previousRects.current = null; - }, [items]); - useEffect(() => { const shuffledItems = shuffle(task.items); setItems(shuffledItems); @@ -90,87 +96,97 @@ export function Order({ task, onCorrect }: OrderProps) { setShuffled(true); }, []); - function handleMove(index: number, direction: -1 | 1) { - const targetIndex = index + direction; - if (targetIndex < 0 || targetIndex >= items.length) { - return; - } + const isAnswered = result === 'correct'; + const taskRef = useFocusOnCorrect(result); + + const sensors = useSensors( + useSensor(PointerSensor), + useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), + ); + + const announcements: Announcements = { + onDragStart({ active }) { + return `Picked up ${active.id}.`; + }, + onDragOver({ active, over }) { + if (!over) return undefined; + return `${active.id} is over position ${items.indexOf(String(over.id)) + 1} of ${items.length}.`; + }, + onDragEnd({ active, over }) { + if (!over) return `${active.id} was dropped.`; + return `${active.id} was dropped at position ${items.indexOf(String(over.id)) + 1} of ${items.length}.`; + }, + onDragCancel({ active }) { + return `Moving ${active.id} was cancelled.`; + }, + }; + + function handleDragStart(event: DragStartEvent) { + setActiveId(String(event.active.id)); + } + + // A single sortable list animates the reorder preview itself while + // dragging (each row's own transform), so the actual order only needs to + // be committed once, here - no live relocation or cancel-revert needed. + function handleDragEnd(event: DragEndEvent) { + const { active, over } = event; + setActiveId(null); + if (!over || active.id === over.id) return; - captureRowPositions(); - const next = [...items]; - [next[index], next[targetIndex]] = [next[targetIndex], next[index]]; - setItems(next); + setItems((previous) => arrayMove(previous, previous.indexOf(String(active.id)), previous.indexOf(String(over.id)))); setResult(null); - setAnnouncement( - `${items[index]} moved ${direction === -1 ? 'up' : 'down'}. Now position ${targetIndex + 1} of ${items.length}.`, - ); + } + + function handleDragCancel() { + setActiveId(null); } function handleReset() { - captureRowPositions(); setItems([...initialOrder]); setResult(null); - setAnnouncement('Order reset.'); } function handleCheck() { const isCorrect = items.every((item, index) => item === task.items[index]); setResult(isCorrect ? 'correct' : 'incorrect'); - if (isCorrect) { - onCorrect(); - } + if (isCorrect) onCorrect(); } - const taskRef = useFocusOnCorrect(result); - return (
{task.question}
-

- {announcement} -

- -
- {items.map((item, index) => ( +
{ - rowRefs.current[item] = node; - }} + className={shuffled ? 'order-list' : 'order-list unshuffled'} + role="group" + aria-labelledby={questionId} > - {index + 1}. - {item} -
- - -
+ {items.map((item) => ( + + ))}
- ))} -
+ + + + {activeId ? ( +
+ + {activeId} +
+ ) : null} +
+ Reset diff --git a/files/framework/astro-react/src/components/tasks/task.css b/files/framework/astro-react/src/components/tasks/task.css index cb58cd2..b862e68 100644 --- a/files/framework/astro-react/src/components/tasks/task.css +++ b/files/framework/astro-react/src/components/tasks/task.css @@ -33,3 +33,39 @@ .feedback.incorrect { color: var(--danger-color); } + +/* Draggable item card, shared by task types that use dnd-kit (categorize, order). */ +.item-card { + display: flex; + align-items: center; + gap: var(--space-md); + background: var(--secondary-background); + border: 1px solid var(--quaternary-background); + border-radius: var(--radius-sm); + padding: var(--space-sm) var(--space-md); + cursor: grab; + touch-action: none; +} + +.item-grip { + flex-shrink: 0; + color: var(--quaternary-color); +} + +.item-card:focus-visible { + outline: var(--border-focus); + outline-offset: 2px; +} + +.item-dragging { + opacity: 0.4; +} + +.item-overlay { + cursor: grabbing; + box-shadow: 0 4px 12px var(--primary-background-translucent); +} + +.unshuffled .item-card { + visibility: hidden; +} diff --git a/files/framework/astro-react/src/test-utils/dnd.ts b/files/framework/astro-react/src/test-utils/dnd.ts new file mode 100644 index 0000000..2574196 --- /dev/null +++ b/files/framework/astro-react/src/test-utils/dnd.ts @@ -0,0 +1,50 @@ +import { vi } from "vitest"; +import { fireEvent } from "@testing-library/react"; + +// dnd-kit measures real DOM rects to resolve collisions, which jsdom doesn't +// compute (everything is 0x0 by default). Stubbing getBoundingClientRect on +// the elements involved lets a real pointer-driven drag resolve to a +// specific drop target, the same way it would in a real layout. +export function mockRect(element: Element, rect: Partial) { + vi.spyOn(element, "getBoundingClientRect").mockReturnValue({ + x: 0, + y: 0, + width: 100, + height: 40, + top: 0, + left: 0, + right: 100, + bottom: 40, + toJSON: () => {}, + ...rect, + }); +} + +// Fires a real pointer-driven drag from `source` into `target`'s mocked +// rect. isPrimary/button are required for PointerSensor's activator to pick +// up the drag at all. +export function dragPointerTo( + source: Element, + target: Element, + targetRect: Partial, + sourceRect: Partial = { top: 0, left: 0, bottom: 40, right: 100 }, +) { + mockRect(source, sourceRect); + mockRect(target, targetRect); + + const centerX = ((targetRect.left ?? 0) + (targetRect.right ?? 100)) / 2; + const centerY = ((targetRect.top ?? 0) + (targetRect.bottom ?? 40)) / 2; + + fireEvent.pointerDown(source, { pointerId: 1, isPrimary: true, button: 0, clientX: 50, clientY: 20 }); + fireEvent.pointerMove(document, { pointerId: 1, clientX: centerX, clientY: centerY }); + fireEvent.pointerUp(document, { pointerId: 1, clientX: centerX, clientY: centerY }); +} + +// dnd-kit's PointerSensor swallows the very next click anywhere in the +// document for ~50ms after a drag ends (it stops propagation on one, to +// suppress the ghost click a real pointerup-after-drag would otherwise +// fire). A test that clicks something right after dragPointerTo needs to +// wait that out first, or the click can be silently eaten. +export async function waitOutDragClickGuard() { + await new Promise((resolve) => setTimeout(resolve, 60)); +} From 9691297ebd093eca6330bd7b118f71777d58e5cb Mon Sep 17 00:00:00 2001 From: moT01 <20648924+moT01@users.noreply.github.com> Date: Fri, 11 Sep 2026 12:56:25 -0500 Subject: [PATCH 7/9] chore: move shared components into shared folder --- .../astro-react/src/components/tasks/categorize.tsx | 6 +++--- .../astro-react/src/components/tasks/crossword.tsx | 4 ++-- .../astro-react/src/components/tasks/fill-in-the-blank.tsx | 4 ++-- .../astro-react/src/components/tasks/image-select.tsx | 4 ++-- .../astro-react/src/components/tasks/multiple-choice.tsx | 6 +++--- files/framework/astro-react/src/components/tasks/order.tsx | 6 +++--- .../astro-react/src/components/tasks/select-all.tsx | 6 +++--- .../src/components/tasks/{ => shared}/drag-grip.tsx | 0 .../src/components/tasks/{ => shared}/option-task.css | 0 .../src/components/tasks/{ => shared}/task-actions.test.tsx | 0 .../src/components/tasks/{ => shared}/task-actions.tsx | 2 +- .../astro-react/src/components/tasks/{ => shared}/task.css | 0 .../astro-react/src/components/tasks/text-select.tsx | 4 ++-- .../astro-react/src/hooks/use-focus-on-correct.test.ts | 2 +- .../framework/astro-react/src/hooks/use-focus-on-correct.ts | 2 +- 15 files changed, 23 insertions(+), 23 deletions(-) rename files/framework/astro-react/src/components/tasks/{ => shared}/drag-grip.tsx (100%) rename files/framework/astro-react/src/components/tasks/{ => shared}/option-task.css (100%) rename files/framework/astro-react/src/components/tasks/{ => shared}/task-actions.test.tsx (100%) rename files/framework/astro-react/src/components/tasks/{ => shared}/task-actions.tsx (94%) rename files/framework/astro-react/src/components/tasks/{ => shared}/task.css (100%) diff --git a/files/framework/astro-react/src/components/tasks/categorize.tsx b/files/framework/astro-react/src/components/tasks/categorize.tsx index da4a722..9174a01 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.tsx @@ -1,4 +1,4 @@ -import './task.css'; +import './shared/task.css'; import './categorize.css'; import { useEffect, useId, useState } from 'react'; import { @@ -19,9 +19,9 @@ import { sortableKeyboardCoordinates } from '@dnd-kit/sortable'; import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; -import { TaskActions, type Result } from './task-actions'; +import { TaskActions, type Result } from './shared/task-actions'; import { Button } from '../button'; -import { DragGrip } from './drag-grip'; +import { DragGrip } from './shared/drag-grip'; const UNPLACED = 'unplaced'; diff --git a/files/framework/astro-react/src/components/tasks/crossword.tsx b/files/framework/astro-react/src/components/tasks/crossword.tsx index 6dcd413..d43a967 100644 --- a/files/framework/astro-react/src/components/tasks/crossword.tsx +++ b/files/framework/astro-react/src/components/tasks/crossword.tsx @@ -1,4 +1,4 @@ -import './task.css'; +import './shared/task.css'; import './crossword.css'; import { useId, useMemo, useRef, useState } from 'react'; import type { FocusEvent, KeyboardEvent } from 'react'; @@ -6,7 +6,7 @@ import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; import { Button } from '../button'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; -import { TaskActions, type Result } from './task-actions'; +import { TaskActions, type Result } from './shared/task-actions'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', diff --git a/files/framework/astro-react/src/components/tasks/fill-in-the-blank.tsx b/files/framework/astro-react/src/components/tasks/fill-in-the-blank.tsx index a93bb26..07e9ab8 100644 --- a/files/framework/astro-react/src/components/tasks/fill-in-the-blank.tsx +++ b/files/framework/astro-react/src/components/tasks/fill-in-the-blank.tsx @@ -1,9 +1,9 @@ -import './task.css'; +import './shared/task.css'; import './fill-in-the-blank.css'; import { useId, useState } from 'react'; import type { Task } from '../../lib/curriculum-tasks'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; -import { TaskActions, type Result } from './task-actions'; +import { TaskActions, type Result } from './shared/task-actions'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', diff --git a/files/framework/astro-react/src/components/tasks/image-select.tsx b/files/framework/astro-react/src/components/tasks/image-select.tsx index 411d67f..0b8c26b 100644 --- a/files/framework/astro-react/src/components/tasks/image-select.tsx +++ b/files/framework/astro-react/src/components/tasks/image-select.tsx @@ -1,11 +1,11 @@ -import './task.css'; +import './shared/task.css'; import './image-select.css'; import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'; import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; import { Button } from '../button'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; -import { TaskActions, type Result } from './task-actions'; +import { TaskActions, type Result } from './shared/task-actions'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', diff --git a/files/framework/astro-react/src/components/tasks/multiple-choice.tsx b/files/framework/astro-react/src/components/tasks/multiple-choice.tsx index 5fe6d28..a86fb89 100644 --- a/files/framework/astro-react/src/components/tasks/multiple-choice.tsx +++ b/files/framework/astro-react/src/components/tasks/multiple-choice.tsx @@ -1,10 +1,10 @@ -import './task.css'; -import './option-task.css'; +import './shared/task.css'; +import './shared/option-task.css'; import { useId, useState } from 'react'; import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; -import { TaskActions, type Result } from './task-actions'; +import { TaskActions, type Result } from './shared/task-actions'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', diff --git a/files/framework/astro-react/src/components/tasks/order.tsx b/files/framework/astro-react/src/components/tasks/order.tsx index 2aa1655..ea1b017 100644 --- a/files/framework/astro-react/src/components/tasks/order.tsx +++ b/files/framework/astro-react/src/components/tasks/order.tsx @@ -1,4 +1,4 @@ -import './task.css'; +import './shared/task.css'; import './order.css'; import { useEffect, useId, useState } from 'react'; import { @@ -25,8 +25,8 @@ import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; import { Button } from '../button'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; -import { TaskActions, type Result } from './task-actions'; -import { DragGrip } from './drag-grip'; +import { TaskActions, type Result } from './shared/task-actions'; +import { DragGrip } from './shared/drag-grip'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', diff --git a/files/framework/astro-react/src/components/tasks/select-all.tsx b/files/framework/astro-react/src/components/tasks/select-all.tsx index fd39154..e2ff02a 100644 --- a/files/framework/astro-react/src/components/tasks/select-all.tsx +++ b/files/framework/astro-react/src/components/tasks/select-all.tsx @@ -1,11 +1,11 @@ -import './task.css'; -import './option-task.css'; +import './shared/task.css'; +import './shared/option-task.css'; import { useId, useRef, useState } from 'react'; import type { KeyboardEvent } from 'react'; import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; -import { TaskActions, type Result } from './task-actions'; +import { TaskActions, type Result } from './shared/task-actions'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', diff --git a/files/framework/astro-react/src/components/tasks/drag-grip.tsx b/files/framework/astro-react/src/components/tasks/shared/drag-grip.tsx similarity index 100% rename from files/framework/astro-react/src/components/tasks/drag-grip.tsx rename to files/framework/astro-react/src/components/tasks/shared/drag-grip.tsx diff --git a/files/framework/astro-react/src/components/tasks/option-task.css b/files/framework/astro-react/src/components/tasks/shared/option-task.css similarity index 100% rename from files/framework/astro-react/src/components/tasks/option-task.css rename to files/framework/astro-react/src/components/tasks/shared/option-task.css diff --git a/files/framework/astro-react/src/components/tasks/task-actions.test.tsx b/files/framework/astro-react/src/components/tasks/shared/task-actions.test.tsx similarity index 100% rename from files/framework/astro-react/src/components/tasks/task-actions.test.tsx rename to files/framework/astro-react/src/components/tasks/shared/task-actions.test.tsx diff --git a/files/framework/astro-react/src/components/tasks/task-actions.tsx b/files/framework/astro-react/src/components/tasks/shared/task-actions.tsx similarity index 94% rename from files/framework/astro-react/src/components/tasks/task-actions.tsx rename to files/framework/astro-react/src/components/tasks/shared/task-actions.tsx index 3bc849a..565754a 100644 --- a/files/framework/astro-react/src/components/tasks/task-actions.tsx +++ b/files/framework/astro-react/src/components/tasks/shared/task-actions.tsx @@ -1,6 +1,6 @@ import './task.css'; import type { ReactNode } from 'react'; -import { Button } from '../button'; +import { Button } from '../../button'; export type Result = 'correct' | 'incorrect' | 'unanswered'; diff --git a/files/framework/astro-react/src/components/tasks/task.css b/files/framework/astro-react/src/components/tasks/shared/task.css similarity index 100% rename from files/framework/astro-react/src/components/tasks/task.css rename to files/framework/astro-react/src/components/tasks/shared/task.css diff --git a/files/framework/astro-react/src/components/tasks/text-select.tsx b/files/framework/astro-react/src/components/tasks/text-select.tsx index 774fc5c..44bf4dc 100644 --- a/files/framework/astro-react/src/components/tasks/text-select.tsx +++ b/files/framework/astro-react/src/components/tasks/text-select.tsx @@ -1,4 +1,4 @@ -import './task.css'; +import './shared/task.css'; import './text-select.css'; import { Fragment, useId, useRef, useState } from 'react'; import type { KeyboardEvent } from 'react'; @@ -6,7 +6,7 @@ import type { Task } from '../../lib/curriculum-tasks'; import { Markdown } from '../markdown'; import { Button } from '../button'; import { useFocusOnCorrect } from '../../hooks/use-focus-on-correct'; -import { TaskActions, type Result } from './task-actions'; +import { TaskActions, type Result } from './shared/task-actions'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', diff --git a/files/framework/astro-react/src/hooks/use-focus-on-correct.test.ts b/files/framework/astro-react/src/hooks/use-focus-on-correct.test.ts index 38eb618..2338b42 100644 --- a/files/framework/astro-react/src/hooks/use-focus-on-correct.test.ts +++ b/files/framework/astro-react/src/hooks/use-focus-on-correct.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from "vitest"; import { renderHook } from "@testing-library/react"; import { useFocusOnCorrect } from "./use-focus-on-correct"; -import type { Result } from "../components/tasks/task-actions"; +import type { Result } from "../components/tasks/shared/task-actions"; describe(useFocusOnCorrect, () => { it("focuses the ref element when result becomes correct", () => { diff --git a/files/framework/astro-react/src/hooks/use-focus-on-correct.ts b/files/framework/astro-react/src/hooks/use-focus-on-correct.ts index fa9c06b..d4d4fe9 100644 --- a/files/framework/astro-react/src/hooks/use-focus-on-correct.ts +++ b/files/framework/astro-react/src/hooks/use-focus-on-correct.ts @@ -1,5 +1,5 @@ import { useEffect, useRef } from 'react'; -import type { Result } from '../components/tasks/task-actions'; +import type { Result } from '../components/tasks/shared/task-actions'; export function useFocusOnCorrect(result: Result | null) { const ref = useRef(null); From db0b17ad61834c43f153d5a46a6e889d28414c55 Mon Sep 17 00:00:00 2001 From: moT01 <20648924+moT01@users.noreply.github.com> Date: Mon, 14 Sep 2026 07:58:41 -0500 Subject: [PATCH 8/9] fix: order tasks --- .../components/tasks/fill-in-the-blank.css | 2 +- .../src/components/tasks/order.css | 16 ++++++++++ .../src/components/tasks/order.test.tsx | 18 +++-------- .../src/components/tasks/order.tsx | 31 +++++++------------ 4 files changed, 33 insertions(+), 34 deletions(-) diff --git a/files/framework/astro-react/src/components/tasks/fill-in-the-blank.css b/files/framework/astro-react/src/components/tasks/fill-in-the-blank.css index b57f5dc..e7bb92f 100644 --- a/files/framework/astro-react/src/components/tasks/fill-in-the-blank.css +++ b/files/framework/astro-react/src/components/tasks/fill-in-the-blank.css @@ -9,7 +9,7 @@ padding: 0.1em var(--space-xs); border: 1px solid var(--quaternary-background); border-radius: var(--radius-sm); - background: var(--primary-background); + background: var(--secondary-background); color: var(--primary-color); font: inherit; text-align: center; diff --git a/files/framework/astro-react/src/components/tasks/order.css b/files/framework/astro-react/src/components/tasks/order.css index fa4f837..0b298fb 100644 --- a/files/framework/astro-react/src/components/tasks/order.css +++ b/files/framework/astro-react/src/components/tasks/order.css @@ -4,7 +4,23 @@ gap: var(--space-xs); } +.order-row { + display: flex; + align-items: center; + gap: var(--space-sm); +} + +.order-row .item-card { + flex: 1; + min-width: 0; +} + .order-position { + flex-shrink: 0; font-weight: 700; min-width: 1.5rem; } + +.unshuffled .order-position { + visibility: hidden; +} diff --git a/files/framework/astro-react/src/components/tasks/order.test.tsx b/files/framework/astro-react/src/components/tasks/order.test.tsx index 423c693..fa8bd5f 100644 --- a/files/framework/astro-react/src/components/tasks/order.test.tsx +++ b/files/framework/astro-react/src/components/tasks/order.test.tsx @@ -12,10 +12,6 @@ const task: Extract = { }; beforeEach(() => { - // Deterministic shuffle: Math.random always returns 0.1 - // Fisher-Yates on ["Alpha","Beta","Gamma"] with 0.1: - // i=2: j=floor(0.1*3)=0, swap [2],[0] → ["Gamma","Beta","Alpha"] - // i=1: j=floor(0.1*2)=0, swap [1],[0] → ["Beta","Gamma","Alpha"] vi.spyOn(Math, "random").mockReturnValue(0.1); }); @@ -23,18 +19,14 @@ function getItemOrder(): string[] { const group = screen.getByRole("group", { name: "Put these in order:" }); return within(group) .queryAllByText((_, element) => element?.className === "item-card") - .map((element) => element.textContent?.replace(/^\d+\.\s*/, "") ?? ""); + .map((element) => element.textContent ?? ""); } -// Sortable collision detection compares the dragged row against every other -// row's rect, not just the drop target - so, unlike categorize's separate -// zones, every row needs a distinct, stacked rect or the drop can land on -// the wrong neighbor. const ROW_HEIGHT = 40; function mockRowRects(order: string[]) { order.forEach((text, index) => { - const row = screen.getByText(text).closest(".item-card"); + const row = screen.getByText(text).closest(".order-row"); if (row) mockRect(row, { top: index * ROW_HEIGHT, left: 0, bottom: (index + 1) * ROW_HEIGHT, right: 100 }); }); } @@ -42,8 +34,8 @@ function mockRowRects(order: string[]) { function dragItemToRow(itemText: string, targetText: string, currentOrder: string[]) { mockRowRects(currentOrder); const item = screen.getByText(itemText); - const sourceRow = item.closest(".item-card"); - const targetRow = screen.getByText(targetText).closest(".item-card"); + const sourceRow = item.closest(".order-row"); + const targetRow = screen.getByText(targetText).closest(".order-row"); if (!sourceRow || !targetRow) throw new Error("Could not find row"); dragPointerTo(item, targetRow, targetRow.getBoundingClientRect(), sourceRow.getBoundingClientRect()); @@ -69,8 +61,6 @@ describe(Order, () => { const user = userEvent.setup(); render(); - // Shuffled: ["Beta", "Gamma", "Alpha"] - dragging Alpha to the front - // gives the correct order in one move. dragItemToRow("Alpha", "Beta", ["Beta", "Gamma", "Alpha"]); await waitOutDragClickGuard(); await user.click(screen.getByRole("button", { name: /check answer/i })); diff --git a/files/framework/astro-react/src/components/tasks/order.tsx b/files/framework/astro-react/src/components/tasks/order.tsx index ea1b017..91e174c 100644 --- a/files/framework/astro-react/src/components/tasks/order.tsx +++ b/files/framework/astro-react/src/components/tasks/order.tsx @@ -54,26 +54,22 @@ type RowProps = { }; function Row({ id, disabled }: RowProps) { - // Unlike categorize's plain useDraggable, order's items need to visibly - // slide into their new slots as you drag past them - that's what applying - // transform/transition here does; DragOverlay only covers the one being held. - const { attributes, listeners, setNodeRef, transform, transition, isDragging, index } = useSortable({ - id, - disabled, - }); + const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging, index } = + useSortable({ id, disabled }); const style = { transform: CSS.Transform.toString(transform), transition }; return ( -
- +
{index + 1}. - {id} +
+ + {id} +
); } @@ -125,9 +121,6 @@ export function Order({ task, onCorrect }: OrderProps) { setActiveId(String(event.active.id)); } - // A single sortable list animates the reorder preview itself while - // dragging (each row's own transform), so the actual order only needs to - // be committed once, here - no live relocation or cancel-revert needed. function handleDragEnd(event: DragEndEvent) { const { active, over } = event; setActiveId(null); From 17de2887c9a40af87d9fdc22b4ff4ab11b4be2f6 Mon Sep 17 00:00:00 2001 From: moT01 <20648924+moT01@users.noreply.github.com> Date: Mon, 14 Sep 2026 09:22:05 -0500 Subject: [PATCH 9/9] fix: comments --- .../astro-react/src/components/tasks/shared/task.css | 1 - files/framework/astro-react/src/test-utils/dnd.ts | 12 ------------ 2 files changed, 13 deletions(-) diff --git a/files/framework/astro-react/src/components/tasks/shared/task.css b/files/framework/astro-react/src/components/tasks/shared/task.css index b862e68..1fa561d 100644 --- a/files/framework/astro-react/src/components/tasks/shared/task.css +++ b/files/framework/astro-react/src/components/tasks/shared/task.css @@ -34,7 +34,6 @@ color: var(--danger-color); } -/* Draggable item card, shared by task types that use dnd-kit (categorize, order). */ .item-card { display: flex; align-items: center; diff --git a/files/framework/astro-react/src/test-utils/dnd.ts b/files/framework/astro-react/src/test-utils/dnd.ts index 2574196..e41ab3f 100644 --- a/files/framework/astro-react/src/test-utils/dnd.ts +++ b/files/framework/astro-react/src/test-utils/dnd.ts @@ -1,10 +1,6 @@ import { vi } from "vitest"; import { fireEvent } from "@testing-library/react"; -// dnd-kit measures real DOM rects to resolve collisions, which jsdom doesn't -// compute (everything is 0x0 by default). Stubbing getBoundingClientRect on -// the elements involved lets a real pointer-driven drag resolve to a -// specific drop target, the same way it would in a real layout. export function mockRect(element: Element, rect: Partial) { vi.spyOn(element, "getBoundingClientRect").mockReturnValue({ x: 0, @@ -20,9 +16,6 @@ export function mockRect(element: Element, rect: Partial) { }); } -// Fires a real pointer-driven drag from `source` into `target`'s mocked -// rect. isPrimary/button are required for PointerSensor's activator to pick -// up the drag at all. export function dragPointerTo( source: Element, target: Element, @@ -40,11 +33,6 @@ export function dragPointerTo( fireEvent.pointerUp(document, { pointerId: 1, clientX: centerX, clientY: centerY }); } -// dnd-kit's PointerSensor swallows the very next click anywhere in the -// document for ~50ms after a drag ends (it stops propagation on one, to -// suppress the ghost click a real pointerup-after-drag would otherwise -// fire). A test that clicks something right after dragPointerTo needs to -// wait that out first, or the click can be silently eaten. export async function waitOutDragClickGuard() { await new Promise((resolve) => setTimeout(resolve, 60)); }