{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "workflows-01",
  "title": "Workflow builder",
  "description": "A canvas where steps are connected by hand: a wire follows the pointer out of a port and lands on the steps that can take it, the warning marks clear as it lands, and Publish refuses with a count until the last problem is fixed in the inspector.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/brand-logos.json",
    "https://ui.ndekocode.dev/r/brand-tile.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/dropdown-menu.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/mesh-tile.json",
    "https://ui.ndekocode.dev/r/morph-button.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/select.json",
    "https://ui.ndekocode.dev/r/textarea.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/index.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId, useMemo, useRef, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport {\n  pressedSolidOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  CircleCheckIcon,\n  TriangleAlertIcon,\n  UndoIcon,\n  XIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { risePresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { Canvas } from './canvas';\nimport { shownNameOf, WORKFLOW_NAME, type Step } from './data';\nimport { problemsOf, problemsOfStep, stepOf } from './graph';\nimport { Inspector } from './inspector';\nimport { layoutOf, type Orientation } from './layout';\nimport {\n  graphOf,\n  INITIAL,\n  LOOP_AFTER_MS,\n  PUBLISH_MS,\n  reducer,\n  RESTING,\n  SCRIPT,\n  type PublishState,\n} from './session';\nimport {\n  BottomSheet,\n  DEFAULT_WIDTH,\n  isOwnEscape,\n  ResizeHandle,\n  SHEET_SHARE,\n} from './side-panel';\nimport { useWidthBand, type WidthBand } from './use-width-band';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\nconst PUBLISH_LABELS: Record<MorphState, string> = {\n  idle: 'Publish',\n  busy: 'Publishing',\n  done: 'Published',\n};\n\nconst MORPH_OF: Record<PublishState, MorphState> = {\n  draft: 'idle',\n  publishing: 'busy',\n  live: 'done',\n};\n\nconst CANVAS_HINT =\n  'Tab moves through the steps. The arrow keys follow the connections. Enter opens a step in the inspector. Alt with an arrow key moves the step along the grid. Delete removes it, and Undo brings it back. The menu of a step connects it without dragging.';\n\ntype RowStyle = React.CSSProperties & { '--inspector': string };\n\ntype Status = 'problems' | 'ready' | 'live';\n\nfunction orientationOf(band: WidthBand | null): Orientation {\n  if (band === 'wide' || band === null) {\n    return 'across';\n  }\n  return 'down';\n}\n\nfunction stepsWordOf(count: number) {\n  if (count === 1) {\n    return '1 step';\n  }\n  return `${count} steps`;\n}\n\nfunction wiresWordOf(count: number) {\n  if (count === 1) {\n    return '1 connection';\n  }\n  return `${count} connections`;\n}\n\nfunction problemWordOf(count: number) {\n  if (count === 1) {\n    return 'problem';\n  }\n  return 'problems';\n}\n\nfunction statusOf(problemCount: number, isLive: boolean): Status {\n  if (problemCount > 0) {\n    return 'problems';\n  }\n  if (isLive) {\n    return 'live';\n  }\n  return 'ready';\n}\n\nfunction stageWordOf(isLive: boolean) {\n  if (isLive) {\n    return 'Live';\n  }\n  return 'Draft';\n}\n\nfunction stageVariantOf(isLive: boolean) {\n  if (isLive) {\n    return 'success';\n  }\n  return 'secondary';\n}\n\nfunction coveredOf(isSheetOpen: boolean) {\n  if (isSheetOpen) {\n    return SHEET_SHARE;\n  }\n  return 0;\n}\n\nfunction shownStepOf(step: Step | undefined, isOpen: boolean) {\n  if (isOpen) {\n    return step;\n  }\n  return undefined;\n}\n\ntype ProblemStatusProps = {\n  count: number;\n  isLive: boolean;\n};\n\nfunction ProblemStatus({ count, isLive }: ProblemStatusProps) {\n  const status = statusOf(count, isLive);\n\n  return (\n    <p className='flex h-8 items-center text-xs'>\n      <Swap swapKey={status}>\n        {status === 'problems' && (\n          <span className='text-warning-foreground flex items-center gap-1.5 tabular-nums'>\n            <TriangleAlertIcon className='size-3.5' />\n            <MotionNumber value={count} />\n            {problemWordOf(count)}\n          </span>\n        )}\n        {status === 'ready' && (\n          <span className='text-success-foreground flex items-center gap-1.5'>\n            <CircleCheckIcon className='size-3.5' />\n            Ready to publish\n          </span>\n        )}\n      </Swap>\n    </p>\n  );\n}\n\ntype UndoLineProps = {\n  step: Step | undefined;\n  onUndo: () => void;\n  onDismiss: () => void;\n};\n\n/** It stays until it is used or dismissed: a timer would take the focus away with it. */\nfunction UndoLine({ step, onUndo, onDismiss }: UndoLineProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const presence = risePresenceOf(shouldReduceMotion);\n\n  return (\n    <AnimatePresence initial={false}>\n      {step && (\n        <motion.div\n          key='undo'\n          className='pointer-events-none absolute inset-x-3 top-3 flex justify-center'\n          {...presence}\n        >\n          <div className='surface-raised pointer-events-auto flex h-9 max-w-full items-center gap-1 rounded-full ps-3.5 pe-1 text-[13px]'>\n            <span className='min-w-0 truncate'>\n              {shownNameOf(step)} removed\n            </span>\n            <Button\n              type='button'\n              variant='ghost'\n              size='sm'\n              data-undo\n              onClick={onUndo}\n              className='text-primary-ink rounded-full'\n            >\n              <UndoIcon />\n              Undo\n            </Button>\n            <Button\n              type='button'\n              variant='ghost'\n              size='icon-sm'\n              aria-label='Dismiss'\n              onClick={onDismiss}\n              className='text-muted-foreground rounded-full'\n            >\n              <XIcon />\n            </Button>\n          </div>\n        </motion.div>\n      )}\n    </AnimatePresence>\n  );\n}\n\n/** It lies over the canvas without taking its presses, so the zoom control under it still works. */\nfunction EmptyCanvas({ onRestore }: { onRestore: () => void }) {\n  return (\n    <div className='pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center'>\n      <p className='text-muted-foreground text-[13px]'>\n        No step is left on the canvas\n      </p>\n      <Button\n        type='button'\n        variant='outline'\n        size='sm'\n        onClick={onRestore}\n        className='pointer-events-auto'\n      >\n        Restore the sample workflow\n      </Button>\n    </div>\n  );\n}\n\nexport default function Workflows01() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const { schedule } = useTimeouts();\n  const rowRef = useRef<HTMLDivElement>(null);\n  const band = useWidthBand(rowRef);\n  const headingId = useId();\n  const hintId = useId();\n  const inspectorId = useId();\n  const [inspectorWidth, setInspectorWidth] = useState(DEFAULT_WIDTH);\n  const [round, setRound] = useState(0);\n  const orientation = orientationOf(band);\n  const layout = useMemo(\n    () => layoutOf(state.steps, state.wires, orientation),\n    [state.steps, state.wires, orientation]\n  );\n  const graph = graphOf(state);\n  const problems = problemsOf(graph);\n  const problemCount = problems.length;\n  const selected = stepOf(state.steps, state.selectedId);\n  const shownStep = shownStepOf(selected, state.isInspectorOpen);\n  const isSheet = band === 'phone';\n  const isPanel = band === 'compact' || band === 'wide';\n  const isSheetOpen = isSheet && shownStep !== undefined;\n  const isLive = state.publish === 'live';\n  const isEmpty = state.steps.length === 0;\n  const stageWord = stageWordOf(isLive);\n  const canReplay = isFinished && !isAutoplaying;\n  const message = spokenUnless(isAutoplaying, state.notice);\n  const stepsWord = stepsWordOf(state.steps.length);\n  const wiresWord = wiresWordOf(state.wires.length);\n  const rowStyle: RowStyle = { '--inspector': `${inspectorWidth}px` };\n\n  function focusLater(selector: string) {\n    requestAnimationFrame(() => {\n      const target = ref.current?.querySelector<HTMLElement>(selector);\n      target?.focus();\n    });\n  }\n\n  /** After a refusal the focus goes to the field to fill, or to the inspector when a wire is missing. */\n  function focusProblemLater() {\n    requestAnimationFrame(() => {\n      const root = ref.current;\n      const field = root?.querySelector<HTMLElement>('[aria-invalid=\"true\"]');\n      const heading = root?.querySelector<HTMLElement>(\n        '[data-inspector-heading]'\n      );\n      const target = field ?? heading;\n      target?.focus();\n    });\n  }\n\n  function open(id: string, isFromKeyboard: boolean) {\n    act({ type: 'opened', id });\n    if (isFromKeyboard) {\n      focusLater('[data-inspector-heading]');\n    }\n  }\n\n  function close() {\n    act({ type: 'closed' });\n    if (state.selectedId !== null) {\n      focusLater(`[data-step-button=\"${state.selectedId}\"]`);\n    }\n  }\n\n  function remove(id: string) {\n    act({ type: 'removed', id });\n    focusLater('[data-undo]');\n  }\n\n  function undo() {\n    const lost = state.removed;\n    act({ type: 'undone' });\n    if (lost) {\n      focusLater(`[data-step-button=\"${lost.step.id}\"]`);\n    }\n  }\n\n  function dismissUndo() {\n    act({ type: 'undoDismissed' });\n    focusLater('[data-canvas-frame]');\n  }\n\n  function publish() {\n    act({ type: 'publishStarted' });\n    if (problemCount > 0) {\n      focusProblemLater();\n      return;\n    }\n    if (state.publish === 'draft') {\n      schedule(() => act({ type: 'publishDone' }), PUBLISH_MS);\n    }\n  }\n\n  /** A new round starts on a fresh canvas, so the view a person left does not hide the demonstration. */\n  function replay() {\n    restart();\n    setRound((current) => current + 1);\n  }\n\n  function closeOnEscape(event: React.KeyboardEvent<HTMLElement>) {\n    if (isOwnEscape(event)) {\n      close();\n    }\n  }\n\n  return (\n    <ClockGate isActive={isInView}>\n      <div\n        ref={ref}\n        className='bg-background text-foreground @container flex h-dvh min-h-[38rem] w-full flex-col overflow-hidden'\n      >\n        <div className='mx-auto flex min-h-0 w-full max-w-7xl flex-1 flex-col gap-3 p-3 @3xl:gap-4 @3xl:p-4'>\n          <header className='flex flex-wrap items-center gap-x-3 gap-y-2'>\n            <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n              <div className='flex items-center gap-2'>\n                <h1 className='truncate text-lg font-semibold'>\n                  {WORKFLOW_NAME}\n                </h1>\n                <Badge variant={stageVariantOf(isLive)}>\n                  <Swap swapKey={stageWord}>{stageWord}</Swap>\n                </Badge>\n              </div>\n              <p className='text-muted-foreground text-xs tabular-nums'>\n                {stepsWord} · {wiresWord}\n              </p>\n            </div>\n            <div className='flex flex-wrap items-center gap-x-3 gap-y-2'>\n              <ReplayButton\n                isShown={canReplay}\n                onReplay={replay}\n                label='Replay the demo'\n              />\n              <ProblemStatus count={problemCount} isLive={isLive} />\n              <MorphButton\n                type='button'\n                state={MORPH_OF[state.publish]}\n                labels={PUBLISH_LABELS}\n                onClick={publish}\n                className={pressedSolidOf(pressed === 'publish')}\n              />\n            </div>\n          </header>\n\n          <div ref={rowRef} style={rowStyle} className='flex min-h-0 flex-1'>\n            <div className='group/canvas bg-foreground/[0.03] relative min-w-0 flex-1 overflow-hidden rounded-xl'>\n              <Canvas\n                key={round}\n                isLaidOut={band !== null}\n                label={`Canvas of ${WORKFLOW_NAME}`}\n                subject='the workflow'\n                hintId={hintId}\n                inspectorId={inspectorId}\n                steps={state.steps}\n                graph={graph}\n                problems={problems}\n                layout={layout}\n                orientation={orientation}\n                selectedId={state.selectedId}\n                isInspectorOpen={state.isInspectorOpen}\n                covered={coveredOf(isSheetOpen)}\n                wiring={state.wiring}\n                isDemonstrating={isAutoplaying}\n                pressed={pressed}\n                onAction={act}\n                onOpen={open}\n                onRemove={remove}\n              />\n              <p id={hintId} className='sr-only'>\n                {CANVAS_HINT}\n              </p>\n              {isEmpty && (\n                <EmptyCanvas onRestore={() => act({ type: 'restored' })} />\n              )}\n              <UndoLine\n                step={state.removed?.step}\n                onUndo={undo}\n                onDismiss={dismissUndo}\n              />\n              {isSheet && (\n                <BottomSheet\n                  id={inspectorId}\n                  isOpen={isSheetOpen}\n                  label='Step inspector'\n                  onClose={close}\n                >\n                  {shownStep && (\n                    <Inspector\n                      step={shownStep}\n                      graph={graph}\n                      problems={problemsOfStep(problems, shownStep.id)}\n                      headingId={headingId}\n                      onAction={act}\n                      onRemove={remove}\n                      onClose={close}\n                    />\n                  )}\n                </BottomSheet>\n              )}\n            </div>\n            {isPanel && shownStep && (\n              <>\n                <ResizeHandle\n                  width={inspectorWidth}\n                  containerRef={rowRef}\n                  onWidthChange={setInspectorWidth}\n                />\n                <aside\n                  id={inspectorId}\n                  aria-label='Step inspector'\n                  onKeyDown={closeOnEscape}\n                  className='bg-card hairline-ring ring-border flex w-(--inspector) max-w-[46%] shrink-0 flex-col rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-opacity duration-200 starting:opacity-0'\n                >\n                  <Inspector\n                    step={shownStep}\n                    graph={graph}\n                    problems={problemsOfStep(problems, shownStep.id)}\n                    headingId={headingId}\n                    onAction={act}\n                    onRemove={remove}\n                    onClose={close}\n                  />\n                </aside>\n              </>\n            )}\n          </div>\n        </div>\n        <LiveRegion message={message} />\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/canvas.tsx",
      "content": "'use client';\n\nimport { useEffect, useLayoutEffect, useRef, useState } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { OUTPUT_IDS, type OutputId, type Step } from './data';\nimport {\n  canConnect,\n  neighbourOf,\n  problemsOfStep,\n  stepOf,\n  type Graph,\n  type Problem,\n} from './graph';\nimport {\n  draggedCellOf,\n  GRID,\n  moveOfKey,\n  nudgedCellOf,\n  stepAt,\n  wirePathOf,\n  type CanvasLayout,\n  type Cell,\n  type Orientation,\n  type Point,\n} from './layout';\nimport type { BuilderAction, Wire, Wiring } from './session';\nimport { StepCard, type Aim } from './step-card';\nimport { usePanZoom } from './use-pan-zoom';\nimport { HeldLayer, WireLayer } from './wires';\nimport { ZoomControl } from './zoom-control';\n\ntype Press = {\n  kind: 'press';\n  pointerId: number;\n  stepId: string;\n  origin: Cell;\n  startX: number;\n  startY: number;\n  isTouch: boolean;\n};\n\ntype Moving = {\n  kind: 'move';\n  pointerId: number;\n  stepId: string;\n  origin: Cell;\n  startX: number;\n  startY: number;\n  cell: Cell;\n};\n\ntype Wired = {\n  kind: 'wire';\n  pointerId: number;\n  from: string;\n  output: OutputId;\n  aim: string | null;\n};\n\n/** What the pointers on the canvas are doing. A press has not yet chosen between a click, a move and a pan. */\ntype Gesture = { kind: 'pan' } | Press | Moving | Wired;\n\nconst MOUSE_SLOP = 4;\n\nconst TOUCH_SLOP = 8;\n\n/** A finger held still this long on a step lifts it. A finger that moves first pans the canvas. */\nconst HOLD_MS = 220;\n\n/** A wire lands on a step from this far around its card. */\nconst AIM_REACH = 14;\n\nconst FRAME = [\n  'absolute inset-0 cursor-grab overflow-hidden rounded-xl outline-none select-none active:cursor-grabbing',\n  'group-focus-within/canvas:touch-none',\n].join(' ');\n\nconst GRID_LINES = [\n  'pointer-events-none absolute inset-0 transition-opacity duration-200',\n  '[--line:color-mix(in_oklab,var(--foreground)_8%,transparent)]',\n  'bg-[linear-gradient(to_right,var(--line)_1px,transparent_1px),linear-gradient(to_bottom,var(--line)_1px,transparent_1px)]',\n].join(' ');\n\nfunction outputOf(value: string | undefined) {\n  const output = OUTPUT_IDS.find((candidate) => candidate === value);\n  return output ?? null;\n}\n\nfunction slopOf(isTouch: boolean) {\n  if (isTouch) {\n    return TOUCH_SLOP;\n  }\n  return MOUSE_SLOP;\n}\n\nfunction gridToneOf(isShown: boolean) {\n  if (isShown) {\n    return 'opacity-100';\n  }\n  return 'opacity-0';\n}\n\n/** A held wire only lives while something holds it: a pointer, or the demonstration. */\nfunction heldWiringOf(isHeld: boolean, wiring: Wiring | null) {\n  if (isHeld) {\n    return wiring;\n  }\n  return null;\n}\n\nfunction aimOf(held: Wiring | null, graph: Graph, stepId: string): Aim {\n  if (!held) {\n    return 'idle';\n  }\n  if (held.from === stepId) {\n    return 'source';\n  }\n  if (held.to === stepId) {\n    return 'aimed';\n  }\n  if (canConnect(graph, held.from, stepId)) {\n    return 'open';\n  }\n  return 'closed';\n}\n\n/** The output a wire leaves: the one being held, or the one the demonstration is pressing. */\nfunction heldOutputOf(\n  stepId: string,\n  held: Wiring | null,\n  pressed: string | null\n) {\n  if (held?.from === stepId) {\n    return held.output;\n  }\n  const output = OUTPUT_IDS.find(\n    (candidate) => pressed === `port-${stepId}-${candidate}`\n  );\n  return output ?? null;\n}\n\n/** The demonstration has no pointer, so its wire is drawn from its port to the step it aims at. */\nfunction demoPathOf(\n  held: Wiring | null,\n  layout: CanvasLayout<Wire>,\n  orientation: Orientation\n) {\n  if (!held || held.to === null) {\n    return null;\n  }\n  const from = layout.places[held.from]?.outputs[held.output];\n  const to = layout.places[held.to]?.input;\n  if (!from || !to) {\n    return null;\n  }\n  return wirePathOf(from, to, orientation);\n}\n\nfunction boxOf(layout: CanvasLayout<Wire>, id: string | null) {\n  if (id === null) {\n    return null;\n  }\n  return layout.places[id]?.box ?? null;\n}\n\nfunction inputOf(layout: CanvasLayout<Wire>, id: string | null) {\n  if (id === null) {\n    return null;\n  }\n  return layout.places[id]?.input ?? null;\n}\n\nfunction heldIdOf(isHeld: boolean, id: string | null) {\n  if (isHeld) {\n    return id;\n  }\n  return null;\n}\n\nfunction clientPointOf(event: React.PointerEvent<HTMLDivElement>): Point {\n  return { x: event.clientX, y: event.clientY };\n}\n\n/**\n * The canvas owns the wheel and the touch gestures while it holds the focus. Some browsers do not\n * give the focus to a pressed button, so the frame takes it first.\n */\nfunction engage(frame: HTMLDivElement) {\n  if (!frame.contains(document.activeElement)) {\n    frame.focus({ preventScroll: true });\n  }\n}\n\nexport type CanvasProps = {\n  /** False until the builder knows how wide it is, and so which way the flow reads. */\n  isLaidOut: boolean;\n  label: string;\n  /** What Fit brings into view, for its accessible name. */\n  subject: string;\n  hintId: string;\n  inspectorId: string;\n  steps: Step[];\n  graph: Graph;\n  problems: Problem[];\n  layout: CanvasLayout<Wire>;\n  orientation: Orientation;\n  selectedId: string | null;\n  isInspectorOpen: boolean;\n  /** The share of the frame a sheet covers from the bottom. */\n  covered: number;\n  wiring: Wiring | null;\n  isDemonstrating: boolean;\n  pressed: string | null;\n  onAction: (action: BuilderAction) => void;\n  onOpen: (id: string, isFromKeyboard: boolean) => void;\n  onRemove: (id: string) => void;\n};\n\nexport function Canvas({\n  isLaidOut,\n  label,\n  subject,\n  hintId,\n  inspectorId,\n  steps,\n  graph,\n  problems,\n  layout,\n  orientation,\n  selectedId,\n  isInspectorOpen,\n  covered,\n  wiring,\n  isDemonstrating,\n  pressed,\n  onAction,\n  onOpen,\n  onRemove,\n}: CanvasProps) {\n  const { frameRef, planeRef, view, isMeasured } = usePanZoom();\n  const isReady = isMeasured && isLaidOut;\n  const [movingId, setMovingId] = useState<string | null>(null);\n  const [isPointerWiring, setIsPointerWiring] = useState(false);\n  const gesture = useRef<Gesture | null>(null);\n  const hold = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n  const didDrag = useRef(false);\n  const liveRef = useRef<SVGPathElement>(null);\n  const gridRef = useRef<HTMLDivElement>(null);\n  const isMoving = movingId !== null;\n  const held = heldWiringOf(isDemonstrating || isPointerWiring, wiring);\n  const demoWiring = heldWiringOf(!isPointerWiring, held);\n  const demoPath = demoPathOf(demoWiring, layout, orientation);\n  const isPinned = isInspectorOpen && !isMoving;\n  const pinnedId = heldIdOf(isPinned, selectedId);\n  const pinnedBox = boxOf(layout, pinnedId);\n\n  useLayoutEffect(() => {\n    view.setScene(layout.bounds, covered);\n  }, [view, layout.bounds, covered]);\n\n  useLayoutEffect(() => {\n    view.pin(pinnedBox);\n  }, [view, pinnedBox]);\n\n  useLayoutEffect(() => {\n    if (isReady) {\n      view.settle();\n    }\n  }, [view, isReady, orientation, covered]);\n\n  useEffect(() => {\n    return () => clearTimeout(hold.current);\n  }, []);\n\n  useEffect(() => {\n    if (!isMoving) {\n      return;\n    }\n    function syncGrid() {\n      const grid = gridRef.current;\n      if (!grid) {\n        return;\n      }\n      const zoom = view.zoom();\n      const origin = view.origin();\n      const cell = GRID[orientation];\n      grid.style.backgroundSize = `${cell.x * zoom}px ${cell.y * zoom}px`;\n      grid.style.backgroundPosition = `${origin.x}px ${origin.y}px`;\n    }\n    syncGrid();\n    return view.subscribe(syncGrid);\n  }, [view, isMoving, orientation]);\n\n  function planePointOf(event: React.PointerEvent<HTMLDivElement>) {\n    return view.toPlane(clientPointOf(event));\n  }\n\n  function aimAt(point: Point, from: string) {\n    const id = stepAt(layout.places, point, AIM_REACH);\n    if (id === null || !canConnect(graph, from, id)) {\n      return null;\n    }\n    return id;\n  }\n\n  /** The wire ends on the pointer, or on the port of the step it would land on. */\n  function drawLive(active: Wired, point: Point) {\n    const from = layout.places[active.from]?.outputs[active.output];\n    if (!from) {\n      return;\n    }\n    const aim = aimAt(point, active.from);\n    const end = inputOf(layout, aim) ?? point;\n    liveRef.current?.setAttribute('d', wirePathOf(from, end, orientation));\n    if (aim !== active.aim) {\n      active.aim = aim;\n      onAction({ type: 'wireAimed', to: aim });\n    }\n  }\n\n  function clearLive() {\n    liveRef.current?.removeAttribute('d');\n  }\n\n  function startWire(\n    event: React.PointerEvent<HTMLDivElement>,\n    from: string,\n    output: OutputId\n  ) {\n    event.currentTarget.setPointerCapture(event.pointerId);\n    const active: Wired = {\n      kind: 'wire',\n      pointerId: event.pointerId,\n      from,\n      output,\n      aim: null,\n    };\n    gesture.current = active;\n    setIsPointerWiring(true);\n    onAction({ type: 'wireStarted', from, output });\n    drawLive(active, planePointOf(event));\n  }\n\n  function lift(press: Press) {\n    clearTimeout(hold.current);\n    frameRef.current?.setPointerCapture(press.pointerId);\n    gesture.current = { ...press, kind: 'move', cell: press.origin };\n    didDrag.current = true;\n    setMovingId(press.stepId);\n  }\n\n  function liftIfStillPressed(pointerId: number) {\n    const active = gesture.current;\n    const isSamePress =\n      active?.kind === 'press' && active.pointerId === pointerId;\n    if (isSamePress) {\n      lift(active);\n    }\n  }\n\n  function startPress(event: React.PointerEvent<HTMLDivElement>, step: Step) {\n    const isTouch = event.pointerType === 'touch';\n    const pointerId = event.pointerId;\n    gesture.current = {\n      kind: 'press',\n      pointerId,\n      stepId: step.id,\n      origin: { level: step.level, lane: step.lane },\n      startX: event.clientX,\n      startY: event.clientY,\n      isTouch,\n    };\n    if (isTouch) {\n      hold.current = setTimeout(() => liftIfStillPressed(pointerId), HOLD_MS);\n    }\n  }\n\n  function startPan(event: React.PointerEvent<HTMLDivElement>) {\n    clearTimeout(hold.current);\n    event.currentTarget.setPointerCapture(event.pointerId);\n    gesture.current = { kind: 'pan' };\n    view.grab(event.pointerId, clientPointOf(event));\n  }\n\n  /** A second finger turns a pan into a pinch, even when the first one came down on a step. */\n  function joinGesture(\n    event: React.PointerEvent<HTMLDivElement>,\n    active: Gesture\n  ) {\n    const isTouchPress = active.kind === 'press' && active.isTouch;\n    if (isTouchPress) {\n      view.grab(active.pointerId, { x: active.startX, y: active.startY });\n      event.currentTarget.setPointerCapture(active.pointerId);\n      startPan(event);\n      return;\n    }\n    if (active.kind === 'pan') {\n      startPan(event);\n    }\n  }\n\n  /** A press in the menu of a step reaches this handler through React, yet it is not on the canvas. */\n  function startGesture(event: React.PointerEvent<HTMLDivElement>) {\n    const target = event.target;\n    const frame = event.currentTarget;\n    const isMainButton = event.button === 0;\n    const isOnCanvas = target instanceof Element && frame.contains(target);\n    if (!isMainButton || !isOnCanvas) {\n      return;\n    }\n    if (target.closest('[data-canvas-control]')) {\n      return;\n    }\n    engage(frame);\n    const active = gesture.current;\n    if (active) {\n      joinGesture(event, active);\n      return;\n    }\n    didDrag.current = false;\n    const card = target.closest<HTMLElement>('[data-step]');\n    const step = stepOf(steps, card?.dataset.step ?? null);\n    const port = target.closest<HTMLElement>('[data-port]');\n    const output = outputOf(port?.dataset.port);\n    if (step && output) {\n      startWire(event, step.id, output);\n      return;\n    }\n    if (step) {\n      startPress(event, step);\n      return;\n    }\n    startPan(event);\n  }\n\n  function movePress(event: React.PointerEvent<HTMLDivElement>, press: Press) {\n    const dx = event.clientX - press.startX;\n    const dy = event.clientY - press.startY;\n    const distance = Math.hypot(dx, dy);\n    if (distance < slopOf(press.isTouch)) {\n      return;\n    }\n    if (press.isTouch) {\n      startPan(event);\n      return;\n    }\n    lift(press);\n  }\n\n  function moveStep(event: React.PointerEvent<HTMLDivElement>, move: Moving) {\n    const zoom = view.zoom();\n    const dx = (event.clientX - move.startX) / zoom;\n    const dy = (event.clientY - move.startY) / zoom;\n    const cell = draggedCellOf(orientation, move.origin, dx, dy);\n    const isSameCell =\n      cell.level === move.cell.level && cell.lane === move.cell.lane;\n    if (isSameCell) {\n      return;\n    }\n    move.cell = cell;\n    onAction({ type: 'moved', id: move.stepId, cell });\n  }\n\n  function moveGesture(event: React.PointerEvent<HTMLDivElement>) {\n    const active = gesture.current;\n    if (!active) {\n      return;\n    }\n    if (active.kind === 'pan') {\n      view.drag(event.pointerId, clientPointOf(event));\n      return;\n    }\n    if (event.pointerId !== active.pointerId) {\n      return;\n    }\n    if (active.kind === 'wire') {\n      drawLive(active, planePointOf(event));\n      return;\n    }\n    if (active.kind === 'press') {\n      movePress(event, active);\n      return;\n    }\n    moveStep(event, active);\n  }\n\n  function endWire(action: BuilderAction) {\n    clearLive();\n    setIsPointerWiring(false);\n    onAction(action);\n  }\n\n  function finishGesture(\n    event: React.PointerEvent<HTMLDivElement>,\n    wireAction: BuilderAction\n  ) {\n    const active = gesture.current;\n    if (!active) {\n      return;\n    }\n    if (active.kind === 'pan') {\n      view.release(event.pointerId);\n      if (!view.isHeld()) {\n        gesture.current = null;\n      }\n      return;\n    }\n    if (event.pointerId !== active.pointerId) {\n      return;\n    }\n    clearTimeout(hold.current);\n    gesture.current = null;\n    if (active.kind === 'wire') {\n      endWire(wireAction);\n      return;\n    }\n    if (active.kind === 'move') {\n      setMovingId(null);\n    }\n  }\n\n  function endGesture(event: React.PointerEvent<HTMLDivElement>) {\n    finishGesture(event, { type: 'wireDropped' });\n  }\n\n  function cancelGesture(event: React.PointerEvent<HTMLDivElement>) {\n    finishGesture(event, { type: 'wireCancelled' });\n  }\n\n  function cancelWire() {\n    const active = gesture.current;\n    if (active?.kind !== 'wire') {\n      return;\n    }\n    const frame = frameRef.current;\n    if (frame?.hasPointerCapture(active.pointerId)) {\n      frame.releasePointerCapture(active.pointerId);\n    }\n    gesture.current = null;\n    endWire({ type: 'wireCancelled' });\n  }\n\n  function focusStep(id: string) {\n    const selector = `[data-step-button=\"${id}\"]`;\n    const button = frameRef.current?.querySelector<HTMLElement>(selector);\n    button?.focus();\n  }\n\n  function handleKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.key === 'Escape') {\n      cancelWire();\n      return;\n    }\n    const target = event.target;\n    if (!(target instanceof Element)) {\n      return;\n    }\n    const button = target.closest<HTMLElement>('[data-step-button]');\n    const step = stepOf(steps, button?.dataset.stepButton ?? null);\n    if (!step) {\n      return;\n    }\n    const isRemoval = event.key === 'Delete' || event.key === 'Backspace';\n    if (isRemoval) {\n      event.preventDefault();\n      onRemove(step.id);\n      return;\n    }\n    if (event.altKey) {\n      const origin = { level: step.level, lane: step.lane };\n      const cell = nudgedCellOf(orientation, origin, event.key);\n      if (cell) {\n        event.preventDefault();\n        onAction({ type: 'moved', id: step.id, cell });\n      }\n      return;\n    }\n    const move = moveOfKey(orientation, event.key);\n    if (!move) {\n      return;\n    }\n    event.preventDefault();\n    const nextId = neighbourOf(graph, step.id, move);\n    if (nextId !== null) {\n      onAction({ type: 'selected', id: nextId });\n      focusStep(nextId);\n    }\n  }\n\n  /** The click that ends a move belongs to the move. A click made with a key never does. */\n  function openStep(id: string, isFromKeyboard: boolean) {\n    const endsMove = didDrag.current && !isFromKeyboard;\n    didDrag.current = false;\n    if (endsMove) {\n      return;\n    }\n    onOpen(id, isFromKeyboard);\n  }\n\n  /** A step that takes the focus from the keyboard is brought into view. A pressed one is already under the pointer. */\n  function revealStep(id: string) {\n    const box = boxOf(layout, id);\n    const isPointerDown = gesture.current !== null;\n    if (box && !isPointerDown) {\n      view.reveal(box);\n    }\n  }\n\n  return (\n    <>\n      <div\n        ref={frameRef}\n        role='group'\n        aria-label={label}\n        aria-describedby={hintId}\n        data-canvas-frame\n        tabIndex={-1}\n        onPointerDown={startGesture}\n        onPointerMove={moveGesture}\n        onPointerUp={endGesture}\n        onPointerCancel={cancelGesture}\n        onLostPointerCapture={cancelGesture}\n        onKeyDown={handleKeys}\n        className={FRAME}\n      >\n        <div\n          ref={gridRef}\n          aria-hidden='true'\n          className={cn(GRID_LINES, gridToneOf(isMoving))}\n        />\n        <div\n          ref={planeRef}\n          className={cn(\n            'absolute top-0 left-0 origin-top-left',\n            !isReady && 'invisible'\n          )}\n        >\n          <WireLayer layout={layout} selectedId={selectedId} />\n          {steps.map((step) => {\n            const place = layout.places[step.id];\n            if (!place) {\n              return null;\n            }\n            const isSelected = step.id === selectedId;\n            return (\n              <StepCard\n                key={step.id}\n                step={step}\n                place={place}\n                graph={graph}\n                problems={problemsOfStep(problems, step.id)}\n                aim={aimOf(held, graph, step.id)}\n                isSelected={isSelected}\n                isOpen={isSelected && isInspectorOpen}\n                isLifted={step.id === movingId}\n                heldOutput={heldOutputOf(step.id, held, pressed)}\n                inspectorId={inspectorId}\n                onOpen={openStep}\n                onReveal={revealStep}\n                onAction={onAction}\n                onRemove={onRemove}\n              />\n            );\n          })}\n          <HeldLayer demoPath={demoPath} liveRef={liveRef} />\n        </div>\n      </div>\n      <ZoomControl view={view} subject={subject} />\n    </>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/canvas.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/step-card.tsx",
      "content": "'use client';\n\nimport {\n  EllipsisIcon,\n  TrashIcon,\n  TriangleAlertIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuLabel,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from '@/registry/ndeko/ui/dropdown-menu';\n\nimport {\n  choiceOf,\n  FIELDS_OF,\n  KIND_WORD,\n  shownNameOf,\n  type OutputId,\n  type Step,\n} from './data';\nimport {\n  outputLinesOf,\n  targetsOf,\n  type Graph,\n  type OutputLine,\n  type Problem,\n} from './graph';\nimport type { Point, StepPlace } from './layout';\nimport type { BuilderAction } from './session';\nimport { StepTile } from './step-tile';\n\n/** What a held wire makes of a step: where it leaves, a step it may land on, the one it is over, or one it cannot reach. */\nexport type Aim = 'idle' | 'source' | 'open' | 'aimed' | 'closed';\n\nconst CARD = [\n  'bg-card hairline-ring ring-border flex size-full cursor-pointer items-center gap-2.5 rounded-xl p-2.5 text-start',\n  'shadow-[0_1px_2px_rgb(0_0_0/0.04)] outline-none transition-[box-shadow,opacity] duration-150 hover:ring-foreground/25',\n  'focus-visible:ring-ring focus-visible:ring-offset-background focus-visible:ring-2 focus-visible:ring-offset-2',\n].join(' ');\n\nconst AIM_CLASS: Record<Aim, string> = {\n  idle: '',\n  source: '',\n  open: 'ring-primary/45 ring-2',\n  aimed: 'ring-primary ring-2',\n  closed: 'opacity-45',\n};\n\nconst PORT =\n  'group/port absolute top-0 left-0 flex size-6 items-center justify-center';\n\nconst DOT =\n  'hairline-ring size-2.5 rounded-full transition-[scale,background-color,box-shadow] duration-150 ease-(--ease-out-strong)';\n\nconst DOT_FREE = 'bg-card ring-foreground/30';\n\nconst DOT_WIRED = 'bg-foreground/45 ring-transparent';\n\nconst DOT_OPEN = 'bg-card ring-primary scale-125 ring-2';\n\nconst DOT_HELD = 'bg-primary ring-primary scale-150';\n\nconst NOTHING = 'nothing';\n\n/** Stripe · Account created: what the step is set to, in one line. */\nfunction detailOf(step: Step) {\n  const parts: string[] = [];\n  for (const spec of FIELDS_OF[step.kind]) {\n    const value = step.values[spec.id] ?? '';\n    const label = choiceOf(spec, value)?.label ?? value;\n    if (label !== '') {\n      parts.push(label);\n    }\n  }\n  return parts.join(' · ');\n}\n\nfunction leadWordOf(line: OutputLine) {\n  if (line.target) {\n    return `${line.word} leads to ${shownNameOf(line.target)}`;\n  }\n  if (line.output === 'next') {\n    return 'The flow ends here';\n  }\n  return `${line.word} leads nowhere`;\n}\n\nfunction problemsWordOf(problems: Problem[]) {\n  const lines = problems.map((problem) => problem.line);\n  if (problems.length === 0) {\n    return '';\n  }\n  if (problems.length === 1) {\n    return `1 problem: ${lines[0]}.`;\n  }\n  return `${problems.length} problems: ${lines.join(', ')}.`;\n}\n\n/** The step said in full, since its place and its wires are only drawn. */\nfunction spokenOf(step: Step, lines: OutputLine[], problems: Problem[]) {\n  const leads = lines.map(leadWordOf);\n  const name = `${KIND_WORD[step.kind]}: ${shownNameOf(step)}.`;\n  return `${name} ${leads.join('. ')}. ${problemsWordOf(problems)}`;\n}\n\nfunction connectLabelOf(line: OutputLine) {\n  if (line.output === 'next') {\n    return 'Connect to';\n  }\n  return `If ${line.word.toLowerCase()}, connect to`;\n}\n\nfunction inputDotOf(aim: Aim, isReached: boolean) {\n  if (aim === 'aimed') {\n    return DOT_HELD;\n  }\n  if (aim === 'open') {\n    return DOT_OPEN;\n  }\n  if (isReached) {\n    return DOT_WIRED;\n  }\n  return DOT_FREE;\n}\n\nfunction outputDotOf(isHeld: boolean, isWired: boolean) {\n  if (isHeld) {\n    return DOT_HELD;\n  }\n  if (isWired) {\n    return DOT_WIRED;\n  }\n  return DOT_FREE;\n}\n\n/** A port sits on the edge of its card, in a square large enough for a finger. */\nfunction portStyleOf(port: Point, place: StepPlace) {\n  const x = port.x - place.box.x - 12;\n  const y = port.y - place.box.y - 12;\n  return { transform: `translate(${x}px, ${y}px)` };\n}\n\ntype StepMenuProps = {\n  step: Step;\n  graph: Graph;\n  lines: OutputLine[];\n  onAction: (action: BuilderAction) => void;\n  onRemove: (id: string) => void;\n};\n\n/** Connecting without dragging: every way out of the step, with the steps it may lead to. */\nfunction StepMenu({ step, graph, lines, onAction, onRemove }: StepMenuProps) {\n  const targets = targetsOf(graph, step.id);\n\n  function connect(output: OutputId, next: unknown) {\n    const target = targets.find((candidate) => candidate.id === next);\n    if (target) {\n      onAction({ type: 'connected', from: step.id, output, to: target.id });\n      return;\n    }\n    onAction({ type: 'disconnected', from: step.id, output });\n  }\n\n  return (\n    <DropdownMenu>\n      <DropdownMenuTrigger\n        render={\n          <Button\n            type='button'\n            variant='ghost'\n            size='icon-sm'\n            data-canvas-control\n            data-step-menu={step.id}\n            aria-label={`Actions for ${shownNameOf(step)}`}\n            className='text-muted-foreground absolute top-1 right-1 size-6'\n          />\n        }\n      >\n        <EllipsisIcon />\n      </DropdownMenuTrigger>\n      <DropdownMenuContent align='end' className='min-w-52'>\n        {lines.map((line) => (\n          <div key={line.output}>\n            <DropdownMenuLabel>{connectLabelOf(line)}</DropdownMenuLabel>\n            <DropdownMenuRadioGroup\n              aria-label={connectLabelOf(line)}\n              value={line.target?.id ?? NOTHING}\n              onValueChange={(next) => connect(line.output, next)}\n            >\n              {targets.map((target) => (\n                <DropdownMenuRadioItem key={target.id} value={target.id}>\n                  {shownNameOf(target)}\n                </DropdownMenuRadioItem>\n              ))}\n              <DropdownMenuRadioItem value={NOTHING}>\n                Nothing\n              </DropdownMenuRadioItem>\n            </DropdownMenuRadioGroup>\n          </div>\n        ))}\n        <DropdownMenuSeparator />\n        <DropdownMenuItem\n          variant='destructive'\n          onClick={() => onRemove(step.id)}\n        >\n          <TrashIcon />\n          Delete step\n        </DropdownMenuItem>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\nexport type StepCardProps = {\n  step: Step;\n  place: StepPlace;\n  graph: Graph;\n  /** The problems of this step alone. */\n  problems: Problem[];\n  aim: Aim;\n  isSelected: boolean;\n  /** The inspector shows this step. */\n  isOpen: boolean;\n  /** A pointer is moving it along the grid. */\n  isLifted: boolean;\n  /** The output a wire is held out of, by a pointer or by the demonstration. */\n  heldOutput: OutputId | null;\n  inspectorId: string;\n  onOpen: (id: string, isFromKeyboard: boolean) => void;\n  onReveal: (id: string) => void;\n  onAction: (action: BuilderAction) => void;\n  onRemove: (id: string) => void;\n};\n\nexport function StepCard({\n  step,\n  place,\n  graph,\n  problems,\n  aim,\n  isSelected,\n  isOpen,\n  isLifted,\n  heldOutput,\n  inspectorId,\n  onOpen,\n  onReveal,\n  onAction,\n  onRemove,\n}: StepCardProps) {\n  const lines = outputLinesOf(graph, step);\n  const [firstProblem] = problems;\n  const isReached = graph.connections.some((link) => link.to === step.id);\n  const isRestingSelected = isSelected && aim === 'idle';\n  const { box } = place;\n  const cardStyle = {\n    width: box.width,\n    height: box.height,\n    transform: `translate(${box.x}px, ${box.y}px)`,\n  };\n\n  function open(event: React.MouseEvent<HTMLButtonElement>) {\n    const isFromKeyboard = event.detail === 0;\n    onOpen(step.id, isFromKeyboard);\n  }\n\n  return (\n    <div\n      data-step={step.id}\n      style={cardStyle}\n      className={cn(\n        'absolute top-0 left-0 transition-transform duration-150 ease-(--ease-out-strong)',\n        isLifted && 'z-10'\n      )}\n    >\n      <button\n        type='button'\n        data-step-button={step.id}\n        aria-label={spokenOf(step, lines, problems)}\n        aria-expanded={isOpen}\n        aria-controls={inspectorId}\n        onClick={open}\n        onFocus={() => onReveal(step.id)}\n        className={cn(\n          CARD,\n          isRestingSelected && 'ring-primary/60 ring-2',\n          isLifted && 'cursor-grabbing shadow-lg shadow-black/10',\n          AIM_CLASS[aim]\n        )}\n      >\n        <StepTile step={step} />\n        <span className='flex max-h-full min-w-0 flex-1 flex-col overflow-hidden'>\n          <span className='text-muted-foreground pe-6 text-[11px] leading-4'>\n            {KIND_WORD[step.kind]}\n          </span>\n          <span className='line-clamp-2 text-[13px] leading-5 font-medium break-words'>\n            {shownNameOf(step)}\n          </span>\n          {firstProblem && (\n            <span className='text-warning-foreground flex items-start gap-1 text-xs leading-4'>\n              <TriangleAlertIcon className='mt-0.5 size-3 shrink-0' />\n              <span className='line-clamp-2'>{firstProblem.line}</span>\n            </span>\n          )}\n          {!firstProblem && (\n            <span className='text-muted-foreground line-clamp-2 text-xs leading-4'>\n              {detailOf(step)}\n            </span>\n          )}\n        </span>\n      </button>\n      <StepMenu\n        step={step}\n        graph={graph}\n        lines={lines}\n        onAction={onAction}\n        onRemove={onRemove}\n      />\n      {place.input && (\n        <span\n          aria-hidden='true'\n          style={portStyleOf(place.input, place)}\n          className={cn(PORT, 'pointer-events-none')}\n        >\n          <span className={cn(DOT, inputDotOf(aim, isReached))} />\n        </span>\n      )}\n      {lines.map((line) => {\n        const port = place.outputs[line.output];\n        if (!port) {\n          return null;\n        }\n        const isHeld = heldOutput === line.output;\n        const isWired = line.target !== undefined;\n        return (\n          <span\n            key={line.output}\n            data-port={line.output}\n            aria-hidden='true'\n            style={portStyleOf(port, place)}\n            className={cn(PORT, 'cursor-crosshair')}\n          >\n            <span\n              className={cn(\n                DOT,\n                'group-hover/port:ring-primary group-hover/port:scale-125',\n                outputDotOf(isHeld, isWired)\n              )}\n            />\n          </span>\n        );\n      })}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/step-card.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/step-tile.tsx",
      "content": "import { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport { GitBranchIcon, PlugIcon, ZapIcon } from '@/registry/ndeko/lib/icons';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { MeshTile } from '@/registry/ndeko/ui/mesh-tile';\n\nimport { choiceOf, FIELDS_OF, type Step } from './data';\n\nconst KIND_PLATE =\n  'gem-plate inline-flex size-7 shrink-0 items-center justify-center rounded-md [--gem:var(--primary)] [&_svg]:size-4';\n\nconst EMPTY_TILE =\n  'keycap-3d text-muted-foreground inline-flex size-7 shrink-0 items-center justify-center rounded-md [&_svg]:size-4';\n\nfunction appBrandOf(step: Step) {\n  const appField = FIELDS_OF.tool.find((spec) => spec.id === 'app');\n  if (!appField) {\n    return undefined;\n  }\n  return choiceOf(appField, step.values.app)?.brand;\n}\n\n/**\n * What a step wears: a trigger and a condition the plate of their kind, an agent its own picture,\n * a tool the mark of the app it acts in.\n */\nexport function StepTile({ step }: { step: Step }) {\n  if (step.kind === 'trigger') {\n    return (\n      <span aria-hidden='true' className={KIND_PLATE}>\n        <ZapIcon />\n      </span>\n    );\n  }\n  if (step.kind === 'condition') {\n    return (\n      <span aria-hidden='true' className={KIND_PLATE}>\n        <GitBranchIcon />\n      </span>\n    );\n  }\n  if (step.kind === 'agent') {\n    const color = seriesColorOf(step.series ?? 1);\n    return <MeshTile seed={step.id} color={color} size='lg' />;\n  }\n  const brand = appBrandOf(step);\n  if (brand) {\n    return <BrandTile brand={brand} size='lg' />;\n  }\n  return (\n    <span aria-hidden='true' className={EMPTY_TILE}>\n      <PlugIcon />\n    </span>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/step-tile.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/wires.tsx",
      "content": "'use client';\n\nimport { motion } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { EASE_OUT_STRONG } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport type { CanvasLayout, PlacedWire } from './layout';\nimport type { Wire } from './session';\n\nconst LAYER =\n  'pointer-events-none absolute top-0 left-0 size-px overflow-visible';\n\n/** Where the browser can ease a path, a wire follows its step when the step moves along the grid. */\nconst WIRE =\n  'fill-none stroke-[1.5px] transition-[d,stroke] duration-[150ms,300ms] ease-(--ease-out-strong) [stroke-linecap:round]';\n\n/** A wire that has just been made shows in the brand colour, then settles among the others. */\nconst LANDED = 'starting:stroke-primary';\n\nconst HELD = 'fill-none stroke-primary stroke-2 [stroke-linecap:round]';\n\nconst DRAW = { duration: 0.5, ease: EASE_OUT_STRONG };\n\nconst REACH = { duration: 0.45, ease: EASE_OUT_STRONG };\n\nfunction toneOf(isLit: boolean) {\n  if (isLit) {\n    return 'stroke-primary/70';\n  }\n  return 'stroke-foreground/30';\n}\n\nfunction drawStartOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return { pathLength: 1 };\n  }\n  return { pathLength: 0 };\n}\n\nfunction touchesStep(wire: Wire, stepId: string | null) {\n  return wire.from === stepId || wire.to === stepId;\n}\n\ntype WirePathProps = {\n  wire: PlacedWire<Wire>;\n  isLit: boolean;\n};\n\n/** Only a wire made from a menu draws itself: one let go by a hand is already where it lands. */\nfunction WirePath({ wire, isLit }: WirePathProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const tone = toneOf(isLit);\n\n  if (wire.link.arrival === 'drawn') {\n    return (\n      <motion.path\n        d={wire.path}\n        initial={drawStartOf(shouldReduceMotion)}\n        animate={{ pathLength: 1 }}\n        transition={DRAW}\n        className={cn(WIRE, LANDED, tone)}\n      />\n    );\n  }\n\n  const hasLanded = wire.link.arrival === 'dropped';\n\n  return <path d={wire.path} className={cn(WIRE, hasLanded && LANDED, tone)} />;\n}\n\ntype WireLayerProps = {\n  layout: CanvasLayout<Wire>;\n  selectedId: string | null;\n};\n\nexport function WireLayer({ layout, selectedId }: WireLayerProps) {\n  return (\n    <svg aria-hidden='true' className={LAYER}>\n      {layout.wires.map((wire) => (\n        <WirePath\n          key={`${wire.id}:${wire.link.to}`}\n          wire={wire}\n          isLit={touchesStep(wire.link, selectedId)}\n        />\n      ))}\n      {layout.labels.map((label) => (\n        <text\n          key={label.id}\n          x={label.x}\n          y={label.y}\n          className='fill-muted-foreground text-[10px] font-medium'\n        >\n          {label.text}\n        </text>\n      ))}\n    </svg>\n  );\n}\n\ntype HeldLayerProps = {\n  /** The wire the demonstration holds out, from its port to the step it aims at. */\n  demoPath: string | null;\n  /** The wire a pointer holds. Its path is written to the element on every move, never rendered. */\n  liveRef: React.Ref<SVGPathElement>;\n};\n\nexport function HeldLayer({ demoPath, liveRef }: HeldLayerProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n\n  return (\n    <svg aria-hidden='true' className={LAYER}>\n      {demoPath && (\n        <motion.path\n          key={demoPath}\n          d={demoPath}\n          initial={drawStartOf(shouldReduceMotion)}\n          animate={{ pathLength: 1 }}\n          transition={REACH}\n          className={HELD}\n        />\n      )}\n      <path ref={liveRef} className={HELD} />\n    </svg>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/wires.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/inspector.tsx",
      "content": "'use client';\n\nimport { useId } from 'react';\n\nimport { TrashIcon, XIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold } from '@/registry/ndeko/ui/chat-motion';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/registry/ndeko/ui/select';\nimport { Textarea } from '@/registry/ndeko/ui/textarea';\n\nimport {\n  FIELDS_OF,\n  KIND_WORD,\n  shownNameOf,\n  type FieldSpec,\n  type Step,\n} from './data';\nimport {\n  outputLinesOf,\n  type Graph,\n  type OutputLine,\n  type Problem,\n  type ProblemField,\n} from './graph';\nimport type { BuilderAction } from './session';\nimport { StepTile } from './step-tile';\n\ntype FieldLook = Omit<FieldSpec, 'id'>;\n\nconst NAME_LOOK: FieldLook = {\n  label: 'Name',\n  control: 'text',\n  placeholder: 'Name the step',\n  missingLine: 'Name the step',\n};\n\nfunction describedByOf(isMissing: boolean, hintId: string) {\n  if (isMissing) {\n    return hintId;\n  }\n  return undefined;\n}\n\n/** The select holds nothing until a choice is made, so its placeholder shows. */\nfunction chosenOf(value: string) {\n  if (value === '') {\n    return null;\n  }\n  return value;\n}\n\nfunction isMissingField(problems: Problem[], field: ProblemField) {\n  return problems.some((problem) => problem.field === field);\n}\n\ntype ControlProps = {\n  look: FieldLook;\n  value: string;\n  fieldId: string;\n  labelId: string;\n  isMissing: boolean;\n  describedBy: string | undefined;\n  onChange: (value: string) => void;\n};\n\nfunction ChoiceControl({\n  look,\n  value,\n  fieldId,\n  labelId,\n  isMissing,\n  describedBy,\n  onChange,\n}: ControlProps) {\n  const choices = look.choices ?? [];\n\n  function change(next: unknown) {\n    const choice = choices.find((candidate) => candidate.value === next);\n    if (choice) {\n      onChange(choice.value);\n    }\n  }\n\n  return (\n    <Select items={choices} value={chosenOf(value)} onValueChange={change}>\n      <SelectTrigger\n        id={fieldId}\n        aria-labelledby={labelId}\n        aria-invalid={isMissing}\n        aria-describedby={describedBy}\n      >\n        <SelectValue placeholder={look.placeholder} />\n      </SelectTrigger>\n      <SelectContent>\n        {choices.map((choice) => (\n          <SelectItem key={choice.value} value={choice.value}>\n            {choice.brand && <BrandTile brand={choice.brand} size='sm' />}\n            {choice.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\ntype FieldRowProps = {\n  look: FieldLook;\n  value: string;\n  isMissing: boolean;\n  onChange: (value: string) => void;\n};\n\n/** The hint of an empty field is the sentence the step shows on the canvas. */\nfunction FieldRow({ look, value, isMissing, onChange }: FieldRowProps) {\n  const fieldId = useId();\n  const labelId = useId();\n  const hintId = useId();\n  const describedBy = describedByOf(isMissing, hintId);\n\n  return (\n    <div className='flex flex-col gap-1.5'>\n      <label id={labelId} htmlFor={fieldId} className='text-xs font-medium'>\n        {look.label}\n      </label>\n      {look.control === 'text' && (\n        <Input\n          id={fieldId}\n          value={value}\n          autoComplete='off'\n          placeholder={look.placeholder}\n          aria-invalid={isMissing}\n          aria-describedby={describedBy}\n          onChange={(event) => onChange(event.target.value)}\n        />\n      )}\n      {look.control === 'textarea' && (\n        <Textarea\n          id={fieldId}\n          value={value}\n          rows={3}\n          placeholder={look.placeholder}\n          aria-invalid={isMissing}\n          aria-describedby={describedBy}\n          onChange={(event) => onChange(event.target.value)}\n        />\n      )}\n      {look.control === 'select' && (\n        <ChoiceControl\n          look={look}\n          value={value}\n          fieldId={fieldId}\n          labelId={labelId}\n          isMissing={isMissing}\n          describedBy={describedBy}\n          onChange={onChange}\n        />\n      )}\n      <Fold open={isMissing}>\n        <p id={hintId} className='text-destructive-ink text-xs'>\n          {look.missingLine}\n        </p>\n      </Fold>\n    </div>\n  );\n}\n\nfunction openWordOf(mustLead: boolean) {\n  if (mustLead) {\n    return 'Not connected';\n  }\n  return 'The flow ends here';\n}\n\nfunction openToneOf(mustLead: boolean) {\n  if (mustLead) {\n    return 'text-warning-foreground';\n  }\n  return 'text-muted-foreground';\n}\n\n/** Both answers of a condition have to lead somewhere. Any other step may end the flow. */\nfunction LeadRow({ line }: { line: OutputLine }) {\n  const mustLead = line.output !== 'next';\n\n  return (\n    <li className='flex items-center gap-2 text-xs'>\n      <span className='text-muted-foreground w-8 shrink-0'>{line.word}</span>\n      {line.target && (\n        <span className='min-w-0 truncate font-medium'>\n          {shownNameOf(line.target)}\n        </span>\n      )}\n      {!line.target && (\n        <span className={cn('min-w-0 truncate', openToneOf(mustLead))}>\n          {openWordOf(mustLead)}\n        </span>\n      )}\n    </li>\n  );\n}\n\nexport type InspectorProps = {\n  step: Step;\n  graph: Graph;\n  /** The problems of this step alone. */\n  problems: Problem[];\n  headingId: string;\n  onAction: (action: BuilderAction) => void;\n  onRemove: (id: string) => void;\n  onClose: () => void;\n};\n\nexport function Inspector({\n  step,\n  graph,\n  problems,\n  headingId,\n  onAction,\n  onRemove,\n  onClose,\n}: InspectorProps) {\n  const lines = outputLinesOf(graph, step);\n  const flowProblems = problems.filter(\n    (problem) => problem.field === undefined\n  );\n  const hasFlowProblems = flowProblems.length > 0;\n\n  return (\n    <div className='flex min-h-0 flex-1 flex-col gap-4'>\n      <header className='flex items-center gap-2.5'>\n        <StepTile step={step} />\n        <div className='flex min-w-0 flex-1 flex-col'>\n          <span className='text-muted-foreground text-[11px] leading-4'>\n            {KIND_WORD[step.kind]}\n          </span>\n          <h2\n            id={headingId}\n            tabIndex={-1}\n            data-inspector-heading\n            className='focus-visible:ring-ring/25 truncate rounded-sm text-sm leading-5 font-medium outline-none focus-visible:ring-[3px]'\n          >\n            {shownNameOf(step)}\n          </h2>\n        </div>\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Close the inspector'\n          onClick={onClose}\n          className='text-muted-foreground'\n        >\n          <XIcon />\n        </Button>\n      </header>\n      <div className='-mx-1 flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-1 pb-1'>\n        {hasFlowProblems && (\n          <ul className='bg-warning/10 text-warning-foreground flex flex-col gap-1 rounded-md px-2.5 py-2 text-xs'>\n            {flowProblems.map((problem) => (\n              <li key={problem.line}>{problem.line}</li>\n            ))}\n          </ul>\n        )}\n        <FieldRow\n          look={NAME_LOOK}\n          value={step.name}\n          isMissing={isMissingField(problems, 'name')}\n          onChange={(name) => onAction({ type: 'renamed', id: step.id, name })}\n        />\n        {FIELDS_OF[step.kind].map((spec) => (\n          <FieldRow\n            key={spec.id}\n            look={spec}\n            value={step.values[spec.id] ?? ''}\n            isMissing={isMissingField(problems, spec.id)}\n            onChange={(value) =>\n              onAction({\n                type: 'fieldChanged',\n                id: step.id,\n                field: spec.id,\n                value,\n              })\n            }\n          />\n        ))}\n        <div className='flex flex-col gap-1.5'>\n          <h3 className='text-xs font-medium'>Leads to</h3>\n          <ul className='bg-foreground/[0.04] flex flex-col gap-1.5 rounded-md px-2.5 py-2'>\n            {lines.map((line) => (\n              <LeadRow key={line.output} line={line} />\n            ))}\n          </ul>\n        </div>\n      </div>\n      <footer>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          onClick={() => onRemove(step.id)}\n          className='text-destructive-ink -ms-2'\n        >\n          <TrashIcon />\n          Delete step\n        </Button>\n      </footer>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/inspector.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/side-panel.tsx",
      "content": "'use client';\n\nimport { useRef } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nexport const DEFAULT_WIDTH = 320;\n\nconst MIN_WIDTH = 264;\n\nconst MAX_WIDTH = 440;\n\nconst KEY_STEP = 16;\n\n/** How far the sheet has to be pulled down before letting go closes it. */\nconst CLOSE_AFTER_PX = 72;\n\n/** The share of the canvas the sheet covers, which the canvas keeps clear of the selected step. */\nexport const SHEET_SHARE = 0.58;\n\nfunction bounded(width: number) {\n  const atLeast = Math.max(MIN_WIDTH, width);\n  return Math.min(MAX_WIDTH, atLeast);\n}\n\n/** The panel sits on the right, so moving the handle to the left widens it. */\nfunction widthFromKey(key: string, width: number) {\n  if (key === 'ArrowLeft') {\n    return bounded(width + KEY_STEP);\n  }\n  if (key === 'ArrowRight') {\n    return bounded(width - KEY_STEP);\n  }\n  if (key === 'Home') {\n    return MAX_WIDTH;\n  }\n  if (key === 'End') {\n    return MIN_WIDTH;\n  }\n  return null;\n}\n\ntype ResizeHandleProps = {\n  width: number;\n  /** The element whose `--inspector` the handle drives. */\n  containerRef: React.RefObject<HTMLElement | null>;\n  onWidthChange: (width: number) => void;\n};\n\n/** While it is dragged the width is written to the container. React hears about it once, on release. */\nexport function ResizeHandle({\n  width,\n  containerRef,\n  onWidthChange,\n}: ResizeHandleProps) {\n  const dragged = useRef<number | null>(null);\n\n  function startDrag(event: React.PointerEvent<HTMLDivElement>) {\n    event.currentTarget.setPointerCapture(event.pointerId);\n    dragged.current = width;\n  }\n\n  function drag(event: React.PointerEvent<HTMLDivElement>) {\n    const container = containerRef.current;\n    const isDragging = dragged.current !== null;\n    if (!container || !isDragging) {\n      return;\n    }\n    const box = container.getBoundingClientRect();\n    const next = bounded(box.right - event.clientX);\n    dragged.current = next;\n    container.style.setProperty('--inspector', `${next}px`);\n  }\n\n  function endDrag() {\n    const next = dragged.current;\n    dragged.current = null;\n    if (next !== null) {\n      onWidthChange(Math.round(next));\n    }\n  }\n\n  function resizeWithKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    const next = widthFromKey(event.key, width);\n    if (next === null) {\n      return;\n    }\n    event.preventDefault();\n    onWidthChange(next);\n  }\n\n  return (\n    <div\n      role='separator'\n      tabIndex={0}\n      aria-orientation='vertical'\n      aria-label='Resize the canvas and the inspector'\n      aria-valuemin={MIN_WIDTH}\n      aria-valuemax={MAX_WIDTH}\n      aria-valuenow={width}\n      onPointerDown={startDrag}\n      onPointerMove={drag}\n      onPointerUp={endDrag}\n      onPointerCancel={endDrag}\n      onDoubleClick={() => onWidthChange(DEFAULT_WIDTH)}\n      onKeyDown={resizeWithKeys}\n      className='group/handle focus-visible:ring-ring/25 flex w-3 shrink-0 cursor-col-resize touch-none items-center justify-center rounded-full outline-none focus-visible:ring-[3px]'\n    >\n      <span className='bg-foreground/15 group-hover/handle:bg-foreground/35 group-active/handle:bg-primary h-8 w-1 rounded-full transition-colors duration-150' />\n    </div>\n  );\n}\n\nfunction panelOf(isOpen: boolean) {\n  if (isOpen) {\n    return 'translate-y-0';\n  }\n  return 'translate-y-[calc(100%+1rem)]';\n}\n\n/**\n * Escape pressed in the panel itself. The list of a select opened from it is drawn elsewhere on the\n * page and closes on its own Escape, which still reaches the panel through React.\n */\nexport function isOwnEscape(event: React.KeyboardEvent<HTMLElement>) {\n  const target = event.target;\n  const isInside =\n    target instanceof Node && event.currentTarget.contains(target);\n  return isInside && event.key === 'Escape';\n}\n\ntype BottomSheetProps = {\n  id: string;\n  isOpen: boolean;\n  label: string;\n  onClose: () => void;\n  children: React.ReactNode;\n};\n\n/**\n * Drawn inside the block, over the lower part of the canvas, which stays in use above it. Its grip\n * follows the finger and closes the sheet when it is pulled far enough.\n */\nexport function BottomSheet({\n  id,\n  isOpen,\n  label,\n  onClose,\n  children,\n}: BottomSheetProps) {\n  const panelRef = useRef<HTMLDivElement>(null);\n  const startY = useRef<number | null>(null);\n  const pulled = useRef(0);\n\n  function startPull(event: React.PointerEvent<HTMLButtonElement>) {\n    event.currentTarget.setPointerCapture(event.pointerId);\n    startY.current = event.clientY;\n    pulled.current = 0;\n  }\n\n  function pull(event: React.PointerEvent<HTMLButtonElement>) {\n    const panel = panelRef.current;\n    const origin = startY.current;\n    if (!panel || origin === null) {\n      return;\n    }\n    const distance = Math.max(0, event.clientY - origin);\n    pulled.current = distance;\n    panel.style.transition = 'none';\n    panel.style.translate = `0 ${distance}px`;\n  }\n\n  function endPull() {\n    const panel = panelRef.current;\n    const wasPulling = startY.current !== null;\n    startY.current = null;\n    if (!panel || !wasPulling) {\n      return;\n    }\n    panel.style.transition = '';\n    panel.style.translate = '';\n    if (pulled.current > CLOSE_AFTER_PX) {\n      pulled.current = 0;\n      onClose();\n    }\n  }\n\n  /** A press on the grip closes the sheet. The click that ends a pull does not. */\n  function closeFromGrip() {\n    const wasPulled = pulled.current > 4;\n    pulled.current = 0;\n    if (!wasPulled) {\n      onClose();\n    }\n  }\n\n  function closeOnEscape(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (isOwnEscape(event)) {\n      onClose();\n    }\n  }\n\n  return (\n    <div\n      ref={panelRef}\n      id={id}\n      role='dialog'\n      aria-label={label}\n      inert={!isOpen}\n      onKeyDown={closeOnEscape}\n      className={cn(\n        'bg-card hairline-ring ring-border absolute inset-x-2 bottom-2 z-10 flex h-[58%] flex-col rounded-2xl px-4 pb-4 shadow-xl shadow-black/8 transition-[translate] duration-300 ease-(--ease-drawer)',\n        panelOf(isOpen)\n      )}\n    >\n      <button\n        type='button'\n        aria-label={`Close ${label}`}\n        onClick={closeFromGrip}\n        onPointerDown={startPull}\n        onPointerMove={pull}\n        onPointerUp={endPull}\n        onPointerCancel={endPull}\n        className='group/grip flex h-7 w-full shrink-0 cursor-grab touch-none items-center justify-center outline-none active:cursor-grabbing'\n      >\n        <span className='bg-foreground/20 group-focus-visible/grip:bg-primary h-1 w-9 rounded-full' />\n      </button>\n      {children}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/side-panel.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/zoom-control.tsx",
      "content": "'use client';\n\nimport { MaximizeIcon, MinusIcon, PlusIcon } from '@/registry/ndeko/lib/icons';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport {\n  MAX_ZOOM,\n  MIN_ZOOM,\n  useZoomPercent,\n  type CanvasView,\n} from './use-pan-zoom';\n\nconst ZOOM_STEP = 1.25;\n\nconst MIN_PERCENT = Math.round(MIN_ZOOM * 100);\n\nconst MAX_PERCENT = Math.round(MAX_ZOOM * 100);\n\ntype ZoomControlProps = {\n  view: CanvasView;\n  /** What Fit brings into view, for its accessible name. */\n  subject: string;\n};\n\n/** It sits on the canvas and is the only part that renders again while the zoom changes. */\nexport function ZoomControl({ view, subject }: ZoomControlProps) {\n  const percent = useZoomPercent(view);\n  const isSmallest = percent <= MIN_PERCENT;\n  const isLargest = percent >= MAX_PERCENT;\n\n  return (\n    <div\n      role='group'\n      aria-label='Zoom'\n      className='bg-card hairline-ring ring-border absolute bottom-3 left-3 flex items-center gap-0.5 rounded-full p-0.5 shadow-[0_1px_2px_rgb(0_0_0/0.05)]'\n    >\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label='Zoom out'\n        disabled={isSmallest}\n        focusableWhenDisabled\n        onClick={() => view.zoomStep(1 / ZOOM_STEP)}\n        className='rounded-full'\n      >\n        <MinusIcon />\n      </Button>\n      <Button\n        type='button'\n        variant='ghost'\n        size='sm'\n        aria-label={`Zoom ${percent}%. Reset to 100%`}\n        onClick={() => view.zoomTo(1)}\n        className='w-12 rounded-full px-0 tabular-nums'\n      >\n        {percent}%\n      </Button>\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label='Zoom in'\n        disabled={isLargest}\n        focusableWhenDisabled\n        onClick={() => view.zoomStep(ZOOM_STEP)}\n        className='rounded-full'\n      >\n        <PlusIcon />\n      </Button>\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label={`Fit ${subject} in view`}\n        onClick={() => view.fit()}\n        className='rounded-full'\n      >\n        <MaximizeIcon />\n      </Button>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/zoom-control.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/use-pan-zoom.ts",
      "content": "'use client';\n\nimport {\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from 'react';\n\ntype Point = {\n  x: number;\n  y: number;\n};\n\ntype Box = Point & {\n  width: number;\n  height: number;\n};\n\ntype Viewport = Point & {\n  zoom: number;\n};\n\ntype Span = {\n  centre: Point;\n  distance: number;\n};\n\nexport const MIN_ZOOM = 0.4;\n\nexport const MAX_ZOOM = 1.6;\n\n/** Fit never enlarges past full size: a small flow stays readable instead of filling the frame. */\nconst FIT_MAX_ZOOM = 1;\n\n/** Nor does it shrink a flow until its text cannot be read: what does not fit is reached by panning. */\nconst FIT_MIN_ZOOM = 0.75;\n\nconst FIT_MARGIN = 20;\n\nconst REVEAL_MARGIN = 16;\n\nconst EASED = 'transform 220ms cubic-bezier(0.23, 1, 0.32, 1)';\n\n/** A wheel that reports lines, as some mice do, moves this many pixels a line. */\nconst LINE_PIXELS = 16;\n\nconst WHEEL_DOM_DELTA_LINE = 1;\n\nconst WHEEL_ZOOM_RATE = 0.01;\n\n/** One wheel event never zooms by more than about a quarter. */\nconst WHEEL_ZOOM_LIMIT = 24;\n\nconst NO_BOX: Box = { x: 0, y: 0, width: 1, height: 1 };\n\nfunction clamp(value: number, min: number, max: number) {\n  const atLeast = Math.max(value, min);\n  return Math.min(atLeast, max);\n}\n\nfunction transitionOf(isEased: boolean) {\n  if (isEased) {\n    return EASED;\n  }\n  return 'none';\n}\n\n/** How far a span has to move to sit between two edges. Its start wins when it is too long to fit. */\nfunction shiftOf(start: number, end: number, min: number, max: number) {\n  if (start < min) {\n    return min - start;\n  }\n  if (end > max) {\n    const back = max - end;\n    const untilStart = min - start;\n    return Math.max(back, untilStart);\n  }\n  return 0;\n}\n\n/**\n * Where the content starts along one axis of the frame: centred when it fits, at the margin when it\n * does not, so the start of the flow is what shows.\n */\nfunction startOf(\n  frameSize: number,\n  contentStart: number,\n  contentSize: number,\n  zoom: number\n) {\n  const scaled = contentSize * zoom;\n  const room = frameSize - FIT_MARGIN * 2;\n  if (scaled <= room) {\n    return (frameSize - scaled) / 2 - contentStart * zoom;\n  }\n  return FIT_MARGIN - contentStart * zoom;\n}\n\nfunction spanOf(pointers: Map<number, Point>): Span | null {\n  const [first, second] = Array.from(pointers.values());\n  if (!first || !second) {\n    return null;\n  }\n  const centre = { x: (first.x + second.x) / 2, y: (first.y + second.y) / 2 };\n  const distance = Math.hypot(second.x - first.x, second.y - first.y);\n  return { centre, distance };\n}\n\nfunction wheelUnitOf(event: WheelEvent) {\n  if (event.deltaMode === WHEEL_DOM_DELTA_LINE) {\n    return LINE_PIXELS;\n  }\n  return 1;\n}\n\n/** Ctrl or Cmd with the wheel, which is also how a trackpad reports a pinch. */\nfunction isZoomWheel(event: WheelEvent) {\n  return event.ctrlKey || event.metaKey;\n}\n\n/**\n * Pan and zoom of a canvas as one transform on one plane element. The transform is written to the\n * element, never through React state: a drag or a pinch changes it on every frame.\n */\nexport function createCanvasView() {\n  let frame: HTMLElement | null = null;\n  let plane: HTMLElement | null = null;\n  let viewport: Viewport = { x: 0, y: 0, zoom: 1 };\n  let content = NO_BOX;\n  let coveredShare = 0;\n  let pinned: Box | null = null;\n  /** True once a person has moved the view: it is no longer refitted when the frame changes size. */\n  let isManual = false;\n  let hasFitted = false;\n  const listeners = new Set<() => void>();\n  const pointers = new Map<number, Point>();\n\n  function sizeOf() {\n    if (!frame) {\n      return null;\n    }\n    return { width: frame.clientWidth, height: frame.clientHeight };\n  }\n\n  function apply(next: Viewport, isEased: boolean) {\n    const x = Math.round(next.x);\n    const y = Math.round(next.y);\n    viewport = { x, y, zoom: next.zoom };\n    if (plane) {\n      plane.style.transition = transitionOf(isEased);\n      plane.style.transform = `translate(${x}px, ${y}px) scale(${next.zoom})`;\n    }\n    listeners.forEach((listener) => listener());\n  }\n\n  function localOf(client: Point): Point {\n    const rect = frame?.getBoundingClientRect();\n    if (!rect) {\n      return client;\n    }\n    return { x: client.x - rect.left, y: client.y - rect.top };\n  }\n\n  function centreOf(): Point {\n    const size = sizeOf();\n    if (!size) {\n      return { x: 0, y: 0 };\n    }\n    return { x: size.width / 2, y: size.height / 2 };\n  }\n\n  /** The point under `anchor` stays under it while the zoom changes. */\n  function zoomedAround(factor: number, anchor: Point): Viewport {\n    const zoom = clamp(viewport.zoom * factor, MIN_ZOOM, MAX_ZOOM);\n    const ratio = zoom / viewport.zoom;\n    const x = anchor.x - (anchor.x - viewport.x) * ratio;\n    const y = anchor.y - (anchor.y - viewport.y) * ratio;\n    return { x, y, zoom };\n  }\n\n  function fitted(): Viewport | null {\n    const size = sizeOf();\n    if (!size) {\n      return null;\n    }\n    const roomX = size.width - FIT_MARGIN * 2;\n    const roomY = size.height - FIT_MARGIN * 2;\n    const scale = Math.min(roomX / content.width, roomY / content.height);\n    const zoom = clamp(scale, FIT_MIN_ZOOM, FIT_MAX_ZOOM);\n    const x = startOf(size.width, content.x, content.width, zoom);\n    const y = startOf(size.height, content.y, content.height, zoom);\n    return { x, y, zoom };\n  }\n\n  function revealed(box: Box): Viewport | null {\n    const size = sizeOf();\n    if (!size) {\n      return null;\n    }\n    const left = box.x * viewport.zoom + viewport.x;\n    const top = box.y * viewport.zoom + viewport.y;\n    const right = left + box.width * viewport.zoom;\n    const bottom = top + box.height * viewport.zoom;\n    const visibleHeight = size.height * (1 - coveredShare);\n    const maxX = size.width - REVEAL_MARGIN;\n    const maxY = visibleHeight - REVEAL_MARGIN;\n    const dx = shiftOf(left, right, REVEAL_MARGIN, maxX);\n    const dy = shiftOf(top, bottom, REVEAL_MARGIN, maxY);\n    if (dx === 0 && dy === 0) {\n      return null;\n    }\n    return { ...viewport, x: viewport.x + dx, y: viewport.y + dy };\n  }\n\n  function refit(isEased: boolean) {\n    const next = fitted();\n    if (next) {\n      hasFitted = true;\n      apply(next, isEased);\n    }\n  }\n\n  /**\n   * Focus on a step outside the frame makes the browser scroll the frame to it. The scroll is taken\n   * back and given to the transform, so the plane stays the only thing that moves.\n   */\n  function absorbScroll() {\n    if (!frame) {\n      return;\n    }\n    const left = frame.scrollLeft;\n    const top = frame.scrollTop;\n    if (left === 0 && top === 0) {\n      return;\n    }\n    frame.scrollLeft = 0;\n    frame.scrollTop = 0;\n    apply({ ...viewport, x: viewport.x - left, y: viewport.y - top }, false);\n  }\n\n  function reveal(box: Box) {\n    absorbScroll();\n    if (!hasFitted) {\n      return;\n    }\n    const next = revealed(box);\n    if (next) {\n      apply(next, true);\n    }\n  }\n\n  function panBy(dx: number, dy: number) {\n    isManual = true;\n    apply({ ...viewport, x: viewport.x + dx, y: viewport.y + dy }, false);\n  }\n\n  function pinch(before: Span, after: Span) {\n    if (before.distance === 0) {\n      return;\n    }\n    const factor = after.distance / before.distance;\n    const zoomed = zoomedAround(factor, localOf(before.centre));\n    const x = zoomed.x + after.centre.x - before.centre.x;\n    const y = zoomed.y + after.centre.y - before.centre.y;\n    isManual = true;\n    apply({ x, y, zoom: zoomed.zoom }, false);\n  }\n\n  return {\n    /** The frame that clips the canvas and the plane that moves inside it. */\n    attach(nextFrame: HTMLElement | null, nextPlane: HTMLElement | null) {\n      frame = nextFrame;\n      plane = nextPlane;\n    },\n    subscribe(listener: () => void) {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n    percent() {\n      return Math.round(viewport.zoom * 100);\n    },\n    zoom() {\n      return viewport.zoom;\n    },\n    origin(): Point {\n      return { x: viewport.x, y: viewport.y };\n    },\n    /** A point of the screen as a point of the plane. */\n    toPlane(client: Point): Point {\n      const local = localOf(client);\n      const x = (local.x - viewport.x) / viewport.zoom;\n      const y = (local.y - viewport.y) / viewport.zoom;\n      return { x, y };\n    },\n    panBy,\n    zoomStep(factor: number) {\n      isManual = true;\n      apply(zoomedAround(factor, centreOf()), true);\n    },\n    zoomTo(zoom: number) {\n      isManual = true;\n      apply(zoomedAround(zoom / viewport.zoom, centreOf()), true);\n    },\n    /** Shows everything again and hands the view back to the canvas, which refits it on its own. */\n    fit() {\n      isManual = false;\n      refit(true);\n    },\n    /** What Fit shows, and the share of the frame a sheet covers from the bottom, from 0 to 1. */\n    setScene(bounds: Box, covered: number) {\n      content = bounds;\n      coveredShare = covered;\n    },\n    /** Called when the frame, the layout or the sheet changed: refits a view nobody moved. */\n    settle() {\n      const isFirst = !hasFitted;\n      if (isFirst || !isManual) {\n        refit(!isFirst);\n      }\n      if (!pinned) {\n        return;\n      }\n      const next = revealed(pinned);\n      if (next) {\n        apply(next, !isFirst);\n      }\n    },\n    reveal,\n    /** The box to keep in view, now and whenever the frame changes size. */\n    pin(box: Box | null) {\n      pinned = box;\n      if (box) {\n        reveal(box);\n      }\n    },\n    absorbScroll,\n    grab(pointerId: number, at: Point) {\n      pointers.set(pointerId, at);\n    },\n    /** One pointer pans. Two pointers pinch: the zoom follows their distance, the pan their middle. */\n    drag(pointerId: number, now: Point) {\n      const last = pointers.get(pointerId);\n      if (!last) {\n        return;\n      }\n      const before = spanOf(pointers);\n      pointers.set(pointerId, now);\n      const after = spanOf(pointers);\n      if (before && after) {\n        pinch(before, after);\n        return;\n      }\n      panBy(now.x - last.x, now.y - last.y);\n    },\n    release(pointerId: number) {\n      pointers.delete(pointerId);\n    },\n    isHeld() {\n      return pointers.size > 0;\n    },\n    /** A plain wheel pans. A zoom wheel zooms around the pointer. */\n    takeWheel(event: WheelEvent) {\n      const unit = wheelUnitOf(event);\n      if (!isZoomWheel(event)) {\n        panBy(-event.deltaX * unit, -event.deltaY * unit);\n        return;\n      }\n      const raw = event.deltaY * unit;\n      const delta = clamp(raw, -WHEEL_ZOOM_LIMIT, WHEEL_ZOOM_LIMIT);\n      const factor = Math.exp(-delta * WHEEL_ZOOM_RATE);\n      const anchor = localOf({ x: event.clientX, y: event.clientY });\n      isManual = true;\n      apply(zoomedAround(factor, anchor), false);\n    },\n  };\n}\n\nexport type CanvasView = ReturnType<typeof createCanvasView>;\n\n/**\n * The frame and the plane of a canvas, with its view. Call it in the component that renders them,\n * before any effect that uses the view. A plain wheel pans only while the focus is inside the\n * parent of the frame, so a page scrolled past the canvas keeps scrolling. A pinch always zooms the\n * canvas under it, never the page.\n */\nexport function usePanZoom() {\n  const frameRef = useRef<HTMLDivElement>(null);\n  const planeRef = useRef<HTMLDivElement>(null);\n  const [view] = useState(createCanvasView);\n  const [isMeasured, setIsMeasured] = useState(false);\n\n  useLayoutEffect(() => {\n    view.attach(frameRef.current, planeRef.current);\n    return () => view.attach(null, null);\n  }, [view]);\n\n  useEffect(() => {\n    const frame = frameRef.current;\n    if (!frame) {\n      return;\n    }\n    const scope = frame.parentElement ?? frame;\n    let hasMeasured = false;\n\n    /** The first fit is left to the canvas, which knows by then what it shows. */\n    function measure() {\n      setIsMeasured(true);\n      if (hasMeasured) {\n        view.settle();\n      }\n      hasMeasured = true;\n    }\n\n    function takeWheel(event: WheelEvent) {\n      const isEngaged = scope.matches(':focus-within');\n      const isZoom = isZoomWheel(event);\n      if (!isEngaged && !isZoom) {\n        return;\n      }\n      event.preventDefault();\n      view.takeWheel(event);\n    }\n\n    const observer = new ResizeObserver(measure);\n    observer.observe(frame);\n    frame.addEventListener('wheel', takeWheel, { passive: false });\n    frame.addEventListener('scroll', view.absorbScroll);\n    return () => {\n      observer.disconnect();\n      frame.removeEventListener('wheel', takeWheel);\n      frame.removeEventListener('scroll', view.absorbScroll);\n    };\n  }, [view]);\n\n  return { frameRef, planeRef, view, isMeasured };\n}\n\nfunction fullSize() {\n  return 100;\n}\n\n/** The zoom as a whole percentage. Only the text that shows it renders again when it changes. */\nexport function useZoomPercent(view: CanvasView) {\n  return useSyncExternalStore(view.subscribe, view.percent, fullSize);\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/use-pan-zoom.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/use-width-band.ts",
      "content": "'use client';\n\nimport { useEffect, useState, type RefObject } from 'react';\n\n/**\n * How wide the builder itself is, whatever the window: a phone gets the flow from top to bottom and\n * the inspector as a sheet, a compact width keeps the flow from top to bottom beside the inspector,\n * a wide one lays the flow from left to right.\n */\nexport type WidthBand = 'phone' | 'compact' | 'wide';\n\nconst PHONE_BELOW = 640;\n\nconst WIDE_FROM = 1100;\n\nfunction bandOf(width: number): WidthBand {\n  if (width < PHONE_BELOW) {\n    return 'phone';\n  }\n  if (width < WIDE_FROM) {\n    return 'compact';\n  }\n  return 'wide';\n}\n\n/** Null until the element has been measured, so nothing is laid out for the wrong width first. */\nexport function useWidthBand(ref: RefObject<HTMLElement | null>) {\n  const [band, setBand] = useState<WidthBand | null>(null);\n\n  useEffect(() => {\n    const element = ref.current;\n    if (!element) {\n      return;\n    }\n    const observer = new ResizeObserver(([entry]) => {\n      setBand(bandOf(entry.contentRect.width));\n    });\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, [ref]);\n\n  return band;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/use-width-band.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/layout.ts",
      "content": "import {\n  OUTPUT_WORD,\n  OUTPUTS_OF,\n  type Connection,\n  type OutputId,\n  type Step,\n} from './data';\nimport type { Move } from './graph';\n\n/** A wide canvas reads from left to right. A narrow one, such as a phone, reads from top to bottom. */\nexport type Orientation = 'across' | 'down';\n\nexport type Point = {\n  x: number;\n  y: number;\n};\n\nexport type Box = Point & {\n  width: number;\n  height: number;\n};\n\nexport type Cell = {\n  level: number;\n  lane: number;\n};\n\n/** A wide canvas has room for a whole name on one line. On a narrow one the name wraps to a second line. */\nconst CARD_WIDTH: Record<Orientation, number> = {\n  across: 240,\n  down: 192,\n};\n\n/** Tall enough for the kind, a name on two lines and one line of detail. */\nconst CARD_HEIGHT = 92;\n\n/** The pixels of one grid unit along the flow and across it. A step is twelve units from the next one. */\nconst PITCH: Record<Orientation, Cell> = {\n  across: { level: 24, lane: 24 },\n  down: { level: 12, lane: 36 },\n};\n\n/** The grid drawn while a step is dragged: the lines a step snaps to. */\nexport const GRID: Record<Orientation, Point> = {\n  across: { x: 24, y: 24 },\n  down: { x: 36, y: 24 },\n};\n\nconst LEVEL_MIN = -20;\n\nconst LEVEL_MAX = 60;\n\nconst LANE_MIN = -10;\n\nconst LANE_MAX = 20;\n\n/** How far a wire runs straight out of a port before it turns. */\nconst MIN_REACH = 36;\n\nexport type StepPlace = {\n  box: Box;\n  /** Where wires arrive. A trigger starts the flow and has none. */\n  input: Point | null;\n  outputs: Partial<Record<OutputId, Point>>;\n};\n\nexport type PlacedWire<Link extends Connection> = {\n  id: string;\n  link: Link;\n  path: string;\n};\n\nexport type OutputLabel = {\n  id: string;\n  text: string;\n  x: number;\n  y: number;\n};\n\nexport type CanvasLayout<Link extends Connection> = {\n  places: Record<string, StepPlace>;\n  wires: PlacedWire<Link>[];\n  /** Yes and No, written where each leaves a condition. */\n  labels: OutputLabel[];\n  bounds: Box;\n};\n\nfunction clamp(value: number, min: number, max: number) {\n  const atLeast = Math.max(value, min);\n  return Math.min(atLeast, max);\n}\n\nfunction originOf(step: Step, orientation: Orientation): Point {\n  const pitch = PITCH[orientation];\n  const along = step.level * pitch.level;\n  const across = step.lane * pitch.lane;\n  if (orientation === 'across') {\n    return { x: along, y: across };\n  }\n  return { x: across, y: along };\n}\n\nfunction inputPointOf(box: Box, orientation: Orientation): Point {\n  if (orientation === 'across') {\n    return { x: box.x, y: box.y + box.height / 2 };\n  }\n  return { x: box.x + box.width / 2, y: box.y };\n}\n\n/** One output leaves from the middle of the edge, two from its thirds. */\nfunction outputPointOf(\n  box: Box,\n  index: number,\n  count: number,\n  orientation: Orientation\n): Point {\n  const share = (index + 1) / (count + 1);\n  if (orientation === 'across') {\n    return { x: box.x + box.width, y: box.y + box.height * share };\n  }\n  return { x: box.x + box.width * share, y: box.y + box.height };\n}\n\nfunction placeOf(step: Step, orientation: Orientation): StepPlace {\n  const origin = originOf(step, orientation);\n  const width = CARD_WIDTH[orientation];\n  const box = { ...origin, width, height: CARD_HEIGHT };\n  const outputIds = OUTPUTS_OF[step.kind];\n  const outputs: Partial<Record<OutputId, Point>> = {};\n  outputIds.forEach((output, index) => {\n    outputs[output] = outputPointOf(box, index, outputIds.length, orientation);\n  });\n  if (step.kind === 'trigger') {\n    return { box, input: null, outputs };\n  }\n  return { box, input: inputPointOf(box, orientation), outputs };\n}\n\nexport function wirePathOf(from: Point, to: Point, orientation: Orientation) {\n  if (orientation === 'across') {\n    const span = Math.abs(to.x - from.x);\n    const reach = Math.max(MIN_REACH, span / 2);\n    const leaveX = from.x + reach;\n    const arriveX = to.x - reach;\n    return `M ${from.x} ${from.y} C ${leaveX} ${from.y}, ${arriveX} ${to.y}, ${to.x} ${to.y}`;\n  }\n  const span = Math.abs(to.y - from.y);\n  const reach = Math.max(MIN_REACH, span / 2);\n  const leaveY = from.y + reach;\n  const arriveY = to.y - reach;\n  return `M ${from.x} ${from.y} C ${from.x} ${leaveY}, ${to.x} ${arriveY}, ${to.x} ${to.y}`;\n}\n\nexport function wireIdOf(link: Connection) {\n  return `${link.from}:${link.output}`;\n}\n\nfunction labelOf(\n  step: Step,\n  output: OutputId,\n  port: Point,\n  orientation: Orientation\n): OutputLabel {\n  const id = `${step.id}:${output}`;\n  const text = OUTPUT_WORD[output];\n  if (orientation === 'across') {\n    return { id, text, x: port.x + 10, y: port.y - 6 };\n  }\n  return { id, text, x: port.x + 9, y: port.y + 14 };\n}\n\nfunction labelsOf(\n  steps: Step[],\n  places: Record<string, StepPlace>,\n  orientation: Orientation\n) {\n  const labels: OutputLabel[] = [];\n  const forks = steps.filter((step) => step.kind === 'condition');\n  for (const step of forks) {\n    for (const output of OUTPUTS_OF.condition) {\n      const port = places[step.id]?.outputs[output];\n      if (port) {\n        labels.push(labelOf(step, output, port, orientation));\n      }\n    }\n  }\n  return labels;\n}\n\nfunction boundsOf(places: StepPlace[], orientation: Orientation): Box {\n  if (places.length === 0) {\n    const width = CARD_WIDTH[orientation];\n    return { x: 0, y: 0, width, height: CARD_HEIGHT };\n  }\n  const lefts = places.map((place) => place.box.x);\n  const tops = places.map((place) => place.box.y);\n  const rights = places.map((place) => place.box.x + place.box.width);\n  const bottoms = places.map((place) => place.box.y + place.box.height);\n  const x = Math.min(...lefts);\n  const y = Math.min(...tops);\n  return {\n    x,\n    y,\n    width: Math.max(...rights) - x,\n    height: Math.max(...bottoms) - y,\n  };\n}\n\n/** Everything the canvas draws, worked out from the steps and their connections alone. */\nexport function layoutOf<Link extends Connection>(\n  steps: Step[],\n  connections: Link[],\n  orientation: Orientation\n): CanvasLayout<Link> {\n  const places: Record<string, StepPlace> = {};\n  for (const step of steps) {\n    places[step.id] = placeOf(step, orientation);\n  }\n  const wires: PlacedWire<Link>[] = [];\n  for (const link of connections) {\n    const from = places[link.from]?.outputs[link.output];\n    const to = places[link.to]?.input;\n    if (from && to) {\n      wires.push({\n        id: wireIdOf(link),\n        link,\n        path: wirePathOf(from, to, orientation),\n      });\n    }\n  }\n  return {\n    places,\n    wires,\n    labels: labelsOf(steps, places, orientation),\n    bounds: boundsOf(Object.values(places), orientation),\n  };\n}\n\n/** The pixels between two drawn lines, along the flow and across it. */\nfunction lineGapOf(orientation: Orientation): Cell {\n  const grid = GRID[orientation];\n  if (orientation === 'across') {\n    return { level: grid.x, lane: grid.y };\n  }\n  return { level: grid.y, lane: grid.x };\n}\n\n/** A whole number of drawn lines, in grid units: on a phone a line is two units apart along the flow. */\nfunction snappedUnitsOf(pixels: number, lineGap: number, unit: number) {\n  const lines = Math.round(pixels / lineGap);\n  const unitsPerLine = Math.round(lineGap / unit);\n  return lines * unitsPerLine;\n}\n\n/** The cell a step dragged by `dx` and `dy` pixels of the canvas snaps to: always on a drawn line. */\nexport function draggedCellOf(\n  orientation: Orientation,\n  origin: Cell,\n  dx: number,\n  dy: number\n): Cell {\n  const pitch = PITCH[orientation];\n  const lineGap = lineGapOf(orientation);\n  let along = dx;\n  let across = dy;\n  if (orientation === 'down') {\n    along = dy;\n    across = dx;\n  }\n  const levelShift = snappedUnitsOf(along, lineGap.level, pitch.level);\n  const laneShift = snappedUnitsOf(across, lineGap.lane, pitch.lane);\n  const level = origin.level + levelShift;\n  const lane = origin.lane + laneShift;\n  return {\n    level: clamp(level, LEVEL_MIN, LEVEL_MAX),\n    lane: clamp(lane, LANE_MIN, LANE_MAX),\n  };\n}\n\nconst DIRECTIONS: Partial<Record<string, Point>> = {\n  ArrowLeft: { x: -1, y: 0 },\n  ArrowRight: { x: 1, y: 0 },\n  ArrowUp: { x: 0, y: -1 },\n  ArrowDown: { x: 0, y: 1 },\n};\n\n/** One line of the grid in the direction of an arrow key, or null for any other key. */\nexport function nudgedCellOf(\n  orientation: Orientation,\n  origin: Cell,\n  key: string\n) {\n  const direction = DIRECTIONS[key];\n  if (!direction) {\n    return null;\n  }\n  const grid = GRID[orientation];\n  const dx = direction.x * grid.x;\n  const dy = direction.y * grid.y;\n  return draggedCellOf(orientation, origin, dx, dy);\n}\n\nconst MOVES: Record<Orientation, Partial<Record<string, Move>>> = {\n  across: {\n    ArrowRight: 'forward',\n    ArrowLeft: 'back',\n    ArrowDown: 'next',\n    ArrowUp: 'previous',\n  },\n  down: {\n    ArrowDown: 'forward',\n    ArrowUp: 'back',\n    ArrowRight: 'next',\n    ArrowLeft: 'previous',\n  },\n};\n\n/** An arrow key follows the flow in the direction the canvas reads. */\nexport function moveOfKey(orientation: Orientation, key: string) {\n  return MOVES[orientation][key] ?? null;\n}\n\nfunction contains(box: Box, point: Point, reach: number) {\n  const isInsideX =\n    point.x >= box.x - reach && point.x <= box.x + box.width + reach;\n  const isInsideY =\n    point.y >= box.y - reach && point.y <= box.y + box.height + reach;\n  return isInsideX && isInsideY;\n}\n\n/** The step under a point of the canvas, with some reach around its card so a wire lands easily. */\nexport function stepAt(\n  places: Record<string, StepPlace>,\n  point: Point,\n  reach: number\n) {\n  const ids = Object.keys(places);\n  const found = ids.find((id) => contains(places[id].box, point, reach));\n  return found ?? null;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/layout.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/graph.ts",
      "content": "import {\n  FIELDS_OF,\n  OUTPUT_WORD,\n  OUTPUTS_OF,\n  type Connection,\n  type FieldId,\n  type OutputId,\n  type Step,\n} from './data';\n\nexport type Graph = {\n  steps: Step[];\n  connections: Connection[];\n};\n\nexport function stepOf(steps: Step[], id: string | null) {\n  if (id === null) {\n    return undefined;\n  }\n  return steps.find((step) => step.id === id);\n}\n\nexport function targetOf(\n  connections: Connection[],\n  from: string,\n  output: OutputId\n) {\n  const link = connections.find(\n    (candidate) => candidate.from === from && candidate.output === output\n  );\n  return link?.to ?? null;\n}\n\nfunction leadsTo(connections: Connection[], start: string, goal: string) {\n  const seen = new Set<string>();\n  const pending = [start];\n  let current = pending.pop();\n  while (current !== undefined) {\n    if (current === goal) {\n      return true;\n    }\n    if (!seen.has(current)) {\n      seen.add(current);\n      const reached = current;\n      const links = connections.filter((link) => link.from === reached);\n      links.forEach((link) => pending.push(link.to));\n    }\n    current = pending.pop();\n  }\n  return false;\n}\n\nexport type Refusal = 'missing' | 'self' | 'start' | 'loop';\n\n/** Why a wire cannot go from one step to another, or null when it can. */\nexport function refusalOf(\n  graph: Graph,\n  from: string,\n  to: string\n): Refusal | null {\n  const source = stepOf(graph.steps, from);\n  const target = stepOf(graph.steps, to);\n  if (!source || !target) {\n    return 'missing';\n  }\n  if (from === to) {\n    return 'self';\n  }\n  if (target.kind === 'trigger') {\n    return 'start';\n  }\n  if (leadsTo(graph.connections, to, from)) {\n    return 'loop';\n  }\n  return null;\n}\n\nexport function canConnect(graph: Graph, from: string, to: string) {\n  return refusalOf(graph, from, to) === null;\n}\n\n/** The steps a wire from `from` may land on. */\nexport function targetsOf(graph: Graph, from: string) {\n  return graph.steps.filter((step) => canConnect(graph, from, step.id));\n}\n\nexport type ProblemField = FieldId | 'name';\n\nexport type Problem = {\n  stepId: string;\n  line: string;\n  /** The field to fill, when the problem is a missing value. */\n  field?: ProblemField;\n};\n\nfunction isBlank(value: string | undefined) {\n  const text = value ?? '';\n  return text.trim() === '';\n}\n\nfunction fieldProblemsOf(step: Step): Problem[] {\n  const problems: Problem[] = [];\n  if (isBlank(step.name)) {\n    problems.push({ stepId: step.id, line: 'Name the step', field: 'name' });\n  }\n  for (const spec of FIELDS_OF[step.kind]) {\n    if (isBlank(step.values[spec.id])) {\n      problems.push({\n        stepId: step.id,\n        line: spec.missingLine,\n        field: spec.id,\n      });\n    }\n  }\n  return problems;\n}\n\nfunction inputProblemsOf(graph: Graph, step: Step): Problem[] {\n  if (step.kind === 'trigger') {\n    return [];\n  }\n  const isReached = graph.connections.some((link) => link.to === step.id);\n  if (isReached) {\n    return [];\n  }\n  return [{ stepId: step.id, line: 'Nothing leads to this step' }];\n}\n\n/** Both answers of a condition have to go somewhere. Any other step may end the flow. */\nfunction outputProblemsOf(graph: Graph, step: Step): Problem[] {\n  if (step.kind !== 'condition') {\n    return [];\n  }\n  const open = OUTPUTS_OF.condition.filter(\n    (output) => targetOf(graph.connections, step.id, output) === null\n  );\n  return open.map((output) => ({\n    stepId: step.id,\n    line: `${OUTPUT_WORD[output]} leads nowhere`,\n  }));\n}\n\nexport function problemsOf(graph: Graph) {\n  const problems: Problem[] = [];\n  for (const step of graph.steps) {\n    problems.push(...fieldProblemsOf(step));\n    problems.push(...inputProblemsOf(graph, step));\n    problems.push(...outputProblemsOf(graph, step));\n  }\n  return problems;\n}\n\nexport function problemsOfStep(problems: Problem[], stepId: string) {\n  return problems.filter((problem) => problem.stepId === stepId);\n}\n\nexport type OutputLine = {\n  output: OutputId;\n  word: string;\n  target: Step | undefined;\n};\n\n/** Where each way out of a step leads, for the inspector and for screen readers. */\nexport function outputLinesOf(graph: Graph, step: Step): OutputLine[] {\n  return OUTPUTS_OF[step.kind].map((output) => {\n    const targetId = targetOf(graph.connections, step.id, output);\n    return {\n      output,\n      word: OUTPUT_WORD[output],\n      target: stepOf(graph.steps, targetId),\n    };\n  });\n}\n\nexport type Move = 'forward' | 'back' | 'next' | 'previous';\n\nfunction forwardOf(graph: Graph, id: string) {\n  const step = stepOf(graph.steps, id);\n  if (!step) {\n    return null;\n  }\n  for (const output of OUTPUTS_OF[step.kind]) {\n    const target = targetOf(graph.connections, id, output);\n    if (target !== null) {\n      return target;\n    }\n  }\n  return null;\n}\n\nfunction backOf(graph: Graph, id: string) {\n  const link = graph.connections.find((candidate) => candidate.to === id);\n  return link?.from ?? null;\n}\n\n/** The steps a fork leads to, in the order of its outputs. */\nfunction siblingsOf(graph: Graph, id: string) {\n  const sourceId = backOf(graph, id);\n  const source = stepOf(graph.steps, sourceId);\n  if (!source) {\n    return [];\n  }\n  const siblings: string[] = [];\n  for (const output of OUTPUTS_OF[source.kind]) {\n    const target = targetOf(graph.connections, source.id, output);\n    if (target !== null && !siblings.includes(target)) {\n      siblings.push(target);\n    }\n  }\n  return siblings;\n}\n\nfunction siblingOf(graph: Graph, id: string, offset: number) {\n  const siblings = siblingsOf(graph, id);\n  const index = siblings.indexOf(id);\n  if (index === -1) {\n    return null;\n  }\n  return siblings[index + offset] ?? null;\n}\n\n/** The step an arrow key moves to: along a connection, or to the other branch of a fork. */\nexport function neighbourOf(graph: Graph, id: string, move: Move) {\n  if (move === 'forward') {\n    return forwardOf(graph, id);\n  }\n  if (move === 'back') {\n    return backOf(graph, id);\n  }\n  if (move === 'next') {\n    return siblingOf(graph, id, 1);\n  }\n  return siblingOf(graph, id, -1);\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/graph.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\nimport { keyDelayOf, prefixesOf } from '@/registry/ndeko/lib/demonstration';\n\nimport {\n  CONNECTIONS,\n  DEMO_INSTRUCTIONS,\n  OUTPUT_WORD,\n  OUTPUTS_OF,\n  shownNameOf,\n  STEPS,\n  type Connection,\n  type FieldId,\n  type OutputId,\n  type Step,\n} from './data';\nimport {\n  canConnect,\n  problemsOf,\n  stepOf,\n  targetOf,\n  type Graph,\n  type Problem,\n} from './graph';\nimport type { Cell } from './layout';\n\n/**\n * How a wire came to be: there from the start, let go by a hand where it now sits, or made from a\n * menu. Only the last one draws itself, since the two others are already where they belong.\n */\nexport type Arrival = 'placed' | 'dropped' | 'drawn';\n\nexport type Wire = Connection & {\n  arrival: Arrival;\n};\n\n/** A wire held out of a port: by a pointer, or by the demonstration. `to` is the step it would land on. */\nexport type Wiring = {\n  from: string;\n  output: OutputId;\n  to: string | null;\n};\n\nexport type Removed = {\n  step: Step;\n  index: number;\n  wires: Wire[];\n};\n\nexport type PublishState = 'draft' | 'publishing' | 'live';\n\nexport type BuilderState = {\n  steps: Step[];\n  wires: Wire[];\n  selectedId: string | null;\n  isInspectorOpen: boolean;\n  wiring: Wiring | null;\n  /** The step Undo brings back, with the wires it had. */\n  removed: Removed | null;\n  publish: PublishState;\n  /** The last change, said to screen readers. */\n  notice: string;\n};\n\nexport type BuilderAction =\n  | { type: 'selected'; id: string | null }\n  | { type: 'opened'; id: string }\n  | { type: 'closed' }\n  | { type: 'renamed'; id: string; name: string }\n  | { type: 'fieldChanged'; id: string; field: FieldId; value: string }\n  | { type: 'wireStarted'; from: string; output: OutputId }\n  | { type: 'wireAimed'; to: string | null }\n  | { type: 'wireDropped' }\n  | { type: 'wireCancelled' }\n  | { type: 'connected'; from: string; output: OutputId; to: string }\n  | { type: 'disconnected'; from: string; output: OutputId }\n  | { type: 'moved'; id: string; cell: Cell }\n  | { type: 'removed'; id: string }\n  | { type: 'undone' }\n  | { type: 'undoDismissed' }\n  | { type: 'publishStarted' }\n  | { type: 'publishDone' }\n  | { type: 'restored' };\n\ntype Beat = SessionStep<BuilderState, BuilderAction>;\n\nfunction placed(link: Connection): Wire {\n  return { ...link, arrival: 'placed' };\n}\n\n/** The connection an action names, without the action's own fields. */\nfunction linkOf(action: Connection): Connection {\n  return { from: action.from, output: action.output, to: action.to };\n}\n\nexport const INITIAL: BuilderState = {\n  steps: STEPS,\n  wires: CONNECTIONS.map(placed),\n  selectedId: null,\n  isInspectorOpen: false,\n  wiring: null,\n  removed: null,\n  publish: 'draft',\n  notice: '',\n};\n\nexport function graphOf(state: BuilderState): Graph {\n  return { steps: state.steps, connections: state.wires };\n}\n\nfunction problemsWordOf(count: number) {\n  if (count === 1) {\n    return '1 problem';\n  }\n  return `${count} problems`;\n}\n\nfunction isFromOutput(wire: Wire, from: string, output: OutputId) {\n  return wire.from === from && wire.output === output;\n}\n\nfunction touches(wire: Wire, id: string) {\n  return wire.from === id || wire.to === id;\n}\n\nfunction selected(state: BuilderState, id: string | null): BuilderState {\n  if (id === null) {\n    return { ...state, selectedId: null, isInspectorOpen: false };\n  }\n  if (!stepOf(state.steps, id)) {\n    return state;\n  }\n  return { ...state, selectedId: id };\n}\n\nfunction opened(state: BuilderState, id: string): BuilderState {\n  if (!stepOf(state.steps, id)) {\n    return state;\n  }\n  return { ...state, selectedId: id, isInspectorOpen: true };\n}\n\nfunction withStep(\n  state: BuilderState,\n  id: string,\n  change: (step: Step) => Step\n): BuilderState {\n  const steps = state.steps.map((step) => {\n    if (step.id === id) {\n      return change(step);\n    }\n    return step;\n  });\n  return { ...state, steps, publish: 'draft', notice: '' };\n}\n\nfunction fieldChanged(\n  state: BuilderState,\n  id: string,\n  field: FieldId,\n  value: string\n) {\n  return withStep(state, id, (step) => ({\n    ...step,\n    values: { ...step.values, [field]: value },\n  }));\n}\n\nfunction wireStarted(\n  state: BuilderState,\n  from: string,\n  output: OutputId\n): BuilderState {\n  const source = stepOf(state.steps, from);\n  const hasOutput =\n    source !== undefined && OUTPUTS_OF[source.kind].includes(output);\n  if (!hasOutput) {\n    return state;\n  }\n  return { ...state, wiring: { from, output, to: null } };\n}\n\nfunction wireAimed(state: BuilderState, to: string | null): BuilderState {\n  const wiring = state.wiring;\n  if (!wiring) {\n    return state;\n  }\n  let target = to;\n  if (to !== null && !canConnect(graphOf(state), wiring.from, to)) {\n    target = null;\n  }\n  if (target === wiring.to) {\n    return state;\n  }\n  return { ...state, wiring: { ...wiring, to: target } };\n}\n\nfunction connectedTo(\n  state: BuilderState,\n  link: Connection,\n  arrival: Arrival\n): BuilderState {\n  const source = stepOf(state.steps, link.from);\n  const target = stepOf(state.steps, link.to);\n  if (!source || !target) {\n    return state;\n  }\n  const hasOutput = OUTPUTS_OF[source.kind].includes(link.output);\n  const isAllowed = hasOutput && canConnect(graphOf(state), link.from, link.to);\n  const isSame = targetOf(state.wires, link.from, link.output) === link.to;\n  if (!isAllowed || isSame) {\n    return state;\n  }\n  const others = state.wires.filter(\n    (wire) => !isFromOutput(wire, link.from, link.output)\n  );\n  const word = OUTPUT_WORD[link.output];\n  const sourceName = shownNameOf(source);\n  const targetName = shownNameOf(target);\n  return {\n    ...state,\n    wires: [...others, { ...link, arrival }],\n    publish: 'draft',\n    notice: `${sourceName}: ${word} now leads to ${targetName}`,\n  };\n}\n\nfunction wireDropped(state: BuilderState): BuilderState {\n  const wiring = state.wiring;\n  if (!wiring) {\n    return state;\n  }\n  const released = { ...state, wiring: null };\n  if (wiring.to === null) {\n    return released;\n  }\n  const link = { from: wiring.from, output: wiring.output, to: wiring.to };\n  return connectedTo(released, link, 'dropped');\n}\n\nfunction disconnected(\n  state: BuilderState,\n  from: string,\n  output: OutputId\n): BuilderState {\n  const source = stepOf(state.steps, from);\n  const wires = state.wires.filter((wire) => !isFromOutput(wire, from, output));\n  const hasChanged = wires.length !== state.wires.length;\n  if (!source || !hasChanged) {\n    return state;\n  }\n  const word = OUTPUT_WORD[output];\n  return {\n    ...state,\n    wires,\n    publish: 'draft',\n    notice: `${shownNameOf(source)}: ${word} leads nowhere now`,\n  };\n}\n\nfunction moved(state: BuilderState, id: string, cell: Cell): BuilderState {\n  const step = stepOf(state.steps, id);\n  const isSamePlace = step?.level === cell.level && step.lane === cell.lane;\n  if (!step || isSamePlace) {\n    return state;\n  }\n  const steps = state.steps.map((candidate) => {\n    if (candidate.id === id) {\n      return { ...candidate, level: cell.level, lane: cell.lane };\n    }\n    return candidate;\n  });\n  return { ...state, steps };\n}\n\nfunction removed(state: BuilderState, id: string): BuilderState {\n  const index = state.steps.findIndex((step) => step.id === id);\n  const step = state.steps[index];\n  if (!step) {\n    return state;\n  }\n  const cut = state.wires.filter((wire) => touches(wire, id));\n  const kept = state.wires.filter((wire) => !touches(wire, id));\n  const steps = state.steps.filter((candidate) => candidate.id !== id);\n  const cleared = { ...state, steps, wires: kept, wiring: null };\n  const wasSelected = state.selectedId === id;\n  let next: BuilderState = cleared;\n  if (wasSelected) {\n    next = { ...cleared, selectedId: null, isInspectorOpen: false };\n  }\n  return {\n    ...next,\n    removed: { step, index, wires: cut },\n    publish: 'draft',\n    notice: `${shownNameOf(step)} removed. Undo is available`,\n  };\n}\n\n/** A wire comes back with its step only where it still fits: its port may have been used since. */\nfunction rewired(state: BuilderState, wire: Wire): BuilderState {\n  const isFree = targetOf(state.wires, wire.from, wire.output) === null;\n  const fits = isFree && canConnect(graphOf(state), wire.from, wire.to);\n  if (!fits) {\n    return state;\n  }\n  return { ...state, wires: [...state.wires, placed(wire)] };\n}\n\nfunction undone(state: BuilderState): BuilderState {\n  const lost = state.removed;\n  if (!lost) {\n    return state;\n  }\n  const steps = [...state.steps];\n  steps.splice(lost.index, 0, lost.step);\n  let next: BuilderState = { ...state, steps, removed: null };\n  for (const wire of lost.wires) {\n    next = rewired(next, wire);\n  }\n  return {\n    ...next,\n    selectedId: lost.step.id,\n    publish: 'draft',\n    notice: `${shownNameOf(lost.step)} is back`,\n  };\n}\n\n/** Publish refuses a workflow with problems and opens the first one, so the way on is in view. */\nfunction refused(state: BuilderState, problems: Problem[]): BuilderState {\n  const [first] = problems;\n  const step = stepOf(state.steps, first.stepId);\n  if (!step) {\n    return state;\n  }\n  const count = problemsWordOf(problems.length);\n  const name = shownNameOf(step);\n  return {\n    ...state,\n    selectedId: step.id,\n    isInspectorOpen: true,\n    notice: `${count} to fix before publishing. ${name}: ${first.line}`,\n  };\n}\n\nfunction publishStarted(state: BuilderState): BuilderState {\n  const problems = problemsOf(graphOf(state));\n  if (problems.length > 0) {\n    return refused(state, problems);\n  }\n  if (state.publish !== 'draft') {\n    return state;\n  }\n  return { ...state, publish: 'publishing', removed: null, notice: '' };\n}\n\nfunction publishDone(state: BuilderState): BuilderState {\n  if (state.publish !== 'publishing') {\n    return state;\n  }\n  return {\n    ...state,\n    publish: 'live',\n    notice: 'Published. The workflow is live',\n  };\n}\n\nexport function reducer(\n  state: BuilderState,\n  action: BuilderAction\n): BuilderState {\n  switch (action.type) {\n    case 'selected':\n      return selected(state, action.id);\n    case 'opened':\n      return opened(state, action.id);\n    case 'closed':\n      return { ...state, isInspectorOpen: false };\n    case 'renamed':\n      return withStep(state, action.id, (step) => ({\n        ...step,\n        name: action.name,\n      }));\n    case 'fieldChanged':\n      return fieldChanged(state, action.id, action.field, action.value);\n    case 'wireStarted':\n      return wireStarted(state, action.from, action.output);\n    case 'wireAimed':\n      return wireAimed(state, action.to);\n    case 'wireDropped':\n      return wireDropped(state);\n    case 'wireCancelled':\n      return { ...state, wiring: null };\n    case 'connected':\n      return connectedTo(state, linkOf(action), 'drawn');\n    case 'disconnected':\n      return disconnected(state, action.from, action.output);\n    case 'moved':\n      return moved(state, action.id, action.cell);\n    case 'removed':\n      return removed(state, action.id);\n    case 'undone':\n      return undone(state);\n    case 'undoDismissed':\n      return { ...state, removed: null };\n    case 'publishStarted':\n      return publishStarted(state);\n    case 'publishDone':\n      return publishDone(state);\n    case 'restored':\n      return { ...INITIAL, notice: 'The sample workflow is back' };\n  }\n}\n\n/** How long publishing takes before the workflow is live. */\nexport const PUBLISH_MS = 1400;\n\nconst CONNECTING: Beat[] = [\n  {\n    after: 1700,\n    by: 'demo',\n    press: 'port-size-no',\n    action: { type: 'wireStarted', from: 'size', output: 'no' },\n  },\n  { after: 520, by: 'demo', action: { type: 'wireAimed', to: 'welcome' } },\n  { after: 900, by: 'demo', action: { type: 'wireDropped' } },\n];\n\n/** One problem is left, so this press is refused and opens the step that has it. */\nconst REFUSED: Beat = {\n  after: 1500,\n  by: 'demo',\n  press: 'publish',\n  action: { type: 'publishStarted' },\n};\n\n/** The text arrives a few letters at a time: the whole builder renders again on each beat. */\nconst TYPED_LETTERS = 3;\n\nfunction typedTextsOf(text: string) {\n  const prefixes = prefixesOf(text);\n  const last = prefixes.length - 1;\n  return prefixes.filter((_, index) => {\n    const endsGroup = index % TYPED_LETTERS === TYPED_LETTERS - 1;\n    return endsGroup || index === last;\n  });\n}\n\nfunction typingBeatOf(value: string, index: number): Beat {\n  return {\n    after: keyDelayOf(index, 1300, 96),\n    by: 'demo',\n    action: {\n      type: 'fieldChanged',\n      id: 'enrich',\n      field: 'instructions',\n      value,\n    },\n  };\n}\n\nconst TYPING = typedTextsOf(DEMO_INSTRUCTIONS).map(typingBeatOf);\n\n/** The last step is the system's answer, so it plays even once a person has taken over. */\nconst PUBLISHING: Beat[] = [\n  {\n    after: 1100,\n    by: 'demo',\n    press: 'publish',\n    action: { type: 'publishStarted' },\n  },\n  { after: PUBLISH_MS, action: { type: 'publishDone' } },\n];\n\nexport const SCRIPT: Beat[] = [\n  ...CONNECTING,\n  REFUSED,\n  ...TYPING,\n  ...PUBLISHING,\n];\n\n/**\n * Under reduced motion the builder rests on the most telling moment: every wire in place, one\n * problem left and the inspector open on the field that has it.\n */\nfunction restingOf() {\n  let state = INITIAL;\n  for (const beat of [...CONNECTING, REFUSED]) {\n    state = reducer(state, beat.action);\n  }\n  return { ...state, wires: state.wires.map(placed), notice: '' };\n}\n\nexport const RESTING = restingOf();\n\nexport const LOOP_AFTER_MS = 4200;\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-01/data.ts",
      "content": "import type { SeriesSlot } from '@/registry/ndeko/lib/agent-run';\nimport type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\n\nexport const WORKFLOW_NAME = 'Signup routing';\n\nexport type StepKind = 'trigger' | 'agent' | 'tool' | 'condition';\n\nexport const KIND_WORD: Record<StepKind, string> = {\n  trigger: 'Trigger',\n  agent: 'Agent',\n  tool: 'Tool',\n  condition: 'Condition',\n};\n\nexport type OutputId = 'next' | 'yes' | 'no';\n\nexport const OUTPUT_IDS: OutputId[] = ['next', 'yes', 'no'];\n\nexport const OUTPUT_WORD: Record<OutputId, string> = {\n  next: 'Next',\n  yes: 'Yes',\n  no: 'No',\n};\n\n/** A condition leaves by Yes or by No. Every other step has one way out. */\nexport const OUTPUTS_OF: Record<StepKind, OutputId[]> = {\n  trigger: ['next'],\n  agent: ['next'],\n  tool: ['next'],\n  condition: ['yes', 'no'],\n};\n\nexport type FieldId =\n  'source' | 'event' | 'model' | 'instructions' | 'app' | 'action' | 'rule';\n\nexport type Choice = {\n  value: string;\n  label: string;\n  brand?: BrandSlug;\n};\n\nexport type FieldSpec = {\n  id: FieldId;\n  label: string;\n  control: 'text' | 'textarea' | 'select';\n  placeholder: string;\n  choices?: Choice[];\n  /** Said under the field and on the step while the field is empty: a workflow cannot be published without it. */\n  missingLine: string;\n};\n\nconst SOURCES: Choice[] = [\n  { value: 'stripe', label: 'Stripe', brand: 'stripe' },\n  { value: 'hubspot', label: 'HubSpot', brand: 'hubspot' },\n  { value: 'intercom', label: 'Intercom', brand: 'intercom' },\n];\n\nconst EVENTS: Choice[] = [\n  { value: 'Account created', label: 'Account created' },\n  { value: 'Plan changed', label: 'Plan changed' },\n  { value: 'Trial ended', label: 'Trial ended' },\n];\n\nconst MODELS: Choice[] = [\n  { value: 'claude', label: 'Claude', brand: 'claude' },\n  { value: 'openai', label: 'ChatGPT', brand: 'openai' },\n  { value: 'gemini', label: 'Gemini', brand: 'gemini' },\n  { value: 'mistral', label: 'Mistral', brand: 'mistral' },\n];\n\nconst APPS: Choice[] = [\n  { value: 'hubspot', label: 'HubSpot', brand: 'hubspot' },\n  { value: 'gmail', label: 'Gmail', brand: 'gmail' },\n  { value: 'linear', label: 'Linear', brand: 'linear' },\n  { value: 'notion', label: 'Notion', brand: 'notion' },\n];\n\nexport const FIELDS_OF: Record<StepKind, FieldSpec[]> = {\n  trigger: [\n    {\n      id: 'source',\n      label: 'Source',\n      control: 'select',\n      placeholder: 'Choose a source',\n      choices: SOURCES,\n      missingLine: 'Choose where the workflow starts',\n    },\n    {\n      id: 'event',\n      label: 'Event',\n      control: 'select',\n      placeholder: 'Choose an event',\n      choices: EVENTS,\n      missingLine: 'Choose the event that starts it',\n    },\n  ],\n  agent: [\n    {\n      id: 'model',\n      label: 'Model',\n      control: 'select',\n      placeholder: 'Choose a model',\n      choices: MODELS,\n      missingLine: 'Choose a model',\n    },\n    {\n      id: 'instructions',\n      label: 'Instructions',\n      control: 'textarea',\n      placeholder: 'What should the agent do?',\n      missingLine: 'Tell the agent what to do',\n    },\n  ],\n  tool: [\n    {\n      id: 'app',\n      label: 'App',\n      control: 'select',\n      placeholder: 'Choose an app',\n      choices: APPS,\n      missingLine: 'Choose the app to act in',\n    },\n    {\n      id: 'action',\n      label: 'Action',\n      control: 'text',\n      placeholder: 'Create a deal',\n      missingLine: 'Say what the tool does',\n    },\n  ],\n  condition: [\n    {\n      id: 'rule',\n      label: 'Rule',\n      control: 'text',\n      placeholder: 'seats is 20 or more',\n      missingLine: 'Write the rule to check',\n    },\n  ],\n};\n\nexport type StepValues = Partial<Record<FieldId, string>>;\n\nexport type Step = {\n  id: string;\n  kind: StepKind;\n  name: string;\n  /** Its place along the flow and across it, in grid units. The layout turns them into pixels. */\n  level: number;\n  lane: number;\n  /** The colour of an agent, kept when the step is renamed. */\n  series?: SeriesSlot;\n  values: StepValues;\n};\n\nexport type Connection = {\n  from: string;\n  output: OutputId;\n  to: string;\n};\n\n/**\n * An invented workflow. The agent has no instructions yet and nothing leaves the No output: the\n * three problems the builder counts when it opens.\n */\nexport const STEPS: Step[] = [\n  {\n    id: 'signup',\n    kind: 'trigger',\n    name: 'New signup',\n    level: 0,\n    lane: 2,\n    values: { source: 'stripe', event: 'Account created' },\n  },\n  {\n    id: 'enrich',\n    kind: 'agent',\n    name: 'Enrich the account',\n    level: 12,\n    lane: 2,\n    series: 2,\n    values: { model: 'claude', instructions: '' },\n  },\n  {\n    id: 'size',\n    kind: 'condition',\n    name: 'Team of 20 or more?',\n    level: 24,\n    lane: 2,\n    values: { rule: 'seats is 20 or more' },\n  },\n  {\n    id: 'deal',\n    kind: 'tool',\n    name: 'Create a deal',\n    level: 38,\n    lane: -1,\n    values: { app: 'hubspot', action: 'Create a deal in Inbound' },\n  },\n  {\n    id: 'welcome',\n    kind: 'tool',\n    name: 'Send the welcome',\n    level: 38,\n    lane: 5,\n    values: { app: 'gmail', action: 'Send the Welcome template' },\n  },\n];\n\nexport const CONNECTIONS: Connection[] = [\n  { from: 'signup', output: 'next', to: 'enrich' },\n  { from: 'enrich', output: 'next', to: 'size' },\n  { from: 'size', output: 'yes', to: 'deal' },\n];\n\n/** What the demonstration types into the agent that has no instructions. */\nexport const DEMO_INSTRUCTIONS = 'Look up the company and count its seats';\n\nexport function choiceOf(spec: FieldSpec, value: string | undefined) {\n  return spec.choices?.find((choice) => choice.value === value);\n}\n\n/** A step whose name was cleared still has to be called something on the canvas and in a sentence. */\nexport function shownNameOf(step: Step) {\n  const name = step.name.trim();\n  if (name === '') {\n    return 'Unnamed step';\n  }\n  return name;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-01/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "workflows"
  ],
  "type": "registry:block"
}