ProSchedulerSign in

Scheduler · Drag & drop

Bulk event placement

Select backlog tasks or scheduled events and drag them together. Groups pack back-to-back, with one validated transaction per scheduler; a conflicting drop leaves every event in place.

Live demo

Select two backlog tasks and drag either onto a resource · Select two scheduled events and drag them together · Transfer a group to the other scheduler or back to the backlog

Fullscreen
import { useState } from "react"
import { ExternalDraggable, ExternalDropZone, ProScheduler, type SchedulerEvent, type PschExternalEvent, type PschEventTransaction } from "@andreisaac/pro-scheduler"
import { backlog, bulkBacklog, bulkSessions } from "./data/planning"
import { studioResources } from "./data/studio"
import { Choice, Log, Toolbar, useLog } from "./kit"

export function BulkPlacementDemo() {
  const [date, setDate] = useState(() => new Date())
  const [mode, setMode] = useState<"scheduler" | "timeline">("timeline")
  const [left, setLeft] = useState(() => bulkSessions(date, "left"))
  const [right, setRight] = useState(() => bulkSessions(date, "right"))
  const [queue, setQueue] = useState<PschExternalEvent[]>(bulkBacklog)
  const [checked, setChecked] = useState<string[]>([])
  const [selectedLeft, setSelectedLeft] = useState<SchedulerEvent[]>([])
  const [selectedRight, setSelectedRight] = useState<SchedulerEvent[]>([])
  const [copy, setCopy] = useState(false)
  const [rtl, setRtl] = useState(false)
  const [rejectReviews, setRejectReviews] = useState(false)
  const { lines, log } = useLog()
  const selectedTasks = queue.filter((task) =>
    checked.includes(String(task.id))
  )
  const apply = (side: "left" | "right", change: PschEventTransaction) => {
    const setter = side === "left" ? setLeft : setRight
    setter((current) => {
      const replaced = new Set(
        [...change.updated, ...change.deleted].map((event) => event.id)
      )
      return [
        ...current.filter((event) => !replaced.has(event.id)),
        ...change.updated,
        ...change.created,
      ]
    })
    const inserted = new Set(change.created.map((event) => event.id))
    setQueue((current) => current.filter((task) => !inserted.has(task.id)))
    setChecked((current) => current.filter((id) => !inserted.has(id)))
    log(
      `${side === "left" ? "Schedule A" : "Schedule B"}: ${change.created.length} inserted, ${change.updated.length} updated, ${change.deleted.length} removed`
    )
  }
  const unschedule = (events: SchedulerEvent[]) => {
    const tasks = events.map((event) => {
      const task: PschExternalEvent = {
        ...event,
        duration:
          (new Date(event.end!).getTime() - new Date(event.start).getTime()) /
          60_000,
      }
      delete task.start
      delete task.end
      delete task.recurring
      delete task.recurringException
      delete task.recurringEventId
      return task
    })
    setQueue((current) => [
      ...current.filter((task) => !tasks.some((next) => next.id === task.id)),
      ...tasks,
    ])
    log(`Backlog received ${events.length} events`)
  }
  const panel = (side: "left" | "right") => (
    <div
      data-bulk-schedule={side}
      data-events={JSON.stringify(side === "left" ? left : right)}
      className="min-w-0"
    >
      <p className="mb-2 text-sm font-medium">
        Schedule {side === "left" ? "A" : "B"} ·{" "}
        {(side === "left" ? selectedLeft : selectedRight).length} selected
      </p>
      <ProScheduler
        data={side === "left" ? left : right}
        resources={studioResources.slice(0, 2)}
        refDate={date}
        onSelectedDateChange={setDate}
        view={
          mode === "timeline"
            ? {
                timeline: { type: "day", startTime: "08:00", endTime: "18:00" },
              }
            : {
                scheduler: {
                  type: "day",
                  resources: true,
                  startTime: "08:00",
                  endTime: "18:00",
                },
              }
        }
        styleConfig={{
          resourceColWidth: 90,
          unitWidthPx: 65,
          fitToWidth: false,
          hourHeightPx: 48,
        }}
        height={mode === "timeline" ? 250 : 440}
        selectMultipleEvents
        dragSelectedEvents
        selectedEvents={side === "left" ? selectedLeft : selectedRight}
        onSelectedEventsChange={
          side === "left" ? setSelectedLeft : setSelectedRight
        }
        externalDrop
        externalDrag
        eventOverlap={false}
        invalid={[
          {
            startTime: "12:00",
            endTime: "13:00",
            recurring: { repeat: "daily" },
            title: "Lunch",
          },
        ]}
        dragTimeStep={15}
        dragToResize={false}
        dragToCreate={false}
        clickToCreate={false}
        eventChangeDelivery="transaction"
        onEventTransaction={(change) => apply(side, change)}
        onEventDelete={() => (copy ? false : undefined)}
        onEventCreate={(draft) =>
          rejectReviews && draft.external?.id === "bulk-design"
            ? false
            : undefined
        }
        onEventUpdate={(event) =>
          rejectReviews && event.id === "bulk-review" ? false : undefined
        }
        onEventCreateFailed={() =>
          log("Drop refused — the whole group stays put")
        }
        onEventUpdateFailed={() =>
          log("Move refused — the whole group stays put")
        }
        dir={rtl ? "rtl" : "ltr"}
      />
    </div>
  )
  return (
    <div data-bulk-demo className="flex flex-col gap-4">
      <Toolbar label="Bulk placement">
        <Choice
          active={mode === "timeline"}
          onClick={() => setMode("timeline")}
        >
          Timeline
        </Choice>
        <Choice
          active={mode === "scheduler"}
          onClick={() => setMode("scheduler")}
        >
          Time grid
        </Choice>
        <Choice
          onClick={() => {
            setChecked([])
            setSelectedLeft([])
            setSelectedRight([])
          }}
        >
          Clear selection
        </Choice>
        <Choice
          onClick={() => {
            setLeft(bulkSessions(date, "left"))
            setRight(bulkSessions(date, "right"))
            setQueue(bulkBacklog)
            setChecked([])
            setSelectedLeft([])
            setSelectedRight([])
            log("Reset")
          }}
        >
          Reset
        </Choice>
        <label className="flex items-center gap-2 text-xs">
          <input
            type="checkbox"
            checked={copy}
            onChange={(event) => setCopy(event.target.checked)}
          />
          Copy transfers
        </label>
        <label className="flex items-center gap-2 text-xs">
          <input
            type="checkbox"
            checked={rtl}
            onChange={(event) => setRtl(event.target.checked)}
          />
          RTL
        </label>
        <label className="flex items-center gap-2 text-xs">
          <input
            type="checkbox"
            checked={rejectReviews}
            onChange={(event) => setRejectReviews(event.target.checked)}
          />
          Reject reviews
        </label>
      </Toolbar>
      <p className="text-sm text-muted-foreground">
        Check backlog tasks and drag any checked card. Click scheduled events to
        select them, then drag one to pack the group. Lunch and existing
        bookings refuse the whole drop.
      </p>
      <ExternalDropZone
        data-bulk-dropzone
        onDrop={(event) => unschedule([event])}
        onEventsDrop={unschedule}
        className="rounded-lg border border-dashed p-3 data-[over]:border-primary data-[over]:bg-primary/5"
      >
        <p className="mb-2 text-xs font-medium text-muted-foreground">
          Backlog · {checked.length} selected · drop scheduled events here to
          unschedule
        </p>
        <div className="grid gap-2 sm:grid-cols-3">
          {queue.map((task) => (
            <div key={String(task.id)} className="flex items-center gap-2">
              <input
                type="checkbox"
                aria-label={`Select ${task.title}`}
                checked={checked.includes(String(task.id))}
                onChange={(event) =>
                  setChecked((current) =>
                    event.target.checked
                      ? [...current, String(task.id)]
                      : current.filter((id) => id !== String(task.id))
                  )
                }
              />
              <ExternalDraggable
                events={
                  checked.includes(String(task.id)) ? selectedTasks : [task]
                }
                data-backlog-id={task.id}
                className="min-w-0 flex-1"
              >
                <Card
                  title={task.title}
                  color={task.color}
                  meta={minutes(task.duration)}
                />
              </ExternalDraggable>
            </div>
          ))}
        </div>
        {!queue.length && (
          <p className="text-sm text-muted-foreground">
            All tasks scheduled. Drag a group here to bring it back.
          </p>
        )}
      </ExternalDropZone>
      <div className="grid gap-4 lg:grid-cols-2">
        {panel("left")}
        {panel("right")}
      </div>
      <Log
        lines={lines}
        empty="Select two or more events to try bulk placement."
      />
    </div>
  )
}

/** A card in a side list. */
function Card({ color, title, meta }: { color?: string; title: string; meta?: string }) {
  return (
    <div className="flex items-center gap-2 rounded-md border border-border bg-card px-2.5 py-2 text-sm shadow-xs">
      <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: color ?? "var(--primary)" }} />
      <span className="min-w-0 flex-1 truncate font-medium">{title}</span>
      {meta && <span className="shrink-0 text-xs text-muted-foreground">{meta}</span>}
    </div>
  )
}

const minutes = (n = 60) => (n >= 60 ? `${n / 60} h` : `${n} min`)

About this demo

Select backlog tasks or scheduled events and drag them together. Groups pack back-to-back, with one validated transaction per scheduler; a conflicting drop leaves every event in place.

Things to try

  • Select two backlog tasks and drag either onto a resource
  • Select two scheduled events and drag them together
  • Transfer a group to the other scheduler or back to the backlog

The props behind it are explained in Selection, drag and drop, links.

Use ProScheduler in your project