---
agent:
  instructions: "Search goop.so for Goop's components, templates, design skill, docs, pricing and terms. Ask in keywords or a plain question, such as \"date picker props\" or \"is the design skill free\"; the answer is the matching page sections in Markdown, each with its address."
  endpoint: "https://goop.so/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# A week schedule

Bookings by person or by room, today's over them, a slot opening its form

Copy the file below whole (`src/screens/schedule.tsx`, say) beside `frame.tsx` (`docs/screen-frame.md`), whose `NAVIGATION` holds its page (`/schedule`), and swap the sample people, rooms and bookings for yours; keep the parts and their props. One body at the panel's full width (PageBody `gutter="page"`): the heading with the week's dates, a SegmentedControl that makes the rows people or rooms, the previous week, Today and the next week, and New booking (the board offers + only on empty cells: New booking books a busy day too); today's bookings under it in one compact row (a SectionHeader with their count, each booking a button), so a phone meets them first too; then the week's WeekBoard across the whole width (at a 1,280 px window its box is about 980 px, the board with room to spare). A booking is a button on the board (Tab reaches each, the arrow keys move from booking to booking, Home and End to the row's first and last); pressing it, or its button in today's row, opens the booking's form in a Sheet. An empty cell is a + button named for its person or room and day: it opens the same form with that day and that person or room filled, 09:00 to 10:00; New booking opens it on the board's first day from today on (a past week or a weekend: the next working day), with the first person and room. The board has no drag and drop: a booking moves by its form (another day in the DatePicker, other hours, another person or room), and the board turns to the week it went to. Two bookings at once for one person or in one room both carry the warning mark, its words read with them. The Sheet closes on Escape, its close button, Close or Save. In a box narrower than 672 px (a phone) the board is a list by day; light, dark, phone and desktop are the parts' own: add no class for them. The days are written in the app's one locale (`LOCALE`), with no date library; the week runs Monday to Friday (`WEEK_DAYS`, 7 for a week with its weekend, which needs about 1,050 px of board or scrolls sideways inside it).

```tsx
// src/screens/schedule.tsx: the week schedule
import { useRef, useState } from 'react';
import { AppFramePanel } from '@/components/goop/patterns/app-frame';
import { PageBody } from '@/components/goop/patterns/page-body';
import { Button, ButtonIcon, ButtonLabel } from '@/components/ui/goop/button';
import {
  DatePicker,
  DatePickerContent,
  DatePickerPanel,
  DatePickerTrigger,
} from '@/components/ui/goop/date-picker';
import { DestructiveButton } from '@/components/ui/goop/destructive-button';
import { Field } from '@/components/ui/goop/field';
import { IconButton, IconButtonIcon } from '@/components/ui/goop/icon-button';
import {
  PageHeader,
  PageHeaderActions,
  PageHeaderContent,
  PageHeaderDescription,
  PageHeaderTitle,
} from '@/components/ui/goop/page-header';
import { PersonSelect } from '@/components/ui/goop/person-select';
import { SectionHeader, SectionHeaderDescription, SectionHeaderTitle } from '@/components/ui/goop/section-header';
import { SegmentedControl, SegmentedControlItem } from '@/components/ui/goop/segmented-control';
import {
  Select,
  SelectContent,
  SelectIcon,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/goop/select';
import {
  Sheet,
  SheetBody,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/goop/sheet';
import { TextInput } from '@/components/ui/goop/text-input';
import { type TimeRange, TimeRangePicker } from '@/components/ui/goop/time-picker';
import {
  WeekBoard,
  type WeekBoardDay,
  type WeekBoardEntry,
  type WeekBoardSlot,
} from '@/components/ui/goop/week-board';
import { ScreenFrame, ScreenTopBar } from './frame';

// ---- the days, with no date library: the app's one locale, the week from Monday
const LOCALE = 'en-GB';
const WEEK_DAYS = 5;
const addDays = (date: Date, n: number) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + n);
const mondayOf = (date: Date) => addDays(date, -((date.getDay() + 6) % 7));
const dayId = (date: Date) =>
  [date.getFullYear(), date.getMonth() + 1, date.getDate()].map((n) => String(n).padStart(2, '0')).join('-');
const dateOf = (id: string) => new Date(`${id}T00:00`);
const longDay = (date: Date) => date.toLocaleDateString(LOCALE, { weekday: 'long', day: 'numeric', month: 'long' });
/** How many weeks from this one the day's week is (0 this week, -1 the last). */
const weeksFrom = (today: Date, date: Date) =>
  Math.round((mondayOf(date).getTime() - mondayOf(today).getTime()) / (7 * 86_400_000));
function weekOf(monday: Date, today: Date): WeekBoardDay[] {
  return Array.from({ length: WEEK_DAYS }, (_, n) => {
    const date = addDays(monday, n);
    return {
      id: dayId(date),
      name: date.toLocaleDateString(LOCALE, { weekday: 'short' }),
      date: String(date.getDate()),
      label: longDay(date),
      today: dayId(date) === dayId(today),
    };
  });
}

// ---- the sample data: swap it for yours
const PEOPLE = [
  { id: 'teodora', name: 'Teodora Valk', role: 'Lead' },
  { id: 'bilal', name: 'Bilal Rashed', role: 'Technician' },
  { id: 'ngozi', name: 'Ngozi Ilori', role: 'Technician' },
  { id: 'dagny', name: 'Dagny Holm', role: 'Trainer' },
  { id: 'cormac', name: 'Cormac Foley', role: 'Surveyor' },
];
const ROOMS = [
  { id: 'north', label: 'North room', description: 'First floor' },
  { id: 'south', label: 'South room', description: 'First floor' },
  { id: 'workshop', label: 'Workshop', description: 'Ground floor' },
];
interface Booking {
  id: string;
  title: string;
  customer: string;
  person: string;
  room: string;
  /** The day, `YYYY-MM-DD`; the hours `HH:MM`. */
  day: string;
  from: string;
  to: string;
}
const THIS_MONDAY = mondayOf(new Date());
const BOOKINGS: Booking[] = (
  [
    [0, 'bilal', 'north', '09:00', '10:00', 'Kick-off call', 'Diallo Dental'],
    [0, 'ngozi', 'workshop', '13:00', '15:00', 'Fitting', 'Eastgate Library'],
    [1, 'teodora', 'south', '10:00', '11:30', 'Design review', 'Harbour Bakery'],
    [1, 'cormac', 'south', '11:00', '12:00', 'Site survey', 'Moss Lane Garage'],
    [2, 'dagny', 'north', '09:30', '10:30', 'Training', 'Eastgate Library'],
    [2, 'bilal', 'workshop', '14:00', '16:00', 'Repair', 'Moss Lane Garage'],
    [3, 'ngozi', 'north', '10:00', '11:00', 'Follow-up', 'Diallo Dental'],
    [3, 'teodora', 'workshop', '15:00', '16:00', 'Handover', 'Harbour Bakery'],
    [4, 'cormac', 'south', '09:00', '10:00', 'Planning', 'Eastgate Library'],
    [4, 'dagny', 'north', '13:00', '14:00', 'Training', 'Diallo Dental'],
    [7, 'teodora', 'north', '09:00', '10:00', 'Kick-off call', 'Moss Lane Garage'],
    [8, 'bilal', 'south', '11:00', '12:30', 'Fitting', 'Harbour Bakery'],
  ] as const
).map(([days, person, room, from, to, title, customer], n) => ({
  id: `b-${n + 1}`,
  title,
  customer,
  person,
  room,
  day: dayId(addDays(THIS_MONDAY, days)),
  from,
  to,
}));
const personOf = (id: string) => PEOPLE.find((person) => person.id === id)?.name ?? '';
const roomOf = (id: string) => ROOMS.find((room) => room.id === id)?.label ?? '';

type By = 'person' | 'room';
/** Two bookings at once for one person or in one room: the first other one, named. */
function clashOf(one: Booking, all: readonly Booking[]): string | undefined {
  const other = all.find(
    (each) =>
      each.id !== one.id &&
      each.day === one.day &&
      each.from < one.to &&
      one.from < each.to &&
      (each.person === one.person || each.room === one.room),
  );
  return other ? `Clashes with ${other.title}` : undefined;
}
function entryOf(one: Booking, by: By, all: readonly Booking[]): WeekBoardEntry {
  const clash = clashOf(one, all);
  const other = by === 'person' ? roomOf(one.room) : personOf(one.person);
  return {
    id: one.id,
    row: by === 'person' ? one.person : one.room,
    day: one.day,
    start: one.from,
    time: `${one.from}–${one.to}`,
    title: one.title,
    description: [one.customer, other].filter(Boolean).join(' · '),
    ...(clash ? { status: { variant: 'warning' as const, label: clash } } : {}),
  };
}

/** What the form holds: a booking being made (`id` null) or changed. */
interface Draft {
  id: string | null;
  title: string;
  customer: string;
  person: string;
  room: string;
  day: Date | null;
  hours: TimeRange;
}
const NOTHING: Draft = { id: null, title: '', customer: '', person: '', room: '', day: null, hours: {} };

export default function ScheduleScreen() {
  const today = new Date();
  const [bookings, setBookings] = useState(BOOKINGS);
  const [by, setBy] = useState<By>('person');
  const [week, setWeek] = useState(0);
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState<Draft>(NOTHING);
  const made = useRef(0);
  const monday = addDays(mondayOf(today), week * 7);
  const days = weekOf(monday, today);
  const rows =
    by === 'person' ? PEOPLE.map((person) => ({ id: person.id, label: person.name, description: person.role })) : ROOMS;
  const shown = bookings.filter((one) => days.some((day) => day.id === one.day));
  const todays = bookings.filter((one) => one.day === dayId(today)).sort((a, b) => a.from.localeCompare(b.from));
  const change = (next: Partial<Draft>) => setDraft((now) => ({ ...now, ...next }));
  const edit = ({ day, from, to, ...one }: Booking) => {
    setDraft({ ...one, day: dateOf(day), hours: { from, to } });
    setOpen(true);
  };
  // an empty slot fills what it knows: its day, and its person or its room; the rest starts at the first of its list
  const book = ({ day, row }: Pick<WeekBoardSlot, 'row'> & { day: Date }) => {
    setDraft({
      ...NOTHING,
      person: by === 'person' && row ? row.id : (PEOPLE[0]?.id ?? ''),
      room: by === 'room' && row ? row.id : (ROOMS[0]?.id ?? ''),
      day,
      hours: { from: '09:00', to: '10:00' },
    });
    setOpen(true);
  };
  // New booking (a busy day has no empty cell): the board's first day from today on, else the next working day
  const nextWorkingDay =
    Array.from({ length: 7 }, (_, n) => addDays(today, n)).find((date) => (date.getDay() + 6) % 7 < WEEK_DAYS) ??
    today;
  const firstDay = days.find((day) => day.id >= dayId(today));
  const { from, to } = draft.hours;
  const ready =
    draft.title.trim() !== '' &&
    draft.person !== '' &&
    draft.room !== '' &&
    draft.day !== null &&
    from !== undefined &&
    to !== undefined &&
    from < to;
  const save = () => {
    if (!ready || !draft.day || !from || !to) return;
    made.current += 1;
    const one: Booking = {
      id: draft.id ?? `new-${made.current}`,
      title: draft.title.trim(),
      customer: draft.customer.trim(),
      person: draft.person,
      room: draft.room,
      day: dayId(draft.day),
      from,
      to,
    };
    setBookings((all) => (draft.id ? all.map((each) => (each.id === draft.id ? one : each)) : [...all, one]));
    // a booking moved to another week takes the board with it
    setWeek(weeksFrom(today, draft.day));
    setOpen(false);
  };
  const cancel = () => {
    setBookings((all) => all.filter((each) => each.id !== draft.id));
    setOpen(false);
  };
  const end = addDays(monday, WEEK_DAYS - 1);
  const range = new Intl.DateTimeFormat(LOCALE, { day: 'numeric', month: 'long', year: 'numeric' }).formatRange(
    monday,
    end,
  );
  return (
    <ScreenFrame current="/schedule">
      <AppFramePanel header={<ScreenTopBar title="Schedule" />}>
        <PageBody gutter="page">
          <PageHeader>
            <PageHeaderContent>
              <PageHeaderTitle asChild>
                <h1>Schedule</h1>
              </PageHeaderTitle>
              <PageHeaderDescription>
                {range} · {shown.length} {shown.length === 1 ? 'booking' : 'bookings'}
              </PageHeaderDescription>
            </PageHeaderContent>
            <PageHeaderActions>
              <SegmentedControl aria-label="Rows by" fit value={by} onValueChange={(next) => setBy(next as By)}>
                <SegmentedControlItem value="person">People</SegmentedControlItem>
                <SegmentedControlItem value="room">Rooms</SegmentedControlItem>
              </SegmentedControl>
              <IconButton aria-label="Previous week" onClick={() => setWeek((n) => n - 1)}>
                <IconButtonIcon icon="chevron-left" />
              </IconButton>
              <Button variant="outline" disabled={week === 0} onClick={() => setWeek(0)}>
                Today
              </Button>
              <IconButton aria-label="Next week" onClick={() => setWeek((n) => n + 1)}>
                <IconButtonIcon icon="chevron-right" />
              </IconButton>
              <Button onClick={() => book({ day: firstDay ? dateOf(firstDay.id) : nextWorkingDay })}>
                <ButtonIcon icon="plus" />
                <ButtonLabel>New booking</ButtonLabel>
              </Button>
            </PageHeaderActions>
          </PageHeader>
          {/* today's bookings in one compact row over the board, first on a phone too: each opens its form */}
          <section aria-labelledby="today-title" className="flex flex-col gap-3">
            <SectionHeader size="sm">
              <SectionHeaderTitle id="today-title" count={todays.length}>
                Today
              </SectionHeaderTitle>
              <SectionHeaderDescription>
                {todays.length > 0 ? longDay(today) : `${longDay(today)}: nothing booked.`}
              </SectionHeaderDescription>
            </SectionHeader>
            {todays.length > 0 ? (
              <ul aria-label="Booked today" className="flex flex-wrap gap-2">
                {todays.map((one) => (
                  <li key={one.id}>
                    <Button variant="outline" onClick={() => edit(one)}>
                      {`${one.from} ${one.title} · ${personOf(one.person)}`}
                    </Button>
                  </li>
                ))}
              </ul>
            ) : null}
          </section>
          <WeekBoard
            aria-label={by === 'person' ? 'Bookings by person' : 'Bookings by room'}
            rowHeading={by === 'person' ? 'Person' : 'Room'}
            days={days}
            rows={rows}
            items={shown.map((one) => entryOf(one, by, bookings))}
            countLabel={(n) => `${n} ${n === 1 ? 'booking' : 'bookings'}`}
            empty="Nothing booked"
            addLabel={({ day, row }) => (row ? `Book ${row.label} on ${day.label}` : `Book on ${day.label}`)}
            onAdd={({ day, row }) => book({ day: dateOf(day.id), row })}
            onItemSelect={(item) => {
              const one = bookings.find((each) => each.id === item.id);
              if (one) edit(one);
            }}
          />
        </PageBody>
      </AppFramePanel>
      <Sheet open={open} onOpenChange={setOpen}>
        <SheetContent closeLabel="Close booking">
          <SheetHeader>
            <SheetTitle>{draft.id ? 'Change booking' : 'New booking'}</SheetTitle>
            <SheetDescription>
              {draft.id ? 'Another day, other hours, another person or room moves it.' : 'Who, where and when.'}
            </SheetDescription>
          </SheetHeader>
          <SheetBody>
            <div className="flex flex-col gap-4">
              <Field orientation="vertical" label="What">
                <TextInput
                  value={draft.title}
                  placeholder="Site visit"
                  onChange={(event) => change({ title: event.currentTarget.value })}
                />
              </Field>
              <Field orientation="vertical" label="Customer">
                <TextInput
                  value={draft.customer}
                  placeholder="Optional"
                  onChange={(event) => change({ customer: event.currentTarget.value })}
                />
              </Field>
              <Field orientation="vertical" label="Person">
                <PersonSelect people={PEOPLE} value={draft.person} onValueChange={(person) => change({ person })} />
              </Field>
              <Field orientation="vertical" label="Room">
                {(control) => (
                  <Select value={draft.room} onValueChange={(room) => change({ room })}>
                    <SelectTrigger {...control}>
                      <SelectValue placeholder="Choose a room" />
                      <SelectIcon />
                    </SelectTrigger>
                    <SelectContent aria-label="Room" search={false}>
                      {ROOMS.map((room) => (
                        <SelectItem key={room.id} value={room.id}>
                          {room.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                )}
              </Field>
              <Field orientation="vertical" label="Day">
                {(control) => (
                  <DatePicker {...control} value={draft.day} onValueChange={(day) => change({ day })}>
                    <DatePickerTrigger locale={LOCALE} placeholder="Pick a day" />
                    <DatePickerContent aria-label="Day">
                      <DatePickerPanel />
                    </DatePickerContent>
                  </DatePicker>
                )}
              </Field>
              <Field orientation="vertical" label="Hours">
                <TimeRangePicker
                  aria-label="Hours"
                  value={draft.hours}
                  onValueChange={(hours) => change({ hours })}
                  locale={LOCALE}
                  step={30}
                  min="07:00"
                  max="20:00"
                />
              </Field>
            </div>
          </SheetBody>
          <SheetFooter>
            {draft.id ? (
              <DestructiveButton icon="trash" onClick={cancel}>
                Cancel booking
              </DestructiveButton>
            ) : null}
            <SheetClose asChild>
              <Button variant="outline">Close</Button>
            </SheetClose>
            <Button disabled={!ready} onClick={save}>
              Save
            </Button>
          </SheetFooter>
        </SheetContent>
      </Sheet>
    </ScreenFrame>
  );
}
```
