diff --git a/__tests__/components/backlog/backlog-split-pane.test.tsx b/__tests__/components/backlog/backlog-split-pane.test.tsx index f57e53f..4505a80 100644 --- a/__tests__/components/backlog/backlog-split-pane.test.tsx +++ b/__tests__/components/backlog/backlog-split-pane.test.tsx @@ -1,9 +1,16 @@ // @vitest-environment jsdom import { describe, it, expect, beforeEach } from 'vitest' import { render, screen } from '@testing-library/react' -import { useSelectionStore } from '@/stores/selection-store' +import { useProductWorkspaceStore } from '@/stores/product-workspace/store' import { BacklogSplitPane } from '@/components/backlog/backlog-split-pane' +function setSelection(pbiId: string | null, storyId: string | null) { + useProductWorkspaceStore.setState((s) => { + s.context.activePbiId = pbiId + s.context.activeStoryId = storyId + }) +} + const PANES = [
PBI pane
,
Stories pane
, @@ -22,7 +29,7 @@ function renderPane() { } beforeEach(() => { - useSelectionStore.setState({ selectedPbiId: null, selectedStoryId: null }) + setSelection(null, null) // Force mobile viewport Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 600 }) window.dispatchEvent(new Event('resize')) @@ -37,7 +44,7 @@ describe('BacklogSplitPane auto-switch', () => { it('auto-switches to tab 1 when PBI is selected', () => { const { rerender } = renderPane() - useSelectionStore.setState({ selectedPbiId: 'pbi-1', selectedStoryId: null }) + setSelection('pbi-1', null) rerender( { it('auto-switches to tab 2 when story is selected', () => { const { rerender } = renderPane() - useSelectionStore.setState({ selectedPbiId: 'pbi-1', selectedStoryId: 'story-1' }) + setSelection('pbi-1', 'story-1') rerender( { it('switches to tab 1 on cascade-reset (story cleared when new PBI selected)', () => { // Start with story selected (tab 2) - useSelectionStore.setState({ selectedPbiId: 'pbi-1', selectedStoryId: 'story-1' }) + setSelection('pbi-1', 'story-1') const { rerender } = renderPane() // Cascade-reset: new PBI → story clears - useSelectionStore.setState({ selectedPbiId: 'pbi-2', selectedStoryId: null }) + setSelection('pbi-2', null) rerender( { + s.context.activeProduct = null + s.context.activePbiId = null + s.context.activeStoryId = null + s.context.activeTaskId = null + s.entities.pbisById = {} + s.entities.storiesById = Object.fromEntries(STORIES.map((st) => [st.id, st])) + s.entities.tasksById = Object.fromEntries(TASKS.map((t) => [t.id, t])) + s.relations.pbiIds = [] + s.relations.storyIdsByPbi = { [PBI_ID]: STORIES.map((st) => st.id) } + s.relations.taskIdsByStory = { [STORY_ID]: TASKS.map((t) => t.id) } + }) +} + +function selectPbi(pbiId: string | null) { + useProductWorkspaceStore.setState((s) => { + s.context.activePbiId = pbiId + s.context.activeStoryId = null + s.context.activeTaskId = null + }) +} + +function selectStory(pbiId: string | null, storyId: string | null) { + useProductWorkspaceStore.setState((s) => { + s.context.activePbiId = pbiId + s.context.activeStoryId = storyId }) } @@ -89,42 +113,40 @@ describe('Backlog 3-pane integration', () => { }) it('StoryPanel shows stories when PBI is selected', () => { - useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: null }) + selectPbi(PBI_ID) render() expect(screen.getByText('Eerste story')).toBeTruthy() }) - it('clicking a story dispatches selectStory to the store', () => { - useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: null }) + it('clicking a story dispatches setActiveStory to the workspace-store', () => { + selectPbi(PBI_ID) render() fireEvent.click(screen.getByText('Eerste story')) - expect(useSelectionStore.getState().selectedStoryId).toBe(STORY_ID) + expect(useProductWorkspaceStore.getState().context.activeStoryId).toBe(STORY_ID) }) - it('cascade-reset: selecting different PBI clears selectedStoryId', () => { - useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: STORY_ID }) - useSelectionStore.getState().selectPbi(ALT_PBI_ID) - expect(useSelectionStore.getState().selectedStoryId).toBeNull() + it('cascade-reset: selecting different PBI clears activeStoryId', () => { + selectStory(PBI_ID, STORY_ID) + useProductWorkspaceStore.getState().setActivePbi(ALT_PBI_ID) + expect(useProductWorkspaceStore.getState().context.activeStoryId).toBeNull() }) it('TaskPanel shows tasks after story is selected', () => { - useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: STORY_ID }) + selectStory(PBI_ID, STORY_ID) render() expect(screen.getByText('Eerste taak')).toBeTruthy() }) it('TaskPanel shows empty state after cascade-reset', () => { - useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: STORY_ID }) + selectStory(PBI_ID, STORY_ID) render() - // Reset via selectPbi - useSelectionStore.getState().selectPbi(ALT_PBI_ID) - // Re-render reflects new store state + useProductWorkspaceStore.getState().setActivePbi(ALT_PBI_ID) render() expect(screen.getAllByText('Selecteer een story om de taken te bekijken.').length).toBeGreaterThan(0) }) it('selected story card has isSelected highlight class applied', () => { - useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: STORY_ID }) + selectStory(PBI_ID, STORY_ID) const { container } = render() // bg-primary-container is applied when isSelected const selected = container.querySelector('.bg-primary-container') diff --git a/__tests__/components/backlog/task-panel.test.tsx b/__tests__/components/backlog/task-panel.test.tsx index 97a5894..69b844c 100644 --- a/__tests__/components/backlog/task-panel.test.tsx +++ b/__tests__/components/backlog/task-panel.test.tsx @@ -1,8 +1,33 @@ // @vitest-environment jsdom import { describe, it, expect, vi, beforeEach } from 'vitest' import { render, screen, fireEvent } from '@testing-library/react' -import { useSelectionStore } from '@/stores/selection-store' -import { useBacklogStore } from '@/stores/backlog-store' +import { useProductWorkspaceStore } from '@/stores/product-workspace/store' +import type { BacklogTask } from '@/stores/product-workspace/types' + +function resetWorkspace() { + useProductWorkspaceStore.setState((s) => { + s.context.activeProduct = null + s.context.activePbiId = null + s.context.activeStoryId = null + s.context.activeTaskId = null + s.entities.pbisById = {} + s.entities.storiesById = {} + s.entities.tasksById = {} + s.relations.pbiIds = [] + s.relations.storyIdsByPbi = {} + s.relations.taskIdsByStory = {} + }) +} + +function setActiveStoryAndTasks(storyId: string | null, tasks: BacklogTask[] = []) { + useProductWorkspaceStore.setState((s) => { + s.context.activeStoryId = storyId + if (storyId) { + s.relations.taskIdsByStory[storyId] = tasks.map((t) => t.id) + for (const task of tasks) s.entities.tasksById[task.id] = task + } + }) +} // Mock next/navigation const mockPush = vi.fn() @@ -57,8 +82,7 @@ function renderPanel(isDemo = false) { describe('TaskPanel', () => { beforeEach(() => { mockPush.mockClear() - useSelectionStore.setState({ selectedStoryId: null, selectedPbiId: null }) - useBacklogStore.setState({ pbis: [], storiesByPbi: {}, tasksByStory: {} }) + resetWorkspace() }) it('shows empty state when no story is selected', () => { @@ -67,40 +91,35 @@ describe('TaskPanel', () => { }) it('shows empty state with action when story selected but no tasks', () => { - useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null }) - useBacklogStore.setState({ tasksByStory: { [STORY_ID]: [] } }) + setActiveStoryAndTasks(STORY_ID, []) renderPanel() expect(screen.getByText('Nog geen taken voor deze story.')).toBeTruthy() expect(screen.getAllByText('+ Nieuwe taak').length).toBeGreaterThanOrEqual(1) }) it('renders task cards when tasks are present', () => { - useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null }) - useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } }) + setActiveStoryAndTasks(STORY_ID, TASKS) renderPanel() expect(screen.getByText('Eerste taak')).toBeTruthy() expect(screen.getByText('Tweede taak')).toBeTruthy() }) it('renders status badges on task cards', () => { - useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null }) - useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } }) + setActiveStoryAndTasks(STORY_ID, TASKS) renderPanel() expect(screen.getByText('To Do')).toBeTruthy() expect(screen.getByText('Bezig')).toBeTruthy() }) it('task cards are rendered inside a grid container', () => { - useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null }) - useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } }) + setActiveStoryAndTasks(STORY_ID, TASKS) const { container } = renderPanel() const grid = container.querySelector('.grid') expect(grid).toBeTruthy() }) it('clicking + button calls router.push with newTask params', () => { - useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null }) - useBacklogStore.setState({ tasksByStory: { [STORY_ID]: [] } }) + setActiveStoryAndTasks(STORY_ID, []) renderPanel() const buttons = screen.getAllByText('+ Nieuwe taak') fireEvent.click(buttons[0]) @@ -108,16 +127,14 @@ describe('TaskPanel', () => { }) it('clicking task card calls router.push with editTask param', () => { - useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null }) - useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } }) + setActiveStoryAndTasks(STORY_ID, TASKS) renderPanel() fireEvent.click(screen.getByText('Eerste taak')) expect(mockPush).toHaveBeenCalledWith(`${CLOSE_PATH}?editTask=task-1`) }) it('+ button is disabled in demo mode', () => { - useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null }) - useBacklogStore.setState({ tasksByStory: { [STORY_ID]: [] } }) + setActiveStoryAndTasks(STORY_ID, []) renderPanel(true) const btn = screen.getAllByText('+ Nieuwe taak')[0].closest('button') expect(btn).toBeTruthy() @@ -125,8 +142,7 @@ describe('TaskPanel', () => { }) it('cards have no drag listeners in demo mode (whole-card drag disabled)', () => { - useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null }) - useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } }) + setActiveStoryAndTasks(STORY_ID, TASKS) // In demo mode, listeners ({} from useSortable mock) are not spread onto the card. // The mock always returns empty listeners, so we just verify the cards render without error. renderPanel(true) diff --git a/components/backlog/backlog-split-pane.tsx b/components/backlog/backlog-split-pane.tsx index 882f13b..8a82a95 100644 --- a/components/backlog/backlog-split-pane.tsx +++ b/components/backlog/backlog-split-pane.tsx @@ -1,13 +1,16 @@ 'use client' import { useState } from 'react' -import { useSelectionStore } from '@/stores/selection-store' +import { useProductWorkspaceStore } from '@/stores/product-workspace/store' import { SplitPane, type SplitPaneProps } from '@/components/split-pane/split-pane' type Props = Omit +// PBI-74 / T-848: leest active PBI/story-ids uit workspace-store. Primitives, +// dus geen useShallow nodig. export function BacklogSplitPane(props: Props) { - const { selectedPbiId, selectedStoryId } = useSelectionStore() + const selectedPbiId = useProductWorkspaceStore((s) => s.context.activePbiId) + const selectedStoryId = useProductWorkspaceStore((s) => s.context.activeStoryId) const [activeTab, setActiveTab] = useState(0) // React-recommended "derived state from props" pattern: update state during render diff --git a/components/backlog/pbi-list.tsx b/components/backlog/pbi-list.tsx index 77d8511..a21260e 100644 --- a/components/backlog/pbi-list.tsx +++ b/components/backlog/pbi-list.tsx @@ -25,9 +25,10 @@ import { CheckSquare, Square } from 'lucide-react' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' -import { useSelectionStore } from '@/stores/selection-store' -import { usePlannerStore } from '@/stores/planner-store' -import { useBacklogStore } from '@/stores/backlog-store' +import { useShallow } from 'zustand/react/shallow' +import { useProductWorkspaceStore } from '@/stores/product-workspace/store' +import { selectVisiblePbis } from '@/stores/product-workspace/selectors' +import type { BacklogPbi as WorkspacePbi } from '@/stores/product-workspace/types' import { deletePbiAction } from '@/actions/pbis' import { reorderPbisAction, updatePbiPriorityAction } from '@/actions/stories' import { cn } from '@/lib/utils' @@ -235,10 +236,13 @@ function SortablePbiRow({ } // --- Main component --- +// PBI-74 / T-849: leest pbis + actieve selectie uit workspace-store via +// useShallow-selector. DnD-mutaties via applyOptimisticMutation/rollback/settle. export function PbiList({ productId, isDemo }: PbiListProps) { - const pbis = useBacklogStore((s) => s.pbis) - const { selectedPbiId, selectPbi } = useSelectionStore() - const { pbiOrder, pbiPriority, initPbis, reorderPbis, rollbackPbis, updatePbiPriority } = usePlannerStore() + // selectVisiblePbis is gesorteerd op priority/sort_order; useShallow + // voorkomt re-render op ongerelateerde store-mutaties (G2). + const pbis = useProductWorkspaceStore(useShallow(selectVisiblePbis)) as WorkspacePbi[] + const selectedPbiId = useProductWorkspaceStore((s) => s.context.activePbiId) // Defaults match SSR; persisted values applied post-mount in the loader effect below. // This avoids hydration mismatch when localStorage holds non-default values. const [filterPriority, setFilterPriority] = useState('all') @@ -295,22 +299,11 @@ export function PbiList({ productId, isDemo }: PbiListProps) { useEffect(() => { if (prefsLoaded) localStorage.setItem('scrum4me:pbi_filter_status', filterStatus) }, [filterStatus, prefsLoaded]) useEffect(() => { if (prefsLoaded) localStorage.setItem('scrum4me:pbi_sort_dir', sortDir) }, [sortDir, prefsLoaded]) - // Sync server data into store — use stable string dep to avoid infinite loop - const pbiIdKey = pbis.map(p => p.id).join(',') - useEffect(() => { - initPbis(productId, pbiIdKey ? pbiIdKey.split(',') : []) - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [productId, pbiIdKey]) - - // Build ordered PBI list from store (or fall back to server order) - const order = pbiOrder[productId] ?? pbis.map(p => p.id) + // pbis komen al gesorteerd binnen via selectVisiblePbis (priority + sort_order). + // Geen aparte order/priority maps meer — workspace-store entities zijn de waarheid. const pbiMap = Object.fromEntries(pbis.map(p => [p.id, p])) - - // Apply priority overrides from store - const orderedPbis = order - .map(id => pbiMap[id]) - .filter(Boolean) - .map(p => ({ ...p, priority: pbiPriority[p.id] ?? p.priority })) + const order = pbis.map(p => p.id) + const orderedPbis = pbis const base = orderedPbis.filter(p => { if (filterPriority !== 'all' && p.priority !== filterPriority) return false @@ -353,30 +346,58 @@ export function PbiList({ productId, isDemo }: PbiListProps) { const overPbi = pbiMap[over.id as string] if (!activePbi || !overPbi) return - const prevOrder = [...order] - const oldIndex = order.indexOf(active.id as string) - const newIndex = order.indexOf(over.id as string) - const newOrder = arrayMove([...order], oldIndex, newIndex) + const store = useProductWorkspaceStore.getState() + const prevOrder = [...store.relations.pbiIds] + const oldIndex = prevOrder.indexOf(active.id as string) + const newIndex = prevOrder.indexOf(over.id as string) + if (oldIndex === -1 || newIndex === -1) return + const newOrder = arrayMove([...prevOrder], oldIndex, newIndex) - // Optimistic update - reorderPbis(productId, newOrder) + // Snapshot rollback-info en pas optimistisch toe. + const orderMutationId = store.applyOptimisticMutation({ + kind: 'pbi-order', + prevPbiIds: prevOrder, + }) + useProductWorkspaceStore.setState((s) => { + s.relations.pbiIds = newOrder + }) const priorityChanged = activePbi.priority !== overPbi.priority + let priorityMutationId: string | null = null + if (priorityChanged) { + priorityMutationId = store.applyOptimisticMutation({ + kind: 'entity-patch', + entity: 'pbi', + id: active.id as string, + prev: store.entities.pbisById[active.id as string], + }) + useProductWorkspaceStore.setState((s) => { + const pbi = s.entities.pbisById[active.id as string] + if (pbi) pbi.priority = overPbi.priority + }) + } startTransition(async () => { + const settle = () => { + const st = useProductWorkspaceStore.getState() + if (priorityMutationId) st.settleMutation(priorityMutationId) + st.settleMutation(orderMutationId) + } + const rollback = (msg: string) => { + const st = useProductWorkspaceStore.getState() + if (priorityMutationId) st.rollbackMutation(priorityMutationId) + st.rollbackMutation(orderMutationId) + toast.error(msg) + } + if (priorityChanged) { - updatePbiPriority(active.id as string, overPbi.priority) const result = await updatePbiPriorityAction(active.id as string, overPbi.priority, productId) - if (!result.success) { - rollbackPbis(productId, prevOrder) - toast.error('Prioriteit opslaan mislukt') - } + if (result.success) settle() + else rollback('Prioriteit opslaan mislukt') } else { const result = await reorderPbisAction(productId, newOrder) - if (!result.success) { - rollbackPbis(productId, prevOrder) - toast.error('Volgorde opslaan mislukt') - } + if (result.success) settle() + else rollback('Volgorde opslaan mislukt') } }) } @@ -384,7 +405,9 @@ export function PbiList({ productId, isDemo }: PbiListProps) { function handleDelete(id: string) { startTransition(async () => { await deletePbiAction(id) - if (selectedPbiId === id) selectPbi(null) + if (selectedPbiId === id) { + useProductWorkspaceStore.getState().setActivePbi(null) + } }) } @@ -561,7 +584,7 @@ export function PbiList({ productId, isDemo }: PbiListProps) { isDemo={isDemo} selectionMode={selectionMode} isChecked={selectedIds.has(pbi.id)} - onSelect={() => selectPbi(pbi.id)} + onSelect={() => useProductWorkspaceStore.getState().setActivePbi(pbi.id)} onToggleCheck={() => toggleCheck(pbi.id)} onEdit={() => setDialogState({ mode: 'edit', productId, pbi })} onDelete={() => handleDelete(pbi.id)} diff --git a/components/backlog/story-panel.tsx b/components/backlog/story-panel.tsx index c1dd2c1..539e277 100644 --- a/components/backlog/story-panel.tsx +++ b/components/backlog/story-panel.tsx @@ -25,9 +25,10 @@ import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { PanelNavBar } from '@/components/shared/panel-nav-bar' -import { useSelectionStore } from '@/stores/selection-store' -import { usePlannerStore } from '@/stores/planner-store' -import { useBacklogStore } from '@/stores/backlog-store' +import { useShallow } from 'zustand/react/shallow' +import { useProductWorkspaceStore } from '@/stores/product-workspace/store' +import { selectStoriesForActivePbi } from '@/stores/product-workspace/selectors' +import type { BacklogStory as WorkspaceStory } from '@/stores/product-workspace/types' import { reorderStoriesAction } from '@/actions/stories' import { StoryDialog, type StoryDialogState } from './story-dialog' import { debugProps } from '@/lib/debug' @@ -122,10 +123,12 @@ function SortableStoryBlock({ } // --- Main component --- +// PBI-74 / T-850: leest stories voor active PBI via selectStoriesForActivePbi +// (useShallow). DnD via applyOptimisticMutation('story-order'). export function StoryPanel({ productId, isDemo }: StoryPanelProps) { - const { selectedPbiId, selectedStoryId, selectStory } = useSelectionStore() - const storiesByPbi = useBacklogStore((s) => s.storiesByPbi) - const { storyOrder, initStories, reorderStories, rollbackStories } = usePlannerStore() + const selectedPbiId = useProductWorkspaceStore((s) => s.context.activePbiId) + const selectedStoryId = useProductWorkspaceStore((s) => s.context.activeStoryId) + const rawStories = useProductWorkspaceStore(useShallow(selectStoriesForActivePbi)) as WorkspaceStory[] const [filterStatus, setFilterStatus] = useState(null) const [filterPriority, setFilterPriority] = useState(null) const [sortMode, setSortMode] = useState(() => { @@ -138,20 +141,10 @@ export function StoryPanel({ productId, isDemo }: StoryPanelProps) { useEffect(() => { localStorage.setItem('scrum4me:story_sort', sortMode) }, [sortMode]) - const rawStories = selectedPbiId ? (storiesByPbi[selectedPbiId] ?? []) : [] - - // Sync into store — use stable string dep to avoid infinite loop - const storyIdKey = rawStories.map(s => s.id).join(',') - useEffect(() => { - if (selectedPbiId) { - initStories(selectedPbiId, storyIdKey ? storyIdKey.split(',') : []) - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [selectedPbiId, storyIdKey]) - + // rawStories komt al gesorteerd binnen via selectStoriesForActivePbi. const storyMap = Object.fromEntries(rawStories.map(s => [s.id, s])) - const order = (selectedPbiId ? storyOrder[selectedPbiId] : null) ?? rawStories.map(s => s.id) - const orderedStories = order.map(id => storyMap[id]).filter(Boolean) + const order = rawStories.map(s => s.id) + const orderedStories = rawStories const base = orderedStories .filter(s => !filterStatus || s.status === filterStatus) @@ -185,14 +178,36 @@ export function StoryPanel({ productId, isDemo }: StoryPanelProps) { const overStory = storyMap[over.id as string] if (!activeStory || !overStory) return - const prevOrder = [...order] - const oldIndex = order.indexOf(active.id as string) - const newIndex = order.indexOf(over.id as string) - const newOrder = arrayMove([...order], oldIndex, newIndex) + const store = useProductWorkspaceStore.getState() + const prevOrder = [...(store.relations.storyIdsByPbi[selectedPbiId] ?? [])] + const oldIndex = prevOrder.indexOf(active.id as string) + const newIndex = prevOrder.indexOf(over.id as string) + if (oldIndex === -1 || newIndex === -1) return + const newOrder = arrayMove([...prevOrder], oldIndex, newIndex) - reorderStories(selectedPbiId, newOrder) + const orderMutationId = store.applyOptimisticMutation({ + kind: 'story-order', + pbiId: selectedPbiId, + prevStoryIds: prevOrder, + }) + useProductWorkspaceStore.setState((s) => { + s.relations.storyIdsByPbi[selectedPbiId] = newOrder + }) const priorityChanged = activeStory.priority !== overStory.priority + let priorityMutationId: string | null = null + if (priorityChanged) { + priorityMutationId = store.applyOptimisticMutation({ + kind: 'entity-patch', + entity: 'story', + id: active.id as string, + prev: store.entities.storiesById[active.id as string], + }) + useProductWorkspaceStore.setState((s) => { + const story = s.entities.storiesById[active.id as string] + if (story) story.priority = overStory.priority + }) + } startTransition(async () => { const result = await reorderStoriesAction( @@ -201,8 +216,13 @@ export function StoryPanel({ productId, isDemo }: StoryPanelProps) { newOrder, priorityChanged ? overStory.priority : undefined ) - if (!result.success) { - rollbackStories(selectedPbiId, prevOrder) + const st = useProductWorkspaceStore.getState() + if (result.success) { + if (priorityMutationId) st.settleMutation(priorityMutationId) + st.settleMutation(orderMutationId) + } else { + if (priorityMutationId) st.rollbackMutation(priorityMutationId) + st.rollbackMutation(orderMutationId) toast.error('Volgorde opslaan mislukt') } }) @@ -284,7 +304,7 @@ export function StoryPanel({ productId, isDemo }: StoryPanelProps) { key={story.id} story={story} isSelected={selectedStoryId === story.id} - onSelect={() => selectStory(story.id)} + onSelect={() => useProductWorkspaceStore.getState().setActiveStory(story.id)} onEdit={() => setStoryDialogState({ mode: 'edit', story, productId })} /> ))} diff --git a/components/backlog/task-panel.tsx b/components/backlog/task-panel.tsx index 4f4f524..622286e 100644 --- a/components/backlog/task-panel.tsx +++ b/components/backlog/task-panel.tsx @@ -26,8 +26,13 @@ import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { PanelNavBar } from '@/components/shared/panel-nav-bar' import { DemoTooltip } from '@/components/shared/demo-tooltip' -import { useSelectionStore } from '@/stores/selection-store' -import { useBacklogStore, type BacklogTask } from '@/stores/backlog-store' +import { useShallow } from 'zustand/react/shallow' +import { useProductWorkspaceStore } from '@/stores/product-workspace/store' +import { selectTasksForActiveStory } from '@/stores/product-workspace/selectors' +import type { + BacklogTask, + TaskDetail, +} from '@/stores/product-workspace/types' import { reorderTasksAction } from '@/actions/tasks' import { BacklogCard } from './backlog-card' import { debugProps } from '@/lib/debug' @@ -52,7 +57,7 @@ function SortableTaskCard({ isDemo, onClick, }: { - task: BacklogTask + task: BacklogTask | TaskDetail isDemo: boolean onClick: () => void }) { @@ -94,22 +99,20 @@ interface TaskPanelProps { closePath: string } +// PBI-74 / T-851: leest tasks voor active story via selectTasksForActiveStory +// (useShallow). DnD via applyOptimisticMutation('task-order'). Detail-view +// (ensureTaskLoaded + isDetail()) zit in de task-dialog, niet in deze lijst. export function TaskPanel({ isDemo, closePath }: TaskPanelProps) { const router = useRouter() const [, startTransition] = useTransition() - const selectedStoryId = useSelectionStore((s) => s.selectedStoryId) - const tasksByStory = useBacklogStore((s) => s.tasksByStory) + const selectedStoryId = useProductWorkspaceStore((s) => s.context.activeStoryId) + const rawTasks = useProductWorkspaceStore(useShallow(selectTasksForActiveStory)) as + | (BacklogTask | TaskDetail)[] const [activeDragId, setActiveDragId] = useState(null) - const [localOrder, setLocalOrder] = useState(null) - const rawTasks = selectedStoryId ? (tasksByStory[selectedStoryId] ?? []) : null - - // Merge local order with rawTasks for optimistic reorder - const tasks: BacklogTask[] | null = rawTasks === null - ? null - : localOrder - ? localOrder.map((id) => rawTasks.find((t) => t.id === id)).filter(Boolean) as BacklogTask[] - : rawTasks + const tasks: (BacklogTask | TaskDetail)[] | null = selectedStoryId + ? rawTasks + : null const sensors = useSensors( useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), @@ -126,19 +129,30 @@ export function TaskPanel({ isDemo, closePath }: TaskPanelProps) { const { active, over } = event if (!over || active.id === over.id) return - const ids = tasks.map((t) => t.id) - const oldIndex = ids.indexOf(active.id as string) - const newIndex = ids.indexOf(over.id as string) + const store = useProductWorkspaceStore.getState() + const prevOrder = [...(store.relations.taskIdsByStory[selectedStoryId] ?? [])] + const oldIndex = prevOrder.indexOf(active.id as string) + const newIndex = prevOrder.indexOf(over.id as string) if (oldIndex === -1 || newIndex === -1) return + const newOrder = arrayMove([...prevOrder], oldIndex, newIndex) - const newOrder = arrayMove(ids, oldIndex, newIndex) - setLocalOrder(newOrder) + const orderMutationId = store.applyOptimisticMutation({ + kind: 'task-order', + storyId: selectedStoryId, + prevTaskIds: prevOrder, + }) + useProductWorkspaceStore.setState((s) => { + s.relations.taskIdsByStory[selectedStoryId] = newOrder + }) startTransition(async () => { const result = await reorderTasksAction(selectedStoryId, newOrder) + const st = useProductWorkspaceStore.getState() if (result?.error) { - setLocalOrder(null) + st.rollbackMutation(orderMutationId) toast.error(result.error) + } else { + st.settleMutation(orderMutationId) } }) } diff --git a/components/shared/set-current-product.tsx b/components/shared/set-current-product.tsx index 3f007e9..63aa151 100644 --- a/components/shared/set-current-product.tsx +++ b/components/shared/set-current-product.tsx @@ -1,26 +1,18 @@ 'use client' import { useEffect } from 'react' -import { useProductStore } from '@/stores/product-store' import { useProductWorkspaceStore } from '@/stores/product-workspace/store' import { debugProps } from '@/lib/debug' -// PBI-74 / T-847: zet zowel oude useProductStore.setCurrentProduct als de -// nieuwe workspace-store.setActiveProduct. setActiveProduct triggert -// ensureProductLoaded met een requestId-guard; de fetch-stub levert tijdens -// Story 2 nog geen echte data — echte LIST-endpoints komen in Story 7 -// (T-870). Restore-hint flow volgt in Story 4 (T-857). +// PBI-74 / T-853: workspace-store is nu enige bron voor active product. +// De voorganger (stores/product-store.ts) wordt in Story 8 (T-876) verwijderd. export function SetCurrentProduct({ id, name }: { id: string; name: string }) { - const { setCurrentProduct, clearCurrentProduct } = useProductStore() - useEffect(() => { - setCurrentProduct(id, name) useProductWorkspaceStore.getState().setActiveProduct({ id, name }) return () => { - clearCurrentProduct() useProductWorkspaceStore.getState().setActiveProduct(null) } - }, [id, name, setCurrentProduct, clearCurrentProduct]) + }, [id, name]) return