# Drag, drop, resize and create

> Let users move events in time and between resources, change durations, create events by dragging, snap to a time grid and reject changes that break your rules.

Editing in the scheduler is direct manipulation: drag a bar to move it, drag one of its edges to change its duration, or drag across empty time in a row to create a new event. Every change snaps to a time grid, can be checked by your own validation function before it is applied, and is reported through an event so you can save it.

**Live demo: Drag, resize and create with validation** (runs on the HTML version of this page). Source of `demos/scheduler-drag-drop.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 { docsTheme, layout, onDocsThemeChange } from './_shared';
import { WEEK_START, serviceJobs, technicians, type ServiceJob, type Technician } from './_scheduler-data';

export const meta = { title: 'Drag, resize and create with validation', height: 480 };

const WORK_START_HOUR = 8;
const WORK_END_HOUR = 18;

function withinWorkingHours(start: Date, end: Date): boolean {
  const sameDay = start.toDateString() === new Date(end.getTime() - 1).toDateString();
  const startHour = start.getHours() + start.getMinutes() / 60;
  const endHour = end.getHours() + end.getMinutes() / 60 || 24;
  return sameDay && startHour >= WORK_START_HOUR && endHour <= WORK_END_HOUR;
}

const time = (d: Date) => d.toLocaleString('en-GB', { weekday: 'short', hour: '2-digit', minute: '2-digit' });

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  toolbar.append(
    'Drag jobs between technicians, resize either edge, or drag on an empty slot to create a job. Moves outside 08:00 to 18:00 or onto team rows are rejected.',
  );
  const end = new Date(WEEK_START);
  end.setDate(end.getDate() + 5);
  let created = 0;

  const scheduler = createScheduler<ServiceJob, Technician>(body, {
    resources: technicians,
    events: serviceJobs(),
    start: WEEK_START,
    end,
    viewPreset: 'hourAndDay',
    snap: 15,
    createOnDrag: true,
    workingTime: { days: [1, 2, 3, 4, 5], startHour: WORK_START_HOUR, endHour: WORK_END_HOUR },
    validateDrop: ({ start: s, end: e, resourceId }) => resourceId.startsWith('tech-') && withinWorkingHours(s, e),
    validateResize: ({ start: s, end: e }) => withinWorkingHours(s, e),
    theme: docsTheme(),
    height: '100%',
    ariaLabel: 'Editable field service schedule',
  });

  const offs = [
    scheduler.on('eventDrop', ({ event, start, resourceId, previous }) => {
      const who = scheduler.getResourceById(resourceId)?.name ?? resourceId;
      const moved = previous.resourceId !== resourceId ? ` and reassigned to ${who}` : '';
      status.textContent = `${event.title} moved to ${time(start)}${moved}.`;
    }),
    scheduler.on('eventResize', ({ event, start, end: e }) => {
      status.textContent = `${event.title} now runs ${time(start)} to ${time(e)}.`;
    }),
    scheduler.on('eventCreate', ({ start, end: e, resourceId, resource }) => {
      if (!resourceId.startsWith('tech-') || !withinWorkingHours(start, e)) {
        status.textContent = 'New jobs must be on a technician row, within working hours.';
        return;
      }
      created += 1;
      scheduler.addEvent({
        id: `new-${created}`,
        resourceId,
        start,
        end: e,
        title: 'New visit',
        customer: 'Unassigned customer',
      });
      status.textContent = `Created a visit for ${resource?.name ?? resourceId} at ${time(start)}.`;
    }),
    scheduler.on('eventRemove', ({ event }) => {
      status.textContent = `${event.title} removed.`;
    }),
  ];
  status.textContent = 'Changes appear here.';
  const stopTheme = onDocsThemeChange((theme) => scheduler.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    scheduler.destroy();
  };
}
```

## Moving events

Press on a bar and drag. A drag starts after the pointer has moved 4 pixels, so a plain click still selects the event. Moving horizontally changes the time; moving vertically moves the event to another resource. The duration stays the same. When you release, the scheduler applies the new position to its own copy of the event and emits `eventDrop`. The `event` in the payload is that updated object; your original array is not mutated, so `getEvents()` is the source of truth for what is on screen.

```ts
scheduler.on('eventDrop', ({ event, start, end, resourceId, previous, source }) => {
  console.info(
    `${event.title} moved from ${previous.resourceId} to ${resourceId}: ${start.toISOString()} to ${end.toISOString()} (${source})`,
  );
});
```

| Field | Type | Description |
| --- | --- | --- |
| `event` | `TEvent` | The event that moved. |
| `start`, `end` | `Date` | The new times. |
| `resourceId` | `string` | The new resource. Equal to `previous.resourceId` when the event only moved in time. |
| `previous` | `{ start, end, resourceId }` | Where the event was before the move, ready to pass to `updateEvent` if you need to roll back. |
| `source` | `'pointer' \| 'keyboard'` | How the move was made. |

## Resizing events

Drag the start or end edge of a bar to change its duration. An event cannot be resized to zero length or past its other edge. The scheduler emits `eventResize` with the edge that moved:

```ts
scheduler.on('eventResize', ({ event, start, end, edge, previous }) => {
  const minutes = (end.getTime() - start.getTime()) / 60_000;
  console.info(`${event.title} is now ${minutes} minutes (${edge} edge moved; was ${previous.start.toISOString()})`);
});
```

## Creating events by dragging

Dragging across empty space in a row selects a time span and emits `eventCreate`. This is on by default; set `createOnDrag: false` to turn it off. The payload describes the span, not an event: the scheduler does not invent ids or titles for your data. Add the event yourself, typically after asking the user for details:

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

interface ServiceJob extends SchedulerEvent {
  customer: string;
}

const scheduler = createScheduler<ServiceJob>(container, {
  resources: technicians,
  events: jobs,
  start: '2026-12-07T06:00',
  end: '2026-12-07T20:00',
  viewPreset: 'hourAndDay',
  snap: 30,
});

scheduler.on('eventCreate', async ({ start, end, resourceId, resource }) => {
  const details = await openNewJobDialog({ technician: resource?.name, start, end });
  if (!details) return;

  scheduler.addEvent({
    id: crypto.randomUUID(),
    resourceId,
    start,
    end,
    title: details.title,
    customer: details.customer,
  });
});
```

To create events from a single click instead of a drag, listen to `scheduleClick`, which reports the clicked time and resource:

```ts
scheduler.on('scheduleClick', ({ date, resourceId }) => {
  const start = date.getTime();
  scheduler.addEvent({
    id: crypto.randomUUID(),
    resourceId,
    start,
    end: start + 60 * 60_000,
    title: 'New visit',
    customer: '',
  });
});
```

## Cancelling a drag

Press <kbd>Escape</kbd> during a move, resize or create drag to cancel it. The event returns to where it was and nothing is emitted.

## Removing events

Pressing <kbd>Delete</kbd> or <kbd>Backspace</kbd> on a focused event removes it (unless the scheduler is `readOnly`), and so does calling `removeEvent(id)`. Both emit `eventRemove`:

```ts
scheduler.on('eventRemove', async ({ event, source }) => {
  if (source === 'api') return;
  await fetch(`/api/jobs/${event.id}`, { method: 'DELETE' });
});
```

`source` is `'keyboard'` for removals by key and `'api'` for `removeEvent()`. Skip `'api'` removals in a persistence listener when your own code already deleted the record on the server.

There is no validator for removals, and `draggable: false` does not protect an event from the keyboard. To keep an event that must not be deleted, add it back in the listener:

```ts
scheduler.on('eventRemove', ({ event, source }) => {
  if (source === 'keyboard' && event.locked) {
    scheduler.addEvent(event);
    showToast(`${event.title} is locked and cannot be removed.`);
  }
});
```

## Snapping

While dragging, start and end times snap to a grid. `snap` sets it:

| Value | Behaviour |
| --- | --- |
| a number | Snap to that many **minutes** of local wall-clock time, for example `5`, `15`, `30` or `60`. |
| `'tick'` | Snap to tick boundaries of the current preset: whole hours in `'hourAndDay'`, whole days in `'dayAndMonth'`. |
| `false` | No grid. Times still resolve to whole minutes. |

When you do not set `snap`, the current view preset's own step is used: 15 minutes in `'hourAndDay'`, 30 minutes in `'dayAndWeek'`, whole days in the week and month presets (see [built-in presets](https://docs.birchui.com/scheduler/view-presets.md#built-in-presets)).

Steps of a whole number of days, such as `snap: 1440`, move events by calendar days. A job at 09:00 stays at 09:00 even when it is moved across a daylight saving change. Snapping to `'tick'` in month presets moves by whole calendar months in the same way.

```ts
scheduler.update({ snap: 15 });
```

## Restricting what can change

| Option or field | Effect |
| --- | --- |
| `readOnly: true` | Turns off moving, resizing, creating and removing for the whole scheduler. Clicks, selection and navigation still work. |
| `draggable: false` on an event | That event cannot be moved. |
| `resizable: false` on an event | That event's duration is fixed. |
| `resizable: 'start'` or `'end'` | Only that edge can be dragged. |
| `createOnDrag: false` | Turns off drag-to-create on empty space. |

```ts
const jobs = [
  { id: 'job-4471', resourceId: 'tech-amira', title: 'Gas safety certificate', start: '2026-12-07T08:00', end: '2026-12-07T09:00', draggable: false, resizable: false },
  { id: 'job-4472', resourceId: 'tech-jonas', title: 'Heat pump install', start: '2026-12-07T09:00', end: '2026-12-07T15:00', resizable: 'end' },
];
```

A common pattern is a read-only board for viewers and an editable one for dispatchers, toggled at runtime:

```ts
scheduler.update({ readOnly: !currentUser.roles.includes('dispatcher') });
```

## Validation

Field and rule checks belong in `validateDrop` and `validateResize`. Each receives the proposed change before it is applied. Return `false` to reject it: the event stays where it was and no `eventDrop` or `eventResize` is emitted. Any other return value accepts the change. If a validator throws, the error is logged with `console.error` and the change is rejected.

While the user drags, the validator runs on every snapped position to drive the preview: a rejected position turns the drag preview red (`--lq-sched-invalid-color`, class `lq-sched-ghost--invalid`), and releasing there leaves the event unchanged. It runs once more when a keyboard move or resize is attempted. Keep validators fast and free of side effects; do not show messages from inside them.

`validateDrop` receives a `DropContext`:

| Field | Description |
| --- | --- |
| `event` | The event being moved. |
| `start`, `end` | Proposed new times, as `Date`. |
| `resourceId`, `resource` | Proposed resource and its object. |
| `previous` | Current `{ start, end, resourceId }`. |

`validateResize` receives a `ResizeContext` with `event`, `start`, `end`, `edge`, `resource` and `previous`.

### Reject double bookings

```ts
const scheduler = createScheduler(container, {
  resources: technicians,
  events: jobs,
  start: '2026-12-07',
  end: '2026-12-12',
  viewPreset: 'dayAndWeek',
  validateDrop: ({ event, start, end, resourceId }) =>
    !scheduler.getEventsInRange(start, end, resourceId).some((other) => other.id !== event.id),
  validateResize: ({ event, start, end }) =>
    !scheduler.getEventsInRange(start, end, event.resourceId).some((other) => other.id !== event.id),
});
```

The validators run only during user interaction, after `createScheduler` has returned, so referring to `scheduler` inside them is safe.

### Keep jobs inside working hours

Check the proposed times on the scheduler's own clock. This helper reads the local hour and weekday in a given time zone:

```ts
const SITE_ZONE = 'Europe/Berlin';
const WORKING_TIME = { days: [1, 2, 3, 4, 5], startHour: 7, endHour: 16 };

const clock = new Intl.DateTimeFormat('en-US', {
  timeZone: SITE_ZONE,
  hourCycle: 'h23',
  weekday: 'short',
  hour: 'numeric',
  minute: 'numeric',
});
const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

function localTime(date: Date) {
  const parts = Object.fromEntries(clock.formatToParts(date).map((p) => [p.type, p.value]));
  return { weekday: WEEKDAYS.indexOf(parts.weekday), hours: Number(parts.hour) + Number(parts.minute) / 60 };
}

function insideWorkingTime(start: Date, end: Date): boolean {
  const from = localTime(start);
  const to = localTime(new Date(end.getTime() - 1));
  return (
    from.weekday === to.weekday &&
    WORKING_TIME.days.includes(from.weekday) &&
    from.hours >= WORKING_TIME.startHour &&
    to.hours < WORKING_TIME.endHour
  );
}

createScheduler(container, {
  resources: crews,
  events: installations,
  start: '2026-12-07',
  end: '2026-12-12',
  viewPreset: 'dayAndWeek',
  timeZone: SITE_ZONE,
  workingTime: WORKING_TIME,
  validateDrop: ({ start, end }) => insideWorkingTime(start, end),
  validateResize: ({ start, end }) => insideWorkingTime(start, end),
});
```

### Match skills to resources

Your own fields on resources and events are available in the context:

```ts
createScheduler(container, {
  resources: technicians,
  events: jobs,
  start: '2026-12-07',
  end: '2026-12-12',
  validateDrop: ({ event, resource }) => {
    const required = event.requiredSkill as string | undefined;
    const skills = (resource?.skills as string[] | undefined) ?? [];
    return !required || skills.includes(required);
  },
});
```

### Server-side checks

Validators must answer synchronously. For checks only the server can make, such as a customer's access window, accept the move in `validateDrop` and roll back in the `eventDrop` listener if the server refuses it:

```ts
scheduler.on('eventDrop', async ({ event, start, end, resourceId, previous }) => {
  const ok = await api.rescheduleJob(event.id, { start, end, resourceId });
  if (!ok) scheduler.updateEvent(event.id, previous);
});
```

Validate new events created by dragging in the `eventCreate` listener before calling `addEvent`.

## Clicks, double clicks and context menus

| Event | Payload | Typical use |
| --- | --- | --- |
| `eventClick` | `{ event, resource, domEvent }` | Open a side panel with job details. |
| `eventDoubleClick` | `{ event, resource, domEvent }` | Open an edit dialog. |
| `eventContextMenu` | `{ event, resource, domEvent }` | Show your own context menu. Call `domEvent.preventDefault()` to suppress the browser's. |
| `scheduleClick` | `{ date, resourceId, resource, domEvent }` | Click on empty time in a row. |
| `resourceClick` | `{ resource, domEvent }` | Click on a resource in the left pane. |

```ts
scheduler.on('eventContextMenu', ({ event, domEvent }) => {
  domEvent.preventDefault();
  jobMenu.open({ x: (domEvent as MouseEvent).clientX, y: (domEvent as MouseEvent).clientY, jobId: event.id });
});
```

## Selection

Clicking a bar selects it, and clicking empty time clears the selection. One event can be selected at a time, and removing the selected event clears it.

```ts
scheduler.selectEvent('job-4472');
scheduler.getSelectedEvent();
scheduler.selectEvent(null);

scheduler.on('selectionChanged', ({ selected, previous }) => {
  detailsPanel.show(selected);
});
```

## Next steps

- [Working time](https://docs.birchui.com/scheduler/working-time.md) to shade non-working hours.
- [Keyboard and accessibility](https://docs.birchui.com/scheduler/accessibility.md) for editing without a pointer.
- [API and events](https://docs.birchui.com/scheduler/api.md) for the complete event list.
