# View presets and zoom

> Choose the time scale of the timeline with built-in view presets, zoom between them, define custom presets and navigate the visible range.

A **view preset** decides how time is drawn: the size of one tick (an hour, a day, a week), how wide each tick is in pixels, the header rows above the timeline and the default snap step for dragging. Switch presets to zoom between a minute-by-minute dispatch view and a year-long capacity plan.

**Live demo: Field service schedule** (runs on the HTML version of this page). Source of `demos/scheduler-basic.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createScheduler, type ViewPresetName } from '@birchui/scheduler';
import { docsTheme, field, layout, onDocsThemeChange, button } from './_shared';
import { WEEK_START, at, serviceJobs, technicians, type ServiceJob, type Technician } from './_scheduler-data';

export const meta = { title: 'Field service schedule', height: 460 };

const PRESETS: ViewPresetName[] = ['hourAndDay', 'dayAndWeek', 'weekAndMonth', 'monthAndYear'];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const preset = document.createElement('select');
  for (const name of PRESETS) preset.add(new Option(name, name, name === 'hourAndDay', name === 'hourAndDay'));

  const end = new Date(WEEK_START);
  end.setDate(end.getDate() + 7);
  const scheduler = createScheduler<ServiceJob, Technician>(body, {
    resources: technicians,
    events: serviceJobs(),
    start: WEEK_START,
    end,
    viewPreset: 'hourAndDay',
    resourceColumns: [
      { field: 'name', header: 'Technician', width: 170 },
      { field: 'skill', header: 'Skill', width: 140 },
    ],
    workingTime: { days: [1, 2, 3, 4, 5], startHour: 8, endHour: 18 },
    readOnly: true,
    theme: docsTheme(),
    height: '100%',
    ariaLabel: 'Field service schedule',
  });

  const onPreset = () => scheduler.setViewPreset(preset.value as ViewPresetName);
  preset.addEventListener('change', onPreset);
  toolbar.append(
    field('View', preset),
    button('Zoom in', () => scheduler.zoomIn()),
    button('Zoom out', () => scheduler.zoomOut()),
    button('Monday 08:00', () => scheduler.scrollToDate(at(0, 8), 'start')),
  );
  const offs = [
    scheduler.on('eventClick', ({ event }) => {
      status.textContent = `${event.title} for ${event.customer}`;
    }),
    scheduler.on('viewPresetChanged', ({ preset: next }) => {
      status.textContent = `View preset: ${typeof next === 'object' && 'name' in next ? String(next.name) : 'custom'}`;
    }),
  ];
  status.textContent = 'Click a job to see its customer.';
  const stopTheme = onDocsThemeChange((theme) => scheduler.update({ theme }));
  return () => {
    preset.removeEventListener('change', onPreset);
    for (const off of offs) off();
    stopTheme();
    scheduler.destroy();
  };
}
```

## Built-in presets

| Preset | One tick | Tick width | Header rows | Default snap |
| --- | --- | --- | --- | --- |
| `'minuteAndHour'` | 15 minutes | 64 px | Hour, then 15-minute marks | 5 minutes |
| `'hourAndDay'` | 1 hour | 56 px | Full date, then hour | 15 minutes |
| `'dayAndWeek'` | 1 day | 150 px | Week range, then weekday and date | 30 minutes |
| `'dayAndMonth'` | 1 day | 40 px | Month and year, then day number | Whole ticks |
| `'weekAndMonth'` | 1 week | 120 px | Month and year, then week range | 1 day |
| `'monthAndYear'` | 1 month | 110 px | Year, then month | 1 day |

Pick one with `viewPreset`:

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

const scheduler = createScheduler(container, {
  resources: crews,
  events: installations,
  start: '2026-12-07',
  end: '2026-12-21',
  viewPreset: 'dayAndWeek',
});
```

Typical choices:

- **Same-day dispatch** of field technicians: `'hourAndDay'` with a range of one or two days.
- **Weekly crew planning**: `'dayAndWeek'` with a range of one to four weeks.
- **Room or equipment booking over a quarter**: `'dayAndMonth'`.
- **Long-range capacity and project staffing**: `'weekAndMonth'` or `'monthAndYear'`.

Header labels are formatted with `Intl.DateTimeFormat` in the scheduler's `locale` and `timeZone`, so `locale: 'de-DE'` gives German month and weekday names with no extra configuration. Weeks start on Monday; set `weekStartsOn` (`0` for Sunday through `6` for Saturday) to change where week ticks and week headers begin.

## The visible range

`start` and `end` set the span of time the timeline covers. The scheduler extends the range outward to whole ticks, so a `'dayAndWeek'` view from `'2026-12-07T10:00'` begins at midnight on December 7.

Every tick in a preset has the same width. In `'monthAndYear'`, February is as wide as March, and in `'hourAndDay'` the day a daylight saving change happens has 23 or 25 hour columns. Positions inside a tick are interpolated by time.

Set `fillWidth: true` to stretch ticks so a short range fills the available width instead of leaving empty space on the right.

### Change the range

```ts
scheduler.setRange('2027-01-04', '2027-01-18');

const { start, end } = scheduler.getRange();
const visible = scheduler.getVisibleRange();
```

`getRange()` returns the whole scrollable span; `getVisibleRange()` returns the part currently on screen. Both return `Date` objects.

`rangeChanged` fires whenever the range changes, which makes it the right place to load events for the new window:

```ts
scheduler.on('rangeChanged', async ({ start, end }) => {
  const response = await fetch(`/api/jobs?from=${start.toISOString()}&to=${end.toISOString()}`);
  scheduler.setEvents(await response.json());
});
```

### Previous and next period

A toolbar that pages through weeks needs only `getRange` and `setRange`:

```ts
const WEEK = 7 * 24 * 60 * 60 * 1000;

function shiftWeek(direction: 1 | -1) {
  const { start, end } = scheduler.getRange();
  scheduler.setRange(start.getTime() + direction * WEEK, end.getTime() + direction * WEEK);
}

document.querySelector('#prev-week')!.addEventListener('click', () => shiftWeek(-1));
document.querySelector('#next-week')!.addEventListener('click', () => shiftWeek(1));
```

Adding milliseconds is fine for whole weeks in most regions, but a week that contains a daylight saving change is one hour shorter or longer. When you page by calendar units, build the new boundaries as local strings such as `'2027-03-29'` so they are read in the scheduler's time zone.

## Scroll to a date, resource or event

```ts
scheduler.scrollToDate('2026-12-09T13:00', 'center');
scheduler.scrollToResource('tech-lucia');
scheduler.scrollToEvent('job-4490');
```

`scrollToDate(date, align)` accepts `'start'`, `'center'` or `'end'` and scrolls horizontally inside the current range. Call `setRange` first if the date lies outside it. The `viewportScroll` event reports the new position along with the visible time span, at most once per animation frame:

```ts
scheduler.on('viewportScroll', ({ visibleStart, visibleEnd }) => {
  rangeLabel.textContent = `${visibleStart.toLocaleDateString()} to ${visibleEnd.toLocaleDateString()}`;
});
```

## Zoom

`zoomIn()` moves to the next more detailed preset and `zoomOut()` to the next coarser one. Both return `false` when there is no further level, which is convenient for disabling buttons:

```ts
const zoomInButton = document.querySelector<HTMLButtonElement>('#zoom-in')!;
const zoomOutButton = document.querySelector<HTMLButtonElement>('#zoom-out')!;

zoomInButton.addEventListener('click', () => {
  zoomInButton.disabled = !scheduler.zoomIn();
  zoomOutButton.disabled = false;
});

zoomOutButton.addEventListener('click', () => {
  zoomOutButton.disabled = !scheduler.zoomOut();
  zoomInButton.disabled = false;
});
```

By default the zoom ladder is every built-in preset, from `'minuteAndHour'` to `'monthAndYear'`. Restrict it with `zoomLevels`, ordered from most detailed to coarsest:

```ts
createScheduler(container, {
  resources,
  events,
  start: '2026-12-07',
  end: '2027-01-04',
  viewPreset: 'dayAndWeek',
  zoomLevels: ['hourAndDay', 'dayAndWeek', 'weekAndMonth'],
});
```

If the current preset is not in the list, zooming starts from the level with the closest scale.

Set a preset directly with `setViewPreset(preset)` or `update({ viewPreset })`, and read it with `getViewPreset()`, which always returns the resolved preset object. `viewPresetChanged` fires after every change, including zooming:

```ts
scheduler.on('viewPresetChanged', ({ preset, previous }) => {
  analytics.track('timeline_zoom', { from: previous.id, to: preset.id });
});
```

## Custom presets

Pass a preset object anywhere a preset name is accepted (`viewPreset`, `zoomLevels`, `setViewPreset`).

| Field | Type | Description |
| --- | --- | --- |
| `id` | `string` | Identifier reported in `viewPresetChanged`. |
| `tickUnit` | `TimeUnit` | `'minute'`, `'hour'`, `'day'`, `'week'`, `'month'`, `'quarter'` or `'year'` (also `'second'` and `'millisecond'`). |
| `tickIncrement` | `number` | Units per tick. `tickUnit: 'hour', tickIncrement: 4` gives four-hour ticks. Defaults to 1. |
| `tickWidth` | `number` | Width of one tick in pixels. |
| `headers` | `HeaderRowConfig[]` | Header rows from top to bottom. Each row has a `unit`, an optional `increment` and an optional `format`. |
| `snap` | `number \| 'tick'` | Default snap step in minutes, or `'tick'` to snap to tick boundaries. |

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

```ts
interface ViewPreset
```

| Property | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `tickUnit` | `TimeUnit` |  |
| `tickIncrement?` | `number` |  |
| `tickWidth` | `number` |  |
| `headers` | `HeaderRowConfig[]` |  |
| `compactHeaders?` | `HeaderRowConfig[]` |  |
| `snap?` | `number \| 'tick'` |  |

A shift-planning view with eight-hour ticks:

```ts
import { createScheduler, type ViewPreset } from '@birchui/scheduler';

const shiftView: ViewPreset = {
  id: 'shifts',
  tickUnit: 'hour',
  tickIncrement: 8,
  tickWidth: 120,
  snap: 60,
  headers: [
    { unit: 'day', format: { weekday: 'long', day: 'numeric', month: 'short' } },
    {
      unit: 'hour',
      increment: 8,
      format: (start, _end, ctx) => {
        const hour = parseInt(ctx.format(start, { hour: 'numeric', hourCycle: 'h23' }), 10);
        return hour < 8 ? 'Night' : hour < 16 ? 'Early' : 'Late';
      },
    },
  ],
};

createScheduler(container, {
  resources: nurses,
  events: shifts,
  start: '2026-12-07',
  end: '2026-12-14',
  viewPreset: shiftView,
  zoomLevels: ['hourAndDay', shiftView, 'dayAndWeek'],
});
```

### Header formats

A header row's `format` is either:

- an `Intl.DateTimeFormatOptions` object, formatted in the scheduler's locale and time zone, or
- a function `(start, end, context) => string`, where `start` and `end` are the cell's `Date` boundaries and `context` provides `format(date, options)`, `formatRange(start, end, options)`, `locale` and `timeZone`.

Use the context's helpers rather than `toLocaleString()` so labels are always rendered in the scheduler's time zone, not the browser's. Without a `format`, each unit has a sensible default, such as `{ hour: 'numeric' }` for hours and `{ month: 'short', year: 'numeric' }` for months.

A fiscal-quarter header:

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

const fiscalQuarters: HeaderRowConfig = {
  unit: 'quarter',
  format: (start, _end, ctx) => {
    const month = parseInt(ctx.format(start, { month: 'numeric' }), 10);
    const year = ctx.format(start, { year: 'numeric' });
    return `Q${Math.ceil(month / 3)} FY${year}`;
  },
};
```

> **Note**
>
> Very long ranges at fine presets produce a lot of ticks. The time axis is virtualized, so only visible ticks are rendered, but there is a hard limit of 200,000 ticks per axis. One year at `'minuteAndHour'` is about 35,000 ticks; choose a coarser preset for multi-year plans.

## Next steps

- [Time zones](https://docs.birchui.com/scheduler/time-zones.md) explains how the axis is computed.
- [Drag, drop, resize and create](https://docs.birchui.com/scheduler/interactions.md#snapping) covers snapping in detail.
- [API and events](https://docs.birchui.com/scheduler/api.md) lists every navigation method.
