{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-data-02",
  "title": "Calendar with an assistant",
  "description": "A week of three calendars that finds the time: ask for 45 minutes with two people, the busy time of everyone is shaded, three numbered dashed slots land in the gaps with their reason, and Book turns the one you pick solid while the others leave, with five seconds to undo.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/avatar.json",
    "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/demonstration.json",
    "https://ui.ndekocode.dev/r/hatch.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/letter-tile.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/toggle-group.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/ai-data/ai-data-02/index.tsx",
      "content": "'use client';\n\nimport { useCallback, useId, useMemo, useRef } from 'react';\n\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport {\n  pressedSolidOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Avatar } from '@/registry/ndeko/ui/avatar';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold } from '@/registry/ndeko/ui/chat-motion';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\nimport { ToggleGroup, ToggleGroupItem } from '@/registry/ndeko/ui/toggle-group';\n\nimport { DAYS, EXAMPLES, PEOPLE, WEEK_LABEL, type DayId } from './data';\nimport {\n  INITIAL,\n  LOOP_AFTER_MS,\n  reducer,\n  RESTING,\n  SCRIPT,\n  takenOf,\n  THINK_MS,\n  UNDO_MS,\n  type CalendarState,\n} from './session';\nimport { SuggestionPanel } from './suggestion-panel';\nimport { WeekCalendar } from './week-calendar';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\nconst [ASK_EXAMPLE] = EXAMPLES;\n\nconst DAY_SEGMENTS: Segment<DayId>[] = DAYS.map((day) => ({\n  value: day.id,\n  label: `${day.label} ${day.date}`,\n}));\n\ntype DotStyle = React.CSSProperties & { '--person': string };\n\nfunction describedByOf(hasHint: boolean, hintId: string) {\n  if (hasHint) {\n    return hintId;\n  }\n  return undefined;\n}\n\n/** The meeting whose undo is still open, for the card that offers it. */\nfunction undoableOf(state: CalendarState) {\n  const booking = state.bookings.find(\n    (candidate) => candidate.id === state.undoId\n  );\n  return booking ?? null;\n}\n\nexport default function AiData02() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const { schedule, clearAll } = useTimeouts();\n  const askId = useId();\n  const hintId = useId();\n  const bookingCount = useRef(0);\n  const taken = useMemo(() => takenOf(state.bookings), [state.bookings]);\n  const hasHint = state.askHint !== null;\n  const message = spokenUnless(isAutoplaying, state.spoken);\n  const canReplay = isFinished && !isAutoplaying;\n\n  const focusLater = useCallback(\n    (selector: string) => {\n      requestAnimationFrame(() => {\n        const target = ref.current?.querySelector<HTMLElement>(selector);\n        target?.focus();\n      });\n    },\n    [ref]\n  );\n\n  /** The busy time stays shaded for a moment before the times are offered, as it does in the demonstration. */\n  function offerLater() {\n    schedule(() => act({ type: 'offered' }), THINK_MS);\n  }\n\n  function ask(event: React.FormEvent<HTMLFormElement>) {\n    event.preventDefault();\n    act({ type: 'asked' });\n    offerLater();\n  }\n\n  function askExample(text: string) {\n    act({ type: 'questionTyped', text });\n    act({ type: 'asked' });\n    offerLater();\n    focusLater('[data-ask-field]');\n  }\n\n  const hover = useCallback(\n    (rank: number | null) => act({ type: 'hovered', rank }),\n    [act]\n  );\n\n  /** The undo leaves with its button: a focus that sat on it goes back to the question box. */\n  const expireUndo = useCallback(\n    (id: string) => {\n      const undoButton = ref.current?.querySelector(`[data-undo=\"${id}\"]`);\n      const hadFocus = undoButton === document.activeElement;\n      act({ type: 'undoExpired', id });\n      if (undoButton && hadFocus) {\n        focusLater('[data-ask-field]');\n      }\n    },\n    [ref, act, focusLater]\n  );\n\n  /** The time that was pressed is gone once it is booked, so the focus goes to Undo, the next thing a person may want. */\n  const book = useCallback(\n    (rank: number) => {\n      bookingCount.current += 1;\n      const id = `booking-${bookingCount.current}`;\n      act({ type: 'booked', rank, id });\n      schedule(() => expireUndo(id), UNDO_MS);\n      focusLater(`[data-undo=\"${id}\"]`);\n    },\n    [act, schedule, expireUndo, focusLater]\n  );\n\n  function undo() {\n    act({ type: 'undone' });\n    focusLater('[data-book=\"1\"]');\n  }\n\n  function clearSearch() {\n    act({ type: 'searchCleared' });\n    focusLater('[data-ask-field]');\n  }\n\n  function showCalendars(values: unknown[]) {\n    const kept = PEOPLE.filter((person) => values.includes(person.id));\n    const shown = kept.map((person) => person.id);\n    act({ type: 'calendarsShown', shown });\n  }\n\n  /** A press that waits on a timer belongs to the round it was made in. */\n  function replay() {\n    clearAll();\n    restart();\n  }\n\n  return (\n    <ClockGate isActive={isInView}>\n      <div\n        ref={ref}\n        className='bg-background text-foreground @container min-h-dvh w-full'\n      >\n        <div className='mx-auto flex max-w-6xl flex-col gap-4 p-4 @3xl:gap-5 @3xl:p-8'>\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              <h1 className='text-lg font-semibold text-balance'>\n                Week of {WEEK_LABEL}\n              </h1>\n              <p className='text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs'>\n                Three calendars\n                <Badge variant='secondary'>Illustrative</Badge>\n              </p>\n            </div>\n            <ReplayButton\n              isShown={canReplay}\n              onReplay={replay}\n              label='Replay'\n            />\n            <ToggleGroup\n              multiple\n              size='sm'\n              aria-label='Calendars shown'\n              value={state.shown}\n              onValueChange={showCalendars}\n            >\n              {PEOPLE.map((person) => {\n                const dotStyle: DotStyle = {\n                  '--person': seriesColorOf(person.series),\n                };\n                return (\n                  <ToggleGroupItem\n                    key={person.id}\n                    value={person.id}\n                    className='gap-1.5 ps-1.5 pe-2.5 text-xs'\n                  >\n                    <Avatar seed={person.name} className='size-5' />\n                    {person.shortName}\n                    <span\n                      aria-hidden='true'\n                      style={dotStyle}\n                      className='size-2 rounded-full bg-(--person)'\n                    />\n                  </ToggleGroupItem>\n                );\n              })}\n            </ToggleGroup>\n          </header>\n\n          <div className='flex flex-col gap-4 @5xl:flex-row @5xl:items-start @5xl:gap-6'>\n            <div className='flex flex-col gap-3 @5xl:w-80 @5xl:shrink-0'>\n              <form onSubmit={ask} className='flex flex-col gap-1.5'>\n                <div className='flex items-center gap-2'>\n                  <label htmlFor={askId} className='sr-only'>\n                    Ask for a time\n                  </label>\n                  <Input\n                    id={askId}\n                    data-ask-field\n                    autoComplete='off'\n                    placeholder={ASK_EXAMPLE}\n                    value={state.question}\n                    aria-invalid={hasHint}\n                    aria-describedby={describedByOf(hasHint, hintId)}\n                    onChange={(event) =>\n                      act({ type: 'questionTyped', text: event.target.value })\n                    }\n                  />\n                  <Button\n                    type='submit'\n                    className={cn(\n                      'shrink-0',\n                      pressedSolidOf(pressed === 'ask')\n                    )}\n                  >\n                    Find a time\n                  </Button>\n                </div>\n                <Fold open={hasHint}>\n                  <p id={hintId} className='text-destructive-ink text-xs'>\n                    {state.askHint}\n                  </p>\n                </Fold>\n              </form>\n              <div className='min-h-[14rem]'>\n                <SuggestionPanel\n                  search={state.search}\n                  hot={state.hot}\n                  booking={undoableOf(state)}\n                  pressed={pressed}\n                  onExample={askExample}\n                  onHover={hover}\n                  onBook={book}\n                  onUndo={undo}\n                  onClear={clearSearch}\n                />\n              </div>\n            </div>\n            <div className='flex min-w-0 flex-1 flex-col gap-3'>\n              <Segments\n                value={state.day}\n                segments={DAY_SEGMENTS}\n                onValueChange={(day) => act({ type: 'dayPicked', day })}\n                label='Day shown'\n                className='w-full @3xl:hidden'\n              />\n              <WeekCalendar\n                shown={state.shown}\n                day={state.day}\n                search={state.search}\n                hot={state.hot}\n                bookings={state.bookings}\n                taken={taken}\n                onHover={hover}\n                onBook={book}\n              />\n            </div>\n          </div>\n        </div>\n        <LiveRegion message={message} />\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/ai-data-02/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/ai-data/ai-data-02/week-calendar.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion, type Transition } from 'motion/react';\nimport { memo } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport { hatchOf } from '@/registry/ndeko/lib/hatch';\nimport { EASE_OUT_STRONG } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { LetterTile } from '@/registry/ndeko/ui/letter-tile';\n\nimport {\n  clockOf,\n  DAYS,\n  EVENTS,\n  HOURS,\n  personOf,\n  timeRangeOf,\n  TODAY,\n  type CalendarEvent,\n  type Day,\n  type DayId,\n  type PersonId,\n} from './data';\nimport { busyBandsOf, type Busy, type Slot, type Suggestion } from './find';\nimport { boxOf, placesOf, type Box, type Place, type Timed } from './layout';\nimport { slotLineOf, type Booking, type Search } from './session';\n\ntype PersonStyle = React.CSSProperties & { '--person': string };\n\n/** A block shorter than this only has room for its title. */\nconst TWO_LINES_FROM_MINUTES = 45;\n\nconst BUSY_HATCH = hatchOf('var(--foreground)', 20);\n\n/** The busy time of one day is shaded a little after the day before it. */\nconst SHADE_STAGGER_MS = 70;\n\n/** The times offered land one after the other, the best first. */\nconst LANDING_STAGGER = 0.08;\n\nconst GRID =\n  'grid grid-cols-[2.75rem_minmax(0,1fr)] @3xl:grid-cols-[2.75rem_repeat(5,minmax(0,1fr))]';\n\nconst BLOCK =\n  'relative flex h-full flex-col overflow-hidden rounded-[5px] py-0.5 ps-2.5 pe-1.5 text-[11px] leading-4';\n\nconst SOLID = 'bg-[color-mix(in_oklab,var(--person)_16%,var(--card))]';\n\nconst GHOST =\n  'hairline-border focus-visible:ring-ring/25 flex h-full w-full cursor-pointer items-start gap-1.5 overflow-hidden rounded-[5px] border-dashed px-1.5 py-0.5 text-start text-[11px] leading-4 font-medium tabular-nums outline-none transition-[background-color,border-color] duration-150 focus-visible:ring-[3px]';\n\nfunction ghostToneOf(isHot: boolean) {\n  if (isHot) {\n    return 'border-primary bg-primary/[0.16] text-primary-ink';\n  }\n  return 'border-primary/50 bg-primary/[0.06] text-primary-ink';\n}\n\nfunction slotIdOf(slot: Slot) {\n  return `${slot.day}-${slot.start}-${slot.end}`;\n}\n\n/** What sits on top of the meetings of a day: a time that is offered, or the meeting it became. */\ntype SlotItem = Timed & {\n  suggestion: Suggestion | null;\n  booking: Booking | null;\n};\n\nfunction offerItemOf(suggestion: Suggestion): SlotItem {\n  return {\n    id: slotIdOf(suggestion),\n    start: suggestion.start,\n    end: suggestion.end,\n    suggestion,\n    booking: null,\n  };\n}\n\nfunction bookingItemOf(booking: Booking): SlotItem {\n  return {\n    id: slotIdOf(booking),\n    start: booking.start,\n    end: booking.end,\n    suggestion: null,\n    booking,\n  };\n}\n\n/** The times are on the calendar only while they are offered. */\nfunction offersOn(search: Search | null, day: DayId) {\n  if (search?.status !== 'offering') {\n    return [];\n  }\n  return search.suggestions.filter((suggestion) => suggestion.day === day);\n}\n\nfunction isAskedFor(search: Search | null, day: DayId) {\n  if (!search) {\n    return false;\n  }\n  return search.request.days.includes(day);\n}\n\n/** While a question is open, the days it does not ask about step back. */\nfunction dimOf(isSetAside: boolean) {\n  if (isSetAside) {\n    return 'opacity-40';\n  }\n  return 'opacity-100';\n}\n\nfunction shadeOf(isShaded: boolean) {\n  if (isShaded) {\n    return 'opacity-100';\n  }\n  return 'opacity-0';\n}\n\nfunction eventVisibilityOf(isShown: boolean) {\n  if (isShown) {\n    return 'opacity-100';\n  }\n  return 'pointer-events-none opacity-0';\n}\n\n/** A narrow page shows the picked day alone; a wide one shows the week. */\nfunction dayVisibilityOf(isPicked: boolean) {\n  if (isPicked) {\n    return 'block';\n  }\n  return 'hidden @3xl:block';\n}\n\nfunction EventBlock({\n  title,\n  start,\n  end,\n  person,\n}: Pick<CalendarEvent, 'title' | 'start' | 'end' | 'person'>) {\n  const owner = personOf(person);\n  const style: PersonStyle = { '--person': seriesColorOf(owner.series) };\n  const hasRoomForTime = end - start >= TWO_LINES_FROM_MINUTES;\n\n  return (\n    <div style={style} className={cn(BLOCK, SOLID)}>\n      <span\n        aria-hidden='true'\n        className='absolute inset-y-0 start-0 w-[3px] bg-(--person)'\n      />\n      <p className='truncate font-medium'>\n        <span className='sr-only'>{owner.shortName}: </span>\n        {title}\n      </p>\n      {hasRoomForTime && (\n        <p className='truncate tabular-nums'>{timeRangeOf(start, end)}</p>\n      )}\n      {!hasRoomForTime && (\n        <span className='sr-only'>{timeRangeOf(start, end)}</span>\n      )}\n    </div>\n  );\n}\n\nconst SLOT_EXIT = {\n  opacity: 0,\n  scale: 0.96,\n  transition: { duration: 0.12, ease: EASE_OUT_STRONG },\n};\n\nconst SLOT_FADE_EXIT = { opacity: 0, transition: { duration: 0.12 } };\n\nconst SLOT_FADE_START = { opacity: 0 };\n\nconst SLOT_START = { opacity: 0, scale: 1.04 };\n\nconst SLOT_FADE_TARGET = { opacity: 1 };\n\nconst SLOT_TARGET = { opacity: 1, scale: 1 };\n\nconst SLOT_BOOKED_TARGET = { opacity: 1, scale: [1.04, 1] };\n\nfunction slotStartOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return SLOT_FADE_START;\n  }\n  return SLOT_START;\n}\n\n/** A time that is booked settles again, from a slightly larger size, as it turns solid. */\nfunction slotTargetOf(isBooked: boolean, shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return SLOT_FADE_TARGET;\n  }\n  if (isBooked) {\n    return SLOT_BOOKED_TARGET;\n  }\n  return SLOT_TARGET;\n}\n\nfunction slotExitOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return SLOT_FADE_EXIT;\n  }\n  return SLOT_EXIT;\n}\n\nfunction slotTransitionOf(suggestion: Suggestion | null): Transition {\n  const settle = { duration: 0.3, ease: EASE_OUT_STRONG };\n  if (!suggestion) {\n    return settle;\n  }\n  const delay = (suggestion.rank - 1) * LANDING_STAGGER;\n  return { ...settle, delay };\n}\n\nfunction boxStyleOf(box: Box): React.CSSProperties {\n  return { top: box.top, height: box.height, left: box.left, width: box.width };\n}\n\nfunction ghostLabelOf(suggestion: Suggestion) {\n  const when = slotLineOf(suggestion);\n  return `Book suggestion ${suggestion.rank}: ${when}. ${suggestion.reason}`;\n}\n\ntype BookedBlockProps = {\n  booking: Booking;\n  shown: PersonId[];\n};\n\n/** A meeting booked here sits on the calendar of everyone in it: it shows while one of them does. */\nfunction BookedBlock({ booking, shown }: BookedBlockProps) {\n  const isShown = booking.attendees.some((person) => shown.includes(person));\n\n  return (\n    <div\n      aria-hidden={!isShown}\n      className={cn(\n        'h-full transition-opacity duration-200',\n        eventVisibilityOf(isShown)\n      )}\n    >\n      <EventBlock\n        title={booking.title}\n        start={booking.start}\n        end={booking.end}\n        person='you'\n      />\n    </div>\n  );\n}\n\ntype SlotBlockProps = {\n  item: SlotItem;\n  place: Place | undefined;\n  shown: PersonId[];\n  hot: number | null;\n  onHover: (rank: number | null) => void;\n  onBook: (rank: number) => void;\n};\n\n/**\n * One element from the dashed offer to the solid meeting: only its look changes when it is booked.\n * It never gets shorter than its number, however short the meeting asked for.\n */\nfunction SlotBlock({\n  item,\n  place,\n  shown,\n  hot,\n  onHover,\n  onBook,\n}: SlotBlockProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const { suggestion, booking } = item;\n  const isBooked = booking !== null;\n  const box = boxOf(item, place);\n\n  return (\n    <motion.div\n      initial={slotStartOf(shouldReduceMotion)}\n      animate={slotTargetOf(isBooked, shouldReduceMotion)}\n      exit={slotExitOf(shouldReduceMotion)}\n      transition={slotTransitionOf(suggestion)}\n      style={boxStyleOf(box)}\n      className='absolute z-10 min-h-5 p-px'\n    >\n      {suggestion && (\n        <button\n          type='button'\n          data-ghost={suggestion.rank}\n          aria-label={ghostLabelOf(suggestion)}\n          onClick={() => onBook(suggestion.rank)}\n          onPointerEnter={() => onHover(suggestion.rank)}\n          onPointerLeave={() => onHover(null)}\n          onFocus={() => onHover(suggestion.rank)}\n          onBlur={() => onHover(null)}\n          className={cn(GHOST, ghostToneOf(hot === suggestion.rank))}\n        >\n          <LetterTile initial={String(suggestion.rank)} size='sm' />\n          <span className='min-w-0 truncate'>\n            {timeRangeOf(suggestion.start, suggestion.end)}\n          </span>\n        </button>\n      )}\n      {booking && <BookedBlock booking={booking} shown={shown} />}\n    </motion.div>\n  );\n}\n\ntype DayColumnProps = {\n  day: Day;\n  isPicked: boolean;\n  shown: PersonId[];\n  search: Search | null;\n  hot: number | null;\n  bookings: Booking[];\n  taken: Busy[];\n  shadeOrder: number;\n  onHover: (rank: number | null) => void;\n  onBook: (rank: number) => void;\n};\n\nfunction DayColumn({\n  day,\n  isPicked,\n  shown,\n  search,\n  hot,\n  bookings,\n  taken,\n  shadeOrder,\n  onHover,\n  onBook,\n}: DayColumnProps) {\n  const events = EVENTS.filter((event) => event.day === day.id);\n  const offers = offersOn(search, day.id);\n  const dayBookings = bookings.filter((booking) => booking.day === day.id);\n  const slots = [...offers.map(offerItemOf), ...dayBookings.map(bookingItemOf)];\n  const places = placesOf([...events, ...slots]);\n  const isSearching = search !== null && search.status !== 'booked';\n  const isAsked = isAskedFor(search, day.id);\n  const isSetAside = isSearching && !isAsked;\n  const isShaded = isSearching && isAsked;\n  let bands: Slot[] = [];\n  if (search && isAsked) {\n    bands = busyBandsOf(taken, search.request.attendees, day.id);\n  }\n  const shadeDelay = `${shadeOrder * SHADE_STAGGER_MS}ms`;\n\n  return (\n    <section\n      aria-label={`${day.name} ${day.date}`}\n      className={cn(\n        'hairline-l border-foreground/[0.07] relative h-[27rem] min-w-0',\n        dayVisibilityOf(isPicked)\n      )}\n    >\n      <div aria-hidden='true' className='absolute inset-0 flex flex-col'>\n        {HOURS.map((hour) => (\n          <span\n            key={hour}\n            className='hairline-t border-foreground/[0.07] flex-1'\n          />\n        ))}\n      </div>\n      <div\n        className={cn(\n          'absolute inset-0 transition-opacity duration-300',\n          dimOf(isSetAside)\n        )}\n      >\n        <ul className='absolute inset-0'>\n          {events.map((event) => {\n            const isShown = shown.includes(event.person);\n            const box = boxOf(event, places.get(event.id));\n            return (\n              <li\n                key={event.id}\n                aria-hidden={!isShown}\n                style={boxStyleOf(box)}\n                className={cn(\n                  'absolute p-px transition-opacity duration-200',\n                  eventVisibilityOf(isShown)\n                )}\n              >\n                <EventBlock\n                  title={event.title}\n                  start={event.start}\n                  end={event.end}\n                  person={event.person}\n                />\n              </li>\n            );\n          })}\n        </ul>\n        {bands.map((band) => {\n          const box = boxOf({ id: 'band', ...band }, undefined);\n          return (\n            <span\n              key={band.start}\n              aria-hidden='true'\n              style={{\n                top: box.top,\n                height: box.height,\n                backgroundImage: BUSY_HATCH,\n                transitionDelay: shadeDelay,\n              }}\n              className={cn(\n                'bg-background/45 pointer-events-none absolute inset-x-0 transition-opacity duration-300 starting:opacity-0',\n                shadeOf(isShaded)\n              )}\n            />\n          );\n        })}\n        <AnimatePresence initial={false}>\n          {slots.map((item) => (\n            <SlotBlock\n              key={item.id}\n              item={item}\n              place={places.get(item.id)}\n              shown={shown}\n              hot={hot}\n              onHover={onHover}\n              onBook={onBook}\n            />\n          ))}\n        </AnimatePresence>\n      </div>\n    </section>\n  );\n}\n\nfunction todayToneOf(isToday: boolean) {\n  if (isToday) {\n    return 'text-primary-ink';\n  }\n  return 'text-foreground';\n}\n\nexport type WeekCalendarProps = {\n  shown: PersonId[];\n  /** The day a narrow page shows. */\n  day: DayId;\n  search: Search | null;\n  hot: number | null;\n  bookings: Booking[];\n  /** The busy time of every person, which the open question shades for those it asks about. */\n  taken: Busy[];\n  onHover: (rank: number | null) => void;\n  onBook: (rank: number) => void;\n};\n\n/** Memoised: a key typed in the question box does not lay the week out again. */\nexport const WeekCalendar = memo(function WeekCalendar({\n  shown,\n  day: pickedDay,\n  search,\n  hot,\n  bookings,\n  taken,\n  onHover,\n  onBook,\n}: WeekCalendarProps) {\n  const askedDays = search?.request.days ?? [];\n\n  return (\n    <div className='bg-card hairline-ring ring-border flex min-w-0 flex-col rounded-xl p-3 pt-2.5 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n      <div aria-hidden='true' className={cn(GRID, 'hidden pb-2 @3xl:grid')}>\n        <span />\n        {DAYS.map((day) => (\n          <p key={day.id} className='flex items-baseline gap-1.5 px-2 text-xs'>\n            <span className='text-muted-foreground'>{day.label}</span>\n            <span\n              className={cn(\n                'font-medium tabular-nums',\n                todayToneOf(day.id === TODAY)\n              )}\n            >\n              {day.date}\n            </span>\n          </p>\n        ))}\n      </div>\n      <div className={GRID}>\n        <div aria-hidden='true' className='flex h-[27rem] flex-col'>\n          {HOURS.map((hour) => (\n            <span\n              key={hour}\n              className='text-muted-foreground flex-1 pe-2 pt-1 text-end text-[11px] leading-none tabular-nums'\n            >\n              {clockOf(hour * 60)}\n            </span>\n          ))}\n        </div>\n        {DAYS.map((day) => (\n          <DayColumn\n            key={day.id}\n            day={day}\n            isPicked={day.id === pickedDay}\n            shown={shown}\n            search={search}\n            hot={hot}\n            bookings={bookings}\n            taken={taken}\n            shadeOrder={askedDays.indexOf(day.id)}\n            onHover={onHover}\n            onBook={onBook}\n          />\n        ))}\n      </div>\n    </div>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/blocks/ai-data-02/week-calendar.tsx"
    },
    {
      "path": "registry/ndeko/blocks/ai-data/ai-data-02/suggestion-panel.tsx",
      "content": "'use client';\n\nimport { pressedSolidOf } from '@/registry/ndeko/lib/demonstration';\nimport {\n  CircleCheckIcon,\n  LoaderIcon,\n  UndoIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { LetterTile } from '@/registry/ndeko/ui/letter-tile';\n\nimport { guestNamesOf, requestLineOf } from './ask';\nimport { dayOf, EXAMPLES, timeRangeOf } from './data';\nimport type { Slot, Suggestion } from './find';\nimport { slotLineOf, type Booking, type Search } from './session';\n\n/**\n * Each time offered arrives a little after the one ranked above it. The wait is on the fade only:\n * the tint that answers the pointer never waits.\n */\nconst ARRIVAL_DELAY = ['delay-0', 'delay-[0ms,75ms]', 'delay-[0ms,150ms]'];\n\nconst ROW =\n  'flex items-center gap-2.5 rounded-lg p-2 transition-[background-color,opacity] duration-[150ms,300ms] starting:opacity-0';\n\nconst EXAMPLE =\n  'focus-visible:ring-ring/25 hover:bg-foreground/[0.05] w-full cursor-pointer rounded-lg px-2.5 py-2 text-start text-[13px] leading-5 text-pretty transition-colors duration-150 outline-none focus-visible:ring-[3px]';\n\nfunction rowToneOf(isHot: boolean) {\n  if (isHot) {\n    return 'bg-foreground/[0.05]';\n  }\n  return undefined;\n}\n\n/** The best time carries the one primary action of the block. */\nfunction bookVariantOf(rank: number) {\n  if (rank === 1) {\n    return 'default';\n  }\n  return 'outline';\n}\n\nfunction calendarsWordOf(count: number) {\n  if (count === 1) {\n    return '1 calendar';\n  }\n  return `${count} calendars`;\n}\n\n/** Thu 19, 11:00 to 11:45. */\nfunction slotLabelOf(slot: Slot) {\n  const day = dayOf(slot.day);\n  return `${day.label} ${day.date}, ${timeRangeOf(slot.start, slot.end)}`;\n}\n\ntype ExamplesProps = {\n  onExample: (text: string) => void;\n};\n\nfunction Examples({ onExample }: ExamplesProps) {\n  return (\n    <div className='flex flex-col gap-1.5'>\n      <p className='text-muted-foreground px-2.5 text-xs'>\n        Ask in your own words, or start from one of these\n      </p>\n      <ul className='flex flex-col'>\n        {EXAMPLES.map((example) => (\n          <li key={example}>\n            <button\n              type='button'\n              onClick={() => onExample(example)}\n              className={EXAMPLE}\n            >\n              {example}\n            </button>\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\ntype SuggestionRowProps = {\n  suggestion: Suggestion;\n  isHot: boolean;\n  isPressed: boolean;\n  onHover: (rank: number | null) => void;\n  onBook: (rank: number) => void;\n};\n\nfunction SuggestionRow({\n  suggestion,\n  isHot,\n  isPressed,\n  onHover,\n  onBook,\n}: SuggestionRowProps) {\n  const { rank } = suggestion;\n\n  return (\n    <li\n      onPointerEnter={() => onHover(rank)}\n      onPointerLeave={() => onHover(null)}\n      className={cn(ROW, ARRIVAL_DELAY[rank - 1], rowToneOf(isHot))}\n    >\n      <LetterTile initial={String(rank)} />\n      <div className='flex min-w-0 flex-1 flex-col'>\n        <p className='truncate text-[13px] leading-5 font-medium tabular-nums'>\n          {slotLabelOf(suggestion)}\n        </p>\n        <p className='text-muted-foreground text-xs text-pretty'>\n          {suggestion.reason}\n        </p>\n      </div>\n      <Button\n        type='button'\n        size='sm'\n        variant={bookVariantOf(rank)}\n        data-book={rank}\n        aria-label={`Book ${slotLineOf(suggestion)}`}\n        onClick={() => onBook(rank)}\n        onFocus={() => onHover(rank)}\n        onBlur={() => onHover(null)}\n        className={pressedSolidOf(isPressed)}\n      >\n        Book\n      </Button>\n    </li>\n  );\n}\n\ntype BookedProps = {\n  booking: Booking;\n  onUndo: () => void;\n};\n\n/** The bar under the card empties over the five seconds the undo stays. */\nfunction Booked({ booking, onUndo }: BookedProps) {\n  const guests = guestNamesOf(booking.attendees);\n\n  return (\n    <div className='bg-success/10 relative flex flex-col gap-2.5 overflow-hidden rounded-lg p-3 transition-opacity duration-200 starting:opacity-0'>\n      <div className='flex items-start gap-2'>\n        <CircleCheckIcon className='text-success-foreground mt-0.5 size-4 shrink-0' />\n        <div className='flex min-w-0 flex-col'>\n          <p className='text-[13px] leading-5 font-medium tabular-nums'>\n            Booked {slotLabelOf(booking)}\n          </p>\n          <p className='text-xs'>With {guests}, on every calendar</p>\n        </div>\n      </div>\n      <div className='flex items-center gap-2 ps-6'>\n        <Button\n          type='button'\n          variant='outline'\n          size='sm'\n          data-undo={booking.id}\n          onClick={onUndo}\n        >\n          <UndoIcon />\n          Undo\n        </Button>\n        <span className='text-xs'>for 5 seconds</span>\n      </div>\n      <span\n        aria-hidden='true'\n        className='bg-success/60 absolute inset-x-0 bottom-0 h-0.5 origin-left scale-x-0 transition-transform duration-[5000ms] ease-linear motion-reduce:hidden starting:scale-x-100'\n      />\n    </div>\n  );\n}\n\nexport type SuggestionPanelProps = {\n  search: Search | null;\n  hot: number | null;\n  /** The meeting that can still be undone. */\n  booking: Booking | null;\n  pressed: string | null;\n  onExample: (text: string) => void;\n  onHover: (rank: number | null) => void;\n  onBook: (rank: number) => void;\n  onUndo: () => void;\n  onClear: () => void;\n};\n\n/** What the assistant says back: what it is checking, the times it found, then the one that was booked. */\nexport function SuggestionPanel({\n  search,\n  hot,\n  booking,\n  pressed,\n  onExample,\n  onHover,\n  onBook,\n  onUndo,\n  onClear,\n}: SuggestionPanelProps) {\n  if (!search) {\n    return <Examples onExample={onExample} />;\n  }\n  const requestLine = requestLineOf(search.request);\n\n  if (search.status === 'shading') {\n    const calendars = calendarsWordOf(search.request.attendees.length);\n    return (\n      <div className='flex flex-col gap-1 px-2.5 py-2'>\n        <p className='flex items-center gap-2 text-[13px] leading-5 font-medium'>\n          <LoaderIcon\n            aria-hidden='true'\n            className='text-muted-foreground size-4 animate-spin'\n          />\n          Checking {calendars}\n        </p>\n        <p className='text-muted-foreground ps-6 text-xs'>{requestLine}</p>\n      </div>\n    );\n  }\n\n  if (search.status === 'booked') {\n    if (!booking) {\n      return null;\n    }\n    return <Booked key={booking.id} booking={booking} onUndo={onUndo} />;\n  }\n\n  return (\n    <div className='flex flex-col gap-1.5'>\n      <div className='flex items-center gap-2 ps-2.5'>\n        <p className='text-muted-foreground min-w-0 flex-1 truncate text-xs'>\n          {requestLine}\n        </p>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          data-search-clear\n          onClick={onClear}\n          className='text-muted-foreground'\n        >\n          Clear\n        </Button>\n      </div>\n      <ol aria-label='Times found' className='flex flex-col gap-0.5'>\n        {search.suggestions.map((suggestion) => (\n          <SuggestionRow\n            key={suggestion.rank}\n            suggestion={suggestion}\n            isHot={hot === suggestion.rank}\n            isPressed={pressed === `book-${suggestion.rank}`}\n            onHover={onHover}\n            onBook={onBook}\n          />\n        ))}\n      </ol>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/ai-data-02/suggestion-panel.tsx"
    },
    {
      "path": "registry/ndeko/blocks/ai-data/ai-data-02/ask.ts",
      "content": "import {\n  DAY_END,\n  DAY_START,\n  dayIndexOf,\n  dayOf,\n  DAYS,\n  PEOPLE,\n  personOf,\n  type DayId,\n  type PersonId,\n} from './data';\n\nexport type MeetingRequest = {\n  minutes: number;\n  /** You are always part of it. */\n  attendees: PersonId[];\n  days: DayId[];\n  /** The part of the day the meeting has to sit in, in minutes since midnight. */\n  from: number;\n  until: number;\n};\n\nexport const NO_ATTENDEE_LINE = 'Say who should join: Maya, Jonas or everyone.';\n\nconst DEFAULT_MINUTES = 30;\n\nconst SHORTEST_MINUTES = 15;\n\nconst LONGEST_MINUTES = 240;\n\nconst NOON = 12 * 60;\n\nconst AFTER_LUNCH = 13 * 60;\n\nconst MINUTES = /\\b(\\d+) ?(?:minutes|minute|mins|min|m)\\b/;\n\nconst HOURS = /\\b(\\d+) ?(?:hours|hour|hrs|hr|h)\\b/;\n\nconst EVERYONE_PHRASES = ['everyone', 'everybody', 'all three', 'the team'];\n\nconst PERSON_PHRASES: Record<PersonId, string[]> = {\n  you: [],\n  maya: ['maya'],\n  jonas: ['jonas'],\n};\n\nconst DAY_PHRASES: Record<DayId, string[]> = {\n  mon: ['monday', 'mon', 'today'],\n  tue: ['tuesday', 'tue', 'tomorrow'],\n  wed: ['wednesday', 'wed'],\n  thu: ['thursday', 'thu'],\n  fri: ['friday', 'fri'],\n};\n\nconst LATE_WEEK_PHRASES = [\n  'before the weekend',\n  'end of the week',\n  'late this week',\n];\n\nconst EARLY_WEEK_PHRASES = ['early this week', 'start of the week'];\n\nconst MORNING_PHRASES = ['morning', 'before lunch', 'before noon'];\n\nconst AFTERNOON_PHRASES = ['afternoon', 'after lunch'];\n\nconst LATE_WEEK: DayId[] = ['thu', 'fri'];\n\nconst EARLY_WEEK: DayId[] = ['mon', 'tue'];\n\nconst ALL_DAYS = DAYS.map((day) => day.id);\n\n/** Lower case words between single spaces, with a space at both ends so a phrase is matched whole. */\nfunction sentenceOf(text: string) {\n  const lowered = text.toLowerCase();\n  const spaced = lowered.replace(/[^a-z0-9]+/g, ' ');\n  const trimmed = spaced.trim();\n  return ` ${trimmed} `;\n}\n\nfunction names(sentence: string, phrases: string[]) {\n  return phrases.some((phrase) => sentence.includes(` ${phrase} `));\n}\n\nfunction countIn(sentence: string, unit: RegExp) {\n  const match = unit.exec(sentence);\n  if (!match) {\n    return null;\n  }\n  return Number(match[1]);\n}\n\nfunction boundedMinutes(minutes: number) {\n  const atLeastShortest = Math.max(SHORTEST_MINUTES, minutes);\n  return Math.min(LONGEST_MINUTES, atLeastShortest);\n}\n\n/** The lengths said in words. A longer phrase is read before the shorter one it contains. */\nfunction spelledMinutesOf(sentence: string) {\n  if (names(sentence, ['an hour and a half'])) {\n    return 90;\n  }\n  if (names(sentence, ['half an hour'])) {\n    return 30;\n  }\n  if (names(sentence, ['an hour', 'one hour'])) {\n    return 60;\n  }\n  return DEFAULT_MINUTES;\n}\n\n/** 45 minutes, 2 hours, 1 hour 30 minutes, or a length said in words. */\nfunction minutesOf(sentence: string) {\n  const minutes = countIn(sentence, MINUTES);\n  const hours = countIn(sentence, HOURS);\n  const hasFigure = minutes !== null || hours !== null;\n  if (!hasFigure) {\n    return spelledMinutesOf(sentence);\n  }\n  const fromHours = (hours ?? 0) * 60;\n  const fromMinutes = minutes ?? 0;\n  return boundedMinutes(fromHours + fromMinutes);\n}\n\nfunction guestsOf(sentence: string) {\n  if (names(sentence, EVERYONE_PHRASES)) {\n    return PEOPLE.filter((person) => person.id !== 'you');\n  }\n  return PEOPLE.filter((person) => names(sentence, PERSON_PHRASES[person.id]));\n}\n\nfunction daysOf(sentence: string) {\n  if (names(sentence, LATE_WEEK_PHRASES)) {\n    return LATE_WEEK;\n  }\n  if (names(sentence, EARLY_WEEK_PHRASES)) {\n    return EARLY_WEEK;\n  }\n  const named = ALL_DAYS.filter((day) => names(sentence, DAY_PHRASES[day]));\n  if (named.length > 0) {\n    return named;\n  }\n  return ALL_DAYS;\n}\n\ntype DayPart = Pick<MeetingRequest, 'from' | 'until'>;\n\nfunction dayPartOf(sentence: string): DayPart {\n  if (names(sentence, MORNING_PHRASES)) {\n    return { from: DAY_START, until: NOON };\n  }\n  if (names(sentence, AFTERNOON_PHRASES)) {\n    return { from: AFTER_LUNCH, until: DAY_END };\n  }\n  return { from: DAY_START, until: DAY_END };\n}\n\n/**\n * Reads a plain request into a meeting to place: how long, with whom, on which days and in which\n * part of the day. A handful of word lists, no model. It returns nothing when nobody is named.\n */\nexport function requestOfQuestion(text: string): MeetingRequest | null {\n  const sentence = sentenceOf(text);\n  const guests = guestsOf(sentence);\n  if (guests.length === 0) {\n    return null;\n  }\n  const guestIds = guests.map((person) => person.id);\n  const dayPart = dayPartOf(sentence);\n  return {\n    minutes: minutesOf(sentence),\n    attendees: ['you', ...guestIds],\n    days: daysOf(sentence),\n    ...dayPart,\n  };\n}\n\n/** Maya and Jonas. */\nexport function guestNamesOf(attendees: PersonId[]) {\n  const guests = attendees.filter((id) => id !== 'you');\n  const shortNames = guests.map((id) => personOf(id).shortName);\n  return shortNames.join(' and ');\n}\n\nfunction areNeighbours(days: DayId[]) {\n  const first = dayIndexOf(days[0]);\n  return days.every((day, index) => dayIndexOf(day) === first + index);\n}\n\n/** Thu, Thu to Fri, Tue and Thu. */\nexport function daysLabelOf(days: DayId[]) {\n  const labels = days.map((day) => dayOf(day).label);\n  const isRange = days.length > 1 && areNeighbours(days);\n  if (isRange) {\n    const last = labels[labels.length - 1];\n    return `${labels[0]} to ${last}`;\n  }\n  return labels.join(' and ');\n}\n\n/** 45 min with Maya and Jonas, Thu to Fri. */\nexport function requestLineOf(request: MeetingRequest) {\n  const guests = guestNamesOf(request.attendees);\n  const days = daysLabelOf(request.days);\n  return `${request.minutes} min with ${guests}, ${days}`;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/ai-data-02/ask.ts"
    },
    {
      "path": "registry/ndeko/blocks/ai-data/ai-data-02/find.ts",
      "content": "import type { MeetingRequest } from './ask';\nimport {\n  DAY_END,\n  DAY_START,\n  dayIndexOf,\n  personOf,\n  type DayId,\n  type PersonId,\n} from './data';\n\nexport type Slot = {\n  day: DayId;\n  start: number;\n  end: number;\n};\n\n/** Time one person is taken: a meeting of theirs, or one booked here that they attend. */\nexport type Busy = Slot & {\n  person: PersonId;\n  title: string;\n};\n\nexport type Suggestion = Slot & {\n  /** 1 is the best time found. */\n  rank: number;\n  reason: string;\n};\n\ntype Candidate = Slot & {\n  score: number;\n  reason: string;\n};\n\n/** Candidate times start on the hour and on the half hour. */\nconst STEP_MINUTES = 30;\n\n/** Less room than this between two meetings reads as back to back. */\nconst BREATHING_MINUTES = 15;\n\nconst LUNCH_START = 12 * 60;\n\nconst LUNCH_END = 13 * 60;\n\nconst LATE_AFTER = 17 * 60;\n\n/** Two times offered on one day sit at least this far apart, so the three are real choices. */\nconst SPREAD_MINUTES = 60;\n\nconst SUGGESTION_COUNT = 3;\n\nconst BACK_TO_BACK_COST = 40;\n\nconst LATE_COST = 30;\n\nconst LUNCH_COST = 25;\n\nconst BEST_SCORE = 100;\n\nfunction overlaps(first: Slot, second: Slot) {\n  const isSameDay = first.day === second.day;\n  const startsBeforeEnd = first.start < second.end;\n  const endsAfterStart = first.end > second.start;\n  return isSameDay && startsBeforeEnd && endsAfterStart;\n}\n\nfunction isFree(taken: Busy[], slot: Slot) {\n  return !taken.some((busy) => overlaps(busy, slot));\n}\n\n/** The meeting one of them leaves right before the slot, if any. */\nfunction meetingJustBefore(taken: Busy[], slot: Slot) {\n  return taken.find((busy) => {\n    const isSameDay = busy.day === slot.day;\n    const gap = slot.start - busy.end;\n    const endsBefore = gap >= 0;\n    const isTooShort = gap < BREATHING_MINUTES;\n    return isSameDay && endsBefore && isTooShort;\n  });\n}\n\n/** The meeting one of them has to reach right after the slot, if any. */\nfunction meetingJustAfter(taken: Busy[], slot: Slot) {\n  return taken.find((busy) => {\n    const isSameDay = busy.day === slot.day;\n    const gap = busy.start - slot.end;\n    const startsAfter = gap >= 0;\n    const isTooShort = gap < BREATHING_MINUTES;\n    return isSameDay && startsAfter && isTooShort;\n  });\n}\n\nfunction whoOf(attendees: PersonId[]) {\n  if (attendees.length > 2) {\n    return 'Everyone';\n  }\n  return 'Both';\n}\n\nfunction ownedTitleOf(busy: Busy) {\n  const owner = personOf(busy.person);\n  return `${owner.possessive} ${busy.title}`;\n}\n\n/**\n * A slot starts from the best score and pays for what makes it worse. Its reason names the first\n * thing a person would mind, or says there is none.\n */\nfunction candidateOf(taken: Busy[], slot: Slot, who: string): Candidate {\n  const before = meetingJustBefore(taken, slot);\n  const after = meetingJustAfter(taken, slot);\n  const startsBeforeLunchEnds = slot.start < LUNCH_END;\n  const endsAfterLunchStarts = slot.end > LUNCH_START;\n  const runsIntoLunch = startsBeforeLunchEnds && endsAfterLunchStarts;\n  const isLate = slot.end > LATE_AFTER;\n  let score = BEST_SCORE;\n  let reason = `${who} free, no back-to-back`;\n  if (isLate) {\n    score -= LATE_COST;\n    reason = `${who} free, last thing in the day`;\n  }\n  if (runsIntoLunch) {\n    score -= LUNCH_COST;\n    reason = `${who} free, runs into lunch`;\n  }\n  if (after) {\n    score -= BACK_TO_BACK_COST;\n    reason = `${who} free, ends as ${ownedTitleOf(after)} starts`;\n  }\n  if (before) {\n    score -= BACK_TO_BACK_COST;\n    reason = `${who} free, straight after ${ownedTitleOf(before)}`;\n  }\n  return { ...slot, score, reason };\n}\n\nfunction candidatesOn(\n  day: DayId,\n  request: MeetingRequest,\n  taken: Busy[],\n  who: string\n) {\n  const candidates: Candidate[] = [];\n  const first = Math.max(DAY_START, request.from);\n  const dayEnd = Math.min(DAY_END, request.until);\n  const lastStart = dayEnd - request.minutes;\n  for (let start = first; start <= lastStart; start += STEP_MINUTES) {\n    const slot = { day, start, end: start + request.minutes };\n    if (isFree(taken, slot)) {\n      candidates.push(candidateOf(taken, slot, who));\n    }\n  }\n  return candidates;\n}\n\n/** The best score first; between equals the earlier day, then the earlier hour. */\nfunction byPreference(first: Candidate, second: Candidate) {\n  if (first.score !== second.score) {\n    return second.score - first.score;\n  }\n  const dayOrder = dayIndexOf(first.day) - dayIndexOf(second.day);\n  if (dayOrder !== 0) {\n    return dayOrder;\n  }\n  return first.start - second.start;\n}\n\nfunction isTooClose(candidate: Candidate, chosen: Candidate) {\n  const isSameDay = candidate.day === chosen.day;\n  const startsBeforeReach = candidate.start < chosen.end + SPREAD_MINUTES;\n  const endsAfterReach = candidate.end > chosen.start - SPREAD_MINUTES;\n  return isSameDay && startsBeforeReach && endsAfterReach;\n}\n\n/**\n * Works out when everyone asked is free for the length asked, and keeps the best three: no model\n * is called. `taken` holds the busy time of every person; only the attendees are looked at.\n */\nexport function suggestionsOf(\n  request: MeetingRequest,\n  taken: Busy[]\n): Suggestion[] {\n  const theirs = taken.filter((busy) =>\n    request.attendees.includes(busy.person)\n  );\n  const who = whoOf(request.attendees);\n  const candidates = request.days.flatMap((day) =>\n    candidatesOn(day, request, theirs, who)\n  );\n  candidates.sort(byPreference);\n  const chosen: Candidate[] = [];\n  for (const candidate of candidates) {\n    const isCrowded = chosen.some((kept) => isTooClose(candidate, kept));\n    if (isCrowded) {\n      continue;\n    }\n    chosen.push(candidate);\n    if (chosen.length === SUGGESTION_COUNT) {\n      break;\n    }\n  }\n  return chosen.map((candidate, index) => ({\n    day: candidate.day,\n    start: candidate.start,\n    end: candidate.end,\n    rank: index + 1,\n    reason: candidate.reason,\n  }));\n}\n\n/** The busy time of the attendees on one day, as bands that do not overlap: what the calendar shades. */\nexport function busyBandsOf(\n  taken: Busy[],\n  attendees: PersonId[],\n  day: DayId\n): Slot[] {\n  const theirs = taken.filter((busy) => {\n    const isAttendee = attendees.includes(busy.person);\n    return isAttendee && busy.day === day;\n  });\n  const ordered = [...theirs];\n  ordered.sort((first, second) => first.start - second.start);\n  const bands: Slot[] = [];\n  for (const busy of ordered) {\n    const last = bands[bands.length - 1];\n    const joinsLast = last !== undefined && busy.start <= last.end;\n    if (joinsLast) {\n      last.end = Math.max(last.end, busy.end);\n      continue;\n    }\n    bands.push({ day, start: busy.start, end: busy.end });\n  }\n  return bands;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/ai-data-02/find.ts"
    },
    {
      "path": "registry/ndeko/blocks/ai-data/ai-data-02/layout.ts",
      "content": "import { DAY_END, DAY_START } from './data';\n\nexport type Timed = {\n  id: string;\n  start: number;\n  end: number;\n};\n\n/** Where a block sits in its day: which column of how many, among the blocks it overlaps. */\nexport type Place = {\n  column: number;\n  columns: number;\n};\n\n/** The box of a block inside its day, as shares of the width and of the height of the day. */\nexport type Box = {\n  top: string;\n  height: string;\n  left: string;\n  width: string;\n};\n\nconst DAY_SPAN = DAY_END - DAY_START;\n\nfunction byStart(first: Timed, second: Timed) {\n  if (first.start !== second.start) {\n    return first.start - second.start;\n  }\n  return second.end - first.end;\n}\n\n/** The first column whose last block has ended, or a new one. */\nfunction freeColumnOf(columnEnds: number[], start: number) {\n  const free = columnEnds.findIndex((end) => end <= start);\n  if (free === -1) {\n    return columnEnds.length;\n  }\n  return free;\n}\n\n/**\n * Blocks that overlap in time share the width of the day, side by side. Blocks are read in order of\n * start; a run of blocks that touch one another is a cluster, and every block of a cluster takes\n * one column of as many as the cluster needed.\n */\nexport function placesOf(items: Timed[]) {\n  const ordered = [...items];\n  ordered.sort(byStart);\n  const places = new Map<string, Place>();\n  let cluster: Timed[] = [];\n  let columnEnds: number[] = [];\n  let clusterEnd = 0;\n\n  function closeCluster() {\n    for (const item of cluster) {\n      const place = places.get(item.id);\n      if (place) {\n        place.columns = columnEnds.length;\n      }\n    }\n    cluster = [];\n    columnEnds = [];\n  }\n\n  for (const item of ordered) {\n    const startsAfterCluster = item.start >= clusterEnd;\n    if (startsAfterCluster) {\n      closeCluster();\n    }\n    const column = freeColumnOf(columnEnds, item.start);\n    columnEnds[column] = item.end;\n    places.set(item.id, { column, columns: 1 });\n    cluster.push(item);\n    clusterEnd = Math.max(clusterEnd, item.end);\n  }\n  closeCluster();\n  return places;\n}\n\nfunction shareOf(part: number, whole: number) {\n  const share = (part / whole) * 100;\n  return `${share}%`;\n}\n\nexport function boxOf(item: Timed, place: Place | undefined): Box {\n  const column = place?.column ?? 0;\n  const columns = place?.columns ?? 1;\n  return {\n    top: shareOf(item.start - DAY_START, DAY_SPAN),\n    height: shareOf(item.end - item.start, DAY_SPAN),\n    left: shareOf(column, columns),\n    width: shareOf(1, columns),\n  };\n}\n",
      "type": "registry:component",
      "target": "components/blocks/ai-data-02/layout.ts"
    },
    {
      "path": "registry/ndeko/blocks/ai-data/ai-data-02/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\nimport { keyDelayOf, prefixesOf } from '@/registry/ndeko/lib/demonstration';\n\nimport {\n  guestNamesOf,\n  NO_ATTENDEE_LINE,\n  requestOfQuestion,\n  type MeetingRequest,\n} from './ask';\nimport {\n  dayOf,\n  EVENTS,\n  EXAMPLES,\n  PEOPLE,\n  timeRangeOf,\n  type DayId,\n  type PersonId,\n} from './data';\nimport { suggestionsOf, type Busy, type Slot, type Suggestion } from './find';\n\nexport type SearchStatus = 'shading' | 'offering' | 'booked';\n\n/** One question and what came of it: first the busy time is shaded, then the times are offered, then one is booked. */\nexport type Search = {\n  request: MeetingRequest;\n  suggestions: Suggestion[];\n  status: SearchStatus;\n};\n\nexport type Booking = Slot & {\n  /** The demonstration and a person name their bookings apart, so an undo that runs out only ever ends its own. */\n  id: string;\n  attendees: PersonId[];\n  title: string;\n};\n\nexport type CalendarState = {\n  question: string;\n  /** Why the last question could not be answered. */\n  askHint: string | null;\n  /** Whose calendars show. */\n  shown: PersonId[];\n  /** The day a narrow page shows. */\n  day: DayId;\n  search: Search | null;\n  /** The suggestion under the pointer or the focus. */\n  hot: number | null;\n  bookings: Booking[];\n  /** The booking that can still be undone. */\n  undoId: string | null;\n  spoken: string;\n};\n\nexport type CalendarAction =\n  | { type: 'questionTyped'; text: string }\n  | { type: 'asked' }\n  | { type: 'offered' }\n  | { type: 'hovered'; rank: number | null }\n  | { type: 'booked'; rank: number; id: string }\n  | { type: 'undone' }\n  | { type: 'undoExpired'; id: string }\n  | { type: 'searchCleared' }\n  | { type: 'calendarsShown'; shown: PersonId[] }\n  | { type: 'dayPicked'; day: DayId };\n\ntype Step = SessionStep<CalendarState, CalendarAction>;\n\nexport const NO_TIME_LINE =\n  'No time fits everyone in that window. Try a shorter meeting or more days.';\n\nconst ALL_PEOPLE = PEOPLE.map((person) => person.id);\n\nexport const INITIAL: CalendarState = {\n  question: '',\n  askHint: null,\n  shown: ALL_PEOPLE,\n  day: 'mon',\n  search: null,\n  hot: null,\n  bookings: [],\n  undoId: null,\n  spoken: '',\n};\n\nfunction busyOfBooking(booking: Booking): Busy[] {\n  return booking.attendees.map((person) => ({\n    person,\n    day: booking.day,\n    start: booking.start,\n    end: booking.end,\n    title: booking.title,\n  }));\n}\n\n/** The time every person is taken: their own meetings, and the ones booked here that they attend. */\nexport function takenOf(bookings: Booking[]): Busy[] {\n  const booked = bookings.flatMap(busyOfBooking);\n  return [...EVENTS, ...booked];\n}\n\nfunction calendarsWordOf(count: number) {\n  if (count === 1) {\n    return '1 calendar';\n  }\n  return `${count} calendars`;\n}\n\nfunction timesWordOf(count: number) {\n  if (count === 1) {\n    return '1 time found';\n  }\n  return `${count} times found`;\n}\n\nexport function slotLineOf(slot: Slot) {\n  const day = dayOf(slot.day);\n  return `${day.name} ${timeRangeOf(slot.start, slot.end)}`;\n}\n\nfunction unanswered(state: CalendarState, hint: string): CalendarState {\n  return { ...state, askHint: hint, spoken: hint };\n}\n\n/** A new question settles the last booking: its undo goes, the meeting stays. */\nfunction asked(state: CalendarState): CalendarState {\n  const request = requestOfQuestion(state.question);\n  if (!request) {\n    return unanswered(state, NO_ATTENDEE_LINE);\n  }\n  const suggestions = suggestionsOf(request, takenOf(state.bookings));\n  if (suggestions.length === 0) {\n    return unanswered(state, NO_TIME_LINE);\n  }\n  const shown = ALL_PEOPLE.filter((person) => {\n    const isShown = state.shown.includes(person);\n    return isShown || request.attendees.includes(person);\n  });\n  const calendars = calendarsWordOf(request.attendees.length);\n  return {\n    ...state,\n    askHint: null,\n    shown,\n    day: request.days[0],\n    search: { request, suggestions, status: 'shading' },\n    hot: null,\n    undoId: null,\n    spoken: `Checking ${calendars}`,\n  };\n}\n\nfunction offered(state: CalendarState): CalendarState {\n  const search = state.search;\n  if (search?.status !== 'shading') {\n    return state;\n  }\n  const [best] = search.suggestions;\n  const times = timesWordOf(search.suggestions.length);\n  const spoken = `${times}. Best: ${slotLineOf(best)}. ${best.reason}`;\n  return {\n    ...state,\n    search: { ...search, status: 'offering' },\n    day: best.day,\n    spoken,\n  };\n}\n\nfunction suggestionOf(search: Search, rank: number) {\n  return search.suggestions.find((candidate) => candidate.rank === rank);\n}\n\n/** A narrow page shows one day: it follows the suggestion a person points at. */\nfunction hovered(state: CalendarState, rank: number | null): CalendarState {\n  const search = state.search;\n  if (search?.status !== 'offering') {\n    return { ...state, hot: null };\n  }\n  if (rank === null) {\n    return { ...state, hot: null };\n  }\n  const suggestion = suggestionOf(search, rank);\n  if (!suggestion) {\n    return { ...state, hot: null };\n  }\n  return { ...state, hot: rank, day: suggestion.day };\n}\n\nfunction booked(state: CalendarState, rank: number, id: string): CalendarState {\n  const search = state.search;\n  if (search?.status !== 'offering') {\n    return state;\n  }\n  const suggestion = suggestionOf(search, rank);\n  if (!suggestion) {\n    return state;\n  }\n  const guests = guestNamesOf(search.request.attendees);\n  const booking: Booking = {\n    id,\n    day: suggestion.day,\n    start: suggestion.start,\n    end: suggestion.end,\n    attendees: search.request.attendees,\n    title: `Sync with ${guests}`,\n  };\n  const spoken = `Booked ${slotLineOf(booking)} with ${guests}. Undo stays for 5 seconds`;\n  return {\n    ...state,\n    question: '',\n    askHint: null,\n    day: booking.day,\n    search: { ...search, status: 'booked' },\n    hot: null,\n    bookings: [...state.bookings, booking],\n    undoId: id,\n    spoken,\n  };\n}\n\n/** The meeting leaves and the times it was picked from are offered again. */\nfunction undone(state: CalendarState): CalendarState {\n  const undoId = state.undoId;\n  if (undoId === null) {\n    return state;\n  }\n  const bookings = state.bookings.filter((booking) => booking.id !== undoId);\n  const next = { ...state, bookings, undoId: null, spoken: 'Booking undone' };\n  const search = state.search;\n  if (search?.status !== 'booked') {\n    return next;\n  }\n  return { ...next, search: { ...search, status: 'offering' } };\n}\n\nfunction undoExpired(state: CalendarState, id: string): CalendarState {\n  if (state.undoId !== id) {\n    return state;\n  }\n  const next = { ...state, undoId: null, spoken: '' };\n  if (state.search?.status !== 'booked') {\n    return next;\n  }\n  return { ...next, search: null };\n}\n\nfunction searchCleared(state: CalendarState): CalendarState {\n  if (state.search?.status === 'booked') {\n    return state;\n  }\n  return { ...state, search: null, hot: null, spoken: '' };\n}\n\nexport function reducer(\n  state: CalendarState,\n  action: CalendarAction\n): CalendarState {\n  switch (action.type) {\n    case 'questionTyped':\n      return { ...state, question: action.text, askHint: null };\n    case 'asked':\n      return asked(state);\n    case 'offered':\n      return offered(state);\n    case 'hovered':\n      return hovered(state, action.rank);\n    case 'booked':\n      return booked(state, action.rank, action.id);\n    case 'undone':\n      return undone(state);\n    case 'undoExpired':\n      return undoExpired(state, action.id);\n    case 'searchCleared':\n      return searchCleared(state);\n    case 'calendarsShown':\n      return { ...state, shown: action.shown };\n    case 'dayPicked':\n      return { ...state, day: action.day };\n  }\n}\n\n/** How long the busy time stays shaded before the times are offered. */\nexport const THINK_MS = 1200;\n\nexport const UNDO_MS = 5000;\n\nconst KEY_MS = 40;\n\nconst DEMO_BOOKING = 'demo';\n\nconst [QUESTION] = EXAMPLES;\n\nfunction typingSteps(text: string, startAfter: number): Step[] {\n  const prefixes = prefixesOf(text);\n  return prefixes.map((typed, index) => ({\n    after: keyDelayOf(index, startAfter, KEY_MS),\n    by: 'demo',\n    action: { type: 'questionTyped', text: typed },\n  }));\n}\n\n/** The question is typed and sent, the assistant shades the busy time and offers three times. */\nconst ASKING: Step[] = [\n  ...typingSteps(QUESTION, 1200),\n  { after: 500, by: 'demo', press: 'ask', action: { type: 'asked' } },\n  { after: THINK_MS, action: { type: 'offered' } },\n];\n\n/** The demonstration looks at each time, books the best one and lets the undo run out. */\nconst BOOKING: Step[] = [\n  { after: 1700, by: 'demo', action: { type: 'hovered', rank: 2 } },\n  { after: 1000, by: 'demo', action: { type: 'hovered', rank: 3 } },\n  { after: 1000, by: 'demo', action: { type: 'hovered', rank: 1 } },\n  {\n    after: 1300,\n    by: 'demo',\n    press: 'book-1',\n    action: { type: 'booked', rank: 1, id: DEMO_BOOKING },\n  },\n  { after: UNDO_MS, action: { type: 'undoExpired', id: DEMO_BOOKING } },\n];\n\nexport const SCRIPT: Step[] = [...ASKING, ...BOOKING];\n\nfunction endOf(script: Step[]) {\n  let state = INITIAL;\n  for (const step of script) {\n    state = reducer(state, step.action);\n  }\n  return state;\n}\n\n/** Under reduced motion the three times are on the calendar, waiting for a choice. */\nexport const RESTING: CalendarState = { ...endOf(ASKING), spoken: '' };\n\nexport const LOOP_AFTER_MS = 2800;\n",
      "type": "registry:component",
      "target": "components/blocks/ai-data-02/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/ai-data/ai-data-02/data.ts",
      "content": "import type { SeriesSlot } from '@/registry/ndeko/lib/agent-run';\n\nexport type PersonId = 'you' | 'maya' | 'jonas';\n\nexport type Person = {\n  id: PersonId;\n  name: string;\n  /** How the person is named in a sentence: You, Maya. */\n  shortName: string;\n  /** Whose event it is: your, Maya's. */\n  possessive: string;\n  series: SeriesSlot;\n};\n\nexport const PEOPLE: Person[] = [\n  {\n    id: 'you',\n    name: 'Lena Brandt',\n    shortName: 'You',\n    possessive: 'your',\n    series: 1,\n  },\n  {\n    id: 'maya',\n    name: 'Maya Okafor',\n    shortName: 'Maya',\n    possessive: \"Maya's\",\n    series: 2,\n  },\n  {\n    id: 'jonas',\n    name: 'Jonas Weber',\n    shortName: 'Jonas',\n    possessive: \"Jonas's\",\n    series: 3,\n  },\n];\n\nconst FALLBACK_PERSON = PEOPLE[0];\n\nexport function personOf(id: PersonId) {\n  const person = PEOPLE.find((candidate) => candidate.id === id);\n  return person ?? FALLBACK_PERSON;\n}\n\nexport type DayId = 'mon' | 'tue' | 'wed' | 'thu' | 'fri';\n\nexport type Day = {\n  id: DayId;\n  label: string;\n  name: string;\n  date: number;\n};\n\n/** One invented working week. Monday is today. */\nexport const DAYS: Day[] = [\n  { id: 'mon', label: 'Mon', name: 'Monday', date: 16 },\n  { id: 'tue', label: 'Tue', name: 'Tuesday', date: 17 },\n  { id: 'wed', label: 'Wed', name: 'Wednesday', date: 18 },\n  { id: 'thu', label: 'Thu', name: 'Thursday', date: 19 },\n  { id: 'fri', label: 'Fri', name: 'Friday', date: 20 },\n];\n\nexport const TODAY: DayId = 'mon';\n\nexport const WEEK_LABEL = 'Nov 16 to 20';\n\nconst FALLBACK_DAY = DAYS[0];\n\nexport function dayOf(id: DayId) {\n  const day = DAYS.find((candidate) => candidate.id === id);\n  return day ?? FALLBACK_DAY;\n}\n\nexport function dayIndexOf(id: DayId) {\n  return DAYS.findIndex((candidate) => candidate.id === id);\n}\n\nconst HOUR = 60;\n\n/** The calendar shows the working day, in minutes since midnight. */\nexport const DAY_START = 9 * HOUR;\n\nexport const DAY_END = 18 * HOUR;\n\nexport const HOURS = [9, 10, 11, 12, 13, 14, 15, 16, 17];\n\n/** 9:00, 13:30: one clock for every time on the block. */\nexport function clockOf(minutes: number) {\n  const hours = Math.floor(minutes / HOUR);\n  const rest = minutes % HOUR;\n  const paddedRest = String(rest).padStart(2, '0');\n  return `${hours}:${paddedRest}`;\n}\n\nexport function timeRangeOf(start: number, end: number) {\n  return `${clockOf(start)} to ${clockOf(end)}`;\n}\n\nfunction at(hours: number, minutes = 0) {\n  return hours * HOUR + minutes;\n}\n\nexport type CalendarEvent = {\n  id: string;\n  person: PersonId;\n  day: DayId;\n  start: number;\n  end: number;\n  title: string;\n};\n\n/** Invented meetings of three invented people. */\nexport const EVENTS: CalendarEvent[] = [\n  {\n    id: 'you-planning',\n    person: 'you',\n    day: 'mon',\n    start: at(9, 30),\n    end: at(10, 30),\n    title: 'Weekly planning',\n  },\n  {\n    id: 'you-budget',\n    person: 'you',\n    day: 'mon',\n    start: at(14),\n    end: at(15),\n    title: 'Budget review',\n  },\n  {\n    id: 'you-customer',\n    person: 'you',\n    day: 'tue',\n    start: at(11),\n    end: at(12),\n    title: 'Customer call',\n  },\n  {\n    id: 'you-roadmap',\n    person: 'you',\n    day: 'wed',\n    start: at(9),\n    end: at(10),\n    title: 'Roadmap sync',\n  },\n  {\n    id: 'you-pricing',\n    person: 'you',\n    day: 'wed',\n    start: at(15),\n    end: at(16, 30),\n    title: 'Pricing workshop',\n  },\n  {\n    id: 'you-hiring',\n    person: 'you',\n    day: 'thu',\n    start: at(9, 30),\n    end: at(10, 30),\n    title: 'Hiring panel',\n  },\n  {\n    id: 'you-one-to-one',\n    person: 'you',\n    day: 'thu',\n    start: at(13, 30),\n    end: at(14, 30),\n    title: 'One to one with Priya',\n  },\n  {\n    id: 'you-rehearsal',\n    person: 'you',\n    day: 'fri',\n    start: at(11),\n    end: at(12),\n    title: 'Demo rehearsal',\n  },\n  {\n    id: 'you-week-review',\n    person: 'you',\n    day: 'fri',\n    start: at(15),\n    end: at(16),\n    title: 'Week review',\n  },\n  {\n    id: 'maya-design-review',\n    person: 'maya',\n    day: 'mon',\n    start: at(10),\n    end: at(11, 30),\n    title: 'Design review',\n  },\n  {\n    id: 'maya-crit',\n    person: 'maya',\n    day: 'tue',\n    start: at(9),\n    end: at(10),\n    title: 'Design crit',\n  },\n  {\n    id: 'maya-interviews',\n    person: 'maya',\n    day: 'tue',\n    start: at(14),\n    end: at(16),\n    title: 'User interviews',\n  },\n  {\n    id: 'maya-brand',\n    person: 'maya',\n    day: 'wed',\n    start: at(11),\n    end: at(12),\n    title: 'Brand sync',\n  },\n  {\n    id: 'maya-prototype',\n    person: 'maya',\n    day: 'thu',\n    start: at(14),\n    end: at(15, 30),\n    title: 'Prototype review',\n  },\n  {\n    id: 'maya-friday-review',\n    person: 'maya',\n    day: 'fri',\n    start: at(9),\n    end: at(10),\n    title: 'Design review',\n  },\n  {\n    id: 'maya-lunch',\n    person: 'maya',\n    day: 'fri',\n    start: at(13),\n    end: at(14),\n    title: 'Lunch and learn',\n  },\n  {\n    id: 'jonas-supplier',\n    person: 'jonas',\n    day: 'mon',\n    start: at(13),\n    end: at(14),\n    title: 'Supplier call',\n  },\n  {\n    id: 'jonas-forecast',\n    person: 'jonas',\n    day: 'tue',\n    start: at(10),\n    end: at(11),\n    title: 'Sales forecast',\n  },\n  {\n    id: 'jonas-pipeline',\n    person: 'jonas',\n    day: 'wed',\n    start: at(14),\n    end: at(15),\n    title: 'Pipeline review',\n  },\n  {\n    id: 'jonas-standup',\n    person: 'jonas',\n    day: 'thu',\n    start: at(9),\n    end: at(9, 30),\n    title: 'Standup',\n  },\n  {\n    id: 'jonas-thursday-supplier',\n    person: 'jonas',\n    day: 'thu',\n    start: at(16),\n    end: at(17, 30),\n    title: 'Supplier call',\n  },\n  {\n    id: 'jonas-quarter',\n    person: 'jonas',\n    day: 'fri',\n    start: at(14),\n    end: at(15),\n    title: 'Quarter close',\n  },\n];\n\n/** Questions a person can send with one press. The first one is the one the demonstration types. */\nexport const EXAMPLES = [\n  '45 minutes with Maya and Jonas before the weekend',\n  'An hour with Jonas tomorrow afternoon',\n  '30 minutes with everyone on Wednesday morning',\n];\n",
      "type": "registry:component",
      "target": "components/blocks/ai-data-02/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "ai-data"
  ],
  "type": "registry:block"
}