Scrum4Me/components/ideas/idea-md-editor.tsx
Janpeter Visser d292e445d9
Sprint: Verbeteren debug mode (#179)
* feat(PBI-49): add debugProps helper + Vitest test

Adds lib/debug.ts with debugProps(id, component, file) that returns
data-debug-id and data-debug-label attrs in dev mode, empty object in
production. Adds __tests__/lib/debug.test.ts covering both modes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(PBI-49): add debug-id pattern doc + CLAUDE.md reference

Adds docs/patterns/debug-id.md documenting the named-component boundary
rule (6 punten), helper-voorbeeld, skip-criteria en motivatie voor
handmatige pad-argumenten. Voegt verwijzing toe aan CLAUDE.md
patterns-tabel.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(PBI-49): migrate 17 shared/ components to debugProps helper

Replace hardcoded data-debug-id + data-debug-label attribute pairs with
{...debugProps(id, component, file)} spread in all 17 components/shared/
files. Existing debug-ids preserved unchanged.

* feat(PBI-49): add debugProps to backlog/, sprint/, solo/ components

* feat(PBI-49): add debugProps to jobs/ + ideas/ components

* feat(PBI-49): add debugProps to products/ + settings/ + notifications/ components

* feat(PBI-49): add debugProps to admin/ + dashboard/ + dialogs/ + mobile/ + split-pane/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(PBI-49): use attr(data-debug-id) for debug tooltip in globals.css

* refactor(PBI-49): remove data-debug-label from debugProps helper + test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(PBI-49): strip unused component/file args from debugProps in shared/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(PBI-49): add BEM sub-element data-debug-id to StatusBar, NavBar, PanelNavBar

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(PBI-49): add BEM sub-element data-debug-id to components/sprint/*

- new-sprint-dialog: __submit on submit button
- sprint-backlog: __list on SprintBacklogLeft + SprintBacklogRight scroll areas
- sprint-board-client: root wrapper div (display:contents) + __drag-overlay
- sprint-header: __title on goal button, __dates on dates button, __actions on action cluster
- sprint-run-controls: root on controls div, __start/__cancel on action buttons; __blockers-dialog on dialog content
- start-sprint-button: root on trigger button, __dialog on dialog content, __submit on submit button
- sync-active-sprint-cookie: no debug-id (returns null, side-effect only), comment added

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(PBI-49): add BEM sub-element data-debug-id to components/backlog/*

* feat(PBI-49): add BEM sub-element data-debug-id to components/ideas/*

* feat(PBI-49): add BEM sub-element data-debug-id to components/dashboard/* + components/markdown.tsx

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(PBI-49): add BEM sub-element data-debug-id to new-product-button

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(PBI-49): add BEM sub-element data-debug-id to components/solo/*

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(PBI-49): add BEM sub-elements to nav-status-indicators

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(PBI-49): add BEM sub-element data-debug-id to components/jobs/*

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(PBI-49): add BEM sub-element data-debug-id to components/products/*

* feat(PBI-49): add BEM sub-element data-debug-id to components/notifications/*

- answer-modal: __content (scroll area), __submit (footer)
- notifications-bridge: skip comment (bridge, non-rendering wrapper)
- notifications-realtime-mount: skip comment (returns null)
- notifications-sheet: __header, __items (questions list)
- push-toggle: __switch (button), __label (button text) on subscribed/unsubscribed states

* feat(PBI-49): add BEM sub-element data-debug-id to components/settings/*

- leave-product-button: root only (single-button component)
- min-quota-editor: __input (number input), __save (save button)
- profile-editor: __username (bio/short-description input), __save (submit)
- role-manager: __roles (checkbox list), __add (save button)
- token-manager: __tokens (active tokens list), __generate (create button)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(PBI-49): add BEM sub-element data-debug-id to admin, auth, dialogs, entity-dialog, mobile, split-pane

* docs(PBI-49): add debug-labels BEM pattern doc + CLAUDE.md entry

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 22:46:29 +02:00

173 lines
5.9 KiB
TypeScript

'use client'
// IdeaMdEditor — bewerk grill_md of plan_md.
//
// - kind='grill': geen yaml-validatie (vrije markdown).
// - kind='plan' : preflight via parsePlanMd (server-side action herhaalt
// validation, dit is alleen UX om eerder te falen).
//
// Save → updateGrillMdAction / updatePlanMdAction. Cmd/Ctrl+S triggert save.
// LocalStorage-backed draft per idea+kind, restore bij heropening.
import { useEffect, useMemo, useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { Save, X } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { debugProps } from '@/lib/debug'
import { parsePlanMd, type PlanParseError } from '@/lib/idea-plan-parser'
import { updateGrillMdAction, updatePlanMdAction } from '@/actions/ideas'
type Kind = 'grill' | 'plan'
interface Props {
ideaId: string
kind: Kind
initialValue: string
onCancel: () => void
}
// Lazily compute the seed: read draft from localStorage on first render, fall
// back to initialValue. Avoids setState-in-useEffect for hydration.
function readSeed(draftKey: string, initialValue: string): {
value: string
restored: boolean
} {
if (typeof window === 'undefined') return { value: initialValue, restored: false }
const draft = window.localStorage.getItem(draftKey)
if (draft && draft !== initialValue) return { value: draft, restored: true }
return { value: initialValue, restored: false }
}
export function IdeaMdEditor({ ideaId, kind, initialValue, onCancel }: Props) {
const router = useRouter()
const draftKey = `idea-md-draft-${ideaId}-${kind}`
const [seed] = useState(() => readSeed(draftKey, initialValue))
const [value, setValue] = useState(seed.value)
const [submitErrors, setSubmitErrors] = useState<PlanParseError[]>([])
const [submitting, startSubmit] = useTransition()
// Eenmalige toast voor restore — de seed is al toegepast bij mount.
useEffect(() => {
if (seed.restored) {
toast.info('Niet-opgeslagen wijziging hersteld uit lokale draft.')
}
}, [seed.restored])
// Auto-save naar localStorage on change.
useEffect(() => {
if (typeof window === 'undefined') return
if (value === initialValue) {
window.localStorage.removeItem(draftKey)
} else {
window.localStorage.setItem(draftKey, value)
}
}, [value, initialValue, draftKey])
// Live yaml-validatie als afgeleide state — geen useEffect nodig.
const validationErrors = useMemo<PlanParseError[]>(() => {
if (kind !== 'plan') return []
if (value === '' || value === initialValue) return []
const r = parsePlanMd(value)
return r.ok ? [] : r.errors
}, [value, initialValue, kind])
// Combine: validation errors voor live feedback, submitErrors voor server-side details.
const errors = submitErrors.length > 0 ? submitErrors : validationErrors
function save() {
if (errors.length > 0 && kind === 'plan') {
toast.error('Frontmatter heeft fouten — fix die eerst.')
return
}
setSubmitErrors([])
startSubmit(async () => {
const r =
kind === 'grill'
? await updateGrillMdAction(ideaId, value)
: await updatePlanMdAction(ideaId, value)
if ('error' in r) {
toast.error(r.error)
if ('details' in r && Array.isArray(r.details)) {
setSubmitErrors(r.details as PlanParseError[])
}
return
}
toast.success('Opgeslagen')
window.localStorage.removeItem(draftKey)
router.refresh()
onCancel()
})
}
// Cmd/Ctrl+S → save
function onKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
e.preventDefault()
save()
}
}
const dirty = value !== initialValue
return (
<div className="space-y-3" {...debugProps('idea-md-editor', 'IdeaMdEditor', 'components/ideas/idea-md-editor.tsx')}>
{errors.length > 0 && (
<div className="rounded-md border border-status-blocked/30 bg-status-blocked/10 p-3 space-y-1">
<p className="text-xs font-medium text-status-blocked">
{kind === 'plan' ? 'YAML-frontmatter fouten' : 'Validatiefouten'}
</p>
<ul className="text-xs text-status-blocked space-y-0.5">
{errors.map((err, i) => (
<li key={i}>
{err.line ? `Regel ${err.line}: ` : ''}
{err.message}
{err.hint && (
<div className="mt-1 text-foreground/80">Tip: {err.hint}</div>
)}
</li>
))}
</ul>
</div>
)}
<Textarea
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={onKeyDown}
rows={24}
className="font-mono text-sm leading-relaxed"
data-debug-id="idea-md-editor__textarea"
placeholder={
kind === 'grill'
? '# Idee — ...\n## Scope\n...'
: '---\npbi:\n title: ...\n priority: 2\nstories:\n - title: ...\n---\n\n# Overwegingen\n...'
}
disabled={submitting}
/>
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">
{dirty ? 'Niet-opgeslagen wijzigingen — Cmd/Ctrl+S om op te slaan' : 'Geen wijzigingen'}
</p>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={onCancel} disabled={submitting}>
<X className="size-3.5 mr-1" />
Annuleer
</Button>
<Button
size="sm"
onClick={save}
disabled={!dirty || submitting || (errors.length > 0 && kind === 'plan')}
data-debug-id="idea-md-editor__save"
>
<Save className="size-3.5 mr-1" />
Opslaan
</Button>
</div>
</div>
</div>
)
}