{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "card-02",
  "title": "Service receipt",
  "description": "A receipt drawn as a ticket with notched edges and a scalloped foot, where the total adds up as service lines are ticked and Start project confirms it.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/checkbox.json",
    "https://ui.ndekocode.dev/r/company-mark.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/morph-button.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/card/card-02.tsx",
      "content": "'use client';\n\nimport { useId, useRef, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport type { AutoplayStep } from '@/registry/ndeko/hooks/use-autoplay';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport {\n  hold,\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  pressedSolidOf,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport { CheckIcon, PencilIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { Checkbox } from '@/registry/ndeko/ui/checkbox';\nimport { CompanyMark } from '@/registry/ndeko/ui/company-mark';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\n\nimport { SampleNote } from './_parts/sample-note';\nimport { TearLine, TICKET_OUTLINE, ticketMaskOf } from './_parts/ticket';\nimport { useCardDemo } from './_parts/use-card-demo';\n\nexport type ReceiptService = {\n  id: string;\n  name: string;\n  detail: string;\n  price: number;\n};\n\n/** A receipt is a draft until Start project is pressed, and confirmed once the start went through. */\nexport type ReceiptStatus = 'draft' | 'starting' | 'confirmed';\n\nconst HEAD_MASK = ticketMaskOf(['left bottom', 'right bottom']);\n\nconst LINES_MASK = ticketMaskOf([\n  'left top',\n  'right top',\n  'left bottom',\n  'right bottom',\n]);\n\nconst FOOT_MASK = ticketMaskOf(['left top', 'right top'], true);\n\nconst TEAR = 'absolute inset-x-3 top-0';\n\n/** Under 18rem the status goes under the reference, so the client and the reference keep the whole width. */\nconst HEAD = [\n  'bg-card grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3 rounded-t-xl px-5 pt-5 pb-4',\n  '@2xs:grid-cols-[auto_minmax(0,1fr)_auto]',\n].join(' ');\n\nconst HEAD_TEXT = 'col-start-2 truncate @max-2xs:whitespace-normal';\n\nconst STATUS_PLACE = [\n  'col-start-2 row-start-3 mt-1.5 justify-self-start',\n  '@2xs:col-start-3 @2xs:row-start-1 @2xs:mt-0',\n].join(' ');\n\nconst LINE = [\n  '-mx-2 flex items-start gap-3 rounded-lg px-2 py-1.5',\n  'transition-[scale,background-color,opacity] duration-150 ease-(--ease-out-strong)',\n].join(' ');\n\nconst LINE_OPEN = 'cursor-pointer hover:bg-foreground/[0.03]';\n\nconst START_LABELS: Record<MorphState, string> = {\n  idle: 'Start project',\n  busy: 'Starting',\n  done: 'Project started',\n};\n\nconst MORPH_STATES: Record<ReceiptStatus, MorphState> = {\n  draft: 'idle',\n  starting: 'busy',\n  confirmed: 'done',\n};\n\nconst LOCALE = 'en-US';\n\nfunction moneyFormatOf(currency: string): Intl.NumberFormatOptions {\n  return { style: 'currency', currency, maximumFractionDigits: 0 };\n}\n\nfunction selectedOf(\n  services: ReceiptService[],\n  selectedIds: readonly string[]\n) {\n  return services.filter((service) => selectedIds.includes(service.id));\n}\n\nfunction totalOf(services: ReceiptService[], selectedIds: readonly string[]) {\n  let total = 0;\n  for (const service of selectedOf(services, selectedIds)) {\n    total += service.price;\n  }\n  return total;\n}\n\nfunction serviceWordOf(count: number) {\n  if (count === 1) {\n    return 'service';\n  }\n  return 'services';\n}\n\nfunction countLineOf(selectedCount: number, serviceCount: number) {\n  if (selectedCount === 0) {\n    return 'Pick a service to start';\n  }\n  const word = serviceWordOf(serviceCount);\n  return `${selectedCount} of ${serviceCount} ${word}`;\n}\n\nfunction lineStateOf(isLocked: boolean) {\n  if (isLocked) {\n    return undefined;\n  }\n  return LINE_OPEN;\n}\n\ntype ServiceLineProps = {\n  service: ReceiptService;\n  price: string;\n  isSelected: boolean;\n  isLocked: boolean;\n  isPressed: boolean;\n  onChange: (isSelected: boolean) => void;\n};\n\nfunction ServiceLine({\n  service,\n  price,\n  isSelected,\n  isLocked,\n  isPressed,\n  onChange,\n}: ServiceLineProps) {\n  const isLeftOut = isLocked && !isSelected;\n\n  return (\n    <li>\n      <label\n        className={cn(\n          LINE,\n          lineStateOf(isLocked),\n          isLeftOut && 'opacity-50',\n          pressedQuietOf(isPressed)\n        )}\n      >\n        <Checkbox\n          checked={isSelected}\n          disabled={isLocked}\n          onCheckedChange={onChange}\n          className='mt-0.5 data-disabled:opacity-100'\n        />\n        <span className='min-w-0 flex-1'>\n          <span className='block truncate text-[13px] font-medium'>\n            {service.name}\n          </span>\n          <span className='text-muted-foreground block text-xs'>\n            {service.detail}\n          </span>\n        </span>\n        <span className='text-[13px] tabular-nums'>{price}</span>\n      </label>\n    </li>\n  );\n}\n\nfunction StatusBadge({ status }: { status: ReceiptStatus }) {\n  const isConfirmed = status === 'confirmed';\n\n  return (\n    <Swap swapKey={String(isConfirmed)}>\n      {isConfirmed && (\n        <Badge variant='success'>\n          <CheckIcon />\n          Confirmed\n        </Badge>\n      )}\n      {!isConfirmed && <Badge variant='secondary'>Draft</Badge>}\n    </Swap>\n  );\n}\n\nexport type ServiceReceiptProps = {\n  client: string;\n  /** What the receipt is for, with its number: \"Quote 0482, website refresh\". */\n  reference: string;\n  services: ReceiptService[];\n  selectedIds: readonly string[];\n  onSelectedChange: (serviceId: string, isSelected: boolean) => void;\n  status: ReceiptStatus;\n  onStart: () => void;\n  /** Back to a draft, to change the selection after the start. */\n  onEdit: () => void;\n  currency?: string;\n  /** Says the prices are made up. Leave it out for real prices. */\n  note?: string;\n  /** The service line a demonstration ticks, shown held down. */\n  pressedServiceId?: string | null;\n  /** Shows Start project held down, for a demonstration that presses it. */\n  isStartPressed?: boolean;\n  className?: string;\n};\n\nexport function ServiceReceipt({\n  client,\n  reference,\n  services,\n  selectedIds,\n  onSelectedChange,\n  status,\n  onStart,\n  onEdit,\n  currency = 'USD',\n  note,\n  pressedServiceId = null,\n  isStartPressed = false,\n  className,\n}: ServiceReceiptProps) {\n  const titleId = useId();\n  const startRef = useRef<HTMLButtonElement>(null);\n  const moneyFormat = moneyFormatOf(currency);\n  const money = new Intl.NumberFormat(LOCALE, moneyFormat);\n  const total = totalOf(services, selectedIds);\n  const selectedCount = selectedOf(services, selectedIds).length;\n  const hasSelection = selectedCount > 0;\n  const isLocked = status !== 'draft';\n  const isConfirmed = status === 'confirmed';\n\n  /** Edit hides once the receipt is a draft again, so the focus moves first to Start project, which stays. */\n  function editFromButton() {\n    startRef.current?.focus();\n    onEdit();\n  }\n\n  return (\n    <section\n      aria-labelledby={titleId}\n      style={TICKET_OUTLINE}\n      className={cn('@container flex w-full flex-col', className)}\n    >\n      <div style={HEAD_MASK} className={HEAD}>\n        <CompanyMark seed={client} size='lg' className='row-span-2 mt-0.5' />\n        <h3\n          id={titleId}\n          className={cn(HEAD_TEXT, 'row-start-1 text-sm font-medium')}\n        >\n          {client}\n        </h3>\n        <p\n          className={cn(\n            HEAD_TEXT,\n            'text-muted-foreground row-start-2 text-xs @2xs:col-[2/4]'\n          )}\n        >\n          {reference}\n        </p>\n        <span className={STATUS_PLACE}>\n          <StatusBadge status={status} />\n        </span>\n      </div>\n      <div className='relative'>\n        <TearLine direction='row' className={TEAR} />\n      </div>\n      <div style={LINES_MASK} className='bg-card px-5 py-2'>\n        <ul aria-label='Services' className='flex flex-col'>\n          {services.map((service) => (\n            <ServiceLine\n              key={service.id}\n              service={service}\n              price={money.format(service.price)}\n              isSelected={selectedIds.includes(service.id)}\n              isLocked={isLocked}\n              isPressed={service.id === pressedServiceId}\n              onChange={(isSelected) =>\n                onSelectedChange(service.id, isSelected)\n              }\n            />\n          ))}\n        </ul>\n      </div>\n      <div className='relative'>\n        <TearLine direction='row' className={TEAR} />\n      </div>\n      <div style={FOOT_MASK} className='bg-card px-5 pt-4 pb-6'>\n        <div className='flex items-end justify-between gap-3'>\n          <div className='min-w-0'>\n            <p className='text-[13px] font-medium'>Total</p>\n            <p className='text-muted-foreground truncate text-xs tabular-nums'>\n              {countLineOf(selectedCount, services.length)}\n            </p>\n          </div>\n          <MotionNumber\n            value={total}\n            locale={LOCALE}\n            format={moneyFormat}\n            className='text-2xl font-semibold'\n          />\n        </div>\n        <div className='mt-4 flex items-center justify-between gap-2'>\n          <Button\n            type='button'\n            variant='ghost'\n            size='sm'\n            onClick={editFromButton}\n            className={cn(\n              'text-muted-foreground -ms-2',\n              !isConfirmed && 'invisible'\n            )}\n          >\n            <PencilIcon />\n            <span className='@max-3xs:sr-only'>Edit</span>\n          </Button>\n          <MorphButton\n            ref={startRef}\n            type='button'\n            state={MORPH_STATES[status]}\n            labels={START_LABELS}\n            disabled={!hasSelection}\n            onClick={onStart}\n            className={pressedSolidOf(isStartPressed)}\n          />\n        </div>\n        {note && <SampleNote className='mt-3 block'>{note}</SampleNote>}\n      </div>\n    </section>\n  );\n}\n\nconst SERVICES: ReceiptService[] = [\n  {\n    id: 'design',\n    name: 'Interface design',\n    detail: 'Eight screens, light and dark',\n    price: 2400,\n  },\n  {\n    id: 'build',\n    name: 'Front-end build',\n    detail: 'Responsive, tested on phones',\n    price: 3800,\n  },\n  {\n    id: 'motion',\n    name: 'Motion pass',\n    detail: 'Transitions and micro-interactions',\n    price: 900,\n  },\n  {\n    id: 'copy',\n    name: 'Copy review',\n    detail: 'Every label, error and empty state',\n    price: 600,\n  },\n];\n\nconst FIRST_SELECTION = ['design', 'build'];\n\nconst CLIENT = 'Halden Works';\n\nconst START_MS = 900;\n\n/** Long enough for the start to go through and for the confirmed receipt to be read. */\nconst CONFIRMED_HOLD_MS = START_MS + 2200;\n\nconst DEMO_MONEY = new Intl.NumberFormat(LOCALE, moneyFormatOf('USD'));\n\nfunction withService(\n  selectedIds: string[],\n  serviceId: string,\n  isSelected: boolean\n) {\n  const others = selectedIds.filter((selectedId) => selectedId !== serviceId);\n  if (isSelected) {\n    return [...others, serviceId];\n  }\n  return others;\n}\n\nfunction announcementOf(status: ReceiptStatus, total: number, count: number) {\n  const word = serviceWordOf(count);\n  const amount = DEMO_MONEY.format(total);\n  const summary = `${count} ${word}, total ${amount}`;\n  if (status === 'confirmed') {\n    return `Project started with ${summary}`;\n  }\n  return summary;\n}\n\nexport default function Card02() {\n  const [selectedIds, setSelectedIds] = useState(FIRST_SELECTION);\n  const [status, setStatus] = useState<ReceiptStatus>('draft');\n  const { schedule, clearAll } = useTimeouts();\n  const line = usePress<string>();\n  const start = usePress<'start'>();\n  const total = totalOf(SERVICES, selectedIds);\n  const announcement = announcementOf(status, total, selectedIds.length);\n\n  function changeSelected(serviceId: string, isSelected: boolean) {\n    setSelectedIds((current) => withService(current, serviceId, isSelected));\n  }\n\n  function startProject() {\n    const isDraft = status === 'draft';\n    const hasSelection = selectedIds.length > 0;\n    const canStart = isDraft && hasSelection;\n    if (!canStart) {\n      return;\n    }\n    setStatus('starting');\n    schedule(() => setStatus('confirmed'), START_MS);\n  }\n\n  function backToDraft() {\n    clearAll();\n    setStatus('draft');\n  }\n\n  function startOver() {\n    backToDraft();\n    setSelectedIds(FIRST_SELECTION);\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: 1400, run: () => line.press('motion') },\n    { after: PRESS_LEAD_MS, run: () => changeSelected('motion', true) },\n    { after: 1200, run: () => line.press('copy') },\n    { after: PRESS_LEAD_MS, run: () => changeSelected('copy', true) },\n    { after: 1300, run: () => line.press('design') },\n    { after: PRESS_LEAD_MS, run: () => changeSelected('design', false) },\n    { after: 1400, run: () => start.press('start') },\n    { after: PRESS_LEAD_MS, run: startProject },\n    { after: CONFIRMED_HOLD_MS, run: hold },\n  ];\n  const { ref, isAutoplaying } = useCardDemo(steps, {\n    loopAfter: 1200,\n    onReset: startOver,\n  });\n\n  return (\n    <div ref={ref} className='min-h-[27rem] w-full max-w-[20rem]'>\n      <ServiceReceipt\n        client={CLIENT}\n        reference='Quote 0482, website refresh'\n        services={SERVICES}\n        selectedIds={selectedIds}\n        onSelectedChange={changeSelected}\n        status={status}\n        onStart={startProject}\n        onEdit={backToDraft}\n        note='Illustrative prices'\n        pressedServiceId={line.pressed}\n        isStartPressed={start.pressed === 'start'}\n      />\n      <LiveRegion message={spokenUnless(isAutoplaying, announcement)} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/card-02.tsx"
    },
    {
      "path": "registry/ndeko/components/card/_parts/sample-note.tsx",
      "content": "import { cn } from '@/registry/ndeko/lib/utils';\n\ntype SampleNoteProps = {\n  /** What the sample is: \"Illustrative\", \"Sample quote\". */\n  children?: React.ReactNode;\n  className?: string;\n};\n\n/** The word that says the figures or the words of a demo are made up. */\nexport function SampleNote({\n  children = 'Illustrative',\n  className,\n}: SampleNoteProps) {\n  return (\n    <span className={cn('text-muted-foreground text-xs', className)}>\n      {children}\n    </span>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/sample-note.tsx"
    },
    {
      "path": "registry/ndeko/components/card/_parts/ticket.tsx",
      "content": "import type { CSSProperties } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\n/** A corner by name, or a custom property that holds one, so a container query can move the notch. */\nexport type TicketCorner =\n  | 'left top'\n  | 'right top'\n  | 'left bottom'\n  | 'right bottom'\n  | `var(--${string})`;\n\nconst NOTCH_PX = 7;\n\nconst SCALLOP_PX = 5;\n\nconst SCALLOP_STEP_PX = 16;\n\n/** Half a pixel of soft edge keeps the curve of a cut from showing steps. */\nconst SOFT_EDGE_PX = 0.5;\n\ntype MaskLayer = { image: string; size: string; repeat: string };\n\nfunction holeAt(position: string, radius: number) {\n  const edge = radius + SOFT_EDGE_PX;\n  return `radial-gradient(circle at ${position}, transparent ${radius}px, black ${edge}px)`;\n}\n\nfunction notchLayerOf(corner: TicketCorner): MaskLayer {\n  return {\n    image: holeAt(corner, NOTCH_PX),\n    size: '100% 100%',\n    repeat: 'no-repeat',\n  };\n}\n\n/** `round` fits a whole number of half circles into the edge, whatever the width of the ticket. */\nconst SCALLOP_LAYER: MaskLayer = {\n  image: holeAt('50% 100%', SCALLOP_PX),\n  size: `${SCALLOP_STEP_PX}px 100%`,\n  repeat: 'round no-repeat',\n};\n\nfunction layersOf(corners: readonly TicketCorner[], hasScallops: boolean) {\n  const notches = corners.map(notchLayerOf);\n  if (hasScallops) {\n    return [...notches, SCALLOP_LAYER];\n  }\n  return notches;\n}\n\n/**\n * The mask of one piece of a ticket: a quarter circle cut out of each named corner, so two pieces\n * that meet show a round notch, and a scalloped bottom edge when asked.\n */\nexport function ticketMaskOf(\n  corners: readonly TicketCorner[],\n  hasScallops = false\n): CSSProperties {\n  const layers = layersOf(corners, hasScallops);\n  const images = layers.map((layer) => layer.image);\n  const sizes = layers.map((layer) => layer.size);\n  const repeats = layers.map((layer) => layer.repeat);\n  return {\n    maskImage: images.join(', '),\n    maskSize: sizes.join(', '),\n    maskRepeat: repeats.join(', '),\n    maskComposite: 'intersect',\n  };\n}\n\nconst OUTLINE_SHADOWS = [\n  'drop-shadow(0 var(--hairline) 0 var(--border))',\n  'drop-shadow(0 calc(var(--hairline) * -1) 0 var(--border))',\n  'drop-shadow(var(--hairline) 0 0 var(--border))',\n  'drop-shadow(calc(var(--hairline) * -1) 0 0 var(--border))',\n  'drop-shadow(0 1px 1px rgb(0 0 0 / 0.04))',\n];\n\n/**\n * A mask cuts away the ring and the shadow of the piece it shapes. The wrapper of a ticket draws\n * the outline instead: one hairline on every side, following each cut.\n */\nexport const TICKET_OUTLINE: CSSProperties = {\n  filter: OUTLINE_SHADOWS.join(' '),\n};\n\nconst PERFORATION =\n  'color-mix(in oklab, var(--foreground) 22%, transparent) 0 4px, transparent 4px 8px';\n\nconst TEAR_ROW: CSSProperties = {\n  backgroundImage: `repeating-linear-gradient(90deg, ${PERFORATION})`,\n};\n\nconst TEAR_COLUMN: CSSProperties = {\n  backgroundImage: `repeating-linear-gradient(180deg, ${PERFORATION})`,\n};\n\ntype TearLineProps = {\n  /** `row` runs across a ticket that tears into a top and a bottom, `column` down one that tears into a left and a right. */\n  direction: 'row' | 'column';\n  className?: string;\n};\n\n/** The perforation where two pieces of a ticket meet, drawn from one notch to the other. */\nexport function TearLine({ direction, className }: TearLineProps) {\n  if (direction === 'column') {\n    return (\n      <span\n        aria-hidden='true'\n        style={TEAR_COLUMN}\n        className={cn('block w-px', className)}\n      />\n    );\n  }\n  return (\n    <span\n      aria-hidden='true'\n      style={TEAR_ROW}\n      className={cn('block h-px', className)}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/ticket.tsx"
    },
    {
      "path": "registry/ndeko/components/card/_parts/use-card-demo.ts",
      "content": "'use client';\n\nimport {\n  useAutoplay,\n  type AutoplayOptions,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\n\n/**\n * What every card demo shares: the demonstration, and the box that keeps its tallest height so a\n * round never moves the page.\n */\nexport function useCardDemo(\n  steps: readonly AutoplayStep[],\n  options?: AutoplayOptions\n) {\n  const demo = useAutoplay(steps, options);\n  const { ref } = demo;\n\n  useKeptHeight(ref);\n\n  return demo;\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/use-card-demo.ts"
    }
  ],
  "categories": [
    "components",
    "card"
  ],
  "type": "registry:component"
}