feat(PBI-74): migreer backlog-componenten naar workspace-store (Story 3)

Story 3 verplaatst alle UI-consumers van de oude vier stores
(useBacklogStore/usePlannerStore/useSelectionStore/useProductStore) naar de
nieuwe product-workspace-store. De oude stores blijven nog bestaan voor
hydration-wrapper en realtime-hook (dual-dispatch); Story 8 ruimt ze op.

- T-848 backlog-split-pane.tsx: leest activePbiId/activeStoryId uit
  context-slice (primitives, geen useShallow nodig).
- T-849 pbi-list.tsx: selectVisiblePbis(useShallow); DnD via
  applyOptimisticMutation('pbi-order' + optionele 'entity-patch' bij
  cross-priority drag), met settle/rollback per server-result.
- T-850 story-panel.tsx: selectStoriesForActivePbi(useShallow); DnD via
  applyOptimisticMutation('story-order' + entity-patch bij priority change).
- T-851 task-panel.tsx: selectTasksForActiveStory(useShallow); DnD via
  applyOptimisticMutation('task-order'); detail-view (ensureTaskLoaded +
  isDetail) zit in de task-dialog (apart component, niet in deze lijst).
- T-852 start-sprint-button.tsx: selectActivePbi + selectStoriesForActivePbi
  voor free-story count.
- T-853 set-current-product.tsx: alleen workspace-store.setActiveProduct
  (oude useProductStore-import verwijderd).
- T-854 G1/G2-audit: alle nieuwe selectors gebruiken module-level EMPTY
  refs (G1) en useShallow voor lijsten (G2). Geen 'Maximum update depth'-
  warnings tijdens npm test.
- T-855 tests bijgewerkt: backlog-split-pane.test, task-panel.test,
  integration.test gebruiken nu setState op workspace-store (helpers
  resetWorkspace/setActiveStoryAndTasks/selectPbi/selectStory).

Verify: lint+typecheck clean, 636/636 tests groen. UI-consumers van
oude stores zijn nu nul (uitgezonderd dual-dispatch in hydration-wrapper en
realtime-hook + dev-fingerprint-helper, die in Story 8/T-873/T-878 verdwijnen).

Refs: PBI-74, ST-1320, T-848..T-855

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Janpeter Visser 2026-05-10 01:12:48 +02:00
parent a98e60fcc7
commit 5aec101c83
9 changed files with 256 additions and 158 deletions

View file

@ -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 = [
<div key="a">PBI pane</div>,
<div key="b">Stories pane</div>,
@ -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(
<BacklogSplitPane
panes={PANES}
@ -52,7 +59,7 @@ describe('BacklogSplitPane auto-switch', () => {
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(
<BacklogSplitPane
panes={PANES}
@ -67,11 +74,11 @@ describe('BacklogSplitPane auto-switch', () => {
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(
<BacklogSplitPane
panes={PANES}

View file

@ -1,8 +1,11 @@
// @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 {
BacklogStory,
BacklogTask,
} from '@/stores/product-workspace/types'
// Mock next/navigation
const mockPush = vi.fn()
@ -61,19 +64,40 @@ const PBI_ID = 'pbi-1'
const ALT_PBI_ID = 'pbi-2'
const STORY_ID = 'story-1'
const STORIES = [
{ id: STORY_ID, code: 'ST-1', title: 'Eerste story', description: null, acceptance_criteria: null, priority: 2, status: 'OPEN', pbi_id: PBI_ID, sprint_id: null, created_at: new Date() },
const STORIES: BacklogStory[] = [
{ id: STORY_ID, code: 'ST-1', title: 'Eerste story', description: null, acceptance_criteria: null, priority: 2, sort_order: 1, status: 'OPEN', pbi_id: PBI_ID, sprint_id: null, created_at: new Date() },
]
const TASKS = [
const TASKS: BacklogTask[] = [
{ id: 'task-1', title: 'Eerste taak', description: null, priority: 2, status: 'TO_DO', sort_order: 1, story_id: STORY_ID, created_at: new Date() },
]
function resetStores() {
useSelectionStore.setState({ selectedPbiId: null, selectedStoryId: null })
useBacklogStore.setState({
pbis: [],
storiesByPbi: { [PBI_ID]: STORIES },
tasksByStory: { [STORY_ID]: TASKS },
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 = 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(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
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(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
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(<TaskPanel productId={PRODUCT_ID} isDemo={false} closePath={`/products/${PRODUCT_ID}`} />)
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(<TaskPanel productId={PRODUCT_ID} isDemo={false} closePath={`/products/${PRODUCT_ID}`} />)
// Reset via selectPbi
useSelectionStore.getState().selectPbi(ALT_PBI_ID)
// Re-render reflects new store state
useProductWorkspaceStore.getState().setActivePbi(ALT_PBI_ID)
render(<TaskPanel productId={PRODUCT_ID} isDemo={false} closePath={`/products/${PRODUCT_ID}`} />)
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(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
// bg-primary-container is applied when isSelected
const selected = container.querySelector('.bg-primary-container')

View file

@ -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)

View file

@ -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<SplitPaneProps, 'activeTab' | 'onActiveTabChange'>
// 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

View file

@ -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<number | 'all'>('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)}

View file

@ -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<string | null>(null)
const [filterPriority, setFilterPriority] = useState<number | null>(null)
const [sortMode, setSortMode] = useState<SortMode>(() => {
@ -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 })}
/>
))}

View file

@ -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<string | null>(null)
const [localOrder, setLocalOrder] = useState<string[] | null>(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)
}
})
}

View file

@ -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 <span {...debugProps('set-current-product')} hidden />
}

View file

@ -21,8 +21,12 @@ import {
entityDialogHeaderClasses,
} from '@/components/shared/entity-dialog-layout'
import { createSprintAction } from '@/actions/sprints'
import { useSelectionStore } from '@/stores/selection-store'
import { useBacklogStore } from '@/stores/backlog-store'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import {
selectActivePbi,
selectStoriesForActivePbi,
} from '@/stores/product-workspace/selectors'
import { useShallow } from 'zustand/react/shallow'
interface StartSprintButtonProps {
productId: string
@ -46,14 +50,11 @@ export function StartSprintButton({ productId, isDemo = false }: StartSprintButt
const [dirty, setDirty] = useState(false)
const formRef = useRef<HTMLFormElement>(null)
const router = useRouter()
const selectedPbiId = useSelectionStore((s) => s.selectedPbiId)
const selectedPbi = useBacklogStore((s) =>
selectedPbiId ? s.pbis.find((p) => p.id === selectedPbiId) ?? null : null,
)
const freeStoryCount = useBacklogStore((s) => {
if (!selectedPbiId) return 0
return (s.storiesByPbi[selectedPbiId] ?? []).filter((story) => story.sprint_id === null).length
})
// PBI-74 / T-852: actief PBI + free-story count via workspace-store selectors.
const selectedPbiId = useProductWorkspaceStore((s) => s.context.activePbiId)
const selectedPbi = useProductWorkspaceStore(selectActivePbi)
const stories = useProductWorkspaceStore(useShallow(selectStoriesForActivePbi))
const freeStoryCount = stories.filter((story) => story.sprint_id === null).length
const [state, formAction, pending] = useActionState<ActionResult | undefined, FormData>(
async (_prev, fd) => {