{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "week-picker",
  "title": "Week Picker",
  "description": "A week picker: a week-year of ISO 8601 weeks as a grid, each cell the week number with the Monday it starts on under it, that hands back a plain \"2026-W07\" string — the same value `<input type=\"week\">` produces, for an input Firefox and Safari have never shipped. Reach for it wherever the thing being chosen is the week itself: a weekly report, export or digest; the period on a timesheet,工数 or overtime submission; a payroll or billing week; a weekly close, cut-off or freeze; sprint and iteration selection; a production, delivery or shipping week; a school or academic week; an on-call or shift rotation; the week a KPI, OKR or target is scored in; a cohort in a week-over-week retention table; and the period selector above any dashboard, chart or ledger that aggregates by week — often paired as two of them for a from/to range. Common asks it answers: \"week picker react\", \"iso week picker\", \"week number picker component\", \"select a week react\", \"weekpicker shadcn\", \"shadcn week picker\", \"shadcn calendar select week\", \"input type=week alternative react\", \"week input safari firefox not supported\", \"MUI week picker equivalent\", \"antd DatePicker picker=week equivalent\", \"react-datepicker showWeekPicker alternative\", \"week range picker react\", \"pick a week for weekly report\", \"timesheet week selector react\", \"payroll week picker\", \"sprint week selector\", \"week over week dashboard period picker\", \"iso 8601 week component\", \"YYYY-Www input react\", \"get iso week number javascript\", \"iso week year vs calendar year\", \"week 53 bug\", \"year has 53 weeks javascript\", \"december week belongs to next year\", \"january week belongs to previous year\", \"week number off by one new year\", \"getWeek returns wrong year\", \"date-fns getISOWeek without date-fns\", \"week start monday vs sunday\", \"store a week not a date range\", \"accessible week picker\", \"grid roving tabindex week\", \"週 選択 react\", \"ISO週 コンポーネント\", \"週次レポート 期間選択\", \"勤怠 週 選択\", \"第53週 バグ\", \"週番号 年またぎ ずれ\", \"週の開始 月曜 日曜\", \"週単位 集計 ダッシュボード\". Official shadcn/ui has no week selection, measured today rather than remembered. Fetching every entry in its registry — 65 listed, 62 fetchable, code-block, questionnaire and trace 404 on both style tracks — and searching all 223,287 bytes of files[].content, isoWeek, weekNumber, weekYear, getISOWeek, weekOfYear, ISO8601, fiscalWeek, weekStartsOn, startOfWeek and endOfWeek are every one of them a zero hit. week is not zero and is worth unfolding rather than rounding: it returns 10, and all 10 are react-day-picker className keys inside its calendar — weekdays, weekday, week, week_number_header, week_number. Official's calendar can therefore *display* a week number beside a row; what it selects is still a day. Being able to show a thing and being able to answer with it are different, and this component answers with it. The decision everything else follows from: a week-year is not a calendar year, and the two are kept as separate numbers because the days do not agree with either. Measured, not recalled: 2026-12-28 is a Monday and 2027-01-03 is a Sunday and both are 2026-W53; the week-year only turns over on 2027-01-04; and 2026 is one of the years with fifty-three weeks — 1992, 1998, 2004, 2009, 2015, 2020, 2026, 2032 and 2037 in this span, measured by the gap between consecutive week-1 Mondays rather than by reciting which weekday 1 January fell on. So nothing here is ordered by (year, week). Every move is made over the Monday that opens a week, counted as whole days from the epoch, which is why the arrow keys walk out of W53 into the next year's W01 without a special case and why adding a week never lands on the wrong day in the two weeks a year that daylight saving moves — a week is seven calendar days, not 604,800,000 milliseconds. PageUp and PageDown hold the week number and walk the years, clamped where the year they arrive in is shorter, so W53 never lands on a cell that does not exist. parseWeekValue does the validation a regular expression cannot: \"2025-W53\" is shaped exactly like a week and is nothing, because 2025 has fifty-two, and a picker that accepts it opens on a cell nobody can select. A min or max that is not a real week is treated as no bound rather than as a silent lock-out. weekDates is the one accessor it hands out, and the type is why that is safe. month-picker deliberately returns no Date, because an instant means having quietly chosen a zone; the same objection holds here, so a week resolves to two inclusive \"YYYY-MM-DD\" calendar dates — zone-free, sortable, and what an API means by ?from=2026-02-09. The end is inclusive because half of all range bugs are an argument about the eighth day. weekDates(\"2026-W53\") answers 2026-12-28 to 2027-01-03: one week, two calendar years, and the shape to test any week-to-dates code against. toWeekValue reads a Date's local fields and never toISOString, which is a month-picker lesson applied one grain finer: UTC is already Monday at 23:00 on a Sunday in Berlin, so the ISO read files a weekly timesheet against the following period for everyone who submits one on a Sunday evening. The dates under the numbers are localised, and the calendar they are written in is pinned to the one the ISO week is defined on. Not fussiness, and measured: asked to write 9 February 2026, th-TH answers 2569, ja-JP-u-ca-japanese answers 令和8年, ar-EG answers in Arabic-Indic digits and fa-IR answers 20 Bahman 1404 — a different day of a different month. Any of those under a cell whose value is \"2026-W07\" leaves the label and the value disagreeing with no way for the reader to tell which one the form posts. Language and date order still follow the locale; only the calendar is held still. It is pinned through Intl.Locale rather than by appending \"-u-ca-gregory\" to the tag, because a locale that already carries an extension — ja-JP-u-ca-japanese is the common one — becomes an invalid tag that way and throws, and the fallback then loses the reader's language entirely. A malformed locale prop falls back instead of taking the page down. The word \"week\" in each cell's accessible name comes from CLDR through Intl.DisplayNames, so it reads 週 in Japanese and Woche in German: a component that localises its dates and then announces them as \"Week 7\" is only half translated. The week-year in the caption is written as a plain number rather than through Intl, because that is the number the form will post. Accessibility is the other half of the work. It is a real role=\"grid\" with a roving tabindex — one tab stop for the whole year, then the arrow keys inside it, because fifty-three tab stops per year is the thing this replaces. Left and right step a week and cross into the neighbouring week-year at the edges rather than dead-ending, up and down move a row and follow the columns prop, Home and End go to the first and last week of the year since rows here are a layout choice and not a calendar unit, and on an RTL page left and right follow the writing direction instead of running backwards. Every cell is named with the localised word, the number and the whole range — \"week 7, Feb 9 – 15, 2026\" — because a bare number stops meaning anything once the arrows have moved, and the date printed under it is aria-hidden so the same date is not read twice. The current week carries aria-current=\"date\". Unavailable weeks are marked aria-disabled rather than with the disabled attribute, so they can still be reached and read: a week the arrow keys skip over silently is a week the user cannot tell exists. Both the locale and the which-week-is-now marker resolve after mount, so a server render and the browser's first paint agree instead of tripping a hydration mismatch, and passing locale skips the swap. Within this registry the neighbours are each another grain or another job: month-picker is the same shape one step coarser, date-range-preset picks an arbitrary period rather than a named week, calendar-heatmap draws a year of days instead of choosing one of its weeks, weekly-hours sets the opening times a business keeps on each weekday, date-input types a single day, time-slot-picker chooses between times inside a day, duration-input measures a length and timezone-select picks a zone. None of them answers with a week. The API: value and onValueChange make it controlled, or defaultValue uncontrolled; weekYear, defaultWeekYear and onWeekYearChange control the year on display; min and max take the same YYYY-Www strings and stop the year arrows as well as the cells; isWeekDisabled handles scattered holes such as a closed payroll period without locking the arrows; locale, columns (3, 4 or 6) and formatWeekLabel cover the display; and name posts the value through a hidden input with a plain form or a server action. The arithmetic is exported as pure functions so a report, a server route, a reminder job or a test can have the same answers without mounting anything: toWeekValue, parseWeekValue, weekDates, weeksInWeekYear and shiftWeekValue. Styled entirely with shadcn tokens (primary, primary-foreground, accent, accent-foreground, input, ring, muted-foreground) so it follows light and dark mode, and it ships zero npm dependencies — no date library, no icon package, one file.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/ui/week-picker.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/**\n * The locale the dates are formatted in before hydration.\n *\n * The runtime's own locale is a property of the machine, so the server's and the browser's can\n * disagree — and the date hints under each week number are the thing that would then differ between\n * the two renders. Both sides start from this constant and the real locale swaps in on mount.\n * Passing `locale` skips the swap entirely and is the fix if the first paint matters.\n */\nconst HYDRATION_LOCALE = \"en-US\"\n\nconst MS_PER_DAY = 864e5\nconst DAYS_PER_WEEK = 7\n\n/**\n * \"2026-W07\". Anchored, zero-padded, and capped at W53 — the highest week number any year has.\n *\n * W53 passing the pattern is not the same as W53 existing: most years have 52 weeks, so\n * `parseWeekValue` checks the number against the year it was written with. The pattern only rules\n * out the shapes that are never a week.\n */\nconst WEEK_VALUE_PATTERN = /^(\\d{4,})-W(0[1-9]|[1-4]\\d|5[0-3])$/\n\n/** The first and last week-year this component will navigate to, matching the 4-digit value shape. */\nconst FIRST_WEEK_YEAR = 1\nconst LAST_WEEK_YEAR = 9999\n\n/**\n * The number of whole days from 1970-01-01 to a calendar date, with no zone and no clock.\n *\n * Every piece of week arithmetic below runs on these integers rather than on `Date` objects,\n * because a week is seven calendar days and not 604,800,000 milliseconds: adding that many to a\n * local `Date` lands on the wrong day in the two weeks a year that daylight saving moves, and the\n * bug shows up as an off-by-one week for half the users and for none of the tests.\n *\n * `new Date(Date.UTC(50, 0, 1))` is the year **1950** — the two-digit-year rule from the original\n * `Date` constructor still applies to `Date.UTC` — so the year is set afterwards instead, which is\n * the difference between a year-99 archive picker being right and being off by nineteen centuries\n * without saying so.\n */\nfunction dayNumberOf(year: number, month: number, day: number): number {\n  const at = new Date(Date.UTC(2000, month - 1, day))\n  at.setUTCFullYear(year)\n  return Math.round(at.getTime() / MS_PER_DAY)\n}\n\nfunction civilFromDayNumber(dayNumber: number): { year: number; month: number; day: number } {\n  const at = new Date(dayNumber * MS_PER_DAY)\n  return { year: at.getUTCFullYear(), month: at.getUTCMonth() + 1, day: at.getUTCDate() }\n}\n\n/** Day of the week with **Monday as 0**, which is the order ISO 8601 counts in. */\nfunction mondayBasedWeekday(dayNumber: number): number {\n  // 1970-01-01 was a Thursday, so day number 0 is weekday 3 once Monday is 0.\n  return (((dayNumber + 3) % DAYS_PER_WEEK) + DAYS_PER_WEEK) % DAYS_PER_WEEK\n}\n\n/**\n * The Monday that opens week 1 of a week-year.\n *\n * ISO 8601 defines week 1 as the week containing the first Thursday of January, which is the same\n * as the week containing 4 January — the form used here because it needs no search. That Monday can\n * fall in December of the previous calendar year, and that is the whole reason a week-year exists\n * as a separate number.\n */\nfunction mondayOfFirstWeek(weekYear: number): number {\n  const fourthOfJanuary = dayNumberOf(weekYear, 1, 4)\n  return fourthOfJanuary - mondayBasedWeekday(fourthOfJanuary)\n}\n\n/**\n * How many weeks a week-year has: **52 or 53**.\n *\n * Derived by measuring the gap to the next week-year rather than by reciting the rule about which\n * weekday 1 January lands on, so there is one fact here instead of two that can disagree. The long\n * years are real and close together — 2020, 2026, 2032 — and a 52-week assumption breaks on every\n * one of them.\n */\nexport function weeksInWeekYear(weekYear: number): number {\n  return (mondayOfFirstWeek(weekYear + 1) - mondayOfFirstWeek(weekYear)) / DAYS_PER_WEEK\n}\n\nfunction weekValueOf(weekYear: number, week: number): string {\n  return `${String(weekYear).padStart(4, \"0\")}-W${String(week).padStart(2, \"0\")}`\n}\n\n/** The ISO week a day number falls in, found through its own Thursday. */\nfunction weekOfDayNumber(dayNumber: number): { weekYear: number; week: number } {\n  const monday = dayNumber - mondayBasedWeekday(dayNumber)\n  // The week belongs to the year its Thursday is in. Reading the Monday's year instead is the\n  // classic one-week error at New Year: 2026-12-28 is a Monday in 2026 and 2027-01-03 is a Sunday\n  // in 2027, and both are 2026-W53.\n  const weekYear = civilFromDayNumber(monday + 3).year\n  return { weekYear, week: (monday - mondayOfFirstWeek(weekYear)) / DAYS_PER_WEEK + 1 }\n}\n\n/**\n * The ISO week a `Date` falls in, as \"2026-W07\", read from its **local** fields — the week the\n * person looking at that date would name.\n *\n * `toISOString()` is the tempting source and it is wrong for half the planet: it reads UTC, so\n * Sunday at 23:00 in Berlin is already Monday in UTC and comes back as the *next* week, which is\n * exactly the moment a weekly timesheet gets filed against the wrong period.\n */\nexport function toWeekValue(date: Date): string {\n  const { weekYear, week } = weekOfDayNumber(\n    dayNumberOf(date.getFullYear(), date.getMonth() + 1, date.getDate())\n  )\n  return weekValueOf(weekYear, week)\n}\n\n/**\n * `{ weekYear, week }` with the week numbered from 1, or null when the string is not a week that\n * exists.\n *\n * Rejects W53 in a 52-week year, which is the validation a bare regular expression cannot do and\n * the one that matters: \"2025-W53\" looks exactly like a week and is nothing, so a picker that\n * accepts it opens on a cell that cannot be selected.\n *\n * Note that `weekYear` is **not** the calendar year of every day in the week — see\n * `weekDates` — and the two must stay separate fields in anything that stores this.\n */\nexport function parseWeekValue(value: string): { weekYear: number; week: number } | null {\n  const parsed = WEEK_VALUE_PATTERN.exec(value)\n  if (!parsed) return null\n  const weekYear = Number(parsed[1])\n  const week = Number(parsed[2])\n  if (weekYear < FIRST_WEEK_YEAR || weekYear > LAST_WEEK_YEAR) return null\n  if (week > weeksInWeekYear(weekYear)) return null\n  return { weekYear, week }\n}\n\nfunction mondayFromValue(value: string | undefined): number | null {\n  if (!value) return null\n  const parsed = parseWeekValue(value)\n  if (!parsed) return null\n  return mondayOfFirstWeek(parsed.weekYear) + (parsed.week - 1) * DAYS_PER_WEEK\n}\n\nfunction toDateKey({ year, month, day }: { year: number; month: number; day: number }): string {\n  return `${String(year).padStart(4, \"0\")}-${String(month).padStart(2, \"0\")}-${String(day).padStart(2, \"0\")}`\n}\n\n/**\n * The seven days a week covers, as **inclusive** \"YYYY-MM-DD\" calendar dates: Monday in `start`,\n * Sunday in `end`.\n *\n * This is the one accessor the component hands out, and the type is the reason it is safe to.\n * `month-picker` deliberately has no `Date` accessor because returning an instant means having\n * silently chosen a zone; the same objection applies here, so these come back as calendar dates —\n * zone-free, sortable, and the same thing an API means by `?from=2026-02-09`. Build the instant\n * where you know the zone.\n *\n * The end is inclusive because a week is seven days and half of all range bugs are an argument\n * about the eighth. The two dates frequently sit in different months, and `weekDates(\"2026-W53\")`\n * answers 2026-12-28 to 2027-01-03 — different *years* — which is the shape to test any\n * week-to-dates code against.\n */\nexport function weekDates(value: string): { start: string; end: string } | null {\n  const monday = mondayFromValue(value)\n  if (monday === null) return null\n  return {\n    start: toDateKey(civilFromDayNumber(monday)),\n    end: toDateKey(civilFromDayNumber(monday + DAYS_PER_WEEK - 1)),\n  }\n}\n\n/**\n * The week `by` weeks away, or null if the input is not a week or the result leaves the range.\n *\n * Walking weeks by adding to the week number is the thing this exists to stop: `2026-W53` plus one\n * is not `2026-W54`, and it is not `2027-W00` either. It steps over the Mondays instead, so the\n * year rolls over on its own and the long years need no special case.\n */\nexport function shiftWeekValue(value: string, by: number): string | null {\n  const monday = mondayFromValue(value)\n  if (monday === null) return null\n  const moved = weekOfDayNumber(monday + by * DAYS_PER_WEEK)\n  if (moved.weekYear < FIRST_WEEK_YEAR || moved.weekYear > LAST_WEEK_YEAR) return null\n  return weekValueOf(moved.weekYear, moved.week)\n}\n\n/**\n * A locale with the calendar and digits pinned to the ones the ISO week is defined on.\n *\n * Not fussiness. Asked to write 9 February 2026, `th-TH` answers 2569, `ja-JP-u-ca-japanese`\n * answers 令和8年, `ar-EG` answers in Arabic-Indic digits and `fa-IR` answers 20 Bahman 1404 — a\n * different day of a different month. Any of those printed under a cell whose value is \"2026-W07\"\n * makes the label and the value disagree, and the reader has no way to tell which one the form will\n * post. Language and date order still follow the locale; only the calendar is held still.\n *\n * Built through `Intl.Locale` rather than by appending \"-u-ca-gregory\" to the tag, because a locale\n * that already carries an extension — `ja-JP-u-ca-japanese` is the common one — produces an invalid\n * tag that way and throws. A malformed `locale` prop throws here too, and falls back to the\n * runtime's own rather than taking the page down.\n */\nfunction gregorianLocale(locale: string | undefined): string | undefined {\n  try {\n    const base = new Intl.Locale(locale ?? new Intl.DateTimeFormat().resolvedOptions().locale)\n    return new Intl.Locale(base.baseName, {\n      calendar: \"gregory\",\n      numberingSystem: \"latn\",\n    }).toString()\n  } catch {\n    return undefined\n  }\n}\n\n/**\n * The reader's word for \"week\", from CLDR.\n *\n * `Intl.DisplayNames` is cast and tried rather than called plainly because \"dateTimeField\" is newer\n * than the ES2020 type surface this registry targets, and a runtime without it throws rather than\n * returning nothing. The English fallback is a last resort, not the default — a component that\n * localises its dates and then announces them as \"Week 7\" is only half translated.\n */\nfunction weekWordIn(locale: string | undefined): string {\n  try {\n    const DisplayNames = Intl.DisplayNames as unknown as {\n      new (locales: string | undefined, options: { type: string }): { of(code: string): string }\n    }\n    return new DisplayNames(locale, { type: \"dateTimeField\" }).of(\"weekOfYear\") || \"week\"\n  } catch {\n    return \"week\"\n  }\n}\n\n/** A `Date` at noon UTC on a calendar date, for handing to `Intl` and nothing else. */\nfunction utcNoonOf(dayNumber: number): Date {\n  return new Date(dayNumber * MS_PER_DAY + MS_PER_DAY / 2)\n}\n\nfunction formatDayRange(\n  formatter: Intl.DateTimeFormat,\n  startDay: number,\n  endDay: number\n): string {\n  // `formatRange` collapses what the two dates share (\"Feb 9 – 15, 2026\") and puts the dash where\n  // the locale wants it. Cast because this registry targets lib ES2020, where it is not in the type\n  // surface yet, and feature-detected so a runtime that predates it still renders a readable range\n  // instead of crashing.\n  const withRange = formatter as Intl.DateTimeFormat & {\n    formatRange?: (start: Date, end: Date) => string\n  }\n  const start = utcNoonOf(startDay)\n  const end = utcNoonOf(endDay)\n  if (typeof withRange.formatRange === \"function\") return withRange.formatRange(start, end)\n  return `${formatter.format(start)} – ${formatter.format(end)}`\n}\n\nexport interface WeekPickerProps\n  extends Omit<\n    React.ComponentPropsWithoutRef<\"div\">,\n    \"onChange\" | \"value\" | \"defaultValue\" | \"children\"\n  > {\n  /** Controlled week as `YYYY-Www`, e.g. \"2026-W07\". Pair with `onValueChange`. */\n  value?: string\n  /** Starting week for an uncontrolled picker. Ignored once `value` is passed. */\n  defaultValue?: string\n  /** Called with the chosen `YYYY-Www`. Never called for a week outside `min`/`max`. */\n  onValueChange?: (value: string) => void\n  /** Controlled week-year on display. Pair with `onWeekYearChange` — see the note on that prop. */\n  weekYear?: number\n  /**\n   * Week-year the grid opens on when nothing is selected. Also the way to make a server render\n   * deterministic: without any of `value`, `defaultValue` or `weekYear`, the opening year comes\n   * from the machine's clock, which the server and the browser can disagree about in the days\n   * around New Year — precisely where the week-year is already its least obvious.\n   */\n  defaultWeekYear?: number\n  /**\n   * Called with the week-year the grid moved to. **Required if you pass `weekYear`**: the arrow\n   * keys leave the displayed year at its edges, and a controlled year that is never updated pins\n   * them inside it.\n   */\n  onWeekYearChange?: (weekYear: number) => void\n  /** Earliest selectable week as `YYYY-Www`, inclusive. Also stops the year arrows. */\n  min?: string\n  /** Latest selectable week as `YYYY-Www`, inclusive. Also stops the year arrows. */\n  max?: string\n  /**\n   * Disables individual weeks on top of `min`/`max` — a closed payroll period, a week with no data.\n   * Called with `YYYY-Www`. Unlike `min`/`max` it does not stop the year arrows, since holes can be\n   * scattered and a year of them is still worth being able to look at.\n   */\n  isWeekDisabled?: (value: string) => boolean\n  /** BCP-47 tag for the dates, e.g. \"ja-JP\". Defaults to the browser's own locale. */\n  locale?: string\n  /** Weeks per row. Default 4. */\n  columns?: 3 | 4 | 6\n  /**\n   * Writes each cell's accessible name. The default is the localised word for \"week\", the number,\n   * and the week's dates — \"week 7, Feb 9 – 15, 2026\".\n   */\n  formatWeekLabel?: (info: {\n    /** The full value, e.g. \"2026-W07\". */\n    value: string\n    /** Week number, from 1. */\n    week: number\n    /** The week-year, which is not always the calendar year of the dates. */\n    weekYear: number\n    /** The week's dates, already localised, e.g. \"Feb 9 – 15, 2026\". */\n    dates: string\n    /** Inclusive calendar dates as \"YYYY-MM-DD\". */\n    start: string\n    end: string\n  }) => string\n  /** Submits the value with a surrounding form, through a hidden input. */\n  name?: string\n  /** Accessible name of the back arrow. */\n  previousYearLabel?: string\n  /** Accessible name of the forward arrow. */\n  nextYearLabel?: string\n}\n\nconst COLUMN_CLASS: Record<3 | 4 | 6, string> = {\n  3: \"grid-cols-3\",\n  4: \"grid-cols-4\",\n  6: \"grid-cols-6\",\n}\n\n/**\n * A week-year of ISO weeks as a grid — pick the week itself, not a day inside it.\n *\n * ```tsx\n * const [week, setWeek] = React.useState(\"2026-W07\")\n *\n * return <WeekPicker value={week} onValueChange={setWeek} max={toWeekValue(new Date())} />\n * ```\n *\n * The value is a plain `YYYY-Www` string — the same one `<input type=\"week\">` produces, for an\n * input Firefox and Safari have never shipped. It sorts and compares as it reads, carries no day\n * and no time zone, and `weekDates` turns it into the two calendar dates a query needs.\n */\nexport const WeekPicker = React.forwardRef<HTMLDivElement, WeekPickerProps>(function WeekPicker(\n  {\n    className,\n    value: valueProp,\n    defaultValue,\n    onValueChange,\n    weekYear: weekYearProp,\n    defaultWeekYear,\n    onWeekYearChange,\n    min,\n    max,\n    isWeekDisabled,\n    locale,\n    columns = 4,\n    formatWeekLabel,\n    name,\n    previousYearLabel = \"Previous year\",\n    nextYearLabel = \"Next year\",\n    ...props\n  },\n  ref\n) {\n  const captionId = React.useId()\n\n  /**\n   * Guards the two things here that come from the machine rather than from props: the locale the\n   * dates are written in, and which week is \"this\" one. Both render as their neutral form until\n   * mount, so the server's output and the browser's first render agree.\n   */\n  const [mounted, setMounted] = React.useState(false)\n  React.useEffect(() => {\n    setMounted(true)\n  }, [])\n\n  const isValueControlled = valueProp !== undefined\n  const [uncontrolledValue, setUncontrolledValue] = React.useState(defaultValue ?? \"\")\n  const value = isValueControlled ? valueProp : uncontrolledValue\n\n  const isYearControlled = weekYearProp !== undefined\n  const [uncontrolledYear, setUncontrolledYear] = React.useState(() => {\n    const selected = parseWeekValue(valueProp ?? defaultValue ?? \"\")\n    if (selected) return selected.weekYear\n    if (defaultWeekYear !== undefined) return defaultWeekYear\n    // The *week-year* of today, which in the last days of December is already the next one.\n    return parseWeekValue(toWeekValue(new Date()))?.weekYear ?? FIRST_WEEK_YEAR\n  })\n  const displayYear = Math.min(\n    Math.max(isYearControlled ? weekYearProp : uncontrolledYear, FIRST_WEEK_YEAR),\n    LAST_WEEK_YEAR\n  )\n\n  const weekCount = weeksInWeekYear(displayYear)\n  const firstMonday = mondayOfFirstWeek(displayYear)\n\n  const [focusedWeek, setFocusedWeek] = React.useState(\n    () => parseWeekValue(valueProp ?? defaultValue ?? \"\")?.week ?? 1\n  )\n\n  /**\n   * A selection made from outside pulls the grid to it. Without this a parent that sets the value\n   * to a week in another year leaves the grid where it was, showing a year of unselected cells with\n   * no hint that the choice landed somewhere off screen.\n   *\n   * Written as an adjustment during render rather than an effect so the corrected year paints in the\n   * same commit as the new value, with no frame showing the old one.\n   */\n  const [lastValue, setLastValue] = React.useState(value)\n  if (value !== lastValue) {\n    setLastValue(value)\n    const selected = parseWeekValue(value)\n    if (selected) {\n      setFocusedWeek(selected.week)\n      if (!isYearControlled && selected.weekYear !== uncontrolledYear) {\n        setUncontrolledYear(selected.weekYear)\n      }\n    }\n  }\n\n  // A 53-week year followed by a 52-week one would otherwise leave the focus on a cell that is not\n  // rendered, and the grid would have no tab stop at all.\n  const safeFocusedWeek = Math.min(focusedWeek, weekCount)\n\n  const labelLocale = locale ?? (mounted ? undefined : HYDRATION_LOCALE)\n  const formatted = React.useMemo(() => {\n    const pinned = gregorianLocale(labelLocale)\n    const word = weekWordIn(pinned)\n    // The cell shows where the week starts, because a column of bare numbers answers \"which week is\n    // this\" with another question. The accessible name carries the whole range and the year, since\n    // \"9\" on its own stops meaning anything the moment the arrows have moved.\n    const short = new Intl.DateTimeFormat(pinned, {\n      month: \"short\",\n      day: \"numeric\",\n      timeZone: \"UTC\",\n    })\n    const full = new Intl.DateTimeFormat(pinned, {\n      year: \"numeric\",\n      month: \"short\",\n      day: \"numeric\",\n      timeZone: \"UTC\",\n    })\n    return Array.from({ length: weekCount }, (_, index) => {\n      const week = index + 1\n      const monday = firstMonday + index * DAYS_PER_WEEK\n      const sunday = monday + DAYS_PER_WEEK - 1\n      const dates = formatDayRange(full, monday, sunday)\n      const start = toDateKey(civilFromDayNumber(monday))\n      const end = toDateKey(civilFromDayNumber(sunday))\n      // Deliberately not named `value`: that is the *selected* week a few lines up, and a cell\n      // carrying the same name for \"the week this cell is\" is one rename away from a picker that\n      // selects whatever it last drew.\n      const cellValue = weekValueOf(displayYear, week)\n      return {\n        week,\n        value: cellValue,\n        start,\n        end,\n        startText: short.format(utcNoonOf(monday)),\n        label: formatWeekLabel\n          ? formatWeekLabel({ value: cellValue, week, weekYear: displayYear, dates, start, end })\n          : `${word} ${week}, ${dates}`,\n      }\n    })\n  }, [labelLocale, weekCount, firstMonday, displayYear, formatWeekLabel])\n\n  const currentMonday = React.useMemo(() => {\n    if (!mounted) return null\n    return mondayFromValue(toWeekValue(new Date()))\n  }, [mounted])\n\n  const minMonday = mondayFromValue(min)\n  const maxMonday = mondayFromValue(max)\n  const selectedMonday = mondayFromValue(value)\n\n  const mondayOfWeek = (week: number) => firstMonday + (week - 1) * DAYS_PER_WEEK\n\n  const outOfRange = (monday: number) =>\n    (minMonday !== null && monday < minMonday) || (maxMonday !== null && monday > maxMonday)\n\n  const disabledAt = (week: number) => {\n    if (outOfRange(mondayOfWeek(week))) return true\n    return isWeekDisabled ? isWeekDisabled(weekValueOf(displayYear, week)) : false\n  }\n\n  /**\n   * Whether the neighbouring year holds anything selectable.\n   *\n   * Measured from that year's own last and first Monday rather than from this one's, because the\n   * two are not seven days apart when a 53-week year is involved.\n   */\n  const previousYearLastMonday =\n    displayYear > FIRST_WEEK_YEAR\n      ? mondayOfFirstWeek(displayYear - 1) + (weeksInWeekYear(displayYear - 1) - 1) * DAYS_PER_WEEK\n      : null\n  const nextYearFirstMonday =\n    displayYear < LAST_WEEK_YEAR ? mondayOfFirstWeek(displayYear + 1) : null\n\n  const canGoBack =\n    previousYearLastMonday !== null &&\n    (minMonday === null || previousYearLastMonday >= minMonday)\n  const canGoForward =\n    nextYearFirstMonday !== null && (maxMonday === null || nextYearFirstMonday <= maxMonday)\n\n  const gridRef = React.useRef<HTMLDivElement>(null)\n  const cellsRef = React.useRef<Array<HTMLButtonElement | null>>([])\n  // Set only by keyboard navigation, so the grid never steals focus on mount or on a parent's\n  // unrelated re-render — it moves focus when, and only when, the user asked it to.\n  const focusPending = React.useRef(false)\n\n  React.useEffect(() => {\n    if (!focusPending.current) return\n    focusPending.current = false\n    cellsRef.current[safeFocusedWeek - 1]?.focus()\n  }, [safeFocusedWeek, displayYear])\n\n  const changeYear = (next: number) => {\n    const clamped = Math.min(Math.max(next, FIRST_WEEK_YEAR), LAST_WEEK_YEAR)\n    if (!isYearControlled) setUncontrolledYear(clamped)\n    onWeekYearChange?.(clamped)\n  }\n\n  const select = (week: number) => {\n    if (disabledAt(week)) return\n    const next = weekValueOf(displayYear, week)\n    setFocusedWeek(week)\n    if (!isValueControlled) setUncontrolledValue(next)\n    onValueChange?.(next)\n  }\n\n  /**\n   * Walks the calendar rather than the grid: a step off either edge lands in the neighbouring\n   * week-year, and the move is made over Mondays so the long years need no special case.\n   */\n  const moveFocusToMonday = (monday: number) => {\n    let target = monday\n    if (minMonday !== null && target < minMonday) target = minMonday\n    if (maxMonday !== null && target > maxMonday) target = maxMonday\n    const moved = weekOfDayNumber(target)\n    if (moved.weekYear < FIRST_WEEK_YEAR || moved.weekYear > LAST_WEEK_YEAR) return\n    focusPending.current = true\n    setFocusedWeek(moved.week)\n    if (moved.weekYear !== displayYear) changeYear(moved.weekYear)\n  }\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    // The rows run with the writing direction, so on an RTL page the cell to the right of the\n    // focused one is the *earlier* week. Read at event time, where there is a real element and no\n    // render to keep deterministic.\n    const rtl = gridRef.current ? getComputedStyle(gridRef.current).direction === \"rtl\" : false\n    const inline = rtl ? -1 : 1\n    const current = mondayOfWeek(safeFocusedWeek)\n    let target: number\n    switch (event.key) {\n      case \"ArrowRight\":\n        target = current + inline * DAYS_PER_WEEK\n        break\n      case \"ArrowLeft\":\n        target = current - inline * DAYS_PER_WEEK\n        break\n      case \"ArrowDown\":\n        target = current + columns * DAYS_PER_WEEK\n        break\n      case \"ArrowUp\":\n        target = current - columns * DAYS_PER_WEEK\n        break\n      // Rows here are a layout choice — three, four or six across — and mean nothing on a calendar,\n      // so Home and End go to the ends of the *year* rather than of the row as they would in a grid\n      // of data.\n      case \"Home\":\n        target = firstMonday\n        break\n      case \"End\":\n        target = mondayOfWeek(weekCount)\n        break\n      // Holds the week number and walks the years, clamped at the end of a 52-week year so W53\n      // never lands on a cell that does not exist.\n      case \"PageUp\":\n      case \"PageDown\": {\n        const nextYear = displayYear + (event.key === \"PageUp\" ? -1 : 1)\n        if (nextYear < FIRST_WEEK_YEAR || nextYear > LAST_WEEK_YEAR) {\n          event.preventDefault()\n          return\n        }\n        const week = Math.min(safeFocusedWeek, weeksInWeekYear(nextYear))\n        target = mondayOfFirstWeek(nextYear) + (week - 1) * DAYS_PER_WEEK\n        break\n      }\n      default:\n        return\n    }\n    event.preventDefault()\n    moveFocusToMonday(target)\n  }\n\n  const rows: Array<Array<(typeof formatted)[number]>> = []\n  for (let start = 0; start < formatted.length; start += columns) {\n    rows.push(formatted.slice(start, start + columns))\n  }\n\n  return (\n    <div ref={ref} className={cn(\"w-full max-w-xs space-y-3\", className)} {...props}>\n      <div className=\"flex items-center justify-between gap-2\">\n        <YearArrow\n          direction=\"back\"\n          label={previousYearLabel}\n          disabled={!canGoBack}\n          onClick={() => changeYear(displayYear - 1)}\n        />\n        {/*\n          Live because the arrows change what the grid means without moving focus: a sighted user\n          watches the year tick over, and this is the same event reaching everyone else.\n\n          Written as a plain number rather than through `Intl`, because this is the week-year of the\n          value — the one the form will post — and a locale on a different calendar would print 2569\n          beside a value that says 2026.\n        */}\n        <div\n          id={captionId}\n          aria-live=\"polite\"\n          className=\"flex-1 text-center text-sm font-medium tabular-nums\"\n        >\n          {displayYear}\n        </div>\n        <YearArrow\n          direction=\"forward\"\n          label={nextYearLabel}\n          disabled={!canGoForward}\n          onClick={() => changeYear(displayYear + 1)}\n        />\n      </div>\n\n      <div\n        ref={gridRef}\n        role=\"grid\"\n        aria-labelledby={captionId}\n        onKeyDown={handleKeyDown}\n        className=\"space-y-1\"\n      >\n        {rows.map((row) => (\n          <div key={row[0].week} role=\"row\" className={cn(\"grid gap-1\", COLUMN_CLASS[columns])}>\n            {row.map((cell) => {\n              const monday = mondayOfWeek(cell.week)\n              const isSelected = selectedMonday === monday\n              const isCurrent = currentMonday === monday\n              const isDisabled = disabledAt(cell.week)\n              return (\n                <div key={cell.week} role=\"gridcell\" aria-selected={isSelected}>\n                  <button\n                    ref={(node) => {\n                      cellsRef.current[cell.week - 1] = node\n                    }}\n                    type=\"button\"\n                    // Roving tabindex: one stop for the whole grid, then the arrow keys inside it.\n                    // Fifty-three tab stops per year is the thing this replaces.\n                    tabIndex={cell.week === safeFocusedWeek ? 0 : -1}\n                    aria-label={cell.label}\n                    // `aria-disabled` rather than `disabled`, so an unavailable week can still be\n                    // reached and read. A week the arrow keys skip over silently is a week the user\n                    // cannot tell exists.\n                    aria-disabled={isDisabled || undefined}\n                    aria-current={isCurrent ? \"date\" : undefined}\n                    onClick={() => select(cell.week)}\n                    onFocus={() => setFocusedWeek(cell.week)}\n                    className={cn(\n                      \"flex w-full flex-col items-center justify-center gap-0.5 rounded-md px-1 py-1.5 transition-colors\",\n                      \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n                      isDisabled\n                        ? \"cursor-default text-muted-foreground opacity-50\"\n                        : \"hover:bg-accent hover:text-accent-foreground\",\n                      isCurrent && !isSelected && \"bg-accent/60 font-medium text-accent-foreground\",\n                      isSelected &&\n                        \"bg-primary text-primary-foreground hover:bg-primary/90 hover:text-primary-foreground\"\n                    )}\n                  >\n                    <span className=\"text-sm leading-none tabular-nums\">{cell.week}</span>\n                    {/*\n                      Hidden from the reading order because the accessible name above already says\n                      the whole range — announcing \"Feb 9\" after \"week 7, Feb 9 – 15, 2026\" is the\n                      same date twice.\n                    */}\n                    <span\n                      aria-hidden=\"true\"\n                      className={cn(\n                        \"text-[10px] leading-none\",\n                        isSelected ? \"opacity-80\" : \"text-muted-foreground\"\n                      )}\n                    >\n                      {cell.startText}\n                    </span>\n                  </button>\n                </div>\n              )\n            })}\n          </div>\n        ))}\n      </div>\n\n      {/* Lets the picker post with a plain form or a server action, with no state plumbing. */}\n      {name ? <input type=\"hidden\" name={name} value={value} /> : null}\n    </div>\n  )\n})\n\nfunction YearArrow({\n  direction,\n  label,\n  disabled,\n  onClick,\n}: {\n  direction: \"back\" | \"forward\"\n  label: string\n  disabled: boolean\n  onClick: () => void\n}) {\n  return (\n    <button\n      type=\"button\"\n      onClick={onClick}\n      disabled={disabled}\n      aria-label={label}\n      className={cn(\n        \"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-input bg-transparent text-muted-foreground transition-colors\",\n        \"hover:bg-accent hover:text-accent-foreground\",\n        \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n        \"disabled:pointer-events-none disabled:opacity-40\"\n      )}\n    >\n      {/* Inline, so two glyphs cost no icon dependency. */}\n      <svg\n        className=\"h-4 w-4 rtl:-scale-x-100\"\n        width=\"16\"\n        height=\"16\"\n        viewBox=\"0 0 24 24\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        aria-hidden=\"true\"\n      >\n        <path d={direction === \"back\" ? \"m15 18-6-6 6-6\" : \"m9 18 6-6-6-6\"} />\n      </svg>\n    </button>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui",
  "docs": "Install any pulld component by name: add \"@pulld\": \"https://pulld.pages.dev/r/{name}.json\" to the registries block in components.json, then `npx shadcn add @pulld/<name>`. All 149 components: https://pulld.pages.dev/?utm_source=cli"
}
