# Scheduler API and events

> Every option, method and event of the scheduler in one place, with types and links to the guides that explain them.

This page is the complete reference for `@birchui/scheduler`. For full type signatures generated from the source, see the [package API reference](https://docs.birchui.com/api/scheduler.md).

```ts
import { createScheduler, schedulerDefinition } from '@birchui/scheduler';
import type { SchedulerApi, SchedulerEvent, SchedulerEvents, SchedulerOptions, SchedulerResource } from '@birchui/scheduler';
```

- `createScheduler(container, options)` renders a scheduler into `container` and returns a `SchedulerApi`.
- `schedulerDefinition` is the widget definition (name, tag name, factory and event list) that the framework adapters and the `<birchui-scheduler>` element are built from.

Both are generic: `createScheduler<TEvent, TResource>` types every payload and return value with your own event and resource interfaces.

## Options

Pass options to `createScheduler`, or change them later with `update(partial)`. Only `resources`, `start` and `end` are required.

### Data

| Option | Type | Description |
| --- | --- | --- |
| `resources` | `TResource[]` | Rows of the timeline. See [Resources](https://docs.birchui.com/scheduler/resources-and-events.md#resources). |
| `events` | `TEvent[]` | Bars on the timeline. See [Events](https://docs.birchui.com/scheduler/resources-and-events.md#events). |
| `resourceColumns` | `SchedulerColumn<TResource>[]` | Columns of the resource pane: `{ field, header, width?, renderer? }`. Default: one Name column, 200 px. |

### Time axis

| Option | Type | Description |
| --- | --- | --- |
| `start`, `end` | `Date \| string \| number` | The range the timeline covers, extended to whole ticks. An invalid `start` falls back to today, an invalid `end` to seven days after `start`, each with a console warning. |
| `viewPreset` | `ViewPresetName \| ViewPreset` | Time scale: `'minuteAndHour'`, `'hourAndDay'`, `'dayAndWeek'`, `'dayAndMonth'`, `'weekAndMonth'`, `'monthAndYear'`, or a [custom preset](https://docs.birchui.com/scheduler/view-presets.md#custom-presets). Default: `'hourAndDay'`. |
| `zoomLevels` | `(ViewPresetName \| ViewPreset)[]` | The ladder used by `zoomIn` and `zoomOut`, from most detailed to coarsest. Default: all six built-in presets. |
| `fillWidth` | `boolean` | Widen ticks so a short range fills the available width. Ticks never get narrower than the preset's `tickWidth`. Default: `true`. |
| `timeZone` | `string` | IANA time zone for the whole timeline. Defaults to the browser's zone; an invalid identifier falls back to it with a warning. See [Time zones](https://docs.birchui.com/scheduler/time-zones.md). |
| `locale` | `string` | BCP 47 locale for header labels and accessible descriptions. Default: the browser's locale. |
| `weekStartsOn` | `0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6` | First day of the week for week ticks, `0` is Sunday. Weeks start on Monday by default. |
| `workingTime` | `{ days, startHour, endHour } \| null` | Working hours and days; time outside them is shaded. See [Working time](https://docs.birchui.com/scheduler/working-time.md). |
| `weekendDays` | `number[]` | Days to shade when `workingTime` is not set. Default: `[0, 6]`. |
| `now` | `Date \| string \| number` | Fixed "current time" for the now line. |
| `showNowLine` | `boolean` | Draw a marker at the current time. Default: `true`. |

### Layout

| Option | Type | Description |
| --- | --- | --- |
| `height` | `number \| string` | Height of the scheduler, in pixels or any CSS length. Without it, the scheduler fills its container's height (at least 240 px). |
| `resourceWidth` | `number` | Width of the resource pane in pixels. Default: the sum of the column widths. |
| `rowHeight` | `number` | Height of a resource row (or lane) in pixels. Default: `44`. |
| `barMargin` | `number` | Space between event bars and the row edges, less than half of `rowHeight`. Default: `5`. |
| `headerRowHeight` | `number` | Height of each time header row. Default: `30`. |
| `eventLayout` | `'stack' \| 'pack' \| 'overlap'` | How overlapping events in a row are laid out. See [Overlapping events](https://docs.birchui.com/scheduler/resources-and-events.md#overlapping-events). Default: `'stack'`. |
| `overscanRows` | `number` | Extra rows rendered above and below the viewport. Default: `4`. |
| `overscanPx` | `number` | Extra pixels of timeline rendered left and right of the viewport. Default: `400`. |

### Editing

| Option | Type | Description |
| --- | --- | --- |
| `readOnly` | `boolean` | Turn off moving, resizing, creating and removing. Default: `false`. |
| `createOnDrag` | `boolean` | Emit `eventCreate` when the user drags across empty time. Default: `true`. |
| `snap` | `number \| 'tick' \| false` | Snap step in minutes, `'tick'` for tick boundaries, or `false`. Defaults to the preset's step. See [Snapping](https://docs.birchui.com/scheduler/interactions.md#snapping). |
| `validateDrop` | `(context: DropContext) => boolean` | Return `false` to reject a proposed move. |
| `validateResize` | `(context: ResizeContext) => boolean` | Return `false` to reject a proposed resize. |

### Rendering and appearance

| Option | Type | Description |
| --- | --- | --- |
| `eventRenderer` | `(event, context) => string \| Node` | Content of each event bar. See [Custom event content](https://docs.birchui.com/scheduler/event-rendering.md#custom-event-content). |
| `tooltips` | `boolean \| ((event, resource) => string)` | Built-in tooltips, or a function returning the tooltip text. Default: `true`. |
| `theme` | `'light' \| 'dark' \| 'auto'` | Bundled theme. Without it, the scheduler inherits the page theme (`lq-theme-dark` on an ancestor). |
| `injectStyles` | `boolean` | Set `false` to skip automatic style injection and import `@birchui/scheduler/styles.css` yourself. |
| `ariaLabel` | `string` | Accessible name of the scheduler. Default: `'Resource schedule'`. |
| `licenseKey` | `string` | License key for this instance. See [Licensing](https://docs.birchui.com/getting-started/licensing.md). |

## Methods

`SchedulerApi` includes the shared widget contract (`element`, `update`, `on`, `destroy`) plus the methods below.

### Data

| Method | Returns | Description |
| --- | --- | --- |
| `setEvents(events)` | `void` | Replace all events. |
| `addEvent(event)` | `void` | Add an event. |
| `updateEvent(id, patch)` | `TEvent \| undefined` | Merge changes into an event and return it. |
| `removeEvent(id)` | `TEvent \| undefined` | Remove an event and return it. Emits `eventRemove` with `source: 'api'`. |
| `getEvents()` | `TEvent[]` | All events, including changes made by the user. |
| `getEventById(id)` | `TEvent \| undefined` | One event. |
| `getEventsInRange(start, end, resourceId?)` | `TEvent[]` | Events overlapping a time span, optionally on one resource, sorted by start. |
| `setResources(resources)` | `void` | Replace all resources. |
| `getResources()` | `TResource[]` | All resources. |
| `getResourceById(id)` | `TResource \| undefined` | One resource. |
| `expandResource(id)` / `collapseResource(id)` | `void` | Expand or collapse a group row. |

### Navigation and zoom

| Method | Returns | Description |
| --- | --- | --- |
| `setRange(start, end)` | `void` | Change the range the timeline covers. |
| `getRange()` | `{ start: Date; end: Date }` | The full range. |
| `getVisibleRange()` | `{ start: Date; end: Date }` | The part of the range on screen. |
| `setViewPreset(preset)` | `void` | Switch to a preset name or object, keeping the time at the center of the view in place. |
| `getViewPreset()` | `ViewPreset` | The current preset, resolved to an object. |
| `zoomIn()` / `zoomOut()` | `boolean` | Move one step along `zoomLevels`; `false` when already at the end. |
| `scrollToDate(date, align?)` | `void` | Scroll a time into view; `align` is `'start'` (default), `'center'` or `'end'`. |
| `scrollToResource(id)` | `void` | Scroll a resource row into view, expanding collapsed parents. |
| `scrollToEvent(id)` | `void` | Scroll an event into view, expanding collapsed parents. |

### Selection

| Method | Returns | Description |
| --- | --- | --- |
| `selectEvent(id \| null)` | `void` | Select an event, or clear the selection with `null`. |
| `getSelectedEvent()` | `TEvent \| null` | The selected event. |

### Geometry

For building overlays, custom drag sources or tests on top of the timeline. Coordinates are in pixels within the timeline's scrollable content.

| Method | Returns | Description |
| --- | --- | --- |
| `dateFromX(x)` | `Date` | Time at a horizontal position. |
| `xFromDate(date)` | `number` | Horizontal position of a time. |
| `resourceFromY(y)` | `TResource \| undefined` | Resource at a vertical position. |
| `getRowBounds(resourceId)` | `{ top: number; height: number } \| undefined` | Vertical position and height of a resource row. |
| `refresh()` | `void` | Re-render everything, for example after your own data used in renderers changed. |

## Events

Subscribe with `on(event, listener)`, which returns an unsubscribe function. Every payload is a single object. A listener that throws never breaks the scheduler: the error is caught and reported with `console.error`, and the remaining listeners still run.

In the framework adapters the same events are `on…` props in React, Solid and Svelte (`onEventDrop`), kebab-case listeners in Vue (`@event-drop`), outputs in Angular (`(eventDrop)`) and kebab-case `CustomEvent`s on `<birchui-scheduler>` (`event-drop`, payload in `detail`). See [Using the Scheduler in your framework](https://docs.birchui.com/frameworks/scheduler.md).

| Event | Payload | When |
| --- | --- | --- |
| `ready` | `{ api }` | Emitted once, in a microtask right after `createScheduler` returns, so a listener attached immediately still receives it. |
| `eventClick` | `{ event, resource, domEvent }` | An event bar was clicked, or <kbd>Enter</kbd> was pressed on it. Also selects the event. |
| `eventDoubleClick` | `{ event, resource, domEvent }` | An event bar was double-clicked. |
| `eventContextMenu` | `{ event, resource, domEvent }` | The context menu was requested on an event bar. |
| `eventDrop` | `{ event, start, end, resourceId, previous, source }` | An event was moved. `previous` is `{ start, end, resourceId }`; `source` is `'pointer'` or `'keyboard'`. |
| `eventResize` | `{ event, start, end, edge, previous, source }` | An event was resized. `edge` is `'start'` or `'end'`; `previous` is `{ start, end }`. |
| `eventCreate` | `{ start, end, resourceId, resource }` | A time span was dragged out on empty space (with `createOnDrag`). |
| `eventRemove` | `{ event, source }` | An event was removed: `'keyboard'` for <kbd>Delete</kbd> or <kbd>Backspace</kbd>, `'api'` for `removeEvent()`. |
| `resourceClick` | `{ resource, domEvent }` | A resource in the left pane was clicked. |
| `resourceToggle` | `{ resource, isExpanded }` | A group row was expanded or collapsed. |
| `scheduleClick` | `{ date, resourceId, resource, domEvent }` | Empty time in a row was clicked. |
| `rangeChanged` | `{ start, end }` | The range changed. |
| `viewPresetChanged` | `{ preset, previous }` | The view preset changed, including by zooming. |
| `viewportScroll` | `{ left, top, visibleStart, visibleEnd }` | The timeline scrolled. Emitted at most once per animation frame. |
| `selectionChanged` | `{ selected, previous }` | The selected event changed. |

```ts
const scheduler = createScheduler(container, options);

const unsubscribe = [
  scheduler.on('eventDrop', ({ event, start, end, resourceId }) => jobs.reschedule(event.id, { start, end, resourceId })),
  scheduler.on('eventResize', ({ event, start, end }) => jobs.reschedule(event.id, { start, end })),
  scheduler.on('rangeChanged', ({ start, end }) => jobs.loadWindow(start, end)),
];

window.addEventListener('pagehide', () => {
  unsubscribe.forEach((stop) => stop());
  scheduler.destroy();
});
```

## Types

| Type | Description |
| --- | --- |
| `SchedulerOptions<TEvent, TResource>` | All options above. |
| `SchedulerApi<TEvent, TResource>` | The object returned by `createScheduler`. |
| `SchedulerEvents<TEvent, TResource>` | Map of event names to payload types, for typing your listeners. |
| `SchedulerResource` | Base resource shape: `id`, `name`, `parentId?`, `color?`, `expanded?`. |
| `SchedulerEvent` | Base event shape: `id`, `resourceId`, `start`, `end`, `title`, `color?`, `draggable?`, `resizable?`, `className?`. |
| `SchedulerColumn<TResource>` | A resource pane column. |
| `DateInput` | `Date \| string \| number`. |
| `ViewPreset`, `ViewPresetName`, `HeaderRowConfig`, `HeaderFormat`, `HeaderLabelContext` | View preset building blocks. |
| `WorkingTime` | `{ days: number[]; startHour: number; endHour: number }`. |
| `SnapSetting` | `number \| 'tick' \| false`. |
| `EventRenderContext`, `DropContext`, `ResizeContext`, `EventInteraction` | Callback and payload contexts. |
| `EventLayoutMode`, `SchedulerTheme`, `ScrollAlign`, `ChangeSource`, `TimeUnit`, `Weekday` | String unions used by the options. |

Type a listener with `SchedulerEvents`:

```ts
import type { SchedulerEvents } from '@birchui/scheduler';

function onJobMoved({ event, start, resourceId }: SchedulerEvents<ServiceJob, Technician>['eventDrop']) {
  dispatchLog.add(`${event.workOrder} reassigned to ${resourceId} at ${start.toISOString()}`);
}

scheduler.on('eventDrop', onJobMoved);
```

The widget contract shared by every Birch UI component:

**`Widget`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface Widget<TOptions, TEvents extends object>
```

| Property | Type | Description |
| --- | --- | --- |
| `readonly element` | `HTMLElement` |  |
| `update` | `(options: Partial<TOptions>) => void` |  |
| `on` | `<K extends keyof TEvents & string>(event: K, listener: Listener<TEvents[K]>) => () => void` |  |
| `destroy` | `() => void` |  |
