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", diff --git a/files/framework/astro-react/src/components/tasks/categorize.css b/files/framework/astro-react/src/components/tasks/categorize.css index b5ac918..917c031 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); } @@ -16,79 +17,31 @@ } .zone { - position: relative; border: 1px solid var(--quaternary-background); border-radius: var(--radius-md); - padding: var(--space-md); + padding: var(--space-sm); } .zone-heading { - position: relative; - z-index: 1; - pointer-events: none; - margin-bottom: var(--space-sm); + margin-bottom: var(--space-xs); 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; -} - -.item-row:not(:disabled):hover { - background: var(--quaternary-background); -} - -.item-row.selected { - background: var(--quaternary-background); - border-color: var(--highlight-color); - font-weight: 700; -} - -.item-row:disabled { - cursor: not-allowed; -} - -.unshuffled .item-row { - visibility: hidden; -} - -.zone-drop { - position: absolute; - inset: 0; - z-index: 0; - width: 100%; - height: 100%; - background: none; - border: none; - border-radius: var(--radius-md); - cursor: pointer; + min-height: 2rem; } -.zone-drop.active:not(:disabled):hover { - background: var(--quaternary-background); +.zone-empty { + border-style: dashed; } -.zone-drop:disabled { - cursor: default; +.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 7fd5275..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 } 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"; +import { dragPointerTo, waitOutDragClickGuard } from "../../test-utils/dnd"; const task: Extract = { type: "categorize", @@ -20,153 +21,132 @@ 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( {}} />); +// 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 }; - expect(getZoneItems("Items")).toEqual( - expect.arrayContaining(["Apple", "Banana", "Carrot"]), - ); +function dragItemToZone(itemText: string, zoneName: string) { + const item = screen.getByText(itemText); + const zone = screen.getByRole("group", { name: zoneName }); + const top = ZONE_TOP[zoneName]; + + dragPointerTo(item, zone, { top, left: 0, bottom: top + 150, right: 300 }); +} + +describe("findContainer", () => { + it("finds the container an item currently belongs to", () => { + const containers = { unplaced: ["a"], Fruit: ["b"] }; + + expect(findContainer(containers, "b")).toBe("Fruit"); }); - it("moves a selected item to a category zone", async () => { - const user = userEvent.setup(); + it("treats a container id as its own container", () => { + const containers = { unplaced: [], Fruit: [] }; - render( {}} />); + expect(findContainer(containers, "Fruit")).toBe("Fruit"); + }); - await user.click(screen.getByRole("button", { name: "Apple" })); - await user.click( - screen.getByRole("button", { - name: /move selected item to fruit/i, - }), - ); + it("returns undefined for an id that isn't in any container", () => { + const containers = { unplaced: ["a"] }; - expect(getZoneItems("Fruit")).toContain("Apple"); - expect(getZoneItems("Items")).not.toContain("Apple"); + expect(findContainer(containers, "z")).toBeUndefined(); }); +}); - it("moves an item back to unplaced when removed from a category", async () => { - const user = userEvent.setup(); +describe("moveItem", () => { + it("moves an item from one container to another", () => { + const containers = { unplaced: ["a", "b"], Fruit: [] }; + + const result = moveItem(containers, "a", "unplaced", "Fruit"); + + expect(result.unplaced).toEqual(["b"]); + expect(result.Fruit).toEqual(["a"]); + }); + + 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"); + + expect(result.Fruit).toEqual(["b", "c", "a"]); + }); +}); +describe(Categorize, () => { + it("starts with all items in the unplaced zone and categories empty", () => { render( {}} />); - // 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, - }), + expect(getZoneItems("Items")).toEqual( + expect.arrayContaining(["Apple", "Banana", "Carrot"]), ); + expect(getZoneItems("Fruit")).toHaveLength(0); + expect(getZoneItems("Vegetable")).toHaveLength(0); + }); - // 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, - }), - ); + it("shows a drop-here placeholder for an empty zone", () => { + render( {}} />); - expect(getZoneItems("Items")).toContain("Apple"); - expect(getZoneItems("Fruit")).not.toContain("Apple"); + expect(within(screen.getByRole("group", { name: "Fruit" })).getByText("Drop here")).toBeInTheDocument(); }); - it("shows correct feedback and calls onCorrect when all items are placed correctly", async () => { - const onCorrect = vi.fn<() => void>(); + it("shows unanswered feedback when not all items are placed", async () => { const user = userEvent.setup(); + render( {}} />); - render(); + await user.click(screen.getByRole("button", { name: /check answer/i })); - 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(screen.getByText("Place all items before checking.")).toBeInTheDocument(); + }); - await user.click( - screen.getByRole("button", { name: /check answer/i }), - ); + it("moves an item into a category by dragging it", () => { + render( {}} />); - expect(screen.getByRole("status")).toHaveTextContent("Correct!"); - expect(onCorrect).toHaveBeenCalledOnce(); + dragItemToZone("Apple", "Fruit"); + + expect(getZoneItems("Fruit")).toContain("Apple"); + expect(getZoneItems("Items")).not.toContain("Apple"); }); - it("shows incorrect feedback for wrong placements", 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( {}} />); - - // 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, - }), - ); + dragItemToZone("Apple", "Fruit"); + dragItemToZone("Banana", "Fruit"); + dragItemToZone("Carrot", "Vegetable"); - await user.click( - screen.getByRole("button", { name: /check answer/i }), - ); + await waitOutDragClickGuard(); + await user.click(screen.getByRole("button", { name: /check answer/i })); - expect(screen.getByRole("status")).toHaveTextContent( - "Not quite. Try again.", - ); + expect(screen.getByText("Correct!")).toBeInTheDocument(); + expect(onCorrect).toHaveBeenCalledOnce(); }); - it("shows unanswered feedback when not all items are placed", async () => { + it("shows incorrect feedback for a wrong placement", async () => { const user = userEvent.setup(); - render( {}} />); - await user.click( - screen.getByRole("button", { name: /check answer/i }), - ); + dragItemToZone("Apple", "Vegetable"); + dragItemToZone("Banana", "Fruit"); + dragItemToZone("Carrot", "Fruit"); - expect(screen.getByRole("status")).toHaveTextContent( - "Place all items before checking.", - ); + await waitOutDragClickGuard(); + await user.click(screen.getByRole("button", { name: /check answer/i })); + + expect(screen.getByText("Not quite. Try again.")).toBeInTheDocument(); }); - it("resets all items to unplaced", async () => { + 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 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 63434cc..9174a01 100644 --- a/files/framework/astro-react/src/components/tasks/categorize.tsx +++ b/files/framework/astro-react/src/components/tasks/categorize.tsx @@ -1,13 +1,29 @@ -import './task.css'; +import './shared/task.css'; import './categorize.css'; import { useEffect, useId, useState } from 'react'; +import { + DndContext, + DragOverlay, + KeyboardSensor, + PointerSensor, + closestCorners, + useDraggable, + useDroppable, + useSensor, + useSensors, + type Announcements, + type DragOverEvent, + type DragStartEvent, +} from '@dnd-kit/core'; +import { sortableKeyboardCoordinates } from '@dnd-kit/sortable'; 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'; +import { Button } from '../button'; +import { DragGrip } from './shared/drag-grip'; -const UNPLACED = null; +const UNPLACED = 'unplaced'; const FEEDBACK_MESSAGES: Record = { correct: 'Correct!', @@ -15,10 +31,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 +42,198 @@ function shuffle(items: T[]): T[] { return copy; } +function zoneLabel(id: string): string { + return id === UNPLACED ? 'Items' : id; +} + +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)); +} + +export function moveItem( + containers: Containers, + activeId: string, + activeContainer: string, + overContainer: string, +): Containers { + return { + ...containers, + [activeContainer]: containers[activeContainer].filter((item) => item !== activeId), + [overContainer]: [...containers[overContainer], activeId], + }; +} + +type ItemProps = { + id: string; + disabled: boolean; +}; + +function Item({ id, disabled }: ItemProps) { + const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ + id, + disabled, + }); + + return ( +
+ + {id} +
+ ); +} + type ZoneProps = { - label: string; - dropLabel: string; + id: string; items: string[]; - selectedItem: string | null; + activeId: 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, activeId, disabled }: ZoneProps) { + const { setNodeRef } = useDroppable({ id, disabled }); + const label = zoneLabel(id); + const settledCount = items.filter((item) => item !== activeId).length; + + const classNames = ['zone']; + if (settledCount === 0) classNames.push('zone-empty'); return ( -
+

{label}

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

Drop here

: null}
-
); } +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 [dragStartContainer, setDragStartContainer] = 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) { + const activeId = String(event.active.id); + setActiveId(activeId); + setDragStartContainer(findContainer(containers, activeId) ?? null); } - function handlePlace(categoryName: string | null) { - if (!selectedItem) { - setAnnouncement('Select an item first.'); - return; - } + function handleDragOver(event: DragOverEvent) { + const { active, over } = event; + if (!over) return; - setPlacements((current) => ({ ...current, [selectedItem]: categoryName })); - setAnnouncement( - categoryName - ? `${selectedItem} moved to ${categoryName}.` - : `${selectedItem} moved back to the unplaced items.`, - ); - setSelectedItem(null); - setResult(null); + const activeId = String(active.id); + const overContainer = findContainer(containers, String(over.id)); + const activeContainer = findContainer(containers, activeId); + + if (!activeContainer || !overContainer || activeContainer === overContainer) return; + + setContainers((previous) => moveItem(previous, activeId, activeContainer, overContainer)); } - function handleReset() { - setPlacements(Object.fromEntries(allItems.map((entry) => [entry.item, UNPLACED]))); - setSelectedItem(null); + function handleDragEnd() { + setActiveId(null); + setDragStartContainer(null); setResult(null); - setAnnouncement('All items reset.'); + } + + function handleDragCancel() { + 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() { - 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 +241,45 @@ 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 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.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/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.css b/files/framework/astro-react/src/components/tasks/order.css index c5917a3..0b298fb 100644 --- a/files/framework/astro-react/src/components/tasks/order.css +++ b/files/framework/astro-react/src/components/tasks/order.css @@ -4,35 +4,23 @@ 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 { +.order-row .item-card { flex: 1; min-width: 0; } -.order-controls { - display: flex; - gap: var(--space-xs); +.order-position { + flex-shrink: 0; + font-weight: 700; + min-width: 1.5rem; } -.order-controls button:disabled { - cursor: not-allowed; - opacity: 0.6; +.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 a0b0f82..fa8bd5f 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", @@ -11,124 +12,80 @@ 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); }); -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 ?? ""); } -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" }), - ); +const ROW_HEIGHT = 40; - expect(getItemOrder()).toEqual(["Gamma", "Beta", "Alpha"]); +function mockRowRects(order: string[]) { + order.forEach((text, index) => { + 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 }); }); +} - 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(".order-row"); + const targetRow = screen.getByText(targetText).closest(".order-row"); + 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!"); + 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..91e174c 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 './shared/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 { TaskActions, type Result } from './shared/task-actions'; +import { DragGrip } from './shared/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,32 @@ function shuffle(items: T[]): T[] { return copy; } +type RowProps = { + id: string; + disabled: boolean; +}; + +function Row({ id, disabled }: RowProps) { + const { attributes, listeners, setNodeRef, setActivatorNodeRef, 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 +82,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 +92,94 @@ 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); - captureRowPositions(); - const next = [...items]; - [next[index], next[targetIndex]] = [next[targetIndex], next[index]]; - setItems(next); + 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)); + } + + function handleDragEnd(event: DragEndEvent) { + const { active, over } = event; + setActiveId(null); + if (!over || active.id === over.id) return; + + 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/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/shared/drag-grip.tsx b/files/framework/astro-react/src/components/tasks/shared/drag-grip.tsx new file mode 100644 index 0000000..ccd0f3b --- /dev/null +++ b/files/framework/astro-react/src/components/tasks/shared/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/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/shared/task.css b/files/framework/astro-react/src/components/tasks/shared/task.css new file mode 100644 index 0000000..1fa561d --- /dev/null +++ b/files/framework/astro-react/src/components/tasks/shared/task.css @@ -0,0 +1,70 @@ +.task { + display: flex; + flex-direction: column; + gap: var(--space-md); + background: var(--tertiary-background); + border-radius: var(--radius-md); + padding: var(--space-lg); + margin-bottom: var(--space-lg); +} + +.task input:disabled { + cursor: not-allowed; +} + +.task-actions { + display: flex; + align-items: center; + gap: var(--space-md); +} + +.feedback { + flex: 1; + min-width: 0; + margin: 0; + font-weight: 700; + min-height: 1.5em; +} + +.feedback.correct { + color: var(--success-color); +} + +.feedback.incorrect { + color: var(--danger-color); +} + +.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/task.css b/files/framework/astro-react/src/components/tasks/task.css deleted file mode 100644 index cb58cd2..0000000 --- a/files/framework/astro-react/src/components/tasks/task.css +++ /dev/null @@ -1,35 +0,0 @@ -.task { - display: flex; - flex-direction: column; - gap: var(--space-md); - background: var(--tertiary-background); - border-radius: var(--radius-md); - padding: var(--space-lg); - margin-bottom: var(--space-lg); -} - -.task input:disabled { - cursor: not-allowed; -} - -.task-actions { - display: flex; - align-items: center; - gap: var(--space-md); -} - -.feedback { - flex: 1; - min-width: 0; - margin: 0; - font-weight: 700; - min-height: 1.5em; -} - -.feedback.correct { - color: var(--success-color); -} - -.feedback.incorrect { - color: var(--danger-color); -} 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); 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..e41ab3f --- /dev/null +++ b/files/framework/astro-react/src/test-utils/dnd.ts @@ -0,0 +1,38 @@ +import { vi } from "vitest"; +import { fireEvent } from "@testing-library/react"; + +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, + }); +} + +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 }); +} + +export async function waitOutDragClickGuard() { + await new Promise((resolve) => setTimeout(resolve, 60)); +}