{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "automations-01",
  "title": "Rule builder",
  "description": "An event, conditions and actions on one rail: rows open and close in place, the rule reads back as a sentence as you edit, mistakes fold in under their row and Save becomes Saving then Saved.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/select.json",
    "https://ui.ndekocode.dev/r/switch.json",
    "https://ui.ndekocode.dev/r/tabs.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/automations/automations-01/index.tsx",
      "content": "'use client';\n\nimport {\n  AnimatePresence,\n  motion,\n  type Transition,\n  type Variants,\n} from 'motion/react';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  ArrowRightIcon,\n  FilterIcon,\n  ZapIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Switch } from '@/registry/ndeko/ui/switch';\nimport { Tabs, TabsList, TabsTab } from '@/registry/ndeko/ui/tabs';\n\nimport {\n  INITIAL_RULE,\n  MATCH_MODES,\n  RULE_NAME,\n  TRIGGERS,\n  WORKSPACE_LINE,\n  type Action,\n  type ActionKind,\n  type Condition,\n  type FieldId,\n  type MatchMode,\n  type Rule,\n  type TriggerId,\n} from './data';\nimport { useHeightPresence } from './motion-parts';\nimport {\n  ActionRow,\n  AddSlot,\n  ChoiceSelect,\n  ConditionRow,\n  RowError,\n  Step,\n} from './rule-parts';\nimport {\n  ACTIONS_ERROR_KEY,\n  actionForKind,\n  conditionForField,\n  errorsOf,\n  hasErrors,\n  replacedById,\n  sameRule,\n  sentenceOf,\n  unusedActionKindOf,\n  unusedFieldOf,\n  withoutId,\n  type RuleErrors,\n} from './rule-model';\nimport { SaveButton, type SaveStatus } from './save-button';\n\nconst CARD_SURFACE =\n  'bg-card hairline-ring ring-border rounded-xl shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:bg-foreground/[0.03]';\n\nconst SAVING_MS = 800;\n\nconst SAVED_HOLD_MS = 1200;\n\nconst FIRST_FREE_ID = 3;\n\nconst SWAP_TRANSITION: Transition = { duration: 0.15, ease: [0.2, 0, 0, 1] };\n\nconst SWAP_VARIANTS: Variants = {\n  enter: { opacity: 0, scale: 0.6, filter: 'blur(2px)' },\n  visible: { opacity: 1, scale: 1, filter: 'blur(0px)' },\n  exit: { opacity: 0, scale: 0.6, filter: 'blur(2px)' },\n};\n\nconst FADE_VARIANTS: Variants = {\n  enter: { opacity: 0 },\n  visible: { opacity: 1 },\n  exit: { opacity: 0 },\n};\n\nconst NO_ERRORS: RuleErrors = {};\n\nfunction swapVariantsOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return FADE_VARIANTS;\n  }\n  return SWAP_VARIANTS;\n}\n\nfunction shownErrorsOf(errors: RuleErrors, showsErrors: boolean) {\n  if (showsErrors) {\n    return errors;\n  }\n  return NO_ERRORS;\n}\n\nfunction delayOf(status: SaveStatus) {\n  if (status === 'saving') {\n    return SAVING_MS;\n  }\n  return SAVED_HOLD_MS;\n}\n\nfunction statusAfter(status: SaveStatus): SaveStatus {\n  if (status === 'saving') {\n    return 'saved';\n  }\n  return 'idle';\n}\n\nfunction conditionsHintOf(count: number, match: MatchMode) {\n  if (count === 0) {\n    return 'No condition: the rule runs every time';\n  }\n  if (count === 1) {\n    return 'The rule runs only when this is true';\n  }\n  if (match === 'any') {\n    return 'The rule runs when any of these is true';\n  }\n  return 'The rule runs when all of these are true';\n}\n\nfunction activeLabelOf(isActive: boolean) {\n  if (isActive) {\n    return 'Active';\n  }\n  return 'Paused';\n}\n\nfunction footerNoteOf(isDirty: boolean, status: SaveStatus) {\n  if (status === 'saved') {\n    return 'Rule saved';\n  }\n  if (isDirty) {\n    return 'Unsaved changes';\n  }\n  return 'No changes';\n}\n\nfunction focusFirstControlOf(rowId: string) {\n  const row = document.querySelector(`[data-rule-row=\"${rowId}\"]`);\n  const control = row?.querySelector<HTMLElement>('button, input');\n  control?.focus();\n}\n\nfunction isMatchMode(value: unknown): value is MatchMode {\n  return MATCH_MODES.some((mode) => mode.value === value);\n}\n\ntype MatchSwitchProps = {\n  value: MatchMode;\n  onValueChange: (value: MatchMode) => void;\n};\n\nfunction MatchSwitch({ value, onValueChange }: MatchSwitchProps) {\n  function changeValue(nextValue: unknown) {\n    if (isMatchMode(nextValue)) {\n      onValueChange(nextValue);\n    }\n  }\n\n  return (\n    <Tabs value={value} onValueChange={changeValue}>\n      <TabsList variant='segmented' aria-label='Conditions to match'>\n        {MATCH_MODES.map((mode) => (\n          <TabsTab key={mode.value} value={mode.value}>\n            {mode.label}\n          </TabsTab>\n        ))}\n      </TabsList>\n    </Tabs>\n  );\n}\n\nfunction ActiveLabel({ isActive }: { isActive: boolean }) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const variants = swapVariantsOf(shouldReduceMotion);\n  const label = activeLabelOf(isActive);\n\n  return (\n    <span className='relative inline-flex w-12'>\n      <AnimatePresence mode='popLayout' initial={false}>\n        <motion.span\n          key={label}\n          variants={variants}\n          initial='enter'\n          animate='visible'\n          exit='exit'\n          transition={SWAP_TRANSITION}\n        >\n          {label}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nexport default function Automations01() {\n  const [rule, setRule] = useState<Rule>(INITIAL_RULE);\n  const [savedRule, setSavedRule] = useState<Rule>(INITIAL_RULE);\n  const [status, setStatus] = useState<SaveStatus>('idle');\n  const [showsErrors, setShowsErrors] = useState(false);\n  const [isActive, setIsActive] = useState(true);\n  const nextIdRef = useRef(FIRST_FREE_ID);\n  const addConditionRef = useRef<HTMLButtonElement>(null);\n  const addActionRef = useRef<HTMLButtonElement>(null);\n  const heightPresence = useHeightPresence();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const switchVariants = swapVariantsOf(shouldReduceMotion);\n  const errors = errorsOf(rule);\n  const shownErrors = shownErrorsOf(errors, showsErrors);\n  const isDirty = !sameRule(rule, savedRule);\n  const conditionCount = rule.conditions.length;\n  const hasSeveralConditions = conditionCount > 1;\n  const sentence = sentenceOf(rule);\n  const footerNote = footerNoteOf(isDirty, status);\n\n  useEffect(() => {\n    if (status === 'idle') {\n      return;\n    }\n    function advance() {\n      const next = statusAfter(status);\n      setStatus(next);\n    }\n    const delay = delayOf(status);\n    const timer = window.setTimeout(advance, delay);\n    return () => window.clearTimeout(timer);\n  }, [status]);\n\n  function nextIdOf(prefix: string) {\n    const id = `${prefix}-${nextIdRef.current}`;\n    nextIdRef.current += 1;\n    return id;\n  }\n\n  function patchRule(patch: Partial<Rule>) {\n    setRule((current) => ({ ...current, ...patch }));\n  }\n\n  function changeTrigger(trigger: TriggerId) {\n    patchRule({ trigger });\n  }\n\n  function changeMatch(match: MatchMode) {\n    patchRule({ match });\n  }\n\n  function addCondition() {\n    const id = nextIdOf('condition');\n    const field = unusedFieldOf(rule.conditions);\n    const condition = conditionForField(id, field);\n    const conditions = [...rule.conditions, condition];\n    patchRule({ conditions });\n    window.requestAnimationFrame(() => focusFirstControlOf(id));\n  }\n\n  function changeCondition(condition: Condition) {\n    const conditions = replacedById(rule.conditions, condition);\n    patchRule({ conditions });\n  }\n\n  function changeConditionField(id: string, field: FieldId) {\n    const condition = conditionForField(id, field);\n    changeCondition(condition);\n  }\n\n  function removeCondition(id: string) {\n    const conditions = withoutId(rule.conditions, id);\n    patchRule({ conditions });\n    addConditionRef.current?.focus();\n  }\n\n  function addAction() {\n    const id = nextIdOf('action');\n    const kind = unusedActionKindOf(rule.actions);\n    const action = actionForKind(id, kind);\n    const actions = [...rule.actions, action];\n    patchRule({ actions });\n    window.requestAnimationFrame(() => focusFirstControlOf(id));\n  }\n\n  function changeAction(action: Action) {\n    const actions = replacedById(rule.actions, action);\n    patchRule({ actions });\n  }\n\n  function changeActionKind(id: string, kind: ActionKind) {\n    const action = actionForKind(id, kind);\n    changeAction(action);\n  }\n\n  function removeAction(id: string) {\n    const actions = withoutId(rule.actions, id);\n    patchRule({ actions });\n    addActionRef.current?.focus();\n  }\n\n  function discard() {\n    setRule(savedRule);\n    setShowsErrors(false);\n  }\n\n  function save() {\n    if (hasErrors(errors)) {\n      setShowsErrors(true);\n      return;\n    }\n    setShowsErrors(false);\n    setSavedRule(rule);\n    setStatus('saving');\n  }\n\n  return (\n    <div className='bg-background text-foreground min-h-dvh w-full'>\n      <div className='mx-auto flex w-full max-w-3xl flex-col gap-5 px-4 py-6 md:px-6 md:py-10'>\n        <header className='flex flex-col gap-1'>\n          <p className='text-muted-foreground text-xs'>{WORKSPACE_LINE}</p>\n          <div className='flex flex-wrap items-center justify-between gap-x-4 gap-y-2'>\n            <h1 className='text-lg font-semibold text-balance'>{RULE_NAME}</h1>\n            <label className='flex cursor-pointer items-center gap-2 text-[13px]'>\n              <Switch checked={isActive} onCheckedChange={setIsActive} />\n              <ActiveLabel isActive={isActive} />\n            </label>\n          </div>\n        </header>\n        <div className={`${CARD_SURFACE} p-4 pb-0 sm:p-6 sm:pb-0`}>\n          <Step\n            icon={ZapIcon}\n            title='When'\n            hint='The event that starts the rule'\n          >\n            <ChoiceSelect\n              label='Event'\n              value={rule.trigger}\n              options={TRIGGERS}\n              onValueChange={changeTrigger}\n              className='sm:w-64'\n            />\n          </Step>\n          <Step\n            icon={FilterIcon}\n            title='If'\n            hint={conditionsHintOf(conditionCount, rule.match)}\n            aside={\n              <AnimatePresence initial={false}>\n                {hasSeveralConditions && (\n                  <motion.div\n                    key='match'\n                    variants={switchVariants}\n                    initial='enter'\n                    animate='visible'\n                    exit='exit'\n                    transition={SWAP_TRANSITION}\n                  >\n                    <MatchSwitch\n                      value={rule.match}\n                      onValueChange={changeMatch}\n                    />\n                  </motion.div>\n                )}\n              </AnimatePresence>\n            }\n          >\n            <div className='flex flex-col'>\n              <ul aria-label='Conditions' className='flex flex-col'>\n                <AnimatePresence initial={false}>\n                  {rule.conditions.map((condition) => (\n                    <motion.li\n                      key={condition.id}\n                      data-rule-row={condition.id}\n                      {...heightPresence}\n                      className='overflow-hidden'\n                    >\n                      <div className='pb-2'>\n                        <ConditionRow\n                          condition={condition}\n                          error={shownErrors[condition.id]}\n                          onFieldChange={(field) =>\n                            changeConditionField(condition.id, field)\n                          }\n                          onChange={changeCondition}\n                          onRemove={() => removeCondition(condition.id)}\n                        />\n                      </div>\n                    </motion.li>\n                  ))}\n                </AnimatePresence>\n              </ul>\n              <AddSlot\n                ref={addConditionRef}\n                label='Add condition'\n                onAdd={addCondition}\n              />\n            </div>\n          </Step>\n          <Step\n            icon={ArrowRightIcon}\n            title='Then'\n            hint='What happens, in this order'\n            isLast\n          >\n            <div className='flex flex-col'>\n              <ol aria-label='Actions' className='flex flex-col'>\n                <AnimatePresence initial={false}>\n                  {rule.actions.map((action) => (\n                    <motion.li\n                      key={action.id}\n                      data-rule-row={action.id}\n                      {...heightPresence}\n                      className='overflow-hidden'\n                    >\n                      <div className='pb-2'>\n                        <ActionRow\n                          action={action}\n                          onKindChange={(kind) =>\n                            changeActionKind(action.id, kind)\n                          }\n                          onChange={changeAction}\n                          onRemove={() => removeAction(action.id)}\n                        />\n                      </div>\n                    </motion.li>\n                  ))}\n                </AnimatePresence>\n              </ol>\n              <AddSlot\n                ref={addActionRef}\n                label='Add action'\n                onAdd={addAction}\n              />\n              <RowError\n                id='automations-01-actions-error'\n                error={shownErrors[ACTIONS_ERROR_KEY]}\n              />\n            </div>\n          </Step>\n        </div>\n        <section\n          aria-labelledby='automations-01-sentence'\n          className='bg-foreground/[0.025] flex flex-col gap-1 rounded-xl px-4 py-3'\n        >\n          <h2\n            id='automations-01-sentence'\n            className='text-muted-foreground text-xs'\n          >\n            The rule reads\n          </h2>\n          <p className='text-[13px] leading-relaxed text-pretty'>{sentence}</p>\n        </section>\n        <div className='flex flex-wrap items-center justify-end gap-2'>\n          <p role='status' className='text-muted-foreground me-auto text-xs'>\n            {footerNote}\n          </p>\n          <Button variant='ghost' disabled={!isDirty} onClick={discard}>\n            Discard\n          </Button>\n          <SaveButton\n            status={status}\n            idleLabel='Save rule'\n            disabled={!isDirty}\n            onSave={save}\n          />\n        </div>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/automations-01/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/automations/automations-01/rule-parts.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId } from 'react';\n\nimport { PlusIcon, XIcon, type Icon } from '@/registry/ndeko/lib/icons';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/registry/ndeko/ui/select';\n\nimport {\n  ACTIONS,\n  FIELDS,\n  type Action,\n  type ActionKind,\n  type Condition,\n  type FieldId,\n  type Option,\n  type OperatorId,\n} from './data';\nimport { FADE_PRESENCE, useHeightPresence } from './motion-parts';\nimport {\n  actionDefinitionOf,\n  actionPhraseOf,\n  conditionPhraseOf,\n  digitsOf,\n  fieldOf,\n  targetOptionsOf,\n} from './rule-model';\n\nconst FIELD_OPTIONS: Option<FieldId>[] = FIELDS.map((field) => ({\n  value: field.id,\n  label: field.label,\n}));\n\nconst ACTION_OPTIONS: Option<ActionKind>[] = ACTIONS.map((action) => ({\n  value: action.kind,\n  label: action.label,\n}));\n\nconst ADD_SLOT = [\n  'flex h-9 w-full cursor-pointer items-center gap-2 rounded-lg px-2.5 text-[13px] text-muted-foreground outline-none',\n  'hairline-border border-dashed border-foreground/20 transition-[color,border-color,scale] duration-150 ease-(--ease-out-strong)',\n  'hover:border-foreground/35 hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/25 active:scale-[0.99]',\n].join(' ');\n\nfunction describedByOf(error: string | undefined, errorId: string) {\n  if (error) {\n    return errorId;\n  }\n  return undefined;\n}\n\nfunction targetLabelOf(target: string | null) {\n  if (target === 'channel') {\n    return 'Channel';\n  }\n  return 'Approver';\n}\n\ntype ChoiceSelectProps<Value extends string> = {\n  label: string;\n  value: Value;\n  options: Option<Value>[];\n  className?: string;\n  onValueChange: (value: Value) => void;\n};\n\nexport function ChoiceSelect<Value extends string>({\n  label,\n  value,\n  options,\n  className,\n  onValueChange,\n}: ChoiceSelectProps<Value>) {\n  function changeValue(nextValue: unknown) {\n    const option = options.find((candidate) => candidate.value === nextValue);\n    if (option) {\n      onValueChange(option.value);\n    }\n  }\n\n  return (\n    <Select items={options} value={value} onValueChange={changeValue}>\n      <SelectTrigger aria-label={label} className={className}>\n        <SelectValue />\n      </SelectTrigger>\n      <SelectContent>\n        {options.map((option) => (\n          <SelectItem key={option.value} value={option.value}>\n            {option.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\ntype StepProps = {\n  icon: Icon;\n  title: string;\n  hint: string;\n  isLast?: boolean;\n  aside?: React.ReactNode;\n  children: React.ReactNode;\n};\n\n/** One step of the rule on a rail: the tile and the line on the left, the step's rows on the right. */\nexport function Step({\n  icon: StepIcon,\n  title,\n  hint,\n  isLast = false,\n  aside,\n  children,\n}: StepProps) {\n  const titleId = useId();\n  const hasLine = !isLast;\n\n  return (\n    <section\n      aria-labelledby={titleId}\n      className='grid grid-cols-[2rem_minmax(0,1fr)] gap-x-3'\n    >\n      <div className='flex flex-col items-center'>\n        <span className='keycap-3d text-muted-foreground flex size-8 shrink-0 items-center justify-center rounded-lg'>\n          <StepIcon />\n        </span>\n        {hasLine && (\n          <span\n            aria-hidden='true'\n            className='hairline-l border-border my-1.5 flex-1'\n          />\n        )}\n      </div>\n      <div className='flex min-w-0 flex-col gap-3 pb-6'>\n        <div className='flex min-h-8 flex-wrap items-center justify-between gap-x-3 gap-y-1'>\n          <div className='flex flex-col'>\n            <h2 id={titleId} className='text-sm font-medium'>\n              {title}\n            </h2>\n            <p className='text-muted-foreground text-xs'>{hint}</p>\n          </div>\n          {aside}\n        </div>\n        {children}\n      </div>\n    </section>\n  );\n}\n\ntype AddSlotProps = {\n  label: string;\n  ref?: React.Ref<HTMLButtonElement>;\n  onAdd: () => void;\n};\n\n/** A dashed slot: the empty place where the next row goes. */\nexport function AddSlot({ label, ref, onAdd }: AddSlotProps) {\n  return (\n    <button ref={ref} type='button' onClick={onAdd} className={ADD_SLOT}>\n      <PlusIcon className='size-4' />\n      {label}\n    </button>\n  );\n}\n\nexport function RowError({ id, error }: { id: string; error?: string }) {\n  const heightPresence = useHeightPresence();\n\n  return (\n    <AnimatePresence initial={false}>\n      {error && (\n        <motion.p\n          key='error'\n          id={id}\n          {...heightPresence}\n          className='text-destructive-ink overflow-hidden text-xs'\n        >\n          <span className='block pt-1.5'>{error}</span>\n        </motion.p>\n      )}\n    </AnimatePresence>\n  );\n}\n\ntype ValueControlProps = {\n  condition: Condition;\n  error?: string;\n  errorId: string;\n  onValueChange: (value: string) => void;\n};\n\nfunction ValueControl({\n  condition,\n  error,\n  errorId,\n  onValueChange,\n}: ValueControlProps) {\n  const field = fieldOf(condition.field);\n  const isInvalid = Boolean(error);\n  const describedBy = describedByOf(error, errorId);\n\n  function typeAmount(event: React.ChangeEvent<HTMLInputElement>) {\n    const digits = digitsOf(event.target.value);\n    onValueChange(digits);\n  }\n\n  function typeText(event: React.ChangeEvent<HTMLInputElement>) {\n    onValueChange(event.target.value);\n  }\n\n  if (field.kind === 'choice') {\n    return (\n      <ChoiceSelect\n        label={`${field.label} value`}\n        value={condition.value}\n        options={field.choices}\n        onValueChange={onValueChange}\n        className='min-w-0 flex-1 sm:w-40 sm:flex-none'\n      />\n    );\n  }\n\n  if (field.kind === 'amount') {\n    return (\n      <div className='relative min-w-0 flex-1 sm:w-32 sm:flex-none'>\n        <span\n          aria-hidden='true'\n          className='text-muted-foreground pointer-events-none absolute start-2.5 top-1/2 -translate-y-1/2 text-[13px]'\n        >\n          €\n        </span>\n        <Input\n          inputMode='numeric'\n          aria-label='Amount in euros'\n          aria-invalid={isInvalid}\n          aria-describedby={describedBy}\n          value={condition.value}\n          onChange={typeAmount}\n          className='ps-6 tabular-nums'\n        />\n      </div>\n    );\n  }\n\n  return (\n    <Input\n      aria-label='Part of the merchant name'\n      aria-invalid={isInvalid}\n      aria-describedby={describedBy}\n      placeholder='For example: air'\n      value={condition.value}\n      onChange={typeText}\n      className='min-w-0 flex-1 sm:w-40 sm:flex-none'\n    />\n  );\n}\n\ntype ConditionRowProps = {\n  condition: Condition;\n  error?: string;\n  onFieldChange: (fieldId: FieldId) => void;\n  onChange: (condition: Condition) => void;\n  onRemove: () => void;\n};\n\nexport function ConditionRow({\n  condition,\n  error,\n  onFieldChange,\n  onChange,\n  onRemove,\n}: ConditionRowProps) {\n  const errorId = useId();\n  const field = fieldOf(condition.field);\n  const phrase = conditionPhraseOf(condition);\n\n  function changeOperator(operator: OperatorId) {\n    onChange({ ...condition, operator });\n  }\n\n  function changeValue(value: string) {\n    onChange({ ...condition, value });\n  }\n\n  return (\n    <div className='flex flex-col'>\n      <div className='flex flex-wrap items-center gap-2'>\n        <ChoiceSelect\n          label='Field'\n          value={condition.field}\n          options={FIELD_OPTIONS}\n          onValueChange={onFieldChange}\n          className='w-[calc(50%-0.25rem)] sm:w-32'\n        />\n        <ChoiceSelect\n          label='Comparison'\n          value={condition.operator}\n          options={field.operators}\n          onValueChange={changeOperator}\n          className='w-[calc(50%-0.25rem)] sm:w-28'\n        />\n        <ValueControl\n          condition={condition}\n          error={error}\n          errorId={errorId}\n          onValueChange={changeValue}\n        />\n        <Button\n          variant='ghost'\n          size='icon'\n          aria-label={`Remove the condition ${phrase}`}\n          onClick={onRemove}\n          className='ms-auto'\n        >\n          <XIcon />\n        </Button>\n      </div>\n      <RowError id={errorId} error={error} />\n    </div>\n  );\n}\n\ntype ActionRowProps = {\n  action: Action;\n  onKindChange: (kind: ActionKind) => void;\n  onChange: (action: Action) => void;\n  onRemove: () => void;\n};\n\nexport function ActionRow({\n  action,\n  onKindChange,\n  onChange,\n  onRemove,\n}: ActionRowProps) {\n  const definition = actionDefinitionOf(action.kind);\n  const targetOptions = targetOptionsOf(action.kind);\n  const hasTarget = targetOptions.length > 0;\n  const phrase = actionPhraseOf(action);\n  const targetLabel = targetLabelOf(definition.target);\n\n  function changeTarget(target: string) {\n    onChange({ ...action, target });\n  }\n\n  return (\n    <div className='flex flex-wrap items-center gap-2'>\n      <ChoiceSelect\n        label='Action'\n        value={action.kind}\n        options={ACTION_OPTIONS}\n        onValueChange={onKindChange}\n        className='min-w-0 flex-1 sm:w-48 sm:flex-none'\n      />\n      <AnimatePresence initial={false} mode='popLayout'>\n        {hasTarget && (\n          <motion.div\n            key={action.kind}\n            {...FADE_PRESENCE}\n            className='order-last w-full sm:order-none sm:w-44'\n          >\n            <ChoiceSelect\n              label={targetLabel}\n              value={action.target}\n              options={targetOptions}\n              onValueChange={changeTarget}\n              className='w-full'\n            />\n          </motion.div>\n        )}\n      </AnimatePresence>\n      <Button\n        variant='ghost'\n        size='icon'\n        aria-label={`Remove the action ${phrase}`}\n        onClick={onRemove}\n        className='ms-auto'\n      >\n        <XIcon />\n      </Button>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/automations-01/rule-parts.tsx"
    },
    {
      "path": "registry/ndeko/blocks/automations/automations-01/rule-model.ts",
      "content": "import {\n  ACTIONS,\n  FIELDS,\n  TARGETS,\n  TRIGGERS,\n  type Action,\n  type ActionDefinition,\n  type ActionKind,\n  type Condition,\n  type FieldDefinition,\n  type FieldId,\n  type Option,\n  type Rule,\n} from './data';\n\nexport type RuleErrors = Record<string, string>;\n\nexport const ACTIONS_ERROR_KEY = 'actions';\n\nconst CURRENCY = new Intl.NumberFormat('en-IE', {\n  style: 'currency',\n  currency: 'EUR',\n  maximumFractionDigits: 0,\n});\n\nconst MISSING_VALUE = '…';\n\nexport function fieldOf(id: FieldId): FieldDefinition {\n  const field = FIELDS.find((candidate) => candidate.id === id);\n  if (field) {\n    return field;\n  }\n  return FIELDS[0];\n}\n\nexport function actionDefinitionOf(kind: ActionKind): ActionDefinition {\n  const action = ACTIONS.find((candidate) => candidate.kind === kind);\n  if (action) {\n    return action;\n  }\n  return ACTIONS[0];\n}\n\nfunction labelIn(options: Option<string>[], value: string) {\n  const option = options.find((candidate) => candidate.value === value);\n  if (option) {\n    return option.label;\n  }\n  return MISSING_VALUE;\n}\n\nexport function targetOptionsOf(kind: ActionKind) {\n  const definition = actionDefinitionOf(kind);\n  if (definition.target === null) {\n    return [];\n  }\n  return TARGETS[definition.target];\n}\n\nexport function firstTargetOf(kind: ActionKind) {\n  const options = targetOptionsOf(kind);\n  if (options.length === 0) {\n    return '';\n  }\n  return options[0].value;\n}\n\nexport function digitsOf(text: string) {\n  return text.replace(/\\D/g, '');\n}\n\nfunction amountLabelOf(value: string) {\n  if (!value) {\n    return MISSING_VALUE;\n  }\n  const amount = Number(value);\n  return CURRENCY.format(amount);\n}\n\nfunction valueLabelOf(condition: Condition, field: FieldDefinition) {\n  if (field.kind === 'amount') {\n    return amountLabelOf(condition.value);\n  }\n  if (field.kind === 'choice') {\n    return labelIn(field.choices, condition.value);\n  }\n  const trimmed = condition.value.trim();\n  if (!trimmed) {\n    return MISSING_VALUE;\n  }\n  return `“${trimmed}”`;\n}\n\nexport function conditionPhraseOf(condition: Condition) {\n  const field = fieldOf(condition.field);\n  const operator = labelIn(field.operators, condition.operator);\n  const value = valueLabelOf(condition, field);\n  return `${field.noun} ${operator} ${value}`;\n}\n\nexport function actionPhraseOf(action: Action) {\n  const options = targetOptionsOf(action.kind);\n  const target = labelIn(options, action.target);\n  if (action.kind === 'ask-approval') {\n    return `ask ${target} to approve`;\n  }\n  if (action.kind === 'post-channel') {\n    return `post in ${target}`;\n  }\n  if (action.kind === 'flag-review') {\n    return 'flag it for review';\n  }\n  if (action.kind === 'decline-payment') {\n    return 'decline the payment';\n  }\n  return 'require a receipt';\n}\n\nfunction listOf(phrases: string[], joiner: string) {\n  if (phrases.length <= 1) {\n    return phrases.join('');\n  }\n  const leading = phrases.slice(0, -1);\n  const head = leading.join(', ');\n  const last = phrases[phrases.length - 1];\n  return `${head} ${joiner} ${last}`;\n}\n\nfunction joinerOf(rule: Rule) {\n  if (rule.match === 'any') {\n    return 'or';\n  }\n  return 'and';\n}\n\nfunction triggerPhraseOf(rule: Rule) {\n  const trigger = TRIGGERS.find((option) => option.value === rule.trigger);\n  if (trigger) {\n    return trigger.phrase;\n  }\n  return MISSING_VALUE;\n}\n\nfunction actionsPhraseOf(rule: Rule) {\n  if (rule.actions.length === 0) {\n    return 'nothing happens yet';\n  }\n  const phrases = rule.actions.map(actionPhraseOf);\n  return listOf(phrases, 'and');\n}\n\n/** The rule read back as one sentence, so the person can check it says what they mean. */\nexport function sentenceOf(rule: Rule) {\n  const trigger = triggerPhraseOf(rule);\n  const actions = actionsPhraseOf(rule);\n  if (rule.conditions.length === 0) {\n    return `When ${trigger}, ${actions}.`;\n  }\n  const conditionPhrases = rule.conditions.map(conditionPhraseOf);\n  const conditions = listOf(conditionPhrases, joinerOf(rule));\n  return `When ${trigger}, if ${conditions}, ${actions}.`;\n}\n\nfunction conditionErrorOf(condition: Condition) {\n  const field = fieldOf(condition.field);\n  if (field.kind === 'amount') {\n    const amount = Number(condition.value);\n    if (amount > 0) {\n      return null;\n    }\n    return 'Enter an amount above €0';\n  }\n  if (field.kind === 'text') {\n    const hasText = condition.value.trim().length > 0;\n    if (hasText) {\n      return null;\n    }\n    return 'Enter part of the merchant name';\n  }\n  return null;\n}\n\nexport function errorsOf(rule: Rule) {\n  const errors: RuleErrors = {};\n  for (const condition of rule.conditions) {\n    const error = conditionErrorOf(condition);\n    if (error) {\n      errors[condition.id] = error;\n    }\n  }\n  if (rule.actions.length === 0) {\n    errors[ACTIONS_ERROR_KEY] =\n      'Add at least one action, or the rule does nothing';\n  }\n  return errors;\n}\n\nexport function hasErrors(errors: RuleErrors) {\n  return Object.keys(errors).length > 0;\n}\n\nexport function sameRule(first: Rule, second: Rule) {\n  const firstText = JSON.stringify(first);\n  const secondText = JSON.stringify(second);\n  return firstText === secondText;\n}\n\nexport function conditionForField(id: string, fieldId: FieldId): Condition {\n  const field = fieldOf(fieldId);\n  return {\n    id,\n    field: fieldId,\n    operator: field.operators[0].value,\n    value: field.defaultValue,\n  };\n}\n\nexport function actionForKind(id: string, kind: ActionKind): Action {\n  return { id, kind, target: firstTargetOf(kind) };\n}\n\n/** The first field the conditions do not test yet, so a new row starts on something useful. */\nexport function unusedFieldOf(conditions: Condition[]) {\n  const usedFields = conditions.map((condition) => condition.field);\n  const unused = FIELDS.find((field) => !usedFields.includes(field.id));\n  if (unused) {\n    return unused.id;\n  }\n  return FIELDS[0].id;\n}\n\n/** The first kind the rule does not use yet, so a new action row starts on something useful. */\nexport function unusedActionKindOf(actions: Action[]) {\n  const usedKinds = actions.map((action) => action.kind);\n  const unused = ACTIONS.find(\n    (definition) => !usedKinds.includes(definition.kind)\n  );\n  if (unused) {\n    return unused.kind;\n  }\n  return ACTIONS[0].kind;\n}\n\nexport function replacedById<Item extends { id: string }>(\n  items: Item[],\n  next: Item\n) {\n  return items.map((item) => {\n    if (item.id === next.id) {\n      return next;\n    }\n    return item;\n  });\n}\n\nexport function withoutId<Item extends { id: string }>(\n  items: Item[],\n  id: string\n) {\n  return items.filter((item) => item.id !== id);\n}\n",
      "type": "registry:component",
      "target": "components/blocks/automations-01/rule-model.ts"
    },
    {
      "path": "registry/ndeko/blocks/automations/automations-01/save-button.tsx",
      "content": "'use client';\n\nimport {\n  AnimatePresence,\n  motion,\n  type Transition,\n  type Variants,\n} from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { CheckIcon, LoaderCircleIcon } from '@/registry/ndeko/lib/icons';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nexport type SaveStatus = 'idle' | 'saving' | 'saved';\n\nconst SWAP_TRANSITION: Transition = { duration: 0.15, ease: [0.2, 0, 0, 1] };\n\nconst SWAP_VARIANTS: Variants = {\n  enter: { opacity: 0, scale: 0.6, filter: 'blur(2px)' },\n  visible: { opacity: 1, scale: 1, filter: 'blur(0px)' },\n  exit: { opacity: 0, scale: 0.6, filter: 'blur(2px)' },\n};\n\nconst FADE_VARIANTS: Variants = {\n  enter: { opacity: 0 },\n  visible: { opacity: 1 },\n  exit: { opacity: 0 },\n};\n\nfunction swapVariantsOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return FADE_VARIANTS;\n  }\n  return SWAP_VARIANTS;\n}\n\nfunction labelOf(status: SaveStatus, idleLabel: string) {\n  if (status === 'saving') {\n    return 'Saving';\n  }\n  if (status === 'saved') {\n    return 'Saved';\n  }\n  return idleLabel;\n}\n\n/** While saving, the pill keeps its full colour: it is working, not unavailable. */\nfunction busyClassOf(isBusy: boolean) {\n  if (isBusy) {\n    return 'data-disabled:opacity-100 disabled:opacity-100';\n  }\n  return undefined;\n}\n\nfunction glyphOf(status: SaveStatus) {\n  if (status === 'saving') {\n    return {\n      key: 'saving',\n      icon: <LoaderCircleIcon className='animate-spin' />,\n    };\n  }\n  if (status === 'saved') {\n    return { key: 'saved', icon: <CheckIcon /> };\n  }\n  return null;\n}\n\ntype SaveButtonProps = {\n  status: SaveStatus;\n  idleLabel: string;\n  disabled?: boolean;\n  onSave: () => void;\n};\n\n/** The label becomes its next state and the pill resizes to it. */\nexport function SaveButton({\n  status,\n  idleLabel,\n  disabled = false,\n  onSave,\n}: SaveButtonProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const variants = swapVariantsOf(shouldReduceMotion);\n  const label = labelOf(status, idleLabel);\n  const glyph = glyphOf(status);\n  const isBusy = status !== 'idle';\n  const isDisabled = disabled || isBusy;\n  const busyClass = busyClassOf(isBusy);\n\n  return (\n    <Button\n      disabled={isDisabled}\n      focusableWhenDisabled\n      onClick={onSave}\n      className={busyClass}\n    >\n      <AnimatedSize\n        as='span'\n        axis='width'\n        contentClassName='relative flex items-center gap-1.5'\n      >\n        <AnimatePresence mode='popLayout' initial={false}>\n          {glyph && (\n            <motion.span\n              key={glyph.key}\n              variants={variants}\n              initial='enter'\n              animate='visible'\n              exit='exit'\n              transition={SWAP_TRANSITION}\n              className='flex'\n            >\n              {glyph.icon}\n            </motion.span>\n          )}\n        </AnimatePresence>\n        <AnimatePresence mode='popLayout' initial={false}>\n          <motion.span\n            key={label}\n            variants={variants}\n            initial='enter'\n            animate='visible'\n            exit='exit'\n            transition={SWAP_TRANSITION}\n          >\n            {label}\n          </motion.span>\n        </AnimatePresence>\n      </AnimatedSize>\n    </Button>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/automations-01/save-button.tsx"
    },
    {
      "path": "registry/ndeko/blocks/automations/automations-01/motion-parts.tsx",
      "content": "'use client';\n\nimport { type MotionProps, type Transition } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nconst EASE_OUT_STRONG: [number, number, number, number] = [0.23, 1, 0.32, 1];\n\nconst ENTER: Transition = { duration: 0.2, ease: EASE_OUT_STRONG };\n\nconst EXIT: Transition = { duration: 0.14, ease: EASE_OUT_STRONG };\n\ntype PresenceProps = Pick<\n  MotionProps,\n  'initial' | 'animate' | 'exit' | 'transition'\n>;\n\nconst HEIGHT_PRESENCE: PresenceProps = {\n  initial: { height: 0, opacity: 0 },\n  animate: { height: 'auto', opacity: 1 },\n  exit: { height: 0, opacity: 0, transition: EXIT },\n  transition: ENTER,\n};\n\nexport const FADE_PRESENCE: PresenceProps = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n  exit: { opacity: 0, transition: EXIT },\n  transition: ENTER,\n};\n\n/** Rows that join or leave a list open and close their own height, so what follows slides. */\nexport function useHeightPresence() {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  if (shouldReduceMotion) {\n    return FADE_PRESENCE;\n  }\n  return HEIGHT_PRESENCE;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/automations-01/motion-parts.tsx"
    },
    {
      "path": "registry/ndeko/blocks/automations/automations-01/data.ts",
      "content": "export type TriggerId =\n  'card-payment' | 'expense-submitted' | 'refund-requested';\n\nexport type FieldId = 'amount' | 'category' | 'team' | 'merchant';\n\nexport type OperatorId = 'over' | 'under' | 'is' | 'is-not' | 'contains';\n\nexport type ValueKind = 'amount' | 'choice' | 'text';\n\nexport type MatchMode = 'all' | 'any';\n\nexport type ActionKind =\n  | 'require-receipt'\n  | 'ask-approval'\n  | 'flag-review'\n  | 'post-channel'\n  | 'decline-payment';\n\nexport type TargetKind = 'person' | 'channel';\n\nexport type Option<Value extends string> = { value: Value; label: string };\n\nexport type FieldDefinition = {\n  id: FieldId;\n  label: string;\n  /** How the field reads inside the rule sentence: \"the amount\". */\n  noun: string;\n  kind: ValueKind;\n  operators: Option<OperatorId>[];\n  choices: Option<string>[];\n  defaultValue: string;\n};\n\nexport type ActionDefinition = {\n  kind: ActionKind;\n  label: string;\n  target: TargetKind | null;\n};\n\nexport type Condition = {\n  id: string;\n  field: FieldId;\n  operator: OperatorId;\n  value: string;\n};\n\nexport type Action = {\n  id: string;\n  kind: ActionKind;\n  target: string;\n};\n\nexport type Rule = {\n  trigger: TriggerId;\n  match: MatchMode;\n  conditions: Condition[];\n  actions: Action[];\n};\n\nexport const RULE_NAME = 'Large card payments need a receipt';\n\nexport const WORKSPACE_LINE = 'Spending rules · Fernhollow Studio';\n\nexport const TRIGGERS: (Option<TriggerId> & { phrase: string })[] = [\n  {\n    value: 'card-payment',\n    label: 'A card payment is made',\n    phrase: 'a card payment is made',\n  },\n  {\n    value: 'expense-submitted',\n    label: 'An expense is submitted',\n    phrase: 'an expense is submitted',\n  },\n  {\n    value: 'refund-requested',\n    label: 'A refund is requested',\n    phrase: 'a refund is requested',\n  },\n];\n\nexport const MATCH_MODES: Option<MatchMode>[] = [\n  { value: 'all', label: 'All' },\n  { value: 'any', label: 'Any' },\n];\n\nconst AMOUNT_OPERATORS: Option<OperatorId>[] = [\n  { value: 'over', label: 'is over' },\n  { value: 'under', label: 'is under' },\n];\n\nconst CHOICE_OPERATORS: Option<OperatorId>[] = [\n  { value: 'is', label: 'is' },\n  { value: 'is-not', label: 'is not' },\n];\n\nconst TEXT_OPERATORS: Option<OperatorId>[] = [\n  { value: 'contains', label: 'contains' },\n];\n\nexport const FIELDS: FieldDefinition[] = [\n  {\n    id: 'amount',\n    label: 'Amount',\n    noun: 'the amount',\n    kind: 'amount',\n    operators: AMOUNT_OPERATORS,\n    choices: [],\n    defaultValue: '100',\n  },\n  {\n    id: 'category',\n    label: 'Category',\n    noun: 'the category',\n    kind: 'choice',\n    operators: CHOICE_OPERATORS,\n    choices: [\n      { value: 'travel', label: 'Travel' },\n      { value: 'meals', label: 'Meals' },\n      { value: 'software', label: 'Software' },\n      { value: 'equipment', label: 'Equipment' },\n      { value: 'office', label: 'Office supplies' },\n    ],\n    defaultValue: 'travel',\n  },\n  {\n    id: 'team',\n    label: 'Team',\n    noun: 'the team',\n    kind: 'choice',\n    operators: CHOICE_OPERATORS,\n    choices: [\n      { value: 'design', label: 'Design' },\n      { value: 'engineering', label: 'Engineering' },\n      { value: 'sales', label: 'Sales' },\n      { value: 'operations', label: 'Operations' },\n    ],\n    defaultValue: 'sales',\n  },\n  {\n    id: 'merchant',\n    label: 'Merchant',\n    noun: 'the merchant',\n    kind: 'text',\n    operators: TEXT_OPERATORS,\n    choices: [],\n    defaultValue: '',\n  },\n];\n\nexport const ACTIONS: ActionDefinition[] = [\n  { kind: 'require-receipt', label: 'Require a receipt', target: null },\n  { kind: 'ask-approval', label: 'Ask for approval', target: 'person' },\n  { kind: 'flag-review', label: 'Flag for review', target: null },\n  { kind: 'post-channel', label: 'Post in a channel', target: 'channel' },\n  { kind: 'decline-payment', label: 'Decline the payment', target: null },\n];\n\nexport const TARGETS: Record<TargetKind, Option<string>[]> = {\n  person: [\n    { value: 'rosa', label: 'Rosa Ilunga' },\n    { value: 'tomas', label: 'Tomás Reyes' },\n    { value: 'amara', label: 'Amara Diallo' },\n    { value: 'jonas', label: 'Jonas Weber' },\n  ],\n  channel: [\n    { value: 'finance', label: '#finance' },\n    { value: 'ops-alerts', label: '#ops-alerts' },\n    { value: 'team-leads', label: '#team-leads' },\n  ],\n};\n\nexport const INITIAL_RULE: Rule = {\n  trigger: 'card-payment',\n  match: 'all',\n  conditions: [\n    { id: 'condition-1', field: 'amount', operator: 'over', value: '75' },\n    {\n      id: 'condition-2',\n      field: 'category',\n      operator: 'is-not',\n      value: 'software',\n    },\n  ],\n  actions: [\n    { id: 'action-1', kind: 'require-receipt', target: '' },\n    { id: 'action-2', kind: 'ask-approval', target: 'rosa' },\n  ],\n};\n",
      "type": "registry:component",
      "target": "components/blocks/automations-01/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "automations"
  ],
  "type": "registry:block"
}