# Undo and redo in the scheduler

> Turn on scheduler history with the undoRedo option, add undo and redo buttons driven by historyChange, and keep a server in step when users undo.

Dispatchers move many jobs in a row and sometimes move the wrong one. The scheduler records moves, resizes, removals and API edits, and undoes them with <kbd>Ctrl</kbd> + <kbd>Z</kbd>. This recipe adds toolbar buttons, a history limit, and persistence that also covers undo and redo.

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

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

export const meta = { title: 'Undo and redo schedule changes', height: 480 };

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const end = new Date(WEEK_START);
  end.setDate(end.getDate() + 5);

  const scheduler = createScheduler<ServiceJob, Technician>(body, {
    resources: technicians,
    events: serviceJobs(),
    start: WEEK_START,
    end,
    viewPreset: 'hourAndDay',
    snap: 15,
    createOnDrag: false,
    undoRedo: { limit: 50 },
    theme: docsTheme(),
    height: '100%',
    ariaLabel: 'Field service schedule with undo and redo',
  });

  const undoButton = button('Undo', () => scheduler.undo());
  const redoButton = button('Redo', () => scheduler.redo());
  const clearButton = button('Clear history', () => scheduler.clearHistory());
  const sync = () => {
    undoButton.disabled = !scheduler.canUndo();
    redoButton.disabled = !scheduler.canRedo();
  };
  toolbar.append(undoButton, redoButton, clearButton, 'Move or resize jobs, then step back and forward.');
  sync();

  const offs = [
    scheduler.on('historyChange', ({ action, kind, changes }) => {
      sync();
      if (action === 'clear') {
        status.textContent = 'History cleared.';
        return;
      }
      const titles = changes.map(({ before, after }) => (after ?? before)?.title ?? 'job').join(', ');
      const verb = action === 'record' ? 'Recorded' : action === 'undo' ? 'Undid' : 'Redid';
      status.textContent = `${verb} ${kind ?? 'change'}: ${titles}.`;
    }),
  ];
  status.textContent = 'History changes appear here.';
  const stopTheme = onDocsThemeChange((theme) => scheduler.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    scheduler.destroy();
  };
}
```

## Steps

1. Set `undoRedo` to `true` (the default, 100 steps) or `{ limit }`.
2. Call `undo()` and `redo()` from your buttons, and enable them from `canUndo()` and `canRedo()`.
3. Update the buttons in a `historyChange` listener, which fires after every recorded change, undo, redo and clear.
4. Persist from `historyChange` too, because undo and redo do not emit `eventDrop` or `eventResize`.

## Buttons

```ts title="dispatch-history.ts"
import { createScheduler } from '@birchui/scheduler';

const scheduler = createScheduler<WorkOrder, Technician>(document.querySelector<HTMLElement>('#dispatch')!, {
  resources: technicians,
  events: workOrders,
  start: '2026-12-07',
  end: '2026-12-12',
  viewPreset: 'hourAndDay',
  undoRedo: { limit: 50 },
});

const undoButton = document.querySelector<HTMLButtonElement>('#undo')!;
const redoButton = document.querySelector<HTMLButtonElement>('#redo')!;

function syncButtons() {
  undoButton.disabled = !scheduler.canUndo();
  redoButton.disabled = !scheduler.canRedo();
}

undoButton.addEventListener('click', () => scheduler.undo());
redoButton.addEventListener('click', () => scheduler.redo());
scheduler.on('historyChange', syncButtons);
syncButtons();
```

`undo()` and `redo()` return `false` when there is nothing to undo or redo. The keyboard shortcuts work while focus is inside the scheduler: <kbd>Ctrl</kbd> + <kbd>Z</kbd> to undo, <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Z</kbd> or <kbd>Ctrl</kbd> + <kbd>Y</kbd> to redo (<kbd>Cmd</kbd> on macOS).

## The historyChange payload

| Field | Description |
| --- | --- |
| `action` | `'record'` for a new change, `'undo'`, `'redo'` or `'clear'`. |
| `kind` | `'move'`, `'resize'`, `'add'`, `'update'` or `'remove'`; `null` for `'clear'`. |
| `changes` | `{ id, before, after }` for every event touched. `after` is the event as it is now, or `null` once removed. |
| `canUndo`, `canRedo` | Whether a step is available after this action. |

For undo, `before` and `after` are already swapped, so `after` is always the current state. One user action can produce several changes: moving one occurrence of a recurring series changes the master and adds a detached event.

## Persist undo and redo

```ts title="persist-history.ts"
scheduler.on('historyChange', ({ action, changes }) => {
  if (action !== 'undo' && action !== 'redo') return;
  for (const { id, after } of changes) {
    if (after) void api.put(`/api/work-orders/${encodeURIComponent(id)}`, after);
    else void api.delete(`/api/work-orders/${encodeURIComponent(id)}`);
  }
});
```

If you already save from `eventDrop` and `eventResize`, add only this listener for undo and redo. To save everything in one place, handle `'record'` the same way; see [Save scheduler changes to a server](https://docs.birchui.com/recipes/scheduler-save-to-server.md).

## Clear the history

Call `clearHistory()` when earlier steps no longer make sense, for example after the dispatcher publishes the day's plan to technicians:

```ts
publishButton.addEventListener('click', async () => {
  await api.post('/api/dispatch/publish', { day: '2026-12-07' });
  scheduler.clearHistory();
});
```

`setEvents()` and `update({ events })` start a new history as well.

## What is recorded

| Recorded | Not recorded |
| --- | --- |
| Drag, resize and keyboard moves | Changes rejected by `validateDrop` or `validateResize` |
| Removing an event with <kbd>Delete</kbd> | Replacing all events with `setEvents()` |
| `addEvent`, `updateEvent`, `removeEvent` | View changes: range, zoom, scrolling, selection |

## Pitfalls

- **`undoRedo: false` turns off `historyChange`.** With no history, nothing is recorded and the event never fires.
- **Rollback after a failed save is a new step.** When the server rejects a move and you call `updateEvent(id, previous)`, that call is itself recorded. Call `undo()` instead to remove the failed step from the history.
- **Read-only mode.** Keyboard undo is ignored while the scheduler is `readOnly`.

## Related

- [Save scheduler changes to a server](https://docs.birchui.com/recipes/scheduler-save-to-server.md).
- [Scheduler API](https://docs.birchui.com/scheduler/api.md).

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

```ts
interface UndoRedoOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `limit?` | `number` |  |
