# Scheduler

> Day, week, month, year, agenda and timeline calendars of events with resources and grouping, recurring series, time zones, quick info popups, an editor dialog, overlap rules, remote data, virtual scrolling and the SchedulerApi.

Canonical: https://salmonui.dev/docs/calendars/scheduler

```tsx
import { Scheduler } from '@salmonui/scheduler';
import '@salmonui/scheduler/styles.css';

<Scheduler data={events} view="week" date="2026-11-23" timeZone="Europe/Berlin" height={640} onSave={(e) => persist(e.data)} />;
```

### Live demo: Scheduler

Live demo: https://salmonui.dev/demos/calendars/scheduler-basic

A week calendar in Europe/Berlin with a recurring standup, overlapping events, an all-day offsite and a blocked lunch; create, edit and delete events.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Scheduler } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string; allDay?: boolean; recurrenceRule?: string; recurrenceExceptions?: string; location?: string; block?: boolean };

const initial: Row[] = [
  { id: 1, title: 'Standup', start: '2026-11-23T09:00', end: '2026-11-23T09:15', recurrenceRule: 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR', location: 'Room 1' },
  { id: 2, title: 'Design review', start: '2026-11-24T10:00', end: '2026-11-24T11:30' },
  { id: 3, title: 'Customer call', start: '2026-11-24T10:30', end: '2026-11-24T11:00' },
  { id: 4, title: 'Team offsite', start: '2026-11-26', end: '2026-11-28', allDay: true },
  { id: 5, title: 'Lunch', start: '2026-11-25T12:00', end: '2026-11-25T13:00', block: true },
];

/** Week, work week, day and month views with a recurring standup, overlapping events, an all-day offsite and a blocked lunch; edits update the rows. */
export default function SchedulerBasicDemo() {
  const [rows, setRows] = useState<readonly Row[]>(initial);
  return (
    <div className="demo-stack">
      <Scheduler
        data={rows}
        view="week"
        date="2026-11-23"
        timeZone="Europe/Berlin"
        height={560}
        editing={{ following: true }}
        onAdd={(e) => setRows(e.data)}
        onSave={(e) => setRows(e.data)}
        onDelete={(e) => setRows(e.data)}
      />
      <p className="demo-status" aria-live="polite">
        {rows.length} rows
      </p>
    </div>
  );
}
```

## State model

`Scheduler` follows the Data Grid model, not the small-component triads.
Options props (`view`, `date`, `data`, `views`, ...) are re-applied when they
change; user actions change the Scheduler's own state and fire after-events
(`onViewChange`, `onDateChange`, `onAdd`, `onSave`, `onDelete`). To own a
value, store it from the after-event and pass it back. Cancellable actions
have a before-event that you cancel with `event.preventDefault()`
(`onBeforeNavigate`, `onBeforeAdd`, `onBeforeSave`, `onBeforeDelete`,
`onBeforePopupOpen`). `ref` receives the `SchedulerApi`; `onReady(api)` fires
once after mount.

## Data and fields

`data` is an array of your rows. Each row needs a stable `id`.
`eventFields` maps the roles to your property names:
`id`, `title`, `start`, `end`, `allDay`, `location`, `description`, `block`,
`readOnly`, `startTimeZone`, `endTimeZone`, `recurrenceRule`,
`recurrenceId`, `recurrenceExceptions` and `followingId`. A role is a
property name or `{ field, label, defaultValue, validation }`.
Times are `Date`s, ISO strings (with `Z` or an offset they are
instants; without, wall times in the event or Scheduler zone) or plain
`{ year, month, day, hour, minute }` objects. Writes keep the style of the
row's own values.

Local writes update the Scheduler's copy of the rows; every after-event
carries the complete new array in `data`, so persisting is one line. A
`data` prop change replaces the copy.

## Views

`views` lists the views of the header (default day, week, work week and
month). An entry is a view type or `{ type, name, label, interval,
startHour, endHour, workDays, showWeekend, readOnly, timeScale, renderEvent,
eventLayout, monthCount, firstMonthOfYear, agendaDayCount,
hideEmptyAgendaDays, orientation, virtualScroll, headerRows,
renderMonthHeader, renderDayHeader }`; entry options override the top-level
props for that view. `interval` makes custom spans: `{ type: 'day', name:
'threeDays', label: '3 days', interval: 3 }`.

- `day`: one column with an all-day row and time slots.
- `week`: seven columns from `firstDayOfWeek` (default from the locale).
- `workWeek`: the `workDays` columns (default Monday to Friday).
- `month`: week rows with stacked events; a date number opens the day view.
`showWeekNumbers` and `weekRule` add week numbers.
- `showWeekend={false}` hides the non-work days in week and month views.
- `timelineDay`, `timelineWeek`, `timelineWorkWeek`, `timelineMonth` and
  `timelineYear`: time runs horizontally, resources are rows ("Timeline
  views" below).
- `year`, `agenda` and `monthAgenda` ("Year and agenda views" below).

Day, week, work week and month are in the initial JavaScript. The timeline
views, the year and agenda views, and resources are separate chunks: the
server renders them in full, the browser loads them when idle after mount
(at once when such a view is shown first; until then the body shows a sized
placeholder with `data-salmon-pending`).

## Timeline views

The timeline views lay the time axis out horizontally: Timeline Day, Week
and Work Week in time slots of the visible hours (`startHour`, `endHour`,
`timeScale`), Timeline Month in one column
per day. With `grouping` every resource is a row; without, the
view is one row. An event starts in the cell of its start and spans its
length; a row shows `eventLayout.maxHeight` lanes (default 2) and "+N more",
or every lane with `autoRowHeight`.

`headerRows` picks the header rows from `'year'`, `'month'`, `'week'`,
`'date'` and `'hour'`, top to bottom, each with an optional
`render({ unit, start, date, text, view })` (default: date and hour in slot
views, date in Timeline Month):

```tsx
<Scheduler
  data={events}
  resources={[rooms]}
  grouping={{ resources: ['rooms'] }}
  view="timelineWeek"
  views={['timelineDay', 'timelineWeek', 'timelineMonth']}
  headerRows={[{ unit: 'week' }, { unit: 'date' }, { unit: 'hour' }]}
  date="2026-11-24"
  timeZone="UTC"
/>
```

Timeline Year puts the months in rows over the days 1 to 31
(`orientation: 'horizontal'`, the default) or in columns over 31 day rows
(`{ type: 'timelineYear', orientation: 'vertical' }`, each cell lists its
day's events). With grouping, Timeline Year has a row per resource over
every day of the year. `firstMonthOfYear` (1 to 12) and `monthCount` set the
months; `renderMonthHeader({ date, text, view })` and
`renderDayHeader({ day, weekday, text, view })` render the month and day
headings.

Cells carry `data-cell-start` / `data-cell-end` (instants in ms) and
`data-resource` (the resource path key, ids joined by `/`); rows carry
`data-resource`, `data-level` and `data-parent` on parent rows.

### Live demo: Scheduler timeline and resources

Live demo: https://salmonui.dev/demos/calendars/scheduler-timeline

Rooms and their people as timeline rows with resource colors and work hours, plus Timeline Year, Year, Agenda and Month Agenda views.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Scheduler, type SchedulerResource } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string; allDay?: boolean; roomId?: number; ownerIds?: number[] };

const rooms: SchedulerResource = {
  field: 'roomId',
  name: 'rooms',
  label: 'Room',
  data: [
    { id: 1, text: 'Studio', color: '#d9480f', startHour: '08:00', endHour: '14:00' },
    { id: 2, text: 'Lab', color: '#1971c2' },
  ],
};
const owners: SchedulerResource = {
  field: 'ownerIds',
  name: 'owners',
  label: 'Owners',
  multiple: true,
  data: [
    { id: 10, text: 'Ana', parentId: 1 },
    { id: 11, text: 'Ben', parentId: 1 },
    { id: 12, text: 'Chen', parentId: 2 },
  ],
};

const initial: Row[] = [
  { id: 1, title: 'Shoot', start: '2026-11-24T09:00', end: '2026-11-24T12:00', roomId: 1, ownerIds: [10, 11] },
  { id: 2, title: 'Edit', start: '2026-11-24T13:00', end: '2026-11-24T16:00', roomId: 1, ownerIds: [11] },
  { id: 3, title: 'Prototype', start: '2026-11-25', end: '2026-11-27', allDay: true, roomId: 2, ownerIds: [12] },
  { id: 4, title: 'Review', start: '2026-11-26T10:00', end: '2026-11-26T11:00', roomId: 2, ownerIds: [12] },
];

/** Rooms and their people as timeline rows, with the timeline, year and agenda views; edits update the rows. */
export default function SchedulerTimelineDemo() {
  const [rows, setRows] = useState<readonly Row[]>(initial);
  return (
    <div className="demo-stack">
      <Scheduler
        data={rows}
        resources={[rooms, owners]}
        grouping={{ resources: ['rooms', 'owners'] }}
        view="timelineWeek"
        views={['timelineDay', 'timelineWeek', 'timelineMonth', { type: 'timelineYear', orientation: 'vertical' }, 'year', 'agenda', 'monthAgenda']}
        timeScale={{ interval: 60, slotCount: 1 }}
        date="2026-11-24"
        timeZone="UTC"
        height={560}
        onAdd={(e) => setRows(e.data)}
        onSave={(e) => setRows(e.data)}
        onDelete={(e) => setRows(e.data)}
      />
      <p className="demo-status" aria-live="polite">
        {rows.length} rows
      </p>
    </div>
  );
}
```

### Virtual scrolling

`virtualScroll` (top level or per view) renders only the resource rows in
view: `true` or `{ overscan, lazyLoad, initialRange }`. Scrolling
raises no events; `api.getRenderedRange()` returns `{ start, end,
resourceIds }` of the rendered rows. The server and the first client render
show `initialRange` (default rows 0 to 20), so server HTML matches
hydration. With a remote `data` source, `lazyLoad: true` reads the events of
the rendered resources only: `read` receives `resourceIds` and runs again
when the rendered rows change.

### Live demo: Large schedules and virtual scrolling

Live demo: https://salmonui.dev/demos/calendars/scheduler-large

A Timeline Month of 1,000 people and 10,000 events that renders only the visible rows, a remote source that reads the rendered people only, scrollToResource under virtualization, a week of 1,000 events and an agenda that appends days as it scrolls.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { NumberField } from '@salmonui/inputs/number-field';
import { Select } from '@salmonui/dropdowns/select';
import { Scheduler, type SchedulerApi, type SchedulerDataSource, type SchedulerResource } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string; personId: number };

const PEOPLE = 1000;
const pad = (n: number) => String(n).padStart(2, '0');

/** 10 events per person in November 2026, deterministic (no random numbers, no clock). */
function makeEvents(people: number): Row[] {
  const out: Row[] = [];
  for (let p = 1; p <= people; p++) {
    for (let k = 0; k < 10; k++) {
      const day = 1 + ((p * 7 + k * 3) % 28);
      const hour = 8 + ((p + k) % 9);
      out.push({ id: p * 100 + k, title: `Shift ${k + 1}`, start: `2026-11-${pad(day)}T${pad(hour)}:00`, end: `2026-11-${pad(day)}T${pad(hour + 2)}:00`, personId: p });
    }
  }
  return out;
}

const people: SchedulerResource = {
  field: 'personId',
  name: 'people',
  label: 'Person',
  data: Array.from({ length: PEOPLE }, (_, i) => ({ id: i + 1, text: `Person ${i + 1}`, color: ['#d9480f', '#1971c2', '#2f9e44', '#9c36b5'][i % 4] })),
};

type Mode = 'timeline' | 'lazy' | 'week' | 'agenda';

const MODES = [
  { value: 'timeline', label: 'Timeline month, 10,000 events' },
  { value: 'lazy', label: 'Timeline month, lazy loading' },
  { value: 'week', label: 'Week, 1,000 events' },
  { value: 'agenda', label: 'Agenda, virtual scrolling' },
];

/** A Timeline Month of 1,000 people and 10,000 events with virtual scrolling, lazy loading per rendered person, scrolling to a person, a week of 1,000 events and an agenda that loads days as it scrolls. */
export default function SchedulerLargeDemo() {
  const events = useMemo(() => makeEvents(PEOPLE), []);
  const weekEvents = useMemo(() => events.filter((e) => e.start >= '2026-11-23' && e.start < '2026-11-30').slice(0, 1000), [events]);
  const apiRef = useRef<SchedulerApi<Row>>(null);
  const [mode, setMode] = useState<Mode>('timeline');
  const [target, setTarget] = useState(750);
  const [status, setStatus] = useState('');
  // The lazy source answers with the events of the rendered people only.
  const source = useMemo<SchedulerDataSource<Row>>(
    () => ({
      read: ({ resourceIds }) => {
        const ids = new Set(resourceIds ?? []);
        const rows = events.filter((e) => ids.has(e.personId));
        setStatus(`read: ${ids.size} rendered people, ${rows.length} events`);
        return new Promise((resolve) => setTimeout(() => resolve({ rows }), 150));
      },
    }),
    [events],
  );
  return (
    <div>
      <div className="demo-toolbar">
        <label>
          Scenario
          <Select
            aria-label="Scenario"
            data={MODES}
            value={mode}
            onValueChange={(value) => {
              if (value == null) return;
              setMode(value as Mode);
              setStatus('');
            }}
          />
        </label>
        {mode === 'timeline' || mode === 'lazy' ? (
          <>
            <label>
              Person
              <NumberField aria-label="Person" min={1} max={PEOPLE} value={target} onValueChange={(value) => value != null && setTarget(value)} style={{ inlineSize: 120 }} />
            </label>
            <Button variant="outline" type="button" onClick={() => apiRef.current?.scrollToResource(target)}>
              scrollToResource
            </Button>
            <Button
              variant="outline"
              type="button"
              onClick={() => {
                const r = apiRef.current?.getRenderedRange();
                setStatus(r ? `getRenderedRange(): rows ${r.start} to ${r.end - 1} of ${PEOPLE}` : '');
              }}
            >
              getRenderedRange()
            </Button>
          </>
        ) : null}
      </div>
      {mode === 'timeline' ? (
        <Scheduler<Row> key="timeline" ref={apiRef} data={events} resources={[people]} grouping={{ resources: ['people'] }} view="timelineMonth" views={['timelineMonth']} virtualScroll={{ overscan: 4 }} date="2026-11-01" timeZone="UTC" height={520} />
      ) : null}
      {mode === 'lazy' ? (
        <Scheduler<Row> key="lazy" ref={apiRef} data={source} resources={[people]} grouping={{ resources: ['people'] }} view="timelineMonth" views={['timelineMonth']} virtualScroll={{ lazyLoad: true, overscan: 2 }} date="2026-11-01" timeZone="UTC" height={520} />
      ) : null}
      {mode === 'week' ? <Scheduler<Row> key="week" data={weekEvents} view="week" views={['week', 'month']} date="2026-11-23" timeZone="UTC" height={520} scrollTime="08:00" /> : null}
      {mode === 'agenda' ? (
        <Scheduler<Row> key="agenda" data={events.slice(0, 600)} view="agenda" views={[{ type: 'agenda', virtualScroll: true, agendaDayCount: 7 }]} date="2026-11-01" timeZone="UTC" height={520} />
      ) : null}
      <p className="demo-status" aria-live="polite">
        {status || `${events.length.toLocaleString('en-US')} events in memory`}
      </p>
    </div>
  );
}
```

## Year and agenda views

- `year`: a month grid per month (`monthCount`, default 12, from
  `firstMonthOfYear`); days with events are marked (`data-has-events`).
  A day opens its list of events; the date heading of that list goes to the
  day view, as it does in the "+N more" list.
- `agenda`: the events of `agendaDayCount` days (default 7) from the date,
  listed by day; `hideEmptyAgendaDays` (default `true`) skips days without
  events. `{ type: 'agenda', virtualScroll: true }` appends the
  next days as the list scrolls.
- `monthAgenda`: a month grid with marked days and the event list of the
  selected day.

## Resources and grouping

`resources` defines what events refer to. Each definition names
the event `field` that holds the item id (an array with `multiple`), a
`name` for grouping, an editor `label` and its `data` items; the item
properties are `id`, `text`, `color`, `parentId`, `workDays`, `startHour`,
`endHour`, `className` and `expanded` unless `idField`, `textField`,
`colorField`, `parentIdField`, `workDaysField`, `startHourField`,
`endHourField`, `classNameField` and `expandedField` rename them. An event
takes its resource's color, mixed against the surface for its background;
the editor shows a select per resource (several values with `multiple`),
and a new event from a resource cell or row gets that resource.

```tsx
const rooms = { field: 'roomId', name: 'rooms', label: 'Room', data: [{ id: 1, text: 'Room A', color: '#d9480f' }, { id: 2, text: 'Room B' }] };
const owners = { field: 'ownerIds', name: 'owners', multiple: true, data: [{ id: 10, text: 'Ann', parentId: 1 }, { id: 11, text: 'Bob', parentId: 2 }] };

<Scheduler data={events} resources={[rooms, owners]} grouping={{ resources: ['rooms', 'owners'] }} view="week" date="2026-11-24" timeZone="UTC" />;
```

`grouping` groups the views: day, week, work week and month get
one header row per resource level above the dates (`byDate: true` puts the
dates first), the timeline views get a row per resource, nested
under its parent. Children are listed under the parent their `parentId`
names; `byParent: false` lists every child under every parent. An
event with several ids shows in each of its resources; with
`sharedEvents: true` the copies select together. Edits always
change the one row.

- `renderResourceHeader(ctx)` renders a resource heading and
  `renderResourceTooltip(ctx)` adds a tooltip to it (`ctx: { resource,
  level, expanded, hasChildren, view }`).
- Parent rows of timeline views expand and collapse
  (`expandedResourceIds` / `onExpandedResourcesChange`, default from the
  `expanded` item property, `api.expandResource(id)`,
  `api.collapseResource(id)`).
- `resources` is reactive: add, remove or replace items by changing the
  prop; `api.getResources()` and `api.getResource(id, name?)` read the
  items.
- `api.scrollToResource(id)` expands the resource's parents and scrolls its
  row or column into view, also under virtual scrolling.
- Each resource's `workDays`, `startHour` and `endHour` mark its own work
  cells (inherited down the tree); `grouping.hideNonWorkingDays` shows each
  resource only on its work days in day, week and work week views.

### Live demo: Resource grouping options

Live demo: https://salmonui.dev/demos/calendars/scheduler-resources

Rooms and the people in them as grouped columns, dates above resources, every person under every room, shared events, custom resource headers and tooltips, people added and removed through the prop, per-person work days, a timeline work week with week, date and hour header rows, and a six-month year view.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Scheduler, type SchedulerApi, type SchedulerResource } from '@salmonui/scheduler';

type Room = { id: number; text: string; color: string };
type Person = { id: number; text: string; parentId: number; workDays: number[]; role: string };
type Row = { id: number; title: string; start: string; end: string; roomId: number; personIds: number[] };

const ROOMS: Room[] = [
  { id: 1, text: 'Studio', color: '#d9480f' },
  { id: 2, text: 'Lab', color: '#1971c2' },
];
const PEOPLE: Person[] = [
  { id: 10, text: 'Ana', parentId: 1, workDays: [1, 2, 3, 4, 5], role: 'Producer' },
  { id: 11, text: 'Ben', parentId: 1, workDays: [1, 2, 3], role: 'Editor (Mon to Wed)' },
  { id: 12, text: 'Chen', parentId: 2, workDays: [2, 3, 4, 5], role: 'Engineer (Tue to Fri)' },
];
const rows: Row[] = [
  { id: 1, title: 'Shoot', start: '2026-11-23T09:00', end: '2026-11-23T12:00', roomId: 1, personIds: [10, 11] },
  { id: 2, title: 'Edit', start: '2026-11-24T13:00', end: '2026-11-24T16:00', roomId: 1, personIds: [11] },
  { id: 3, title: 'Prototype', start: '2026-11-25T10:00', end: '2026-11-25T15:00', roomId: 2, personIds: [12] },
  { id: 4, title: 'All hands', start: '2026-11-26T11:00', end: '2026-11-26T12:00', roomId: 2, personIds: [10, 12] },
];

/** Resource grouping by parent or every combination, dates above resources, shared events, resource header templates and tooltips, reactive resources, per-resource work days, timeline work week, year options and timeline header rows. */
export default function SchedulerResourcesDemo() {
  const apiRef = useRef<SchedulerApi<Row>>(null);
  const [byDate, setByDate] = useState(false);
  const [byParent, setByParent] = useState(true);
  const [shared, setShared] = useState(true);
  const [hideOff, setHideOff] = useState(false);
  const [people, setPeople] = useState<Person[]>(PEOPLE);
  const [status, setStatus] = useState('');
  const rooms: SchedulerResource<Room> = { field: 'roomId', name: 'rooms', label: 'Room', data: ROOMS };
  const staff: SchedulerResource<Person> = { field: 'personIds', name: 'people', label: 'People', multiple: true, data: people };
  return (
    <div>
      <div className="demo-toolbar">
        <Checkbox checked={byDate} onCheckedChange={(checked) => setByDate(checked)}>
          Dates above resources
        </Checkbox>
        <Checkbox checked={!byParent} onCheckedChange={(checked) => setByParent(!checked)}>
          Everyone under every room
        </Checkbox>
        <Checkbox checked={shared} onCheckedChange={(checked) => setShared(checked)}>
          Shared events select together
        </Checkbox>
        <Checkbox checked={hideOff} onCheckedChange={(checked) => setHideOff(checked)}>
          Hide each person&apos;s days off
        </Checkbox>
        <Button variant="outline" type="button" disabled={people.some((p) => p.id === 13)} onClick={() => setPeople((list) => [...list, { id: 13, text: 'Dana', parentId: 2, workDays: [1, 2, 3, 4, 5], role: 'Intern' }])}>
          Add Dana to the Lab
        </Button>
        <Button variant="outline" type="button" disabled={!people.some((p) => p.id === 13)} onClick={() => setPeople((list) => list.filter((p) => p.id !== 13))}>
          Remove Dana
        </Button>
        <Button variant="outline" type="button" onClick={() => setStatus(`getResources(): ${(apiRef.current?.getResources() ?? []).map((r) => `${r.resource}:${r.text}`).join(', ')}`)}>
          getResources()
        </Button>
      </div>
      <Scheduler<Row>
        ref={apiRef}
        data={rows}
        resources={[rooms, staff]}
        grouping={{ resources: ['rooms', 'people'], byDate, byParent, sharedEvents: shared, hideNonWorkingDays: hideOff }}
        renderResourceHeader={({ resource, level }) => (level === 0 ? <strong>{resource.text}</strong> : <span>{resource.text}</span>)}
        renderResourceTooltip={({ resource }) => (resource.data as Partial<Person>).role ?? `Room: ${resource.text}`}
        view="workWeek"
        views={[
          'workWeek',
          { type: 'timelineWorkWeek', headerRows: [{ unit: 'week', render: ({ text }) => <em>{text}</em> }, { unit: 'date' }, { unit: 'hour' }] },
          { type: 'year', firstMonthOfYear: 9, monthCount: 6, renderMonthHeader: ({ text }) => <strong>{text}</strong> },
        ]}
        date="2026-11-23"
        timeZone="UTC"
        locale="en-GB"
        startHour="08:00"
        endHour="18:00"
        height={560}
      />
      <p className="demo-status" aria-live="polite">
        {status || 'Hover a person heading for the tooltip'}
      </p>
    </div>
  );
}
```

## Navigation

`date` / `onDateChange` and `view` / `onViewChange` are the reactive pair.
The header previous, next and today buttons and
`api.navigate('previous' | 'next' | 'today')` move by one page;
`api.setView(view, date?)` and `api.setDate(date)` jump. `onBeforeNavigate`
(`kind: 'date' | 'view'`) cancels. `min` and `max` stop navigation and the
header calendar. The date range button shows
`Intl.DateTimeFormat.formatRange` text (`renderDateRange` replaces it,
`api.getDateRangeText()` reads it) and opens a `Calendar` popover
to pick a date.

### Live demo: Views, navigation and work hours

Live demo: https://salmonui.dev/demos/calendars/scheduler-views-navigation

Day, week, work week, a custom 3-day view and a read-only month with per-view options, controlled view and date, a cancellable navigation, min and max, visible and work hours, time scale, week numbers, header items and the date range text.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { Scheduler, type SchedulerApi } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string; allDay?: boolean };

const rows: Row[] = [
  { id: 1, title: 'Sprint planning', start: '2026-11-23T09:30', end: '2026-11-23T11:00' },
  { id: 2, title: 'Early deploy', start: '2026-11-24T07:00', end: '2026-11-24T07:45' },
  { id: 3, title: 'Design review', start: '2026-11-25T14:00', end: '2026-11-25T15:30' },
  { id: 4, title: 'Late support shift', start: '2026-11-26T19:00', end: '2026-11-26T21:00' },
  { id: 5, title: 'Retro', start: '2026-11-27T16:00', end: '2026-11-27T17:00' },
  { id: 6, title: 'Hackathon', start: '2026-11-28', end: '2026-11-30', allDay: true },
  { id: 7, title: 'Quarter close', start: '2026-12-15', end: '2026-12-16', allDay: true },
];

const SLOTS = [15, 30, 60].map((n) => ({ value: n, label: `${n} minutes` }));

/** View types and per-view options, a 3-day view, navigation limits, visible and work hours, time scale, week numbers and the header items. */
export default function SchedulerViewsNavigationDemo() {
  const apiRef = useRef<SchedulerApi<Row>>(null);
  const [view, setView] = useState('week');
  const [date, setDate] = useState('2026-11-23');
  const [showWeekend, setShowWeekend] = useState(true);
  const [slot, setSlot] = useState(30);
  const [blockDecember, setBlockDecember] = useState(false);
  const [log, setLog] = useState<string[]>([]);
  const add = (line: string) => setLog((lines) => [line, ...lines].slice(0, 6));
  return (
    <div>
      <div className="demo-toolbar">
        <Checkbox checked={showWeekend} onCheckedChange={(checked) => setShowWeekend(checked)}>
          Show weekend
        </Checkbox>
        <label>
          Slot
          <Select aria-label="Slot" data={SLOTS} value={slot} onValueChange={(value) => value != null && setSlot(Number(value))} />
        </label>
        <Checkbox checked={blockDecember} onCheckedChange={(checked) => setBlockDecember(checked)}>
          Cancel navigation to a week starting in December
        </Checkbox>
        <Button variant="outline" type="button" onClick={() => apiRef.current?.setView('threeDays', '2026-11-25')}>
          setView(&apos;threeDays&apos;, 25 Nov)
        </Button>
        <Button variant="outline" type="button" onClick={() => apiRef.current?.scrollToTime('19:00')}>
          scrollToTime(&apos;19:00&apos;)
        </Button>
        <Button variant="outline" type="button" onClick={() => apiRef.current?.setWorkHours(['2026-11-27'], '12:00', '16:00')}>
          Friday works 12:00 to 16:00
        </Button>
        <Button variant="outline" type="button" onClick={() => apiRef.current?.resetWorkHours()}>
          Reset work hours
        </Button>
        <Button variant="outline" type="button" onClick={() => add(`getDateRangeText(): ${apiRef.current?.getDateRangeText() ?? ''}`)}>
          getDateRangeText()
        </Button>
        <Button variant="outline" type="button" onClick={() => apiRef.current?.refresh()}>
          refresh()
        </Button>
      </div>
      <Scheduler<Row>
        ref={apiRef}
        data={rows}
        view={view}
        date={date}
        timeZone="Europe/Berlin"
        locale="en-GB"
        hourCycle="h23"
        dateFormat={{ weekday: 'short', day: 'numeric', month: 'short' }}
        firstDayOfWeek={1}
        showWeekNumbers
        weekRule="firstFourDayWeek"
        showWeekend={showWeekend}
        workDays={[1, 2, 3, 4, 5]}
        startHour="06:00"
        endHour="22:00"
        workHours={{ highlight: true, start: '08:30', end: '17:30' }}
        scrollTime="08:00"
        timeScale={{ enabled: true, interval: slot * 2, slotCount: 2 }}
        renderMajorSlot={(ctx) => <strong>{ctx.text}</strong>}
        currentTimeIndicator={{ label: true }}
        min="2026-11-01"
        max="2027-01-31"
        views={[
          'day',
          { type: 'week', startHour: '07:00', endHour: '21:00' },
          { type: 'workWeek', label: 'Work week' },
          { type: 'day', name: 'threeDays', label: '3 days', interval: 3 },
          { type: 'month', showWeekend: true, readOnly: true, eventLayout: { maxHeight: 2 } },
        ]}
        toolbar={['previous', 'next', 'today', 'dateRange', 'views', { id: 'next-review', label: 'Next review', align: 'end', onClick: () => apiRef.current?.setDate('2026-11-25') }]}
        onBeforeNavigate={(e) => {
          if (blockDecember && e.kind === 'date' && e.date.month === 12) {
            e.preventDefault();
            add(`onBeforeNavigate cancelled ${String(e.date)}`);
          }
        }}
        onViewChange={(next, e) => {
          setView(next);
          add(`onViewChange(${next}) from ${e.previousView}`);
        }}
        onDateChange={(next, e) => {
          setDate(next.toString());
          add(`onDateChange(${String(next)}) from ${String(e.previousDate)} (${e.source})`);
        }}
        height={560}
        width="100%"
        className="demo-scheduler"
      />
      <p className="demo-status" aria-live="polite">
        view <code>{view}</code>, date <code>{date}</code>
      </p>
      <div className="demo-log">
        <ol>{log.length ? log.map((line, i) => <li key={`${i}-${line}`}>{line}</li>) : <li>Navigate or switch views</li>}</ol>
      </div>
    </div>
  );
}
```

## Time

- `timeZone` (IANA) is the zone the events are shown in. Without it the
  client uses the host zone after hydration and the server renders an empty
  frame; pass it for server rendering.
- Per-event `startTimeZone` / `endTimeZone` read wall times in that zone;
  the editor offers a searchable zone list (`timeZones`, default
  `Intl.supportedValuesOf('timeZone')`).
- `startHour` / `endHour` (`'HH:mm'`) limit the visible hours;
  `workHours: { highlight, start, end }` marks work hours, and
  `api.setWorkHours(dates, start, end)` / `api.resetWorkHours(dates?)`
  override single days.
- `timeScale: { enabled, interval, slotCount }` sets the major slot length
  in minutes and its minor slots; `renderMajorSlot` / `renderMinorSlot`
  render the labels.
- The current time marker (`currentTimeIndicator`) and today are added
  after hydration only.
- The day views scroll to the work start; `scrollTime` and
  `api.scrollToTime(time, { date })` move it.
- `calendar` relabels dates with an `Intl` calendar (including Islamic); `dateFormat` and `hourCycle` set the formats.

### Live demo: Time zones, languages and calendars

Live demo: https://salmonui.dev/demos/calendars/scheduler-globalization

Events stored with their own IANA zones shown in a zone you pick, a zone list in the editor, the time zone helper functions, German strings through localeText, and Arabic with the Islamic calendar right to left.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Select } from '@salmonui/dropdowns/select';
import { getTimeZoneOffset, Scheduler, toZonedDateTime, type SchedulerProps } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string; startTimeZone?: string; endTimeZone?: string; location?: string };

const rows: Row[] = [
  { id: 1, title: 'Berlin standup', start: '2026-11-24T09:00', end: '2026-11-24T09:30', startTimeZone: 'Europe/Berlin', endTimeZone: 'Europe/Berlin', location: 'Berlin' },
  { id: 2, title: 'New York sync', start: '2026-11-24T10:00', end: '2026-11-24T11:00', startTimeZone: 'America/New_York', endTimeZone: 'America/New_York', location: 'New York' },
  { id: 3, title: 'Tokyo review', start: '2026-11-25T17:00', end: '2026-11-25T18:00', startTimeZone: 'Asia/Tokyo', endTimeZone: 'Asia/Tokyo', location: 'Tokyo' },
  { id: 4, title: 'Release (UTC)', start: '2026-11-26T14:00:00Z', end: '2026-11-26T15:00:00Z' },
];

const ZONES = ['Europe/Berlin', 'America/New_York', 'Asia/Tokyo', 'Asia/Riyadh', 'UTC'];

type Setup = { label: string; props: Partial<SchedulerProps<Row>> };
const SETUPS: Record<string, Setup> = {
  en: { label: 'English (en-GB)', props: { locale: 'en-GB' } },
  de: {
    label: 'Deutsch (de-DE, localeText)',
    props: { locale: 'de-DE', localeText: { previous: 'Zurück', next: 'Weiter', today: 'Heute', viewDay: 'Tag', viewWeek: 'Woche', viewWorkWeek: 'Arbeitswoche', viewMonth: 'Monat', allDay: 'Ganztägig', save: 'Speichern', cancel: 'Abbrechen', delete: 'Löschen', edit: 'Bearbeiten', moreDetails: 'Weitere Details', addTitle: 'Titel hinzufügen', fieldTitle: 'Titel', fieldLocation: 'Ort', fieldStart: 'Beginn', fieldEnd: 'Ende' } },
  },
  ar: { label: 'العربية, Islamic calendar, RTL', props: { locale: 'ar-SA', calendar: 'islamic-umalqura', dir: 'rtl' } },
};

const ZONE_ITEMS = ZONES.map((z) => ({ value: z, label: z }));
const SETUP_ITEMS = Object.entries(SETUPS).map(([key, s]) => ({ value: key, label: s.label }));

/** Events in several IANA zones shown in a chosen zone, per-event zones in the editor, the time zone helpers, locales, localeText, the Islamic calendar and RTL. */
export default function SchedulerGlobalizationDemo() {
  const [zone, setZone] = useState('Europe/Berlin');
  const [setup, setSetup] = useState('en');
  const [data, setData] = useState<readonly Row[]>(rows);
  const release = '2026-11-26T14:00:00Z';
  const wall = toZonedDateTime(release, zone);
  const offset = getTimeZoneOffset(release, zone);
  return (
    <div>
      <div className="demo-toolbar">
        <label>
          Show in
          <Select aria-label="Show in" data={ZONE_ITEMS} value={zone} onValueChange={(value) => value != null && setZone(String(value))} />
        </label>
        <label>
          Language
          <Select aria-label="Language" data={SETUP_ITEMS} value={setup} onValueChange={(value) => value != null && setSetup(String(value))} />
        </label>
      </div>
      <Scheduler<Row>
        key={setup}
        data={data}
        view="week"
        views={['day', 'week', 'workWeek', 'month']}
        date="2026-11-23"
        timeZone={zone}
        timeZones={ZONES}
        startHour="00:00"
        scrollTime="08:00"
        height={520}
        onAdd={(e) => setData(e.data)}
        onSave={(e) => setData(e.data)}
        onDelete={(e) => setData(e.data)}
        {...SETUPS[setup]?.props}
      />
      <p className="demo-status" aria-live="polite">
        The release at {release}: <code>toZonedDateTime</code> gives {String(wall)} in {zone}, <code>getTimeZoneOffset</code> {offset} minutes.
      </p>
    </div>
  );
}
```

## Layout

Overlapping timed events share their time column side by side; events that
cross midnight and all-day events sit in the all-day row as bars split per
week with `data-continues-start` / `data-continues-end` parts. `eventOrder(a, b)` orders events that start together.
`eventLayout: { spannedPlacement, maxHeight, moreIndicator, minimumDuration }`
controls where spanning events go, how many lanes show before "+N more", and
the shortest drawn height. "+N more" opens a popover of the day's
events (`onMoreEventsClick`, `event.navigate(view)` to go to a view
instead). The all-day row expands with its toggle
(`allDayRowExpanded` / `onAllDayRowExpandedChange`, `allDayRowScroll`). `autoRowHeight` grows month and timeline rows to fit every event
instead of "+N more".

### Live demo: Event layout and more indicators

Live demo: https://salmonui.dev/demos/calendars/scheduler-event-layout

A busy week with a collapsible, scrollable all-day row, a night shift across midnight in the all-day row or the time slots, a minimum drawn height, a lane limit with +N more and its popover or day navigation, and auto row height.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { Scheduler } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string; allDay?: boolean };

const pad = (n: number) => String(n).padStart(2, '0');
// A busy week: all-day items, a timed event across midnight, short tasks and a crowded Wednesday.
const rows: Row[] = [
  { id: 1, title: 'Conference', start: '2026-11-23', end: '2026-11-26', allDay: true },
  { id: 2, title: 'On call', start: '2026-11-24', end: '2026-11-29', allDay: true },
  { id: 3, title: 'Offsite prep', start: '2026-11-25', end: '2026-11-26', allDay: true },
  { id: 4, title: 'Budget due', start: '2026-11-25', end: '2026-11-26', allDay: true },
  { id: 5, title: 'Night migration', start: '2026-11-24T22:00', end: '2026-11-25T04:00' },
  { id: 6, title: 'Quick check', start: '2026-11-23T10:00', end: '2026-11-23T10:05' },
  ...Array.from({ length: 7 }, (_, i) => ({ id: 10 + i, title: `Interview ${i + 1}`, start: `2026-11-25T${pad(9 + i)}:00`, end: `2026-11-25T${pad(9 + i)}:45` })),
  ...Array.from({ length: 6 }, (_, i) => ({ id: 20 + i, title: `Call ${i + 1}`, start: `2026-11-26T${pad(9 + i)}:00`, end: `2026-11-26T${pad(10 + i)}:00` })),
];

const PLACEMENTS = [
  { value: 'allDayRow', label: 'in the all-day row' },
  { value: 'timeSlot', label: 'split into the time slots' },
];
const LANES = [1, 2, 3].map((n) => ({ value: n, label: String(n) }));

/** All-day row expand and scroll, events across midnight, minimum height, lanes and "+N more", the more popover or navigation, and auto row height. */
export default function SchedulerEventLayoutDemo() {
  const [placement, setPlacement] = useState<'allDayRow' | 'timeSlot'>('allDayRow');
  const [maxHeight, setMaxHeight] = useState(2);
  const [autoRowHeight, setAutoRowHeight] = useState(false);
  const [navigateOnMore, setNavigateOnMore] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [status, setStatus] = useState('');
  return (
    <div>
      <div className="demo-toolbar">
        <label>
          Events across midnight
          <Select aria-label="Events across midnight" data={PLACEMENTS} value={placement} onValueChange={(value) => value != null && setPlacement(value as 'allDayRow' | 'timeSlot')} />
        </label>
        <label>
          Lanes before +N more
          <Select aria-label="Lanes before +N more" data={LANES} value={maxHeight} onValueChange={(value) => value != null && setMaxHeight(Number(value))} />
        </label>
        <Checkbox checked={autoRowHeight} onCheckedChange={(checked) => setAutoRowHeight(checked)}>
          Auto row height (no +N more)
        </Checkbox>
        <Checkbox checked={navigateOnMore} onCheckedChange={(checked) => setNavigateOnMore(checked)}>
          +N more opens the day view
        </Checkbox>
      </div>
      <Scheduler<Row>
        data={rows}
        view="week"
        views={['week', 'month', 'timelineWeek']}
        date="2026-11-23"
        timeZone="UTC"
        locale="en-GB"
        height={560}
        scrollTime="08:00"
        eventLayout={{ spannedPlacement: placement, maxHeight, moreIndicator: true, minimumDuration: 20, ignoreWhitespace: true }}
        autoRowHeight={autoRowHeight}
        allDayRowExpanded={expanded}
        onAllDayRowExpandedChange={(next) => {
          setExpanded(next);
          setStatus(`onAllDayRowExpandedChange(${String(next)})`);
        }}
        allDayRowScroll
        onMoreEventsClick={(e) => {
          setStatus(`onMoreEventsClick: ${e.rows.length} events on ${String(e.date)}`);
          if (navigateOnMore) e.navigate('day');
        }}
      />
      <p className="demo-status" aria-live="polite">
        {status || 'Expand the all-day row or click +N more'}
      </p>
    </div>
  );
}
```

## Recurring events

A row with `recurrenceRule` (an RRULE string) is a series. Its occurrences
are expanded per visible range by the RRULE engine (see
[RecurrenceEditor](https://salmonui.dev/docs/calendars/recurrence-editor)) and keep their wall
time across DST; `recurrenceExceptions` (comma separated
`20261125T140000Z` stamps, or an array of times) are skipped, and a row with
`recurrenceId` is an edited occurrence. Editing or deleting an
occurrence asks for the scope: "This event" adds an exception to
the series and an edited child; "All events" changes the series (moving it
by the occurrence's time change and dropping edited occurrences); with
`editing.following`, "This and following events" ends the series before the
occurrence (`UNTIL`) and starts a new series linked by `followingId`.
With `editing.recurrencePrompt: false` there is no prompt;
`event.setScope(scope)` in `onBeforeSave` / `onBeforeDelete` decides.
`editing.validateRecurrence` (default true) rejects a duration longer than
the repeat interval and an occurrence moved onto the day of another one.
`api.getOccurrences(id)`, `api.getOccurrencesInRange(start,
end)` and `api.getDeletedOccurrences(id)` query series.

### Live demo: Recurring series and edit scopes

Live demo: https://salmonui.dev/demos/calendars/scheduler-recurrence

A daily standup with a skipped day and a moved occurrence, the "this event / following / all events" prompt, a scope chosen in onBeforeSave without the prompt, recurrence validation, and getOccurrences, getDeletedOccurrences and getOccurrencesInRange.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { Scheduler, type EditScope, type SchedulerApi } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string; recurrenceRule?: string; recurrenceExceptions?: string; recurrenceId?: number; followingId?: number };

const initial: Row[] = [
  // Daily standup; 25 November is skipped (an exception) and 26 November was moved to 10:00 (an edited occurrence).
  { id: 1, title: 'Standup', start: '2026-11-23T09:00', end: '2026-11-23T09:15', recurrenceRule: 'FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR;COUNT=20', recurrenceExceptions: '20261125T090000Z,20261126T090000Z' },
  { id: 2, title: 'Standup (moved)', start: '2026-11-26T10:00', end: '2026-11-26T10:15', recurrenceId: 1 },
  { id: 3, title: 'Weekly 1:1', start: '2026-11-24T14:00', end: '2026-11-24T14:30', recurrenceRule: 'FREQ=WEEKLY;BYDAY=TU' },
];

const SCOPES = (['occurrence', 'following', 'series'] as const).map((s) => ({ value: s, label: s }));

/** Recurring series with exceptions and an edited occurrence, the scope prompt with "following", a scope chosen in code, recurrence validation and the occurrence methods. */
export default function SchedulerRecurrenceDemo() {
  const apiRef = useRef<SchedulerApi<Row>>(null);
  const [rows, setRows] = useState<readonly Row[]>(initial);
  const [prompt, setPrompt] = useState(true);
  const [scope, setScope] = useState<EditScope>('occurrence');
  const [log, setLog] = useState<string[]>([]);
  const add = (line: string) => setLog((lines) => [line, ...lines].slice(0, 8));
  const day = (d: Date) => d.toISOString().slice(0, 16).replace('T', ' ');
  return (
    <div>
      <div className="demo-toolbar">
        <Checkbox checked={prompt} onCheckedChange={(checked) => setPrompt(checked)}>
          Ask for the scope
        </Checkbox>
        <label>
          Scope without the prompt
          <Select aria-label="Scope without the prompt" data={SCOPES} value={scope} onValueChange={(value) => value != null && setScope(value as EditScope)} disabled={prompt} />
        </label>
        <Button variant="outline" type="button" onClick={() => add(`getOccurrences(1): ${(apiRef.current?.getOccurrences(1) ?? []).slice(0, 6).map((o) => day(o.start)).join(', ')} ...`)}>
          getOccurrences(1)
        </Button>
        <Button variant="outline" type="button" onClick={() => add(`getDeletedOccurrences(1): ${(apiRef.current?.getDeletedOccurrences(1) ?? []).map(day).join(', ') || 'none'}`)}>
          getDeletedOccurrences(1)
        </Button>
        <Button
          variant="outline"
          type="button"
          onClick={() => {
            const list = apiRef.current?.getOccurrencesInRange(new Date(Date.UTC(2026, 10, 30)), new Date(Date.UTC(2026, 11, 5))) ?? [];
            add(`getOccurrencesInRange(30 Nov-4 Dec): ${list.length} occurrences`);
          }}
        >
          getOccurrencesInRange
        </Button>
      </div>
      <Scheduler<Row>
        ref={apiRef}
        data={rows}
        view="week"
        views={['week', 'month', 'agenda']}
        date="2026-11-23"
        timeZone="UTC"
        height={480}
        scrollTime="08:00"
        editing={{ following: true, recurrencePrompt: prompt, validateRecurrence: true }}
        onBeforeSave={(e) => {
          if (!prompt && e.occurrenceStart) e.setScope(scope);
        }}
        onBeforeDelete={(e) => {
          if (!prompt && e.occurrenceStart) e.setScope(scope);
        }}
        onBeforePopupOpen={(e) => {
          if (e.popup === 'validationAlert' || e.popup === 'recurrenceAlert') add(`popup: ${e.popup}`);
        }}
        onSave={(e) => {
          setRows(e.data);
          add(`onSave scope ${e.scope}: +${e.added.length} ~${e.changed.length} -${e.deleted.length}`);
        }}
        onDelete={(e) => {
          setRows(e.data);
          add(`onDelete scope ${e.scope}`);
        }}
        onAdd={(e) => setRows(e.data)}
      />
      <div className="demo-log" aria-live="polite">
        <ol>{log.length ? log.map((line, i) => <li key={`${i}-${line}`}>{line}</li>) : <li>Edit or delete an occurrence</li>}</ol>
      </div>
      <details>
        <summary>Rows ({rows.length})</summary>
        <pre style={{ fontSize: 12, whiteSpace: 'pre-wrap' }}>{JSON.stringify(rows, null, 1)}</pre>
      </details>
    </div>
  );
}
```

## Editing

`editing` is `true`, `false` or `{ add, edit, delete, dialog, following,
recurrencePrompt, validateRecurrence, createId, renderDialog,
renderDialogHeader, renderDialogFooter }`; `readOnly` on the
Scheduler, on a view, or the `readOnly` role on a row allows details only.

- A cell click selects the cell and opens the cell quick info popup (title
  and Save, More details); an event click opens the event popup (details,
  Edit, Delete). `quickInfo: false` turns them off, `{ onSelectionEnd,
  renderHeader, renderContent, renderFooter }` customizes them.
- A double click (or Alt+Enter) opens the editor dialog: title, location,
  start and end `DatePicker`s, all day, start and end time zones, the
  embedded `RecurrenceEditor` and the description. Field
  validation follows `eventFields.<role>.validation` with the Data Grid
  rule names (`required`, `minLength`, `maxLength`, `pattern`, `validate`).
  A new event starts with the `defaultValue` of its title, location and
  description roles. `editing.renderDialog` replaces the body with your own
  fields (`{ isNew, values, setValue, errors, row, save, cancel, delete }`): `values` holds the roles, the resource fields and the row's
  other properties by their own names, and `setValue(name, value)` on a
  property outside the roles writes that property on save.
- `editing.inline` edits in place: typing in a focused cell opens
  a title input there (Enter or leaving it creates the event, Escape
  cancels), and Enter on an event edits its title (a series occurrence
  changes the series). A cell click then only selects; the cell quick info
  stays closed so typing reaches the cell.
- `onBeforePopupOpen` / `onPopupClose` report `popup: 'editor' | 'quickInfo'
  | 'moreEvents' | 'recurrenceAlert' | 'deleteAlert' | 'validationAlert' |
  'overlapAlert'`; `api.openQuickInfo(target)`, `api.closeQuickInfo()`,
  `api.openEditor(target, { mode })` and `api.closeEditor()` open and close
  them from code.
- `api.addEvents(rows)`, `api.saveEvent(row, { scope, occurrenceStart })` and
  `api.deleteEvents(ids, { scope })` write from code and return
  `{ status, rows }`.

## Availability

A row with the `block` role is a blocked time: creates, saves and moves
into it are rejected and it renders hatched (`api.getBlockEvents()`). `overlap={false}` rejects writes that collide with another event;
`onOverlap(event)` reports the conflicting rows
(`preventDefault()` suppresses the alert), and `api.openOverlapAlert()` /
`api.closeOverlapAlert()` show it. `api.isSlotAvailable(start, end)` checks a
slot.

### Live demo: Editing, popups and validation

Live demo: https://salmonui.dev/demos/calendars/scheduler-editing

Events with your own property names mapped through eventFields, validated subject and room fields with a default room, the quick info popups and the editor dialog, add, edit and delete permissions, overlap prevention, a blocked window, a locked event, read-only mode, inline editing, click events and the CRUD methods.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Scheduler, type SchedulerApi } from '@salmonui/scheduler';

// Your own property names, mapped to the Scheduler roles through eventFields.
type Row = { Id: number; Subject: string; StartTime: string; EndTime: string; Room?: string; Locked?: boolean; Blocked?: boolean };

const initial: Row[] = [
  { Id: 1, Subject: 'Client workshop', StartTime: '2026-11-23T10:00', EndTime: '2026-11-23T12:00', Room: 'Atrium' },
  { Id: 2, Subject: 'Board meeting (locked)', StartTime: '2026-11-24T09:00', EndTime: '2026-11-24T11:00', Room: 'Boardroom', Locked: true },
  { Id: 3, Subject: 'Maintenance window', StartTime: '2026-11-25T12:00', EndTime: '2026-11-25T14:00', Blocked: true },
  { Id: 4, Subject: 'Team lunch', StartTime: '2026-11-26T12:30', EndTime: '2026-11-26T13:30', Room: 'Cafe' },
];

/** Editing permissions, mapped and validated fields, quick info popups and the editor dialog, overlap rules, blocked and read-only events, inline editing, click events and the CRUD methods. */
export default function SchedulerEditingDemo() {
  const apiRef = useRef<SchedulerApi<Row>>(null);
  const [rows, setRows] = useState<readonly Row[]>(initial);
  const [perm, setPerm] = useState({ add: true, edit: true, delete: true });
  const [overlap, setOverlap] = useState(false);
  const [readOnly, setReadOnly] = useState(false);
  const [inline, setInline] = useState(false);
  const [log, setLog] = useState<string[]>([]);
  const add = (line: string) => setLog((lines) => [line, ...lines].slice(0, 10));
  const toggle = (key: keyof typeof perm) => setPerm((p) => ({ ...p, [key]: !p[key] }));
  return (
    <div>
      <div className="demo-toolbar">
        {(['add', 'edit', 'delete'] as const).map((key) => (
          <Checkbox key={key} checked={perm[key]} onCheckedChange={() => toggle(key)}>
            editing.{key}
          </Checkbox>
        ))}
        <Checkbox checked={!overlap} onCheckedChange={(checked) => setOverlap(!checked)}>
          Prevent overlaps
        </Checkbox>
        <Checkbox checked={readOnly} onCheckedChange={(checked) => setReadOnly(checked)}>
          readOnly
        </Checkbox>
        <Checkbox checked={inline} onCheckedChange={(checked) => setInline(checked)}>
          Inline editing
        </Checkbox>
      </div>
      <div className="demo-toolbar">
        <Button variant="outline" type="button" onClick={() => add(`addEvents: ${apiRef.current?.addEvents([{ Id: 0, Subject: 'Added from code', StartTime: '2026-11-27T15:00', EndTime: '2026-11-27T16:00', Room: 'Atrium' }]).status}`)}>
          addEvents
        </Button>
        <Button
          variant="outline"
          type="button"
          onClick={() => {
            const row = rows.find((r) => r.Id === 4);
            if (row) add(`saveEvent: ${apiRef.current?.saveEvent({ ...row, StartTime: '2026-11-26T13:00', EndTime: '2026-11-26T14:00' }).status}`);
          }}
        >
          saveEvent (lunch to 13:00)
        </Button>
        <Button variant="outline" type="button" onClick={() => add(`deleteEvents: ${apiRef.current?.deleteEvents([1]).status}`)}>
          deleteEvents([1])
        </Button>
        <Button variant="outline" type="button" onClick={() => apiRef.current?.openEditor({ start: '2026-11-27T09:00', end: '2026-11-27T10:00' })}>
          openEditor (new)
        </Button>
        <Button variant="outline" type="button" onClick={() => apiRef.current?.openQuickInfo(4)}>
          openQuickInfo(4)
        </Button>
        <Button
          variant="outline"
          type="button"
          onClick={() => {
            const free = apiRef.current?.isSlotAvailable(new Date(Date.UTC(2026, 10, 23, 10, 30)), new Date(Date.UTC(2026, 10, 23, 11, 0)));
            add(`isSlotAvailable(Mon 10:30-11:00): ${String(free)}`);
          }}
        >
          isSlotAvailable(Mon 10:30)
        </Button>
      </div>
      <Scheduler<Row>
        ref={apiRef}
        data={rows}
        eventFields={{
          id: 'Id',
          title: { field: 'Subject', label: 'Subject', validation: { required: 'A subject is required.', minLength: 3 } },
          start: 'StartTime',
          end: 'EndTime',
          location: { field: 'Room', label: 'Room', defaultValue: 'Atrium', validation: { validate: (v) => (v === 'Basement' ? 'The basement is closed.' : null) } },
          readOnly: 'Locked',
          block: 'Blocked',
        }}
        editing={{ ...perm, inline }}
        readOnly={readOnly}
        overlap={overlap}
        onOverlap={(e) => add(`onOverlap: ${e.row.Subject} collides with ${e.conflicts.map((c) => c.Subject).join(', ')}`)}
        view="week"
        views={['day', 'week', 'month']}
        date="2026-11-23"
        timeZone="UTC"
        height={540}
        scrollTime="08:00"
        onCellClick={(e) => add(`onCellClick ${e.start.toISOString().slice(5, 16)}${e.allDay ? ' (all day)' : ''}`)}
        onCellDoubleClick={() => add('onCellDoubleClick')}
        onEventClick={(e) => add(`onEventClick ${e.row.Subject}`)}
        onEventDoubleClick={(e) => add(`onEventDoubleClick ${e.row.Subject}`)}
        onBeforePopupOpen={(e) => add(`onBeforePopupOpen(${e.popup})`)}
        onPopupClose={(e) => add(`onPopupClose(${e.popup})`)}
        onAdd={(e) => {
          setRows(e.data);
          add(`onAdd: ${e.rows.map((r) => r.Subject).join(', ')}`);
        }}
        onSave={(e) => {
          setRows(e.data);
          add(`onSave: ${e.changed.map((r) => r.Subject).join(', ')}`);
        }}
        onDelete={(e) => {
          setRows(e.data);
          add(`onDelete: ${e.deleted.map((r) => r.Subject).join(', ')}`);
        }}
      />
      <div className="demo-log" aria-live="polite">
        <ol>{log.length ? log.map((line, i) => <li key={`${i}-${line}`}>{line}</li>) : <li>Click a cell or an event</li>}</ol>
      </div>
    </div>
  );
}
```

## Remote data

`data` may be a source with `read({ range, view, signal })` and an optional
`write({ action, added, changed, deleted, signal })`. The visible
range is the query: every navigation reads again (aborting a superseded
read). Writes apply at once and show a pending state on the event; a
rejection (or `{ status: 'rejected' }`) reverts and calls `onError({ error,
action })`. `onDataLoad({ range, rows })` follows each read;
`api.reloadEvents()` reads again and `api.setLoading(loading)` drives the
loading part, replaced by `renderLoading`.

```ts
const source: SchedulerDataSource<Row> = {
  read: ({ range, signal }) => fetch(`/events?from=${range.start.toISOString()}&to=${range.end.toISOString()}`, { signal }).then((r) => r.json()).then((rows) => ({ rows })),
  write: ({ added, changed, deleted, signal }) => fetch('/events', { method: 'POST', body: JSON.stringify({ added, changed, deleted }), signal }).then(() => ({ status: 'applied' })),
};
```

## Queries

`api.getEvents({ start, end, includeOccurrences })`, `api.getViewEvents()`,
`api.getEventInfo(id | element)`, `api.getViewDates()`,
`api.getCellInfo(element)` and `api.getSelectedCells()` return application
rows and dates; ids are your ids (new ids come from `editing.createId`,
default the next number or a random id). `api.refresh()`
re-measures and `api.reloadEvents()` re-reads.
`api.getState()` / `api.restoreState(state)` save and restore view, date and
the all-day row.

### Live demo: Remote events

Live demo: https://salmonui.dev/demos/calendars/scheduler-remote

A data source read per visible range with latency and abort, writes that apply at once and revert when the server rejects them, onDataLoad and onError, a custom loading indicator, setLoading, reloadEvents and the event query methods.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Scheduler, type SchedulerApi, type SchedulerDataSource } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string };

const pad = (n: number) => String(n).padStart(2, '0');
// The "server": two events per weekday from November 2026 to January 2027.
function serverRows(): Row[] {
  const out: Row[] = [];
  let id = 1;
  for (let t = Date.UTC(2026, 10, 1); t < Date.UTC(2027, 1, 1); t += 86_400_000) {
    const d = new Date(t);
    if (d.getUTCDay() === 0 || d.getUTCDay() === 6) continue;
    const day = d.toISOString().slice(0, 10);
    out.push({ id: id++, title: 'Standup', start: `${day}T09:00`, end: `${day}T09:15` });
    out.push({ id: id++, title: `Focus block ${pad(d.getUTCDate())}`, start: `${day}T13:00`, end: `${day}T15:00` });
  }
  return out;
}

/** A remote event source read per visible range with latency, writes that the server can reject, the loading indicator and the query methods. */
export default function SchedulerRemoteDemo() {
  const apiRef = useRef<SchedulerApi<Row>>(null);
  const server = useRef<Row[] | null>(null);
  const [reject, setReject] = useState(false);
  const rejectRef = useRef(false);
  const [log, setLog] = useState<string[]>([]);
  const add = (line: string) => setLog((lines) => [line, ...lines].slice(0, 8));
  const source = useMemo<SchedulerDataSource<Row>>(
    () => ({
      read: ({ range, signal }) =>
        new Promise((resolve, rejectRead) => {
          const db = (server.current ??= serverRows());
          const from = range.start.toISOString().slice(0, 10);
          const to = range.end.toISOString().slice(0, 10);
          const timer = setTimeout(() => resolve({ rows: db.filter((r) => r.start >= from && r.start < to) }), 600);
          signal.addEventListener('abort', () => {
            clearTimeout(timer);
            rejectRead(new DOMException('Aborted', 'AbortError'));
          });
        }),
      write: ({ action, added, changed, deleted }) =>
        new Promise((resolve) =>
          setTimeout(() => {
            if (rejectRef.current) return resolve({ status: 'rejected' });
            const db = (server.current ??= serverRows());
            for (const r of deleted) db.splice(db.findIndex((x) => x.id === r.id), 1);
            for (const r of changed) db.splice(db.findIndex((x) => x.id === r.id), 1, r);
            db.push(...added);
            resolve({ status: 'applied' });
            add(`write ${action}: +${added.length} ~${changed.length} -${deleted.length}`);
          }, 500),
        ),
    }),
    [],
  );
  return (
    <div>
      <div className="demo-toolbar">
        <Checkbox
          checked={reject}
          onCheckedChange={(checked) => {
            rejectRef.current = checked;
            setReject(checked);
          }}
        >
          Server rejects writes
        </Checkbox>
        <Button variant="outline" type="button" onClick={() => apiRef.current?.reloadEvents()}>
          reloadEvents()
        </Button>
        <Button
          variant="outline"
          type="button"
          onClick={() => {
            apiRef.current?.setLoading(true);
            setTimeout(() => apiRef.current?.setLoading(false), 1500);
          }}
        >
          setLoading for 1.5 s
        </Button>
        <Button variant="outline" type="button" onClick={() => add(`getViewEvents(): ${apiRef.current?.getViewEvents().length ?? 0} occurrences in view`)}>
          getViewEvents()
        </Button>
        <Button
          variant="outline"
          type="button"
          onClick={() => {
            const list = apiRef.current?.getEvents({ start: new Date(Date.UTC(2026, 10, 25)), end: new Date(Date.UTC(2026, 10, 26)) }) ?? [];
            add(`getEvents(25 Nov): ${list.map((e) => e.row.title).join(', ') || 'none'}`);
          }}
        >
          getEvents(25 Nov)
        </Button>
        <Button variant="outline" type="button" onClick={() => add(`getViewDates(): ${apiRef.current?.getViewDates().map(String).join(', ') ?? ''}`)}>
          getViewDates()
        </Button>
      </div>
      <Scheduler<Row>
        ref={apiRef}
        data={source}
        view="week"
        views={['day', 'week', 'month']}
        date="2026-11-23"
        timeZone="UTC"
        height={520}
        scrollTime="08:00"
        renderLoading={() => <span role="status">Loading events from the server…</span>}
        onDataLoad={(e) => add(`onDataLoad: ${e.rows.length} rows for ${e.range.start.toISOString().slice(0, 10)} to ${e.range.end.toISOString().slice(0, 10)}`)}
        onError={(e) => add(`onError(${e.action}): ${String(e.error)}; the change was reverted`)}
      />
      <div className="demo-log" aria-live="polite">
        <ol>{log.length ? log.map((line, i) => <li key={`${i}-${line}`}>{line}</li>) : <li>Navigate, edit or press a button</li>}</ol>
      </div>
    </div>
  );
}
```

## Event selection and shortcuts

A click selects an event, Ctrl / Cmd + click toggles one, Shift + click adds
every visible event between the last selected one and the clicked one in time
order. `onEventSelectionChange(ids, event)` reports event ids (a series once)
with the occurrence `keys` and `rows`; `selectedEventIds` is reactive and
selects every visible occurrence of those events.

Inside the Scheduler, Alt+1..9 switch to the nth view, Ctrl / Cmd + Left /
Right go to the previous / next range (mirrored in RTL), Delete asks to delete
the selected event and Escape clears the event selection.

## Keyboard and accessibility

Each view grid (day, week and month cells, timeline rows) is one tab stop
with a roving tabindex (WAI-ARIA grid pattern): Tab enters on the last
focused item, the selected cell or the first visible cell, and Tab leaves
the grid. The arrow keys move between the cells and the parts inside them
(events, "+N more", the month date links) by screen position, so they follow
the layout in RTL too: an event comes right after the cell it starts in,
moving down or toward the inline end, and a wide bar keeps the column it was
entered from. Home / End go to the first / last cell of the row; Escape on an
event returns to its cell. Enter or Space on a cell opens its quick info
(Alt+Enter the editor), on an event the quick info; the list views keep every
event as a tab stop.

Events are buttons named by their title, time (and location) and, in grouped
views, their resource; cells are `gridcell`s labelled with their date, time
and resource, with `aria-selected` for the cell selection.

`keyBindings` remaps the commands (`Mod` is Ctrl or Cmd; an empty list turns
a command off): `navigation.previous` / `navigation.next` (Mod+Left /
Right), `view.1` .. `view.9` (Alt+1..9), `event.delete` (Delete),
`selection.clear` (Escape) and `clipboard.copy` / `cut` / `paste` (Mod+C /
X / V). The grid's arrow, Home and End keys are fixed.

```tsx
<Scheduler data={events} keyBindings={{ 'navigation.next': ['Alt+PageDown'], 'event.delete': [] }} />;
```

### Live demo: Selection, keyboard, clipboard and menus

Live demo: https://salmonui.dev/demos/calendars/scheduler-selection-keyboard

Cell range selection kept in one day column, event selection with Ctrl / Cmd and Shift, a roving-tabindex grid with remapped navigation shortcuts, clipboard copy, cut and paste, a context menu on cells and events, and event tooltips with one suppressed.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Scheduler, type EventId, type SchedulerApi } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string; location?: string; private?: boolean };

const initial: Row[] = [
  { id: 1, title: 'Design sync', start: '2026-11-23T09:00', end: '2026-11-23T10:00', location: 'Room 2' },
  { id: 2, title: 'Code review', start: '2026-11-23T11:00', end: '2026-11-23T12:00', location: 'Online' },
  { id: 3, title: 'Doctor (private)', start: '2026-11-24T08:00', end: '2026-11-24T09:00', private: true },
  { id: 4, title: 'Release check', start: '2026-11-25T15:00', end: '2026-11-25T16:00', location: 'Room 5' },
];

/** Cell range selection, event selection with Ctrl and Shift, keyboard grid navigation and remapped shortcuts, clipboard copy, cut and paste, a context menu and event tooltips. */
export default function SchedulerSelectionKeyboardDemo() {
  const apiRef = useRef<SchedulerApi<Row>>(null);
  const [rows, setRows] = useState<readonly Row[]>(initial);
  const [selected, setSelected] = useState<readonly EventId[]>([]);
  const [range, setRange] = useState('');
  const [log, setLog] = useState<string[]>([]);
  const add = (line: string) => setLog((lines) => [line, ...lines].slice(0, 8));
  const hhmm = (d: Date) => d.toISOString().slice(5, 16).replace('T', ' ');
  return (
    <div>
      <div className="demo-toolbar">
        <Button variant="outline" type="button" onClick={() => setSelected([1, 2])}>
          Select design sync and code review
        </Button>
        <Button variant="outline" type="button" onClick={() => void apiRef.current?.copy().then((n) => add(`api.copy(): ${n}`))}>
          api.copy()
        </Button>
        <Button variant="outline" type="button" onClick={() => void apiRef.current?.paste({ start: new Date(Date.UTC(2026, 10, 27, 9)) }).then((r) => add(`api.paste(Fri 09:00): ${r.status}`))}>
          api.paste(Fri 09:00)
        </Button>
        <Button variant="outline" type="button" onClick={() => apiRef.current?.closeTooltip()}>
          closeTooltip()
        </Button>
      </div>
      <Scheduler<Row>
        ref={apiRef}
        aria-label="Team calendar"
        data={rows}
        view="week"
        views={['day', 'week', 'workWeek', 'month']}
        date="2026-11-23"
        timeZone="UTC"
        locale="en-GB"
        height={520}
        scrollTime="08:00"
        cellSelection="multiple"
        cellSelectionRows={false}
        onCellSelectionChange={(s) => setRange(`${hhmm(s.start)} to ${hhmm(s.end)}${s.allDay ? ' (all day)' : ''}`)}
        selectedEventIds={selected}
        onEventSelectionChange={(ids, e) => {
          setSelected(ids);
          add(`onEventSelectionChange: [${ids.join(', ')}] via ${e.source}`);
        }}
        keyBindings={{ 'navigation.next': ['Alt+PageDown', 'Mod+ArrowRight'], 'navigation.previous': ['Alt+PageUp', 'Mod+ArrowLeft'] }}
        clipboard
        onBeforePaste={(e) => {
          e.data = e.data.map((r) => ({ ...r, title: e.cut ? r.title : `${r.title} (copy)` }));
          add(`onBeforePaste: ${e.data.length} event(s), cut ${String(e.cut)}`);
        }}
        contextMenu={(ctx) =>
          ctx.kind === 'event'
            ? [{ id: 'edit', label: 'Edit' }, { id: 'duplicate', label: 'Duplicate to next day' }, { type: 'separator' }, { id: 'delete', label: 'Delete' }]
            : [{ id: 'newEvent', label: 'New event' }, { id: 'newRecurringEvent', label: 'New recurring event' }, { id: 'today', label: 'Today' }]
        }
        onContextMenuItemClick={(e) => {
          add(`onContextMenuItemClick: ${e.id} on ${e.context.kind}`);
          if (e.id === 'duplicate' && e.context.kind === 'event') {
            const r = e.context.row;
            const shift = (s: string) => new Date(new Date(`${s}Z`).getTime() + 86_400_000).toISOString().slice(0, 16);
            apiRef.current?.addEvents([{ ...r, id: 0, title: `${r.title} (copy)`, start: shift(r.start), end: shift(r.end) }]);
          }
        }}
        tooltip={{ render: ({ row }) => `${row.title}${row.location ? ` · ${row.location}` : ''}` }}
        onBeforeTooltipOpen={(e) => {
          if (e.row.private) e.preventDefault();
        }}
        onAdd={(e) => setRows(e.data)}
        onSave={(e) => setRows(e.data)}
        onDelete={(e) => setRows(e.data)}
      />
      <p className="demo-status" aria-live="polite">
        Selected events: [{selected.join(', ')}] · Selected cells: {range || 'none'}
      </p>
      <div className="demo-log">
        <ol>{log.length ? log.map((line, i) => <li key={`${i}-${line}`}>{line}</li>) : <li>Select, copy, paste or right-click</li>}</ol>
      </div>
    </div>
  );
}
```

## Adaptive layout

`adaptive` switches to a compact layout for narrow screens: the view buttons
become a view menu (a `select`), the time axis narrows and grouped views
show one resource at a time with a resource picker (a `select`, which opens
as the platform's sheet on touch devices). `adaptive` is always compact,
also in server markup; `adaptive={{ breakpoint: 640 }}` is compact while the
Scheduler's own width is below the breakpoint, measured after hydration (the
server renders the full layout, so hydration matches). The shown resource is
the first leaf unless `selectedResourceId` names one; picking another fires
`onSelectedResourceChange(id, event)`, and the prop is re-applied when it
changes.

```tsx
<Scheduler data={events} resources={[rooms]} grouping={{ resources: ['rooms'] }} adaptive={{ breakpoint: 640 }} />;
```

### Live demo: Adaptive layout and theming

Live demo: https://salmonui.dev/demos/calendars/scheduler-adaptive-theming

A clinic schedule that switches to the compact layout below 700 px of its own width with a view menu and one doctor at a time, resource colors mixed against the theme seeds, and events in the server-rendered HTML.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Select } from '@salmonui/dropdowns/select';
import { Scheduler, type SchedulerResource } from '@salmonui/scheduler';
import { ThemeProvider, type SalmonHexColor } from '@salmonui/core/theme';

type Row = { id: number; title: string; start: string; end: string; doctorId: number };

const doctors: SchedulerResource = {
  field: 'doctorId',
  name: 'doctors',
  label: 'Doctor',
  data: [
    { id: 1, text: 'Dr. Alvarez', color: '#2f9e44' },
    { id: 2, text: 'Dr. Brooks', color: '#9c36b5' },
    { id: 3, text: 'Dr. Chen', color: '#e8590c' },
  ],
};

const rows: Row[] = [
  { id: 1, title: 'Check-up', start: '2026-11-23T09:00', end: '2026-11-23T09:30', doctorId: 1 },
  { id: 2, title: 'Follow-up', start: '2026-11-23T10:00', end: '2026-11-23T10:30', doctorId: 2 },
  { id: 3, title: 'Consultation', start: '2026-11-24T11:00', end: '2026-11-24T12:00', doctorId: 3 },
  { id: 4, title: 'Vaccination', start: '2026-11-25T14:00', end: '2026-11-25T14:15', doctorId: 1 },
];

const WIDTHS = { phone: 380, tablet: 640, desktop: 1000 } as const;
const SEEDS: SalmonHexColor[] = ['#2563eb', '#0f766e', '#be185d'];
const WIDTH_ITEMS = Object.entries(WIDTHS).map(([key, px]) => ({ value: key, label: `${key} (${px} px)` }));
const SEED_ITEMS = SEEDS.map((s) => ({ value: s, label: s }));

/** The adaptive layout below a container width with one resource at a time, the color seeds and resource colors, and server-rendered events. */
export default function SchedulerAdaptiveThemingDemo() {
  const [width, setWidth] = useState<keyof typeof WIDTHS>('phone');
  const [primary, setPrimary] = useState<SalmonHexColor>('#2563eb');
  const [doctor, setDoctor] = useState<unknown>(2);
  return (
    <div>
      <div className="demo-toolbar">
        <label>
          Container
          <Select aria-label="Container" data={WIDTH_ITEMS} value={width} onValueChange={(value) => value != null && setWidth(value as keyof typeof WIDTHS)} />
        </label>
        <label>
          Primary seed
          <Select aria-label="Primary seed" data={SEED_ITEMS} value={primary} onValueChange={(value) => value != null && setPrimary(value as SalmonHexColor)} />
        </label>
      </div>
      <ThemeProvider theme={{ colors: { primary } }}>
        <div style={{ inlineSize: WIDTHS[width], maxInlineSize: '100%' }}>
          <Scheduler<Row>
            data={rows}
            resources={[doctors]}
            grouping={{ resources: ['doctors'] }}
            adaptive={{ breakpoint: 700 }}
            selectedResourceId={doctor}
            onSelectedResourceChange={(id) => setDoctor(id)}
            view="week"
            views={['day', 'week', 'month']}
            date="2026-11-23"
            timeZone="UTC"
            locale="en-GB"
            height={520}
            scrollTime="08:00"
          />
        </div>
      </ThemeProvider>
      <p className="demo-status" aria-live="polite">
        Shown resource: {String(doctor)}
      </p>
    </div>
  );
}
```

## Clipboard

With `clipboard`, Ctrl / Cmd + C copies the selected events, Ctrl / Cmd + X
cuts them and Ctrl / Cmd + V pastes at the selected cells (else the focused
cell); `api.copy()`, `api.cut()` and `api.paste(target?)` work without the
prop. Pasted events keep their offsets from the earliest copied one, which
lands at the target start; on a month cell or the all-day row they move by
whole days and keep their time of day. A grouped target cell sets the
resource. Copies are new events without recurrence (through `addEvents`, so
`onBeforeAdd` / `onAdd` and overlap rules apply); a cut pastes once and moves
the events through the save path (`onBeforeSave` / `onSave`, one occurrence
of a series as an exception). `onBeforePaste` sees the rows with their new
times and cancels with `preventDefault()` or replaces `event.data`. The
clipboard belongs to one Scheduler instance; it does not use the system
clipboard.

```tsx
<Scheduler data={events} clipboard onBeforePaste={(e) => (e.data = e.data.map((r) => ({ ...r, title: `${r.title} (copy)` })))} />;
```

## Drag, resize and swipe

Editable events move by pointer (`draggable`, default `true`) and resize from
their start and end edges (`resizable`, default `true`): the block edges of
timed events in day views, the inline edges of bars in the all-day row, Month
and the timelines. A drag starts after a 4 px move (a 400 ms hold on touch);
Escape cancels it. While the pointer moves, a copy of the event follows in the
top layer and nothing re-renders: the drop commits once through the regular
save path (`onBeforeSave` / `onSave`, overlap rules and blocks, the recurrence
scope alert for occurrences, a remote source's pending state and revert).

```tsx
<Scheduler
  data={events}
  dragOptions={{ snapMinutes: 15, navigateOnEdge: true, multiple: true, excludeSelector: '.no-drag' }}
  onEventDragStart={(e) => e.row.locked && e.preventDefault()}
  onBeforeEventDrop={(e) => isWorkingTime(e.start, e.end) || e.preventDefault()}
  onEventDrop={(e) => log(e.result.status)}
  onBeforeEventResizeEnd={(e) => e.end.getTime() - e.start.getTime() <= 4 * 3_600_000 || e.preventDefault()}
/>;
```

- Timed starts and ends snap to `dragOptions.snapMinutes` (default the slot
  length); the all-day row, Month and the day timelines move by whole days and
  keep the time of day. A timed event stays timed and an all-day event stays
  in day cells.
- `onEventDragStart` / `onEventResizeStart` cancel the gesture,
  `onEventDrag` / `onEventResize` fire at most once per frame when the
  proposed time or resource changes, `onBeforeEventDrop` /
  `onBeforeEventResizeEnd` cancel the drop and `onEventDrop` /
  `onEventResizeEnd` report the save `result`.
- `autoScroll` (default `true`) scrolls the view near its edges;
  `navigateOnEdge` (`true` or `{ delay }`, default 1000 ms) goes to the
  previous / next range while the pointer rests at the Scheduler's inline
  edge.
- `dragOptions.multiple` moves every selected event (see
  [Event selection](https://salmonui.dev/docs/calendars/scheduler#event-selection-and-shortcuts)) by the same offset.
- Dropping on another resource row or column changes the event's resource
  ids (the origin resource is replaced, other ids of a `multiple` resource are
  kept).
- `onExternalDrop({ data, start, end, allDay, resourceIds })` receives HTML
  drag data dropped on a slot; the rows it returns are added (`onBeforeAdd` /
  `onAdd`). A drop over `dragOptions.dragOutArea` (an element or a selector)
  fires `onEventDragOut` instead of moving the event.
- Schedulers with the same `dragOptions.group` accept each other's events:
  the target adds a copy (`onAdd`) and the source deletes the event
  (`onDelete`). Recurring events do not leave their Scheduler. A Data Grid
  row drag reaches a Scheduler through `rowDrag.targetId` (the Scheduler
  `id`): the drop's `target` is the Scheduler, so `onRowDrop` hit-tests the
  last pointer position (`document.elementFromPoint`) and
  `api.getCellInfo(element)` gives the slot for `api.addEvents`.
- `swipeNavigation` (default `true` on coarse pointers) navigates on a quick
  horizontal touch swipe over a day or month view, mirrored in RTL; a gesture
  that starts on an event is a drag.
- In RTL the pointer's x maps mirrored on timelines and the inline end edge
  is on the left.

### Live demo: Drag, resize and drop

Live demo: https://salmonui.dev/demos/calendars/scheduler-drag-drop

Events that move and resize in 15-minute steps with cancellable start, drop and resize events, several selected events dragged together, backlog items dropped onto slots, events dragged out to a remove area and between two Schedulers, and touch swipe navigation.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Scheduler } from '@salmonui/scheduler';

type Row = { id: number | string; title: string; start: string | Date; end: string | Date; locked?: boolean };

const mine: Row[] = [
  { id: 1, title: 'Write report', start: '2026-11-23T09:00', end: '2026-11-23T11:00' },
  { id: 2, title: 'Review PRs', start: '2026-11-24T10:00', end: '2026-11-24T11:00' },
  { id: 3, title: 'Prepare slides', start: '2026-11-24T14:00', end: '2026-11-24T15:30' },
  { id: 4, title: 'Fixed: audit (no drag)', start: '2026-11-25T09:00', end: '2026-11-25T10:00', locked: true },
];
const teammate: Row[] = [{ id: 101, title: 'Pair session', start: '2026-11-23T13:00', end: '2026-11-23T14:00' }];
const backlog = ['Call supplier', 'Update roadmap', 'Expense report'];
const hhmm = (d: Date) => d.toISOString().slice(11, 16);

/** Drag and resize with snapping and cancellable events, multi-drag of selected events, drops from an external list and onto a remove area, and two Schedulers that exchange events. */
export default function SchedulerDragDropDemo() {
  const [rows, setRows] = useState<readonly Row[]>(mine);
  const [other, setOther] = useState<readonly Row[]>(teammate);
  const [selected, setSelected] = useState<readonly (number | string)[]>([]);
  const [items, setItems] = useState(backlog);
  const [log, setLog] = useState<string[]>([]);
  const add = (line: string) => setLog((lines) => [line, ...lines].slice(0, 8));
  const common = { date: '2026-11-23', timeZone: 'UTC', locale: 'en-GB', scrollTime: '08:00', quickInfo: false, views: ['week' as const, 'month' as const] };
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
        <ul aria-label="Backlog: drag an item onto a time slot" style={{ display: 'flex', flexWrap: 'wrap', gap: 8, listStyle: 'none', padding: 0, margin: 0 }}>
          {items.map((item) => (
            <li key={item} draggable onDragStart={(e) => e.dataTransfer.setData('text/plain', item)} style={{ padding: '6px 12px', border: '1px solid var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-md)', whiteSpace: 'nowrap', cursor: 'grab' }}>
              {item}
            </li>
          ))}
        </ul>
        <div data-drag-out="" style={{ padding: '6px 12px', border: '1px dashed var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-md)' }}>
          Drop an event here to unschedule it
        </div>
      </div>
      <Scheduler<Row>
        id="drag-mine"
        aria-label="My week"
        data={rows}
        view="week"
        height={460}
        {...common}
        selectedEventIds={selected}
        onEventSelectionChange={(ids) => setSelected(ids)}
        dragOptions={{ snapMinutes: 15, multiple: true, navigateOnEdge: true, dragOutArea: '[data-drag-out]', group: 'team' }}
        onEventDragStart={(e) => {
          if (e.row.locked) {
            e.preventDefault();
            add(`onEventDragStart cancelled for ${e.row.title}`);
          }
        }}
        onEventDrag={(e) => add(`onEventDrag ${e.rows.length} event(s) to ${hhmm(e.start)}`)}
        onBeforeEventDrop={(e) => {
          if (e.start.getUTCHours() < 8) {
            e.preventDefault();
            add('onBeforeEventDrop cancelled: before 08:00');
          }
        }}
        onEventDrop={(e) => add(`onEventDrop ${e.result.status}: ${e.rows.map((r) => r.title).join(', ')}`)}
        onEventResizeStart={(e) => add(`onEventResizeStart (${e.edge})`)}
        onBeforeEventResizeEnd={(e) => {
          if (e.end.getTime() - e.start.getTime() > 3 * 3_600_000) {
            e.preventDefault();
            add('onBeforeEventResizeEnd cancelled: longer than 3 hours');
          }
        }}
        onEventResizeEnd={(e) => add(`onEventResizeEnd ${e.result.status}: ${hhmm(e.start)} to ${hhmm(e.end)}`)}
        onExternalDrop={(e) => {
          const title = e.data?.getData('text/plain');
          if (!title) return null;
          setItems((list) => list.filter((x) => x !== title));
          add(`onExternalDrop ${title} at ${hhmm(e.start)}`);
          return [{ id: `new-${title}`, title, start: e.start, end: new Date(e.start.getTime() + 3_600_000) }];
        }}
        onEventDragOut={(e) => {
          add(`onEventDragOut ${e.row.title}`);
          setRows((list) => list.filter((r) => r.id !== e.row.id));
          setItems((list) => [...list, e.row.title]);
        }}
        swipeNavigation
        onDateChange={(d, e) => add(`onDateChange ${String(d)} (${e.source})`)}
        onAdd={(e) => setRows(e.data)}
        onSave={(e) => setRows(e.data)}
        onDelete={(e) => setRows(e.data)}
      />
      <Scheduler<Row>
        id="drag-teammate"
        aria-label="Teammate's week"
        data={other}
        view="week"
        height={320}
        {...common}
        dragOptions={{ group: 'team' }}
        onAdd={(e) => {
          setOther(e.data);
          add(`Teammate onAdd: ${e.rows.map((r) => r.title).join(', ')}`);
        }}
        onSave={(e) => setOther(e.data)}
        onDelete={(e) => setOther(e.data)}
      />
      <div className="demo-log" aria-live="polite">
        <ol>{log.length ? log.map((line, i) => <li key={`${i}-${line}`}>{line}</li>) : <li>Drag or resize an event</li>}</ol>
      </div>
    </div>
  );
}
```

## Export and import

`exportToCsv` writes RFC 4180 CSV without a writer package and escapes
spreadsheet formulas in text cells by default (`escapeFormulas: false`
restores raw output). `exportToExcel`,
`exportToICalendar` and `importICalendar` load their writer from
`exportWriters`, dynamic imports of `@salmonui/export` subpaths, so
the writers stay out of your bundle until the first call:

```tsx
<Scheduler
  ref={apiRef}
  data={events}
  exportWriters={{ excel: () => import('@salmonui/export/xlsx'), ics: () => import('@salmonui/export/ics') }}
  onBeforeExport={(e) => e.format === 'excel' && !canExport && e.preventDefault()}
/>;

await apiRef.current.exportToExcel({ fields: ['title', 'start', 'end'], headerTexts: { title: 'Subject' }, fileName: 'week' });
await apiRef.current.exportToCsv({ includeOccurrences: true, separator: ';' });
await apiRef.current.exportToICalendar({ calendarName: 'Team' });
await apiRef.current.importICalendar(file); // a File, Blob or text; fires onBeforeAdd / onAdd
```

Each export resolves to `{ fileName, mimeType, data }` (null when
`onBeforeExport` prevents it), fires `onExport` with the file, and downloads
it unless `download: false`. `fields` pick roles (`title`), mapped properties
or other row properties; `includeOccurrences` writes one row per occurrence of
the visible range (or `range`); `rows` exports other rows. Dates are written in the Scheduler zone: zoned ISO 8601 in CSV,
date-time cells in XLSX. iCalendar timed events use TZID wall times (UTC with
`utc: true`), series carry their RRULE and deleted occurrences as EXDATE, and
edited occurrences are VEVENTs with a RECURRENCE-ID; on import, EXDATE and
RECURRENCE-ID values become `recurrenceExceptions`.

### Live demo: Export, import and print

Live demo: https://salmonui.dev/demos/calendars/scheduler-export-print

XLSX export with chosen fields and headers, CSV with one row per occurrence and escaped formulas, an iCalendar file with RRULE and EXDATE, iCalendar import from text or a file, and printing the rendered week.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Scheduler, type SchedulerApi, type SchedulerExportWriters } from '@salmonui/scheduler';

type Row = { id: number | string; title: string; start: string | Date; end: string | Date; location?: string; recurrenceRule?: string; recurrenceExceptions?: string };

const initial: Row[] = [
  { id: 1, title: 'Standup', start: '2026-11-23T09:00', end: '2026-11-23T09:15', recurrenceRule: 'FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR', recurrenceExceptions: '20261125T090000Z', location: 'Room 1' },
  { id: 2, title: 'Budget review', start: '2026-11-24T14:00', end: '2026-11-24T15:30', location: 'Boardroom' },
  { id: 3, title: '=HYPERLINK("x") formula-looking title', start: '2026-11-26T11:00', end: '2026-11-26T12:00' },
];

// Writers load on first use: dynamic imports of @salmonui/export subpaths.
const writers: SchedulerExportWriters = {
  excel: () => import('@salmonui/export/xlsx'),
  ics: () => import('@salmonui/export/ics'),
};

const SAMPLE_ICS = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Demo//EN', 'BEGIN:VEVENT', 'UID:imported-1@demo', 'DTSTAMP:20261120T000000Z', 'DTSTART:20261127T130000Z', 'DTEND:20261127T140000Z', 'SUMMARY:Imported workshop', 'LOCATION:Online', 'END:VEVENT', 'END:VCALENDAR'].join('\r\n');

/** Excel, CSV and iCalendar export through lazily loaded writers, iCalendar import from a file or text, and printing the rendered view. */
export default function SchedulerExportPrintDemo() {
  const apiRef = useRef<SchedulerApi<Row>>(null);
  const [rows, setRows] = useState<readonly Row[]>(initial);
  const [preview, setPreview] = useState('');
  const [status, setStatus] = useState('');
  const download = useRef(true);
  const fileInput = useRef<HTMLInputElement>(null);
  return (
    <div>
      <div className="demo-toolbar">
        <Checkbox
          defaultChecked
          onCheckedChange={(checked) => {
            download.current = checked;
          }}
        >
          Download files
        </Checkbox>
        <Button
          variant="outline"
          type="button"
          onClick={() =>
            void apiRef.current?.exportToExcel({ fields: ['title', 'start', 'end', 'location'], headerTexts: { title: 'Subject' }, fileName: 'week', sheetName: 'Week 48', download: download.current }).then((f) => setStatus(f ? `${f.fileName}: ${f.data.byteLength} bytes (${f.mimeType})` : 'cancelled'))
          }
        >
          Export Excel
        </Button>
        <Button
          variant="outline"
          type="button"
          onClick={() =>
            void apiRef.current?.exportToCsv({ includeOccurrences: true, separator: ';', fileName: 'week', download: download.current }).then((f) => {
              setStatus(f ? `${f.fileName} (${f.mimeType})` : 'cancelled');
              setPreview(f?.data ?? '');
            })
          }
        >
          Export CSV (occurrences)
        </Button>
        <Button
          variant="outline"
          type="button"
          onClick={() =>
            void apiRef.current?.exportToICalendar({ calendarName: 'Team week', fileName: 'team', download: download.current }).then((f) => {
              setStatus(f ? `${f.fileName} (${f.mimeType})` : 'cancelled');
              setPreview(f?.data ?? '');
            })
          }
        >
          Export iCalendar
        </Button>
        <Button variant="outline" type="button" onClick={() => void apiRef.current?.importICalendar(SAMPLE_ICS).then((r) => setStatus(`importICalendar: ${r.status}, ${r.rows.length} event(s)`))}>
          Import sample .ics
        </Button>
        <Button variant="outline" type="button" onClick={() => fileInput.current?.click()}>
          Import a .ics file…
        </Button>
        <input
          ref={fileInput}
          type="file"
          accept=".ics,text/calendar"
          hidden
          onChange={(e) => {
            const file = e.target.files?.[0];
            e.target.value = '';
            if (file) void apiRef.current?.importICalendar(file).then((r) => setStatus(`importICalendar(${file.name}): ${r.status}, ${r.rows.length} event(s)`));
          }}
        />
        <Button variant="outline" type="button" onClick={() => void apiRef.current?.print({ width: '27cm' }).then((ok) => setStatus(`print(): ${String(ok)}`))}>
          Print
        </Button>
      </div>
      <Scheduler<Row>
        ref={apiRef}
        data={rows}
        view="week"
        views={['week', 'month']}
        date="2026-11-23"
        timeZone="Europe/Berlin"
        locale="en-GB"
        height={480}
        scrollTime="08:00"
        exportWriters={writers}
        onExport={(e) => setStatus(`onExport(${e.format}): ${e.file.fileName}`)}
        onBeforePrint={() => setStatus('onBeforePrint')}
        onAfterPrint={() => setStatus('onAfterPrint: the print dialog closed')}
        onAdd={(e) => setRows(e.data)}
        onSave={(e) => setRows(e.data)}
        onDelete={(e) => setRows(e.data)}
      />
      <p className="demo-status" aria-live="polite">
        {status || 'Export, import or print'}
      </p>
      {preview ? <pre className="demo-log" style={{ maxBlockSize: 200, whiteSpace: 'pre-wrap' }}>{preview}</pre> : null}
    </div>
  );
}
```

## Context menu

`contextMenu` opens the Menu family's `ContextMenu` on cells and events:
right-click, a touch long-press, Shift+F10 or the ContextMenu
key on a focused cell or event. `true` shows the default items, built from
`localeText`: **New event**, **New recurring event** (the editor opens with a
daily rule) and **Today** on cells, **Edit** and **Delete** on events (with
the recurrence scope and delete prompts). An array shows the same items
everywhere; a function returns the items for each target, and an empty array
or `null` leaves the browser's own menu:

```tsx
import '@salmonui/buttons/menu/styles.css';

<Scheduler
  data={events}
  contextMenu={(ctx) =>
    ctx.kind === 'event'
      ? [{ id: 'duplicate', label: 'Duplicate' }, { type: 'separator' }, { id: 'delete', label: 'Delete' }]
      : [{ id: 'newEvent', label: 'New event' }]
  }
  onContextMenuItemClick={(e) => {
    if (e.id === 'duplicate' && e.context.kind === 'event') duplicate(e.context.row);
  }}
/>;
```

The context is `{ kind: 'cell', start, end, allDay, resources, element }`
(the whole selected range when the cell is in it; `resources` holds the
resource ids of the cell's group) or `{ kind: 'event', occurrence, row,
element }`.
`onContextMenuItemClick` receives `{ id, item, context, source }`; the default
ids (`newEvent`, `newRecurringEvent`, `today`, `edit`, `delete`) run their
action unless you call `preventDefault()`. The menu is a lazy chunk loaded
when the browser is idle after mount (a request before that opens once it
loads), and its styles are the Menu family's: import
`@salmonui/buttons/menu/styles.css` next to the Scheduler stylesheet. Focus
returns to the cell or event when the menu closes.

## Tooltips

`tooltip` shows Layout's `Tooltip` on events: after a short hover delay, and at once when an event gets
keyboard focus. It shows the title, the time range and the location;
`tooltip={{ render }}` replaces the content. `onBeforeTooltipOpen` receives
`{ occurrence, row, element, source }` and `preventDefault()` keeps the
tooltip closed; `api.closeTooltip()` closes it. Escape, leaving the event,
blur and a press close it, and the event is described by the tooltip while
it is open. One tooltip serves every event (a lazy chunk with delegated
listeners, so the events render no extra markup); import
`@salmonui/overlays/tooltip/styles.css` next to the Scheduler stylesheet.

```tsx
import '@salmonui/overlays/tooltip/styles.css';

<Scheduler data={events} tooltip={{ render: ({ row }) => `${row.title} · ${row.owner}` }} onBeforeTooltipOpen={(e) => e.row.private && e.preventDefault()} />;
```

## Print

`api.print({ height, width })` prints the rendered view: a copy
of the Scheduler goes into a print-only container (inside a copy of its
theme scope, so the colors match), the rest of the page is hidden while the
browser's print dialog is open, and `window.print()` runs. Without `height`
the scroll areas grow to their content, so a day or week view prints every
hour; numbers are pixels, strings any CSS length (`'20cm'`). `onBeforePrint`
receives the options and `preventDefault()` cancels (the promise resolves
`false`); `onAfterPrint` fires with the window's `afterprint`, after the
copy is removed. The print code is a lazy chunk loaded by the first call.

```tsx
<Scheduler ref={apiRef} data={events} onBeforePrint={(e) => !canPrint && e.preventDefault()} onAfterPrint={() => track('print')} />;

await apiRef.current.print({ width: '27cm' });
```

## Customizing

- `renderEvent(ctx)` renders the event content (`{ row, id, title, start,
  end, allDay, view, recurring, selected, timeText }`), per view through
  `views`.
- `getEventProps(ctx)` adds `className`, `style`, `data-*` or `hidden`;
`getCellProps(ctx)` does the same for cells, with
  `ctx.part: 'workCell' | 'monthCell' | 'allDayCell' | 'dateHeader' | ...`.
- `renderCell`, `renderCellHeader`, `renderDateHeader` and
  `renderHeaderIndent` render cell parts.
- `toolbar` lists the header items: `'previous'`, `'next'`, `'today'`,
  `'dateRange'`, `'newEvent'`, `'views'` and `{ id, label, align, onClick,
  render }` items; `toolbar={false}` hides the header and `renderToolbar`
  wraps it.
- `onCellClick`, `onCellDoubleClick`, `onEventClick` and `onEventDoubleClick`
  fire before the built-in popup or editor (`preventDefault()` skips it);
  `onHover` reports the part under the pointer.
- `cellSelection="multiple"` selects a time range by dragging or Shift+click
  (`onCellSelectionChange`, `api.getSelectedCells()`); `cellSelectionRows:
  false` keeps a drag in one day column (day views) or one row.
- `locale` and `localeText` (`SCHEDULER_DEFAULT_LOCALE_TEXT`, Data Grid
  message format) translate every string.
- `height`, `width`, `className` and `style` size the root.

### Live demo: Templates and render hooks

Live demo: https://salmonui.dev/demos/calendars/scheduler-templates

Event content per view, event and cell classes and data attributes, date and cell header templates, a header indent, a date range and toolbar wrapper, custom quick info sections and a custom editor dialog with a RecurrenceEditor bound to the form.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Select } from '@salmonui/dropdowns/select';
import { TextField } from '@salmonui/inputs/text-field';
import { RecurrenceEditor, Scheduler } from '@salmonui/scheduler';

type Row = { id: number; title: string; start: string; end: string; kind: 'meeting' | 'focus' | 'travel'; recurrenceRule?: string };

const initial: Row[] = [
  { id: 1, title: 'Planning', start: '2026-11-23T09:00', end: '2026-11-23T10:30', kind: 'meeting', recurrenceRule: 'FREQ=WEEKLY;BYDAY=MO' },
  { id: 2, title: 'Deep work', start: '2026-11-24T13:00', end: '2026-11-24T16:00', kind: 'focus' },
  { id: 3, title: 'Train to Munich', start: '2026-11-25T07:00', end: '2026-11-25T11:00', kind: 'travel' },
  { id: 4, title: 'Customer demo', start: '2026-11-26T15:00', end: '2026-11-26T16:00', kind: 'meeting' },
];

const ICON: Record<Row['kind'], string> = { meeting: '👥', focus: '🎯', travel: '🚆' };
const HOLIDAY = '2026-11-27';
const KINDS = [
  { value: 'meeting', label: 'Meeting' },
  { value: 'focus', label: 'Focus' },
  { value: 'travel', label: 'Travel' },
];

/** Event, cell, header and date range templates, render hooks, custom quick info content and a custom editor dialog that embeds RecurrenceEditor. */
export default function SchedulerTemplatesDemo() {
  const [rows, setRows] = useState<readonly Row[]>(initial);
  return (
    <Scheduler<Row>
      data={rows}
      view="week"
      views={['week', { type: 'month', renderEvent: ({ row }) => <span>{`${ICON[row.kind]} ${row.title}`}</span> }]}
      date="2026-11-23"
      timeZone="UTC"
      locale="en-GB"
      height={560}
      scrollTime="07:00"
      renderEvent={({ row, timeText, recurring }) => (
        <span style={{ display: 'grid' }}>
          <strong>
            <span aria-hidden="true">{ICON[row.kind]} </span>
            {row.title}
            {recurring ? ' (repeats)' : ''}
          </strong>
          <small>{timeText}</small>
        </span>
      )}
      getEventProps={({ row }) => ({ className: `demo-event demo-event--${row.kind}`, 'data-kind': row.kind, ...(row.kind === 'travel' ? { style: { fontStyle: 'italic' } } : {}) })}
      getCellProps={({ part, date }) => (date.toString() === HOLIDAY && (part === 'workCell' || part === 'dateHeader' || part === 'allDayCell') ? { title: 'Company holiday', 'data-holiday': true, style: { background: 'var(--salmon-color-warning-subtle)' } } : undefined)}
      renderDateHeader={({ date }) => (
        <span>
          {date.day}/{date.month}
          {date.toString() === HOLIDAY ? ' 🎉' : ''}
        </span>
      )}
      renderCellHeader={({ date }) => <span>{date.day === 1 ? `1 ${['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.month - 1]}` : date.day}</span>}
      renderCell={({ part, date }) => (part === 'monthCell' && date.toString() === HOLIDAY ? <small style={{ opacity: 0.7 }}>Holiday</small> : null)}
      renderHeaderIndent={() => <small>UTC</small>}
      renderDateRange={({ text }) => <span>📅 {text}</span>}
      renderToolbar={({ items, dateRangeText }) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          {items}
          <span className="demo-status" style={{ margin: 0 }}>
            Showing {dateRangeText}
          </span>
        </div>
      )}
      quickInfo={{
        renderHeader: (ctx) => <strong>{ctx.kind === 'event' && ctx.row ? `${ICON[ctx.row.kind]} ${ctx.row.title}` : 'New entry'}</strong>,
        renderContent: (ctx) => <p style={{ margin: 0 }}>{`${ctx.start.toISOString().slice(11, 16)} to ${ctx.end.toISOString().slice(11, 16)} UTC`}</p>,
        renderFooter: (ctx) => (
          <Button variant="outline" type="button" onClick={ctx.close}>
            Got it
          </Button>
        ),
      }}
      editing={{
        renderDialogHeader: ({ isNew }) => <span>{isNew ? 'Plan something' : 'Change the plan'}</span>,
        renderDialog: ({ values, setValue, errors }) => (
          <div style={{ display: 'grid', gap: 12 }}>
            <TextField label="Title" value={String(values['title'] ?? '')} onValueChange={(value) => setValue('title', value)} invalid={Boolean(errors['title'])} />
            <label style={{ display: 'grid', gap: 4 }}>
              Kind
              <Select aria-label="Kind" data={KINDS} value={String(values['kind'] ?? 'meeting')} onValueChange={(value) => value != null && setValue('kind', String(value))} />
            </label>
            <RecurrenceEditor value={(values['recurrenceRule'] as string | null | undefined) ?? null} onValueChange={(rule) => setValue('recurrenceRule', rule)} start={values['start'] instanceof Date ? values['start'] : undefined} />
          </div>
        ),
        renderDialogFooter: ({ save, cancel, delete: remove, isNew }) => (
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            {isNew ? null : (
              <Button variant="outline" tone="danger" type="button" onClick={remove}>
                Delete
              </Button>
            )}
            <Button variant="outline" type="button" onClick={cancel}>
              Cancel
            </Button>
            <Button tone="primary" type="button" onClick={save}>
              Save plan
            </Button>
          </div>
        ),
      }}
      onAdd={(e) => setRows(e.data)}
      onSave={(e) => setRows(e.data)}
      onDelete={(e) => setRows(e.data)}
    />
  );
}
```

## Server rendering and theming

With `date`, `view` and an explicit `timeZone`, the server renders every
view with its events, including the timeline, year and agenda views and the
resource groups; today and the current time marker appear after hydration
only, and a virtualized timeline renders its `initialRange` rows.

Parts are `.salmon-scheduler__*` classes with state in `data-*` attributes
(`data-selected`, `data-work`, `data-has-events`, `data-today`,
`data-continues-start`, ...). Resource colors reach CSS as
`--salmon-scheduler-event-color` and are mixed against the theme seeds; in
forced colors mode events keep a system-color border. `dir="rtl"`
mirrors the layout and the navigation arrows.

## Built on

The editor dialog, alerts and popovers render on the client only. The
editor and alerts are Layout's `Dialog` (a modal `<dialog>`: contained Tab
order, Escape, focus back to the event); its `Select`, `DatePicker` and
`RecurrenceEditor` popups open inside the dialog, and Escape closes an open
popup before the dialog. The quick info and "+N more" popups are Layout's
`Popover`. `@salmonui/scheduler/styles.css` carries the rules of everything
the Scheduler renders (the dialog, popover, Select and DatePicker rules and
the plain button rules), so it is the only stylesheet besides
`@salmonui/core/styles.css`; only the lazy context menu and tooltip need
their own stylesheets (above).

## Performance

Occurrences are expanded and laid out for the visible range only; Month
keeps the visible lanes per cell in the DOM ("+N more" for the rest) and the
timeline renders a window of resource rows. Drag and resize move a copy of
the event outside React and commit once on drop. Gated on the production
build: a Week with 1,000 events
renders to painted within 39 ms, a Month with 5,000 events within 19 ms, a
Timeline Month with 1,000 resources and 10,000 events within 28 ms, and a
drag frame costs at most 2.7 ms of script (p95) with no React render per
pointer move.

## State and persistence

Components never write to browser storage, because server output must not
depend on it and the storage policy belongs to the application.
`api.getState()` returns `{ view, date, allDayExpanded }`, and
`api.restoreState(state)` accepts all or part of it. Scroll time and
expanded resources are not in the snapshot: keep them in your own state
and reapply them with `api.scrollToTime(time)` and
`api.expandResource(id)`.

```tsx
const ref = useRef<SchedulerApi<Meeting>>(null);

<Scheduler
  ref={ref}
  data={meetings}
  onReady={(api) => {
    const saved = localStorage.getItem('calendar');
    if (saved) api.restoreState(JSON.parse(saved));
  }}
/>;

// Later, for example when the user leaves the page:
localStorage.setItem('calendar', JSON.stringify(ref.current?.getState()));
```

## Lifecycle, events and templates

- **Templates.** Customize events with render props such as
  `renderEvent`. Salmon UI never renders HTML strings, so there are no
  string templates (they would need a runtime compiler that breaks a strict
  CSP) and no HTML sanitizer option. Text from data is always escaped; if
  you must render HTML, sanitize it in your application before it reaches a
  render prop.
- **Dialogs.** The editor and popups mount when they open, so a
  Scheduler that never opens them pays nothing at first render. Their code
  is a lazy chunk loaded on demand, with no prop that preloads it. Code that
  works with the editor DOM goes in `editing.renderDialog` or
  `onBeforePopupOpen`.
- **Agent tools.** WebMCP is a proposed browser API with no
  stable specification, and a component should not register agent tools
  on its own. Register your own tools over `SchedulerApi` methods such as
  `addEvents`, `saveEvent`, `deleteEvents`, `getEvents` and `setView`, with
  your own confirmation step.
- **Lifecycle.** React owns mounting and unmounting.
  `onReady(api)` fires once after the first commit; teardown code goes in
  an effect cleanup.
- **Action events.** Each action has a typed before / after
  pair: `onBeforeAdd` / `onAdd`, `onBeforeSave` / `onSave`,
  `onBeforeDelete` / `onDelete`, `onBeforeNavigate`, `onBeforeEventDrop`,
  and `onError({ error, action })` for failures. Payloads stay specific,
  event objects are only allocated for bound handlers, and
  `event.preventDefault()` cancels.

## API reference

The API reference for
[`@salmonui/scheduler`](https://salmonui.dev/docs/reference/scheduler) lists every
prop, method and type.
