An open source design system that's fully customizable and agent ready
TypeScript
docs(useCalendarConstraints): add hook docs and a hotel booking range example block (#10151)
Utkarsh patwa62c7802e873e
diff --git a/.changeset/hook-doc-use-calendar-constraints.md b/.changeset/hook-doc-use-calendar-constraints.mdnew file mode 100644index 0000000000..8d450d366c--- /dev/null+++ b/.changeset/hook-doc-use-calendar-constraints.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[docs] Hook docs for `useCalendarConstraints`, so `astryx hook useCalendarConstraints` and `astryx search` return it, and a `useCalendarConstraints — Hotel Booking Range` example block: a booking range picker that enforces min/max dates, disables closed Mondays, and caps reservations at 7 nights once check-in is selected. Copy it with `astryx template useCalendarConstraintsHookUsage <path>`.++@utkarshpatwa393-sysdiff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex e2fbf2c366..86b592d476 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -794,6 +794,7 @@"/templates/table/","/templates/theme-showcase/","/templates/useAnnounceHookUsage/",+ "/templates/useCalendarConstraintsHookUsage/","/templates/useCalendarDaysHookUsage/","/templates/useCalendarNavigationHookUsage/","/templates/useClickableContainerHookUsage/",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 9e5c50c185..f76fbf320a 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3711,6 +3711,11 @@"path": "examples/use-app-shell-mobile/custom-mobile-trigger","aliases": []},+ {+ "name": "example-use-calendar-constraints-hotel-booking-range",+ "path": "examples/use-calendar-constraints/hotel-booking-range",+ "aliases": []+ },{"name": "example-use-calendar-days-month-grid","path": "examples/use-calendar-days/month-grid",@@ -4031,6 +4036,11 @@"path": "hooks/use-app-shell-mobile","aliases": []},+ {+ "name": "hook-use-calendar-constraints",+ "path": "hooks/use-calendar-constraints",+ "aliases": []+ },{"name": "hook-use-calendar-days","path": "hooks/use-calendar-days",diff --git a/packages/cli/api/component/__fixtures__/resolutions/modules.txt b/packages/cli/api/component/__fixtures__/resolutions/modules.txtindex 6e41d1a8ee..7c4098115a 100644--- a/packages/cli/api/component/__fixtures__/resolutions/modules.txt+++ b/packages/cli/api/component/__fixtures__/resolutions/modules.txt@@ -247,7 +247,7 @@ useAutoMediaMode useAutoMediaMode hooks/useAnimatedLayout.doc.mjs hooks/useAutoMuseBackdropPress useBackdropPress Layer/Layer.doc.mjs Layer/useBackdropPress.tsuseBaseTablePlugins useBaseTablePlugins Table/Table.doc.mjs Table/useBaseTablePlugins.tsuseBusyAnnouncement useBusyAnnouncement hooks/useAnimatedLayout.doc.mjs hooks/useBusyAnnouncement.ts-useCalendarConstraints useCalendarConstraints Calendar/Calendar.doc.mjs Calendar/hooks/useCalendarConstraints.ts+useCalendarConstraints useCalendarConstraints Calendar/useCalendarConstraints.doc.mjs Calendar/hooks/useCalendarConstraints.tsuseCalendarDays useCalendarDays Calendar/useCalendarDays.doc.mjs Calendar/hooks/useCalendarDays.tsuseCalendarNavigation useCalendarNavigation Calendar/useCalendarNavigation.doc.mjs Calendar/hooks/useCalendarNavigation.tsuseChatComposerTokens useChatComposerTokens Chat/Chat.doc.mjs Chat/useChatComposerTokens.tsdiff --git a/packages/cli/api/template/use-calendar-constraints-hook-usage.test.tsx b/packages/cli/api/template/use-calendar-constraints-hook-usage.test.tsxnew file mode 100644index 0000000000..f5d6ebea2f--- /dev/null+++ b/packages/cli/api/template/use-calendar-constraints-hook-usage.test.tsx@@ -0,0 +1,131 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @vitest-environment jsdom++/**+ * The useCalendarConstraints example demonstrates a hotel booking range picker+ * enforcing season bounds (Jun 5 - Jun 25), closed Mondays, and a 7-night+ * maximum stay once check-in is selected.+ */++import {act} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import UseCalendarConstraintsHookUsage from '../../assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage';++(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =+ true;++let root: Root | null = null;+let container: HTMLElement;++function findButtonByDay(dayNumber: number): HTMLButtonElement | undefined {+ const buttons = Array.from(+ container.querySelectorAll('tbody button'),+ ) as HTMLButtonElement[];+ return buttons.find(btn => btn.textContent?.trim() === String(dayNumber));+}++function clickDay(dayNumber: number): void {+ const btn = findButtonByDay(dayNumber);+ expect(btn).toBeDefined();+ act(() => {+ btn?.click();+ });+}++function clickReset(): void {+ const resetBtn = Array.from(container.querySelectorAll('button')).find(+ btn => btn.textContent?.trim() === 'Reset',+ );+ expect(resetBtn).toBeDefined();+ act(() => {+ resetBtn?.click();+ });+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root?.render(<UseCalendarConstraintsHookUsage />);+ });+});++afterEach(() => {+ if (root) {+ act(() => {+ root?.unmount();+ });+ }+ container.remove();+});++describe('UseCalendarConstraintsHookUsage', () => {+ it('disables dates outside season bounds and on closed Mondays initially', () => {+ // June 1, 2026 is Monday and before min (Jun 5) -> disabled+ expect(findButtonByDay(1)?.disabled).toBe(true);+ // June 4, 2026 is Thursday before min -> disabled+ expect(findButtonByDay(4)?.disabled).toBe(true);++ // June 5, 2026 is Friday (season start) -> enabled+ expect(findButtonByDay(5)?.disabled).toBe(false);++ // June 8, 2026 is Monday -> disabled by custom rule+ expect(findButtonByDay(8)?.disabled).toBe(true);++ // June 15, 2026 is Monday -> disabled by custom rule+ expect(findButtonByDay(15)?.disabled).toBe(true);++ // June 25, 2026 is Thursday (season end) -> enabled+ expect(findButtonByDay(25)?.disabled).toBe(false);++ // June 26, 2026 is Friday (after max) -> disabled+ expect(findButtonByDay(26)?.disabled).toBe(true);+ });++ it('restricts dates beyond maxRangeSpan after check-in is picked and restores after booking', () => {+ // Pick check-in: June 5+ clickDay(5);++ expect(container.textContent).toContain('Check-in: Jun 5 (pick check-out)');+ expect(findButtonByDay(5)?.getAttribute('aria-pressed')).toBe('true');++ // With check-in on Jun 5 and maxRangeSpan 8:+ // Reachable span is 7 nights: June 5 to June 12+ // June 10 (Wednesday) is within 7 nights -> enabled+ expect(findButtonByDay(10)?.disabled).toBe(false);+ // June 12 (Friday, exactly 7 nights) -> enabled+ expect(findButtonByDay(12)?.disabled).toBe(false);+ // June 13 (Saturday, 8 nights away) -> disabled by maxRangeSpan!+ expect(findButtonByDay(13)?.disabled).toBe(true);++ // Pick check-out: June 10+ clickDay(10);+ expect(container.textContent).toContain('Booked: Jun 5 – Jun 10');+ expect(findButtonByDay(10)?.getAttribute('aria-pressed')).toBe('true');++ // Once booked, rangeAnchor is cleared so later dates (e.g. June 13) are no longer capped+ expect(findButtonByDay(13)?.disabled).toBe(false);++ // Click Reset+ clickReset();+ expect(container.textContent).toContain('Pick a check-in date');+ expect(findButtonByDay(5)?.getAttribute('aria-pressed')).toBe('false');+ });++ it('treats a pick on or before check-in as a new check-in (reverse pick)', () => {+ // Pick check-in: June 12+ clickDay(12);+ expect(container.textContent).toContain(+ 'Check-in: Jun 12 (pick check-out)',+ );++ // Reverse pick: click June 6 (earlier than June 12)+ clickDay(6);+ // Should now become the new check-in date+ expect(container.textContent).toContain('Check-in: Jun 6 (pick check-out)');+ expect(findButtonByDay(6)?.getAttribute('aria-pressed')).toBe('true');+ expect(findButtonByDay(12)?.getAttribute('aria-pressed')).toBe('false');+ });+});diff --git a/packages/cli/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.doc.mjsnew file mode 100644index 0000000000..15c51ecaf8--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'useCalendarConstraints',+ name: 'useCalendarConstraints — Hotel Booking Range',+ displayName: 'useCalendarConstraints — Hotel Booking Range',+ description:+ 'A hotel booking range picker enforcing season min/max dates, a 7-night maximum stay once check-in is picked, and a custom rule disabling closed Mondays.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['Button', 'Layout', 'Text'],+};diff --git a/packages/cli/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.tsxnew file mode 100644index 0000000000..72677b3fe5--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.tsx@@ -0,0 +1,146 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useState} from 'react';+import {+ useCalendarConstraints,+ useCalendarDays,+ type CalendarDay,+} from '@astryxdesign/core/Calendar';+import {Button} from '@astryxdesign/core/Button';+import {HStack, VStack} from '@astryxdesign/core/Layout';+import {Text} from '@astryxdesign/core/Text';++// Hotel closed on Mondays (day === 1)+const isNotMonday = (date: Date) => date.getDay() !== 1;++export default function UseCalendarConstraintsHookUsage() {+ const [checkIn, setCheckIn] = useState<CalendarDay['date'] | null>(null);+ const [checkOut, setCheckOut] = useState<CalendarDay['date'] | null>(null);++ // June 2026 season: open Jun 5 – Jun 25, max 7 nights (8-day span), closed Mondays.+ // When checkOut is already chosen, clear rangeAnchor so full season remains viewable without lingering span restrictions.+ const {isDateDisabled} = useCalendarConstraints({+ min: '2026-06-05',+ max: '2026-06-25',+ maxRangeSpan: 8,+ rangeAnchor: checkOut ? null : checkIn,+ dateConstraints: [isNotMonday],+ });++ const {weeks, dayNames} = useCalendarDays({+ year: 2026,+ month: 6,+ weekStartsOn: 0,+ hasVariableRowCount: true,+ });++ const handleSelect = (day: CalendarDay) => {+ if (day.isOutside || isDateDisabled(day.date)) {+ return;+ }+ // If no check-in yet, or already booked, or clicking on/before current check-in: start new check-in+ if (!checkIn || checkOut || day.date.day <= checkIn.day) {+ setCheckIn(day.date);+ setCheckOut(null);+ } else {+ // Pick is after checkIn: set as check-out+ setCheckOut(day.date);+ }+ };++ const handleReset = () => {+ setCheckIn(null);+ setCheckOut(null);+ };++ return (+ <VStack gap={3}>+ <VStack gap={1}>+ <Text type="body" weight="bold">+ Hotel Booking — June 2026+ </Text>+ <Text type="supporting" color="secondary">+ Season: Jun 5 – Jun 25 · Max stay: 7 nights · Closed Mondays+ </Text>+ </VStack>+ <HStack gap={2} vAlign="center">+ <Text type="supporting">+ {checkIn+ ? checkOut+ ? `Booked: Jun ${checkIn.day} – Jun ${checkOut.day}`+ : `Check-in: Jun ${checkIn.day} (pick check-out)`+ : 'Pick a check-in date'}+ </Text>+ {checkIn && (+ <Button+ label="Reset"+ size="sm"+ variant="secondary"+ onClick={handleReset}+ />+ )}+ </HStack>+ <table style={{tableLayout: 'fixed', width: 280}}>+ <thead>+ <tr>+ {dayNames.map((name, i) => (+ <th key={i} scope="col">+ <Text type="supporting" color="secondary">+ {name}+ </Text>+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {weeks.map(week => (+ <tr key={week[0].iso}>+ {week.map(day => {+ if (day.isOutside) {+ return <td key={day.iso} align="center" />;+ }++ const disabled = isDateDisabled(day.date);+ const isSelected =+ (checkIn &&+ checkIn.day === day.date.day &&+ checkIn.month === day.date.month) ||+ (checkOut &&+ checkOut.day === day.date.day &&+ checkOut.month === day.date.month);++ return (+ <td key={day.iso} align="center">+ <button+ type="button"+ disabled={disabled}+ onClick={() => handleSelect(day)}+ aria-pressed={isSelected ? 'true' : 'false'}+ aria-label={`June ${day.dayNumber}`}+ style={{+ width: 32,+ height: 32,+ borderRadius: 6,+ border: isSelected ? '1px solid currentColor' : 'none',+ background: 'transparent',+ opacity: disabled ? 0.35 : 1,+ cursor: disabled ? 'not-allowed' : 'pointer',+ }}>+ <Text+ type="body"+ color={disabled ? 'secondary' : 'primary'}>+ {day.dayNumber}+ </Text>+ </button>+ </td>+ );+ })}+ </tr>+ ))}+ </tbody>+ </table>+ </VStack>+ );+}diff --git a/packages/core/src/Calendar/useCalendarConstraints.doc.mjs b/packages/core/src/Calendar/useCalendarConstraints.doc.mjsnew file mode 100644index 0000000000..20974d40ed--- /dev/null+++ b/packages/core/src/Calendar/useCalendarConstraints.doc.mjs@@ -0,0 +1,151 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').HookDoc} */+export const docs = {+ name: 'useCalendarConstraints',+ displayName: 'useCalendarConstraints',+ group: 'Calendar',+ keywords: [+ 'calendar',+ 'constraints',+ 'isDateDisabled',+ 'dateConstraints',+ 'min',+ 'max',+ 'rangeSpan',+ 'rangeAnchor',+ 'disabled dates',+ 'hotel booking',+ ],+ params: [+ {+ name: 'options',+ type: 'UseCalendarConstraintsOptions',+ description: 'Configuration for date bounds, range-span limits, and custom rules.',+ required: true,+ },+ {+ name: 'options.min',+ type: 'ISODateString',+ description:+ 'Earliest selectable date in ISO format (YYYY-MM-DD). Dates strictly before this are disabled.',+ required: false,+ },+ {+ name: 'options.max',+ type: 'ISODateString',+ description:+ 'Latest selectable date in ISO format (YYYY-MM-DD). Dates strictly after this are disabled.',+ required: false,+ },+ {+ name: 'options.dateConstraints',+ type: 'ReadonlyArray<(date: Date) => boolean>',+ description:+ 'Custom date constraint predicates. Receives a native Date; if any returns false, the date is disabled.',+ required: false,+ },+ {+ name: 'options.maxRangeSpan',+ type: 'number',+ description:+ 'Maximum days a range may span, counting both endpoints (a value of 7 allows a 7-day window). Inactive until rangeAnchor is set.',+ required: false,+ },+ {+ name: 'options.minRangeSpan',+ type: 'number',+ description:+ 'Minimum days a range must span, counting both endpoints. Disables dates that would make the range shorter than minRangeSpan days (except rangeAnchor itself, which remains enabled so pickers forbidding single-day selections must refuse a second click on the anchor).',+ required: false,+ },+ {+ name: 'options.rangeAnchor',+ type: 'PlainDate | null',+ description:+ 'The in-progress range start date. Span constraints are measured from this date. Null when no selection is underway.',+ required: false,+ },+ ],+ returns: [+ {+ name: 'isDateDisabled',+ type: '(date: PlainDate) => boolean',+ description:+ 'Predicate returning true when a PlainDate falls outside min/max bounds, is closer to rangeAnchor than minRangeSpan allows (except rangeAnchor itself), exceeds maxRangeSpan relative to rangeAnchor, or fails any dateConstraints predicate.',+ },+ {+ name: 'minDate',+ type: 'PlainDate | null',+ description: 'Parsed minimum date as a PlainDate object, or null if min was not provided.',+ },+ {+ name: 'maxDate',+ type: 'PlainDate | null',+ description: 'Parsed maximum date as a PlainDate object, or null if max was not provided.',+ },+ ],+ usage: {+ description:+ 'Provides date constraint validation for calendar views and custom range pickers. It combines boundary dates, span limits measured from an in-progress range start, and custom rules (such as weekly closures or blackout dates) into an isDateDisabled predicate. Calendar uses it internally to disable day buttons; use it directly when building bespoke scheduling interfaces or range pickers.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Pass rangeAnchor only after the user selects an initial range start, so all eligible start dates remain selectable before the first click.',+ },+ {+ guidance: true,+ description:+ 'Use dateConstraints for recurring or dynamic rules, such as disabling closed weekdays, past holidays, or sold-out dates.',+ },+ {+ guidance: false,+ description:+ 'Perform slow network calls or heavy calculations inside dateConstraints predicates, because isDateDisabled is evaluated synchronously for each day rendered in the grid.',+ },+ ],+ },+ relatedComponents: ['Calendar'],+ relatedHooks: ['useCalendarDays', 'useCalendarNavigation'],+ importPath: '@astryxdesign/core/Calendar',+ category: 'utilities',+};++/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */+export const docsDense = {+ description:+ 'Provides date constraint validation combining min/max bounds, range-span caps relative to rangeAnchor, and custom rule functions into isDateDisabled.',+ paramDescriptions: {+ options: 'Date constraint configuration.',+ 'options.min': 'Earliest selectable ISO date.',+ 'options.max': 'Latest selectable ISO date.',+ 'options.dateConstraints': 'Array of predicates returning false for disabled dates.',+ 'options.maxRangeSpan': 'Max days in range counting endpoints, measured from rangeAnchor.',+ 'options.minRangeSpan': 'Min days in range counting endpoints, measured from rangeAnchor.',+ 'options.rangeAnchor': 'Active range start PlainDate for span constraints.',+ },+ returnDescriptions: {+ isDateDisabled: 'Function returning true if PlainDate violates any constraint.',+ minDate: 'Parsed min PlainDate or null.',+ maxDate: 'Parsed max PlainDate or null.',+ },+ usage: {+ description:+ 'Combines bounds, spans, and predicates into isDateDisabled for calendar and date-picker layouts.',+ bestPractices: [+ {+ guidance: true,+ description: 'Set rangeAnchor only while actively picking a range end.',+ },+ {+ guidance: true,+ description: 'Use dateConstraints for recurring blackout dates or closures.',+ },+ {+ guidance: false,+ description: 'Run expensive computation inside dateConstraints.',+ },+ ],+ },+};