{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scheduler",
  "title": "Scheduler engine",
  "description": "Drag-and-drop month/week/day scheduler with recurrence, resource lanes and free-slot search. Zero dependencies.",
  "files": [
    {
      "path": "components/slotgrid/core.ts",
      "content": "// Slotgrid core: framework-free date math, recurrence and layout shared by every Slotgrid\n// shell (React, Web Component, WordPress, Shopify). No dependencies. Times are local Dates.\n\nexport type View = \"month\" | \"week\" | \"day\";\nexport type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6;\n\nexport interface Recurrence {\n  freq: \"daily\" | \"weekly\" | \"monthly\";\n  /** Every n days/weeks/months. Default 1. */\n  interval?: number;\n  /** Total occurrences in the series, counted from the first one. */\n  count?: number;\n  /** Last allowed occurrence start (inclusive). */\n  until?: Date;\n  /** Weekly only. Defaults to the weekday of `start`. */\n  byWeekday?: Weekday[];\n  /** Occurrence starts to skip, e.g. one deleted instance. */\n  exclude?: Date[];\n}\n\nexport interface SlotgridEvent {\n  id: string;\n  title: string;\n  start: Date;\n  end: Date;\n  allDay?: boolean;\n  /** Any CSS color. */\n  color?: string;\n  resourceId?: string;\n  recurrence?: Recurrence;\n}\n\n/** One concrete appearance of an event; recurring events produce many. */\nexport interface Occurrence<E extends SlotgridEvent = SlotgridEvent> {\n  key: string;\n  event: E;\n  start: Date;\n  end: Date;\n}\n\n/** An occurrence clipped to one day column, positioned in minutes from midnight. */\nexport interface PlacedSegment<E extends SlotgridEvent = SlotgridEvent> {\n  occurrence: Occurrence<E>;\n  top: number;\n  bottom: number;\n  col: number;\n  cols: number;\n  startsToday: boolean;\n  endsToday: boolean;\n}\n\nexport const MINUTE = 60_000;\nconst DAY_MINUTES = 24 * 60;\n\n// ─── Date helpers ───────────────────────────────────────────────────────────────────────\n\nexport function startOfDay(d: Date): Date {\n  const x = new Date(d);\n  x.setHours(0, 0, 0, 0);\n  return x;\n}\n\n/** Calendar-day arithmetic, so a DST change keeps the wall-clock time. */\nexport function addDays(d: Date, n: number): Date {\n  const x = new Date(d);\n  x.setDate(x.getDate() + n);\n  return x;\n}\n\nexport function addMinutes(d: Date, n: number): Date {\n  return new Date(d.getTime() + n * MINUTE);\n}\n\nexport function daysInMonth(d: Date): number {\n  return new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();\n}\n\n/** Clamps the day, so Jan 31 + 1 month is the last day of February. */\nexport function addMonths(d: Date, n: number): Date {\n  const x = new Date(d);\n  const day = x.getDate();\n  x.setDate(1);\n  x.setMonth(x.getMonth() + n);\n  x.setDate(Math.min(day, daysInMonth(x)));\n  return x;\n}\n\nexport function startOfWeek(d: Date, weekStartsOn: Weekday = 1): Date {\n  const x = startOfDay(d);\n  return addDays(x, -((x.getDay() - weekStartsOn + 7) % 7));\n}\n\nexport function isSameDay(a: Date, b: Date): boolean {\n  return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();\n}\n\nexport function minutesIntoDay(d: Date): number {\n  return d.getHours() * 60 + d.getMinutes();\n}\n\nexport function overlaps(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): boolean {\n  return aStart < bEnd && bStart < aEnd;\n}\n\nexport function snap(minutes: number, step: number): number {\n  return Math.round(minutes / step) * step;\n}\n\n// ─── Navigation ─────────────────────────────────────────────────────────────────────────\n\n/** Days drawn by a view: 1 for day, 7 for week, 42 (six full weeks) for month. */\nexport function visibleDays(view: View, date: Date, weekStartsOn: Weekday = 1): Date[] {\n  if (view === \"day\") return [startOfDay(date)];\n  const first =\n    view === \"week\"\n      ? startOfWeek(date, weekStartsOn)\n      : startOfWeek(new Date(date.getFullYear(), date.getMonth(), 1), weekStartsOn);\n  return Array.from({ length: view === \"week\" ? 7 : 42 }, (_, i) => addDays(first, i));\n}\n\nexport function visibleRange(view: View, date: Date, weekStartsOn: Weekday = 1): { start: Date; end: Date } {\n  const days = visibleDays(view, date, weekStartsOn);\n  return { start: days[0]!, end: addDays(days[days.length - 1]!, 1) };\n}\n\nexport function navigate(view: View, date: Date, direction: -1 | 1): Date {\n  if (view === \"month\") return addMonths(date, direction);\n  return addDays(date, direction * (view === \"week\" ? 7 : 1));\n}\n\n// ─── Recurrence ─────────────────────────────────────────────────────────────────────────\n\nconst MAX_STEPS = 20_000;\n\n/** Every occurrence overlapping [rangeStart, rangeEnd), sorted by start. */\nexport function expandOccurrences<E extends SlotgridEvent>(events: E[], rangeStart: Date, rangeEnd: Date): Occurrence<E>[] {\n  const out: Occurrence<E>[] = [];\n  for (const event of events) {\n    if (!event.recurrence) {\n      if (overlaps(event.start, event.end, rangeStart, rangeEnd)) {\n        out.push({ key: event.id, event, start: event.start, end: event.end });\n      }\n      continue;\n    }\n    const duration = event.end.getTime() - event.start.getTime();\n    const excluded = new Set((event.recurrence.exclude ?? []).map((d) => d.getTime()));\n    for (const start of seriesStarts(event, rangeEnd)) {\n      const end = new Date(start.getTime() + duration);\n      if (excluded.has(start.getTime()) || !overlaps(start, end, rangeStart, rangeEnd)) continue;\n      out.push({ key: `${event.id}@${start.toISOString()}`, event, start, end });\n    }\n  }\n  return out.sort((a, b) => a.start.getTime() - b.start.getTime() || b.end.getTime() - a.end.getTime());\n}\n\n/** Series starts in order, stopping at `until`, `count` or the first start at/after `stopAt`. */\nfunction* seriesStarts(event: SlotgridEvent, stopAt: Date): Generator<Date> {\n  const rule = event.recurrence!;\n  const interval = Math.max(1, rule.interval ?? 1);\n  const first = event.start;\n  let emitted = 0;\n  const accept = (d: Date) => !(rule.until && d > rule.until) && !(rule.count !== undefined && emitted >= rule.count) && d < stopAt;\n\n  for (let step = 0; step < MAX_STEPS; step++) {\n    let batch: Date[];\n    if (rule.freq === \"daily\") {\n      batch = [addDays(first, step * interval)];\n    } else if (rule.freq === \"monthly\") {\n      const target = new Date(first.getFullYear(), first.getMonth() + step * interval, 1, first.getHours(), first.getMinutes());\n      // Months without that day are skipped (RFC 5545), not clamped.\n      batch = first.getDate() <= daysInMonth(target) ? [new Date(target.setDate(first.getDate()))] : [];\n    } else {\n      const days = [...new Set(rule.byWeekday?.length ? rule.byWeekday : [first.getDay() as Weekday])].sort((a, b) => a - b);\n      const weekStart = addDays(startOfWeek(first, 0), step * interval * 7);\n      batch = days\n        .map((wd) => {\n          const d = addDays(weekStart, wd);\n          d.setHours(first.getHours(), first.getMinutes(), first.getSeconds(), first.getMilliseconds());\n          return d;\n        })\n        .filter((d) => d >= first);\n    }\n    for (const d of batch) {\n      if (!accept(d)) return;\n      emitted++;\n      yield d;\n    }\n  }\n}\n\n// ─── Layout ─────────────────────────────────────────────────────────────────────────────\n\n/** Timed occurrences clipped to `day` and packed into side-by-side columns where they overlap. */\nexport function layoutDay<E extends SlotgridEvent>(occurrences: Occurrence<E>[], day: Date): PlacedSegment<E>[] {\n  const dayStart = startOfDay(day);\n  const dayEnd = addDays(dayStart, 1);\n  const segs: PlacedSegment<E>[] = [];\n  for (const occurrence of occurrences) {\n    if (occurrence.event.allDay || !overlaps(occurrence.start, occurrence.end, dayStart, dayEnd)) continue;\n    const startsToday = occurrence.start >= dayStart;\n    const endsToday = occurrence.end <= dayEnd;\n    const top = startsToday ? minutesIntoDay(occurrence.start) : 0;\n    const bottom = endsToday && occurrence.end < dayEnd ? minutesIntoDay(occurrence.end) : DAY_MINUTES;\n    segs.push({ occurrence, top, bottom: Math.max(bottom, top + 1), col: 0, cols: 1, startsToday, endsToday });\n  }\n  segs.sort((a, b) => a.top - b.top || b.bottom - a.bottom);\n\n  // Greedy column packing inside clusters of transitively overlapping segments.\n  let cluster: PlacedSegment<E>[] = [];\n  let columnEnds: number[] = [];\n  let clusterEnd = -1;\n  const flush = () => {\n    for (const s of cluster) s.cols = columnEnds.length;\n    cluster = [];\n    columnEnds = [];\n  };\n  for (const s of segs) {\n    if (s.top >= clusterEnd) flush();\n    let col = columnEnds.findIndex((end) => end <= s.top);\n    if (col === -1) col = columnEnds.push(0) - 1;\n    columnEnds[col] = s.bottom;\n    s.col = col;\n    cluster.push(s);\n    clusterEnd = Math.max(clusterEnd, s.bottom);\n  }\n  flush();\n  return segs;\n}\n\n/** Occurrences touching `day`, all-day first, then by start, longer first. */\nexport function occurrencesOnDay<E extends SlotgridEvent>(occurrences: Occurrence<E>[], day: Date): Occurrence<E>[] {\n  const dayStart = startOfDay(day);\n  const dayEnd = addDays(dayStart, 1);\n  return occurrences\n    .filter((o) => overlaps(o.start, o.end, dayStart, dayEnd) || (o.event.allDay && isSameDay(o.start, day)))\n    .sort(\n      (a, b) =>\n        Number(!!b.event.allDay) - Number(!!a.event.allDay) ||\n        a.start.getTime() - b.start.getTime() ||\n        b.end.getTime() - a.end.getTime(),\n    );\n}\n\n// ─── Editing ────────────────────────────────────────────────────────────────────────────\n\nexport function moveOccurrence(o: Occurrence, deltaDays: number, deltaMinutes: number): { start: Date; end: Date } {\n  return {\n    start: addMinutes(addDays(o.start, deltaDays), deltaMinutes),\n    end: addMinutes(addDays(o.end, deltaDays), deltaMinutes),\n  };\n}\n\nexport function resizeOccurrence(o: Occurrence, deltaMinutes: number, minMinutes: number): { start: Date; end: Date } {\n  const minEnd = addMinutes(o.start, minMinutes);\n  const end = addMinutes(o.end, deltaMinutes);\n  return { start: o.start, end: end < minEnd ? minEnd : end };\n}\n\n// ─── Formatting ─────────────────────────────────────────────────────────────────────────\n\nexport function formatTime(d: Date, locale?: string): string {\n  return new Intl.DateTimeFormat(locale, { hour: \"numeric\", minute: \"2-digit\" }).format(d);\n}\n\nexport function formatHour(hour: number, locale?: string): string {\n  return new Intl.DateTimeFormat(locale, { hour: \"numeric\" }).format(new Date(2000, 0, 1, hour));\n}\n\nexport function formatTitle(view: View, date: Date, locale?: string, weekStartsOn: Weekday = 1): string {\n  if (view === \"month\") return new Intl.DateTimeFormat(locale, { month: \"long\", year: \"numeric\" }).format(date);\n  if (view === \"day\") {\n    return new Intl.DateTimeFormat(locale, { weekday: \"long\", month: \"long\", day: \"numeric\", year: \"numeric\" }).format(date);\n  }\n  const days = visibleDays(\"week\", date, weekStartsOn);\n  // formatRange is ES2021; typed by hand so the file compiles under older lib targets.\n  const fmt = new Intl.DateTimeFormat(locale, { month: \"short\", day: \"numeric\", year: \"numeric\" }) as Intl.DateTimeFormat & { formatRange(a: Date, b: Date): string };\n  return fmt.formatRange(days[0]!, days[6]!);\n}\n\nexport function weekdayLabels(weekStartsOn: Weekday = 1, locale?: string, width: \"short\" | \"narrow\" = \"short\"): string[] {\n  const fmt = new Intl.DateTimeFormat(locale, { weekday: width });\n  // 2023-01-01 was a Sunday.\n  return Array.from({ length: 7 }, (_, i) => fmt.format(new Date(2023, 0, 1 + ((weekStartsOn + i) % 7))));\n}\n\n// ─── Resources ──────────────────────────────────────────────────────────────────────────\n\nexport interface Resource {\n  id: string;\n  title: string;\n  /** Any CSS color, used as the default for this resource's events. */\n  color?: string;\n  [key: string]: unknown;\n}\n\n/** A timed occurrence placed on a horizontal timeline row, in minutes from `rangeStart`. */\nexport interface LanePlacement<E extends SlotgridEvent = SlotgridEvent> {\n  occurrence: Occurrence<E>;\n  left: number;\n  right: number;\n  lane: number;\n  lanes: number;\n}\n\n/**\n * Packs one resource's occurrences into stacked lanes for a horizontal timeline that spans\n * [rangeStart, rangeEnd). Overlapping items go to separate lanes; `lanes` is per cluster.\n */\nexport function layoutLanes<E extends SlotgridEvent>(occurrences: Occurrence<E>[], rangeStart: Date, rangeEnd: Date): LanePlacement<E>[] {\n  const span = (rangeEnd.getTime() - rangeStart.getTime()) / MINUTE;\n  const items: LanePlacement<E>[] = occurrences\n    .filter((o) => overlaps(o.start, o.end, rangeStart, rangeEnd))\n    .map((occurrence) => ({\n      occurrence,\n      left: Math.max(0, (occurrence.start.getTime() - rangeStart.getTime()) / MINUTE),\n      right: Math.min(span, (occurrence.end.getTime() - rangeStart.getTime()) / MINUTE),\n      lane: 0,\n      lanes: 1,\n    }))\n    .sort((a, b) => a.left - b.left || b.right - a.right);\n\n  let cluster: LanePlacement<E>[] = [];\n  let laneEnds: number[] = [];\n  let clusterEnd = -1;\n  const flush = () => {\n    for (const it of cluster) it.lanes = laneEnds.length;\n    cluster = [];\n    laneEnds = [];\n  };\n  for (const it of items) {\n    if (it.left >= clusterEnd) flush();\n    let lane = laneEnds.findIndex((end) => end <= it.left);\n    if (lane === -1) lane = laneEnds.push(0) - 1;\n    laneEnds[lane] = it.right;\n    it.lane = lane;\n    cluster.push(it);\n    clusterEnd = Math.max(clusterEnd, it.right);\n  }\n  flush();\n  return items;\n}\n\n/** Occurrences grouped by resource id, in resource order. Unassigned ones are dropped. */\nexport function groupByResource<E extends SlotgridEvent>(occurrences: Occurrence<E>[], resources: Resource[]): Map<string, Occurrence<E>[]> {\n  const map = new Map<string, Occurrence<E>[]>(resources.map((r) => [r.id, []]));\n  for (const o of occurrences) if (o.event.resourceId) map.get(o.event.resourceId)?.push(o);\n  return map;\n}\n\n/** Free slots of `minutes` length between `from` and `to` that do not overlap any occurrence. */\nexport function freeSlots(occurrences: { start: Date; end: Date }[], from: Date, to: Date, minutes: number, step = minutes): Date[] {\n  const out: Date[] = [];\n  for (let t = from.getTime(); t + minutes * MINUTE <= to.getTime(); t += step * MINUTE) {\n    const s = new Date(t);\n    const e = new Date(t + minutes * MINUTE);\n    if (!occurrences.some((o) => overlaps(s, e, o.start, o.end))) out.push(s);\n  }\n  return out;\n}\n",
      "type": "registry:lib",
      "target": "components/slotgrid/core.ts"
    },
    {
      "path": "components/slotgrid/scheduler.tsx",
      "content": "\"use client\";\n\n// Slotgrid Scheduler for React + Tailwind (shadcn theme tokens). Month, week and day views,\n// drag to move, drag the bottom edge to resize, drag on empty time to create.\n// Zero dependencies besides React; all date logic lives in ./core.\n\nimport * as React from \"react\";\nimport {\n  addDays,\n  expandOccurrences,\n  formatHour,\n  formatTime,\n  formatTitle,\n  isSameDay,\n  layoutDay,\n  minutesIntoDay,\n  moveOccurrence,\n  navigate,\n  occurrencesOnDay,\n  resizeOccurrence,\n  snap,\n  startOfDay,\n  visibleDays,\n  visibleRange,\n  weekdayLabels,\n  type Occurrence,\n  type SlotgridEvent,\n  type View,\n  type Weekday,\n} from \"./core\";\n\nexport type { Occurrence, Recurrence, SlotgridEvent, View, Weekday } from \"./core\";\n\nexport interface EventChange<E extends SlotgridEvent = SlotgridEvent> {\n  event: E;\n  occurrence: Occurrence<E>;\n  start: Date;\n  end: Date;\n}\n\nexport interface SchedulerProps<E extends SlotgridEvent = SlotgridEvent> {\n  events: E[];\n  /** Controlled view. Pair with onViewChange. */\n  view?: View;\n  defaultView?: View;\n  onViewChange?: (view: View) => void;\n  /** Controlled date. Pair with onDateChange. */\n  date?: Date;\n  defaultDate?: Date;\n  onDateChange?: (date: Date) => void;\n  /** Views offered in the switcher. */\n  views?: View[];\n  weekStartsOn?: Weekday;\n  /** BCP 47 tag such as \"en-US\" or \"tr-TR\". Defaults to the browser locale. */\n  locale?: string;\n  /** Snap step and grid line spacing in minutes. */\n  slotMinutes?: number;\n  hourHeight?: number;\n  dayStartHour?: number;\n  dayEndHour?: number;\n  /** Hour the time grid scrolls to on open. */\n  scrollToHour?: number;\n  /** Height of the whole scheduler. */\n  height?: number | string;\n  editable?: boolean;\n  onEventChange?: (change: EventChange<E>) => void;\n  onEventClick?: (occurrence: Occurrence<E>) => void;\n  onSlotSelect?: (range: { start: Date; end: Date; allDay: boolean }) => void;\n  renderEvent?: (occurrence: Occurrence<E>) => React.ReactNode;\n  /** Labels for the toolbar, for translation. */\n  labels?: Partial<Record<\"today\" | \"previous\" | \"next\" | \"more\" | View, string>>;\n  className?: string;\n}\n\nconst DEFAULT_LABELS = { today: \"Today\", previous: \"Previous\", next: \"Next\", more: \"more\", month: \"Month\", week: \"Week\", day: \"Day\" };\nconst DRAG_THRESHOLD = 4;\nconst cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(\" \");\n\nfunction useControllable<T>(value: T | undefined, initial: T, onChange?: (v: T) => void): [T, (v: T) => void] {\n  const [inner, setInner] = React.useState(initial);\n  const current = value === undefined ? inner : value;\n  const set = React.useCallback(\n    (v: T) => {\n      if (value === undefined) setInner(v);\n      onChange?.(v);\n    },\n    [value, onChange],\n  );\n  return [current, set];\n}\n\n// The clock is read only in effects: server rendering (and Next.js prerendering) must not\n// depend on the current time, or the markup would differ from the browser's.\nfunction useNow(): Date | null {\n  const [now, setNow] = React.useState<Date | null>(null);\n  React.useEffect(() => {\n    setNow(new Date());\n    const id = setInterval(() => setNow(new Date()), 60_000);\n    return () => clearInterval(id);\n  }, []);\n  return now;\n}\n\nfunction eventStyle(color?: string): React.CSSProperties | undefined {\n  if (!color) return undefined;\n  return { backgroundColor: `color-mix(in oklab, ${color} 16%, var(--background, white))`, borderLeftColor: color };\n}\n\n// ─── Root ───────────────────────────────────────────────────────────────────────────────\n\nexport function Scheduler<E extends SlotgridEvent = SlotgridEvent>(props: SchedulerProps<E>) {\n  const {\n    events,\n    views = [\"month\", \"week\", \"day\"],\n    weekStartsOn = 1,\n    locale,\n    height = 680,\n    className,\n  } = props;\n  const labels = { ...DEFAULT_LABELS, ...props.labels };\n  const [view, setView] = useControllable<View>(props.view, props.defaultView ?? \"week\", props.onViewChange);\n  const [chosenDate, setDate] = useControllable<Date | null>(props.date, props.defaultDate ?? null, props.onDateChange as (d: Date | null) => void);\n  // The grid is drawn only after mount (now is null until then): event times and labels depend\n  // on the browser's time zone and locale, which a server render cannot know.\n  const now = useNow();\n  const date = now && (chosenDate ?? now);\n\n  const days = React.useMemo(() => (date ? visibleDays(view, date, weekStartsOn) : []), [view, date, weekStartsOn]);\n  const occurrences = React.useMemo(() => {\n    if (!date) return [];\n    const { start, end } = visibleRange(view, date, weekStartsOn);\n    return expandOccurrences(events, start, end);\n  }, [events, view, date, weekStartsOn]);\n\n  const openDay = (day: Date) => {\n    setDate(day);\n    if (views.includes(\"day\")) setView(\"day\");\n  };\n\n  return (\n    <div\n      className={cx(\"flex flex-col overflow-hidden rounded-xl border border-border bg-background text-foreground text-sm\", className)}\n      style={{ height }}\n      data-slotgrid=\"\"\n    >\n      <div className=\"flex flex-wrap items-center gap-2 border-b border-border px-3 py-2\">\n        <button type=\"button\" className={btn} onClick={() => setDate(new Date())}>\n          {labels.today}\n        </button>\n        <div className=\"flex\">\n          <button type=\"button\" aria-label={labels.previous} className={cx(iconBtn, \"rounded-r-none\")} onClick={() => date && setDate(navigate(view, date, -1))}>\n            <Chevron dir=\"left\" />\n          </button>\n          <button type=\"button\" aria-label={labels.next} className={cx(iconBtn, \"-ml-px rounded-l-none\")} onClick={() => date && setDate(navigate(view, date, 1))}>\n            <Chevron dir=\"right\" />\n          </button>\n        </div>\n        <h2 className=\"mr-auto px-1 text-base font-semibold tracking-tight\">{date && formatTitle(view, date, locale, weekStartsOn)}</h2>\n        {views.length > 1 && (\n          <div className=\"inline-flex rounded-md bg-muted p-0.5\" role=\"tablist\">\n            {views.map((v) => (\n              <button\n                key={v}\n                type=\"button\"\n                role=\"tab\"\n                aria-selected={v === view}\n                onClick={() => setView(v)}\n                className={cx(\n                  \"rounded-[5px] px-3 py-1 text-xs font-medium transition-colors\",\n                  v === view ? \"bg-background text-foreground shadow-sm\" : \"text-muted-foreground hover:text-foreground\",\n                )}\n              >\n                {labels[v]}\n              </button>\n            ))}\n          </div>\n        )}\n      </div>\n      {!date ? (\n        <div className=\"flex-1\" />\n      ) : view === \"month\" ? (\n        <MonthView {...props} days={days} date={date} occurrences={occurrences} weekStartsOn={weekStartsOn} moreLabel={labels.more} onOpenDay={openDay} />\n      ) : (\n        <TimeGrid {...props} days={days} occurrences={occurrences} weekStartsOn={weekStartsOn} onOpenDay={openDay} showDayHeader={view === \"week\"} />\n      )}\n    </div>\n  );\n}\n\nconst btn =\n  \"inline-flex h-8 items-center justify-center rounded-md border border-border bg-background px-3 text-xs font-medium shadow-xs transition-colors hover:bg-accent hover:text-accent-foreground\";\nconst iconBtn =\n  \"inline-flex h-8 w-8 items-center justify-center rounded-md border border-border bg-background shadow-xs transition-colors hover:bg-accent hover:text-accent-foreground\";\n\nfunction Chevron({ dir }: { dir: \"left\" | \"right\" }) {\n  return (\n    <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <path d={dir === \"left\" ? \"m15 18-6-6 6-6\" : \"m9 18 6-6-6-6\"} />\n    </svg>\n  );\n}\n\n// ─── Time grid (week / day) ─────────────────────────────────────────────────────────────\n\ntype GridDrag<E extends SlotgridEvent> =\n  | { kind: \"move\" | \"resize\"; occ: Occurrence<E>; x0: number; y0: number; day0: number; dDays: number; dMin: number; moved: boolean }\n  | { kind: \"select\"; day: number; from: number; to: number };\n\ninterface ViewProps<E extends SlotgridEvent> extends SchedulerProps<E> {\n  days: Date[];\n  occurrences: Occurrence<E>[];\n  weekStartsOn: Weekday;\n  onOpenDay: (day: Date) => void;\n}\n\nfunction TimeGrid<E extends SlotgridEvent>(p: ViewProps<E> & { showDayHeader: boolean }) {\n  const { days, locale, slotMinutes = 30, hourHeight = 48, dayStartHour = 0, dayEndHour = 24, scrollToHour = 8, editable = true } = p;\n  const now = useNow();\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const colsRef = React.useRef<HTMLDivElement>(null);\n  const [drag, setDrag] = React.useState<GridDrag<E> | null>(null);\n  const dragRef = React.useRef(drag);\n  dragRef.current = drag;\n\n  const startMin = dayStartHour * 60;\n  const totalMin = (dayEndHour - dayStartHour) * 60;\n  const pxPerMin = hourHeight / 60;\n  const hours = Array.from({ length: dayEndHour - dayStartHour }, (_, i) => dayStartHour + i);\n\n  React.useEffect(() => {\n    // A few px above the hour so its label is not clipped.\n    scrollRef.current?.scrollTo({ top: Math.max(0, (scrollToHour - dayStartHour) * hourHeight - 8) });\n  }, [scrollToHour, dayStartHour, hourHeight, days.length]);\n\n  // While dragging, the dragged occurrence is replaced by its preview so layout reflows live.\n  const shown = React.useMemo(() => {\n    if (!drag || drag.kind === \"select\" || !drag.moved) return p.occurrences;\n    const next = drag.kind === \"move\" ? moveOccurrence(drag.occ, drag.dDays, drag.dMin) : resizeOccurrence(drag.occ, drag.dMin, slotMinutes);\n    return p.occurrences.map((o) => (o.key === drag.occ.key ? { ...o, ...next } : o));\n  }, [drag, p.occurrences, slotMinutes]);\n\n  const pointerToCell = (clientX: number, clientY: number) => {\n    const r = colsRef.current!.getBoundingClientRect();\n    const day = Math.min(days.length - 1, Math.max(0, Math.floor(((clientX - r.left) / r.width) * days.length)));\n    const min = Math.min(totalMin, Math.max(0, (clientY - r.top) / pxPerMin));\n    return { day, min };\n  };\n\n  const track = (onMove: (e: PointerEvent) => void, onUp: (e: PointerEvent) => void) => {\n    const move = (e: PointerEvent) => onMove(e);\n    const up = (e: PointerEvent) => {\n      window.removeEventListener(\"pointermove\", move);\n      window.removeEventListener(\"pointerup\", up);\n      window.removeEventListener(\"pointercancel\", up);\n      onUp(e);\n    };\n    window.addEventListener(\"pointermove\", move);\n    window.addEventListener(\"pointerup\", up);\n    window.addEventListener(\"pointercancel\", up);\n  };\n\n  const beginEventDrag = (e: React.PointerEvent, occ: Occurrence<E>, kind: \"move\" | \"resize\") => {\n    if (e.button !== 0) return;\n    e.stopPropagation();\n    const canEdit = editable && !!p.onEventChange && !occ.event.recurrence;\n    const { day } = pointerToCell(e.clientX, e.clientY);\n    setDrag({ kind, occ, x0: e.clientX, y0: e.clientY, day0: day, dDays: 0, dMin: 0, moved: false });\n    track(\n      (ev) => {\n        const d = dragRef.current;\n        if (!d || d.kind === \"select\") return;\n        const moved = d.moved || Math.hypot(ev.clientX - d.x0, ev.clientY - d.y0) > DRAG_THRESHOLD;\n        if (!moved || !canEdit) return;\n        const cell = pointerToCell(ev.clientX, ev.clientY);\n        setDrag({ ...d, moved, dMin: snap((ev.clientY - d.y0) / pxPerMin, slotMinutes), dDays: kind === \"move\" ? cell.day - d.day0 : 0 });\n      },\n      () => {\n        const d = dragRef.current;\n        setDrag(null);\n        if (!d || d.kind === \"select\") return;\n        if (!d.moved) return p.onEventClick?.(occ);\n        if (!d.dMin && !d.dDays) return;\n        const next = d.kind === \"move\" ? moveOccurrence(occ, d.dDays, d.dMin) : resizeOccurrence(occ, d.dMin, slotMinutes);\n        p.onEventChange?.({ event: occ.event, occurrence: occ, ...next });\n      },\n    );\n  };\n\n  const beginSelect = (e: React.PointerEvent) => {\n    if (e.button !== 0 || !p.onSlotSelect) return;\n    const { day, min } = pointerToCell(e.clientX, e.clientY);\n    const from = Math.floor(min / slotMinutes) * slotMinutes;\n    setDrag({ kind: \"select\", day, from, to: from + slotMinutes });\n    track(\n      (ev) => {\n        const d = dragRef.current;\n        if (!d || d.kind !== \"select\") return;\n        const cur = pointerToCell(ev.clientX, ev.clientY).min;\n        setDrag({ ...d, to: Math.max(d.from + slotMinutes, Math.ceil(cur / slotMinutes) * slotMinutes) });\n      },\n      () => {\n        const d = dragRef.current;\n        setDrag(null);\n        if (!d || d.kind !== \"select\") return;\n        const day = days[d.day];\n        if (!day) return;\n        const base = startOfDay(day);\n        p.onSlotSelect?.({ start: new Date(base.getTime() + (startMin + d.from) * 60_000), end: new Date(base.getTime() + (startMin + d.to) * 60_000), allDay: false });\n      },\n    );\n  };\n\n  const allDay = days.map((day) => shown.filter((o) => o.event.allDay && occurrencesOnDay([o], day).length));\n  const hasAllDay = allDay.some((list) => list.length);\n  const cols = `repeat(${days.length}, minmax(0, 1fr))`;\n\n  return (\n    <div className=\"flex min-h-0 flex-1 flex-col\">\n      {p.showDayHeader && (\n        <div className=\"flex border-b border-border\">\n          <div className=\"w-14 shrink-0\" />\n          <div className=\"grid flex-1\" style={{ gridTemplateColumns: cols }}>\n            {days.map((day, i) => {\n              const today = !!now && isSameDay(day, now);\n              return (\n                <button\n                  key={i}\n                  type=\"button\"\n                  onClick={() => p.onOpenDay(day)}\n                  className=\"flex flex-col items-center gap-0.5 border-l border-border py-1.5 first:border-l-0 hover:bg-accent/50\"\n                >\n                  <span className=\"text-[11px] uppercase tracking-wide text-muted-foreground\">{weekdayLabels(day.getDay() as Weekday, locale)[0]}</span>\n                  <span className={cx(\"flex h-7 min-w-7 items-center justify-center rounded-full px-1 text-base font-medium\", today && \"bg-primary text-primary-foreground\")}>\n                    {day.getDate()}\n                  </span>\n                </button>\n              );\n            })}\n          </div>\n        </div>\n      )}\n      {hasAllDay && (\n        <div className=\"flex border-b border-border\">\n          <div className=\"w-14 shrink-0\" />\n          <div className=\"grid flex-1\" style={{ gridTemplateColumns: cols }}>\n            {allDay.map((list, i) => (\n              <div key={i} className=\"flex min-w-0 flex-col gap-0.5 border-l border-border p-1 first:border-l-0\">\n                {list.map((o) => (\n                  <button\n                    key={o.key}\n                    type=\"button\"\n                    onClick={() => p.onEventClick?.(o)}\n                    className=\"truncate rounded-sm border-l-[3px] border-primary bg-primary/10 px-1.5 py-0.5 text-left text-xs font-medium\"\n                    style={eventStyle(o.event.color)}\n                  >\n                    {p.renderEvent ? p.renderEvent(o) : o.event.title}\n                  </button>\n                ))}\n              </div>\n            ))}\n          </div>\n        </div>\n      )}\n      <div ref={scrollRef} className=\"relative min-h-0 flex-1 overflow-y-auto\">\n        <div className=\"flex\" style={{ height: totalMin * pxPerMin }}>\n          <div className=\"relative w-14 shrink-0\">\n            {hours.map((h, i) =>\n              i === 0 ? null : (\n                <span key={h} className=\"absolute right-2 -translate-y-1/2 text-[11px] text-muted-foreground\" style={{ top: i * hourHeight }}>\n                  {formatHour(h, locale)}\n                </span>\n              ),\n            )}\n          </div>\n          <div\n            ref={colsRef}\n            className={cx(\"relative grid flex-1 touch-none select-none\", p.onSlotSelect && \"cursor-crosshair\")}\n            style={{\n              gridTemplateColumns: cols,\n              backgroundImage: `repeating-linear-gradient(to bottom, var(--border, #e5e7eb) 0 1px, transparent 1px ${hourHeight}px)`,\n            }}\n            onPointerDown={beginSelect}\n          >\n            {days.map((day, i) => {\n              const segs = layoutDay(shown, day).filter((s) => s.bottom > startMin && s.top < startMin + totalMin);\n              const today = !!now && isSameDay(day, now);\n              const nowMin = now ? minutesIntoDay(now) - startMin : -1;\n              return (\n                <div key={i} className={cx(\"relative border-l border-border first:border-l-0\", today && \"bg-primary/[0.03]\")}>\n                  {drag?.kind === \"select\" && drag.day === i && (\n                    <div\n                      className=\"pointer-events-none absolute inset-x-1 z-10 rounded-md border border-primary/50 bg-primary/15 px-1.5 py-0.5 text-[11px] font-medium text-primary\"\n                      style={{ top: drag.from * pxPerMin, height: (drag.to - drag.from) * pxPerMin }}\n                    >\n                      {formatTime(new Date(startOfDay(day).getTime() + (startMin + drag.from) * 60_000), locale)}\n                    </div>\n                  )}\n                  {segs.map((s) => {\n                    const o = s.occurrence;\n                    const top = Math.max(0, s.top - startMin);\n                    const bottom = Math.min(totalMin, s.bottom - startMin);\n                    const active = drag && drag.kind !== \"select\" && drag.occ.key === o.key;\n                    const short = (bottom - top) * pxPerMin < 36;\n                    return (\n                      <div\n                        key={o.key}\n                        role=\"button\"\n                        tabIndex={0}\n                        onPointerDown={(e) => beginEventDrag(e, o, \"move\")}\n                        onKeyDown={(e) => e.key === \"Enter\" && p.onEventClick?.(o)}\n                        className={cx(\n                          \"group absolute overflow-hidden rounded-md border-l-[3px] border-primary bg-primary/10 px-1.5 py-0.5 text-xs leading-tight shadow-xs ring-1 ring-background\",\n                          editable && p.onEventChange && !o.event.recurrence ? \"cursor-grab\" : \"cursor-pointer\",\n                          active && drag.moved && \"z-20 cursor-grabbing opacity-90 shadow-lg\",\n                        )}\n                        style={{\n                          top: top * pxPerMin,\n                          height: Math.max(18, (bottom - top) * pxPerMin - 1),\n                          left: `calc(${(s.col / s.cols) * 100}% + 1px)`,\n                          width: `calc(${100 / s.cols}% - 3px)`,\n                          ...eventStyle(o.event.color),\n                        }}\n                      >\n                        {p.renderEvent ? (\n                          p.renderEvent(o)\n                        ) : (\n                          <div className={cx(short && \"flex gap-1\")}>\n                            <div className=\"truncate font-medium\">{o.event.title}</div>\n                            <div className=\"truncate text-muted-foreground\">\n                              {formatTime(o.start, locale)}\n                              {!short && ` – ${formatTime(o.end, locale)}`}\n                            </div>\n                          </div>\n                        )}\n                        {editable && p.onEventChange && !o.event.recurrence && s.endsToday && (\n                          <div\n                            className=\"absolute inset-x-0 bottom-0 h-2 cursor-ns-resize opacity-0 group-hover:opacity-100\"\n                            onPointerDown={(e) => beginEventDrag(e, o, \"resize\")}\n                          >\n                            <div className=\"mx-auto mt-0.5 h-1 w-6 rounded-full bg-foreground/30\" />\n                          </div>\n                        )}\n                      </div>\n                    );\n                  })}\n                  {today && nowMin >= 0 && nowMin <= totalMin && (\n                    <div className=\"pointer-events-none absolute inset-x-0 z-30 h-0.5 bg-red-500\" style={{ top: nowMin * pxPerMin }}>\n                      <div className=\"absolute -left-1 -top-[3px] h-2 w-2 rounded-full bg-red-500\" />\n                    </div>\n                  )}\n                </div>\n              );\n            })}\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n// ─── Month ──────────────────────────────────────────────────────────────────────────────\n\nconst MAX_CHIPS = 3;\n\nfunction MonthView<E extends SlotgridEvent>(p: ViewProps<E> & { date: Date; moreLabel: string }) {\n  const { days, date, locale, weekStartsOn, editable = true } = p;\n  const now = useNow();\n  const [drag, setDrag] = React.useState<{ occ: Occurrence<E>; from: number; over: number; moved: boolean } | null>(null);\n  const dragRef = React.useRef(drag);\n  dragRef.current = drag;\n\n  const cellAt = (x: number, y: number) => {\n    const el = document.elementFromPoint(x, y)?.closest<HTMLElement>(\"[data-sg-day]\");\n    return el ? Number(el.dataset.sgDay) : null;\n  };\n\n  const beginDrag = (e: React.PointerEvent, occ: Occurrence<E>, from: number) => {\n    if (e.button !== 0) return;\n    e.stopPropagation();\n    const canEdit = editable && !!p.onEventChange && !occ.event.recurrence;\n    const x0 = e.clientX;\n    const y0 = e.clientY;\n    setDrag({ occ, from, over: from, moved: false });\n    const move = (ev: PointerEvent) => {\n      const d = dragRef.current;\n      if (!d || !canEdit) return;\n      const moved = d.moved || Math.hypot(ev.clientX - x0, ev.clientY - y0) > DRAG_THRESHOLD;\n      const over = cellAt(ev.clientX, ev.clientY);\n      setDrag({ ...d, moved, over: over ?? d.over });\n    };\n    const up = () => {\n      window.removeEventListener(\"pointermove\", move);\n      window.removeEventListener(\"pointerup\", up);\n      const d = dragRef.current;\n      setDrag(null);\n      if (!d) return;\n      if (!d.moved) return p.onEventClick?.(occ);\n      if (d.over !== d.from) p.onEventChange?.({ event: occ.event, occurrence: occ, ...moveOccurrence(occ, d.over - d.from, 0) });\n    };\n    window.addEventListener(\"pointermove\", move);\n    window.addEventListener(\"pointerup\", up);\n  };\n\n  return (\n    <div className=\"flex min-h-0 flex-1 flex-col\">\n      <div className=\"grid grid-cols-7 border-b border-border\">\n        {weekdayLabels(weekStartsOn, locale).map((w) => (\n          <div key={w} className=\"py-1.5 text-center text-[11px] uppercase tracking-wide text-muted-foreground\">\n            {w}\n          </div>\n        ))}\n      </div>\n      <div className=\"grid min-h-0 flex-1 grid-cols-7 grid-rows-6 select-none\">\n        {days.map((day, i) => {\n          const list = occurrencesOnDay(p.occurrences, day);\n          const outside = day.getMonth() !== date.getMonth();\n          const isOver = drag?.moved && drag.over === i;\n          return (\n            <div\n              key={i}\n              data-sg-day={i}\n              onClick={() => p.onSlotSelect?.({ start: startOfDay(day), end: addDays(startOfDay(day), 1), allDay: true })}\n              className={cx(\n                \"flex min-h-0 min-w-0 flex-col gap-0.5 overflow-hidden border-b border-l border-border p-1 [&:nth-child(7n+1)]:border-l-0\",\n                outside && \"bg-muted/40\",\n                isOver && \"bg-primary/10\",\n                p.onSlotSelect && \"cursor-pointer\",\n              )}\n            >\n              <button\n                type=\"button\"\n                onClick={(e) => {\n                  e.stopPropagation();\n                  p.onOpenDay(day);\n                }}\n                className={cx(\n                  \"flex h-6 min-w-6 items-center justify-center self-start rounded-full px-1 text-xs font-medium hover:bg-accent\",\n                  outside && \"text-muted-foreground\",\n                  !!now && isSameDay(day, now) && \"bg-primary text-primary-foreground hover:bg-primary\",\n                )}\n              >\n                {day.getDate()}\n              </button>\n              {list.slice(0, MAX_CHIPS).map((o) => (\n                <div\n                  key={o.key}\n                  role=\"button\"\n                  tabIndex={0}\n                  onClick={(e) => e.stopPropagation()}\n                  onPointerDown={(e) => beginDrag(e, o, i)}\n                  onKeyDown={(e) => e.key === \"Enter\" && p.onEventClick?.(o)}\n                  className={cx(\n                    \"flex min-w-0 items-center gap-1 rounded-sm px-1 py-px text-xs\",\n                    o.event.allDay ? \"border-l-[3px] border-primary bg-primary/10 font-medium\" : \"hover:bg-accent\",\n                    drag?.moved && drag.occ.key === o.key && \"opacity-40\",\n                    editable && p.onEventChange && !o.event.recurrence ? \"cursor-grab\" : \"cursor-pointer\",\n                  )}\n                  style={o.event.allDay ? eventStyle(o.event.color) : undefined}\n                >\n                  {!o.event.allDay && (\n                    <span className=\"h-1.5 w-1.5 shrink-0 rounded-full bg-primary\" style={o.event.color ? { backgroundColor: o.event.color } : undefined} />\n                  )}\n                  {!o.event.allDay && <span className=\"shrink-0 text-muted-foreground\">{formatTime(o.start, locale)}</span>}\n                  <span className=\"truncate\">{p.renderEvent ? p.renderEvent(o) : o.event.title}</span>\n                </div>\n              ))}\n              {list.length > MAX_CHIPS && (\n                <button\n                  type=\"button\"\n                  onClick={(e) => {\n                    e.stopPropagation();\n                    p.onOpenDay(day);\n                  }}\n                  className=\"self-start px-1 text-[11px] font-medium text-muted-foreground hover:text-foreground\"\n                >\n                  +{list.length - MAX_CHIPS} {p.moreLabel}\n                </button>\n              )}\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/slotgrid/scheduler.tsx"
    }
  ],
  "type": "registry:component"
}