Field service dispatch
An urgent job lands in the queue. Find the crew that can take it before it is due.
- Field service
- Fieldwork
- External drag and drop
- Summary rows
- Minimap
- Live search
- Multi-selection
- Active areas
- Filters
- Detail panel
- Theming
- Demo with synthetic data
Mission
0 of 3 steps doneMonday, 8:40 AM: J-5107, an urgent HVAC repair at a clinic in Zone C1, has just come in, due at 2 PM. And Crew S2’s van broke down this morning.
Show only HVAC crews and jobs. — To do
Use “HVAC” in the toolbar. The filter applies to the board’s rows and to the queue.
Drag J-5107 from the queue onto Crew C1, between 10 AM and noon. — To do
Other crews refuse it: wrong trade, another region or too late. “Assign” on the ticket shows every crew’s first free slot, drive included.
Crew S2’s van broke down: select both of its jobs and return them to the queue. — To do
Show every trade again, click J-5110, Ctrl/⌘+click J-5111 (or drag a box around both), then use “Return to queue”.
About 30 seconds. Steps tick off as you complete them.
Keyboard: focus the grid, then use arrow keys, Enter and Alt+arrows to move.
Preview of the first frameLive: the real Pro engine, running in your browserAbout 30 seconds. Steps tick off as you complete them. Keyboard: focus the grid, then use arrow keys, Enter and Alt+arrows to move.
The situation.
Fieldwork is a fictional technical service company with six crews in three regions. Each crew has its trades (HVAC, electrical, plumbing), works from 8 AM to 6 PM, drives out from its region’s depot and only covers its own region. Jobs come in with an estimate, a site, a service zone and a due time, and some of them are urgent.
A dispatcher’s morning is a queue and a board. Dropping a job on the wrong crew wastes a visit; missing the due time breaks a service agreement; a van off the road strands every job behind it. The board has to say, while the job is being dragged, whether a crew can take it and why not, offer the same check without a mouse, and show how much time each job really holds, the drive included.
What you will do
You will narrow the board to one trade, place an urgent job on the only crew that can reach it in time, and send a stranded crew’s jobs back to the queue in one action.
Where the library ends and your application begins.
SuperScheduler provides
- Queue tickets dragged onto the board with SuperScheduler.Scheduler.makeDraggable, checked frame by frame in onEventMoving and committed in onEventMoved (args.external).
- rowHeaderColumns with technician avatars, trade chips, a region stripe and the crew’s load, and a frozen top row whose onBeforeCellRender cells count the free crews per hour.
- Two-line cards from onBeforeEventRender with a time-anchored drive area at the start, SLA badges, and hover actions as areas with visibility: 'Hover'.
- rows.filter and onRowFilter for trade, region and the live search; multiselect with rectangleSelectHandling: 'EventSelect'; disabled cells for time off.
- Day and week zoomLevels with showNonBusiness: false, separators for the dispatcher’s clock, the drag card, the event hover card, a context menu and createHistory from super-scheduler/history.
- The minimap (super-scheduler/minimap) over a fixed range of the dispatch week, fed with the application’s own hourly series; its brush is a slider from the keyboard too.
This example’s code decides
- Which crew can take which job: trade, region, working hours, time off and due time, with the drive from the depot counted in.
- The queue itself: every job that is not on the board, so returning jobs is a single state update.
- Service levels: the countdown before a queued job must leave, the margin a booking leaves, and what counts as at risk.
- The Assign panel: each crew’s first free slot found by the rules, with no routing between jobs.
- Every figure: unassigned jobs, jobs at risk, crews on the road, today’s load, free crews per hour.
- The fleet load the minimap draws: booked time over the time crews are on the road, hour by hour and day by day, with the high and full thresholds the crew meters use.
The code behind this demo.
These are the files this page runs, not a simplified copy. They compile against the public SuperScheduler Pro exports.
The integration: scales, the row header columns, the free-crews row, the cards with their drive area and SLA badge, the filters, multi-selection, time off as disabled cells, and the callbacks that check every slot, drops from the queue included.
/**
* Fieldwork dispatch board: a frozen "Crews free" row over crews grouped by region, one working
* week. Jobs arrive from the queue rail under the board (an external drag, see ./tray) or move
* between crews on the board.
*
* Library: tree rows with rowHeaderColumns, a frozen summary row painted by onBeforeCellRender,
* row filtering (trade, region, live search), external drops, drag between rows with per-frame
* vetoes, the drag card, conflict highlighting, two-line cards with a time-anchored drive area and
* hover actions, event multi-selection and rectangle selection, the event hover card
* (super-scheduler/react-render), a context menu, undo history, disabled cells, separators, day
* and week scales, keyboard moves. Application: which crew can take which job (skill, region,
* working hours, availability, due time, the drive from the depot), service levels, free crews and
* load. Those rules live in ./rules; nothing here plans routes.
*/
import { useCallback, useEffect, useMemo, useRef, type RefObject } from 'react'
import { SuperScheduler } from 'super-scheduler'
import type { SchedulerEventsChangeArgs } from 'super-scheduler'
import type { SchedulerHistory } from 'super-scheduler/history'
import { SuperSchedulerComponent, type SchedulerRenderProps } from 'super-scheduler/react-render'
import { format, plural } from '~/i18n/format'
import { DAY, HOUR, MINUTE, civil, formatCivil, parseCivil } from '../../scheduler/civil'
import { headerLabel } from '../../scheduler/header-format'
import { createEventMenu } from '../kit/context-menu'
import { formatClock, formatDay, formatSpan, formatWhen } from '../kit/format'
import { useEventHover, type HoverCardModel } from '../kit/hover-card'
import { KEYS } from '../kit/keys'
import { useDropRefusal } from '../kit/use-drop-refusal'
import { createDragCard } from '../kit/verdict'
import { skinClass, skinMenuTheme } from '../registry'
import type { DemoCommon } from '../types'
import {
FREE_ROW,
SKILL_TONES,
crewOf,
readJobFields,
regionOf,
toBooking,
toResources,
type JobEvent,
} from './adapter'
import {
COLUMN_WIDTHS,
COMPACT_ROW_HEADER,
EVENT_HEIGHT,
FREE_ROW_HEIGHT,
HEADER_HEIGHTS,
HOUR_WIDTH,
REGION_ROW_HEIGHT,
ROW_MARGIN,
WEEK_CELL_WIDTH,
} from './geometry'
import {
BLOCKS,
CREWS,
NOW,
WEEK,
WORKING_HOURS,
ZONE_TRAVEL,
jobById,
type Crew,
type Job,
type JobType,
type RegionId,
} from './model'
import {
TIGHT_SLACK,
crewLoad,
loadLevel,
crewsFree,
dueSlack,
earliestOption,
slaState,
slotRefusal,
type Booking,
type Option,
type Refusal,
} from './rules'
import { ZOOM_IDS, type FieldworkText, type SkillFilter, type ZoomId } from './text'
import 'super-scheduler/styles.css'
import '../../scheduler/skin.css'
import './tokens.css'
import './fieldwork.css'
const SLUG = 'field-service-dispatch'
const NOW_TICKS = parseCivil(NOW)
/** What the board asks the demo to do (context menu and hover actions). */
export type JobAction = 'details' | 'earliest' | 'crew-day' | 'send-back'
/** Which crews the board shows: a trade, a set of regions and the live search. */
export interface BoardFilter {
readonly skill: SkillFilter
readonly regions: readonly RegionId[]
readonly query: string
}
export interface FieldworkSchedulerProps {
readonly events: JobEvent[]
/** The same jobs as bookings: cards, figures, the menu and the verdict read them. */
readonly bookings: readonly Booking[]
/** Jobs whose crew is off the road at that time (the breakdown). */
readonly conflicts: readonly string[]
readonly text: FieldworkText
readonly common: DemoCommon
/** BCP 47 tag for labels, and the scheduler locale id. */
readonly tag: string
readonly schedulerLocale: string
/** Scale on mount. Later changes go through control.zoom so the view animates. */
readonly initialZoom: ZoomId
readonly filter: BoardFilter
/** Narrow stage: the row header keeps the crew column only. */
readonly compact: boolean
readonly history: SchedulerHistory
readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
/** The selected jobs, after every click, Ctrl/⌘+click, rectangle or keyboard selection. */
readonly onSelection: (ids: readonly string[]) => void
/** `external`: the job came from the queue. */
readonly onMoved: (id: string, external: boolean) => void
readonly onRefused: (id: string, refusal: Refusal) => void
readonly onAction: (action: JobAction, id: string) => void
readonly onZoomLevel: (level: ZoomId) => void
}
/** The earliest slot any crew offers a job, from the dispatcher's "now" (menu and sheet share it). */
export function earliestOf(
job: Job,
bookings: readonly Booking[],
current: Booking,
): Option | null {
return earliestOption(job, CREWS, NOW, WORKING_HOURS, BLOCKS, bookings, current.crew)
}
/** A working day in hours, or the week in two-hour cells. */
const SCALES: Readonly<Record<ZoomId, SuperScheduler.ZoomLevelProperties>> = {
day: {
scale: 'Hour',
cellWidth: HOUR_WIDTH,
timeHeaders: [
{ groupBy: 'Day', height: HEADER_HEIGHTS[0] },
{ groupBy: 'Hour', height: HEADER_HEIGHTS[1] },
],
},
week: {
scale: 'CellDuration',
cellDuration: 120,
cellWidth: WEEK_CELL_WIDTH,
timeHeaders: [
{ groupBy: 'Day', height: HEADER_HEIGHTS[0] },
{ groupBy: 'Cell', height: HEADER_HEIGHTS[1] },
],
},
}
// Same order as ZOOM_IDS, so onZoom's level index maps back to an id.
const ZOOM_LEVELS: SuperScheduler.ZoomLevel[] = ZOOM_IDS.map((id) => ({
id,
properties: SCALES[id],
}))
/** Every job the control holds right now, as bookings the rules read. */
function bookingsIn(control: SuperScheduler.Scheduler): Booking[] {
return control.events.list.flatMap((event) => toBooking(event) ?? [])
}
/** Checks one proposed slot of a job (on the board or dragged from the queue) for a crew. */
function refusalFor(
control: SuperScheduler.Scheduler | null,
data: object,
id: string,
resource: SuperScheduler.ResourceId,
start: SuperScheduler.Date,
end: SuperScheduler.Date,
): Refusal | null {
const fields = readJobFields(data)
const crew = crewOf(resource)
if (control === null || fields === null || crew === null) return null
return slotRefusal(
{ id, ...fields },
crew,
civil(start.ticks),
civil(end.ticks),
WORKING_HOURS,
BLOCKS,
bookingsIn(control),
)
}
function initials(name: string): string {
return name
.split(/\s+/)
.map((part) => part.charAt(0))
.join('')
.slice(0, 2)
.toUpperCase()
}
/** Does the live search find this crew (its name, a technician, or one of its jobs)? */
export function crewMatches(
crew: Crew,
query: string,
bookings: readonly Booking[],
text: FieldworkText,
): boolean {
const q = query.trim().toLocaleLowerCase()
if (q === '') return true
if (text.crews[crew.id].toLocaleLowerCase().includes(q)) return true
if (crew.members.some((member) => member.toLocaleLowerCase().includes(q))) return true
return bookings.some((booking) => {
if (booking.crew !== crew.id) return false
const job = jobById(booking.job)
return job !== null && jobMatches(job, q, text)
})
}
function jobMatches(job: Job, q: string, text: FieldworkText): boolean {
return (
job.id.toLocaleLowerCase().includes(q) ||
text.sites[job.site].toLocaleLowerCase().includes(q) ||
text.types[job.type].toLocaleLowerCase().includes(q) ||
text.zones[job.zone].toLocaleLowerCase().includes(q)
)
}
// Glyphs drawn in cards and hover actions (trusted markup, classes only).
const TYPE_GLYPH: Readonly<Record<JobType, string>> = {
repair:
'<path d="M10.2 2.6a3.4 3.4 0 0 0-3.1 4.7L2.6 11.8a1.2 1.2 0 0 0 1.7 1.7l4.5-4.5a3.4 3.4 0 0 0 4.7-3.1l-1.9 1.9-1.7-.4-.4-1.7z"/>',
maintenance:
'<circle cx="8" cy="8" r="2.2"/><path d="M8 1.8v1.7M8 12.5v1.7M1.8 8h1.7M12.5 8h1.7M3.6 3.6l1.2 1.2M11.2 11.2l1.2 1.2M3.6 12.4l1.2-1.2M11.2 4.8l1.2-1.2"/>',
install: '<path d="M5.5 2v3.5M10.5 2v3.5M3.8 5.5h8.4v2.2a4.2 4.2 0 0 1-8.4 0zM8 11.9V14"/>',
inspection:
'<rect x="3.2" y="2.6" width="9.6" height="11" rx="1.4"/><path d="M6 2.6v1.4h4V2.6M5.8 9l1.5 1.5 3-3"/>',
}
const GLYPH = {
flag: '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4 14V2.5M4 3h7.5l-1.6 2.8L11.5 8.6H4"/></svg>',
earliest:
'<svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="9" r="5"/><path d="M8 6.5V9l1.6 1.2M6.5 2h3"/></svg>',
back: '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6 4 2.5 7.5 6 11"/><path d="M2.8 7.5h6.7a3.5 3.5 0 0 1 0 7H7"/></svg>',
details:
'<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="2" y="2" width="12" height="12" rx="2"/><path d="M10 2v12M4.5 6h3M4.5 9h3"/></svg>',
van: '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M1.8 4.5h7.4v6.5H1.8zM9.2 6.6h2.6l2.4 2.4v2H9.2"/><circle cx="4.4" cy="11.6" r="1.3"/><circle cx="11.6" cy="11.6" r="1.3"/></svg>',
} as const
function typeGlyph(type: JobType): string {
return `<svg class="fw-ev__glyph" viewBox="0 0 16 16" aria-hidden="true">${TYPE_GLYPH[type]}</svg>`
}
export function FieldworkScheduler(props: FieldworkSchedulerProps) {
const { events, bookings, conflicts, text, common, tag, schedulerLocale, initialZoom } = props
const { filter, compact, history, controlRef } = props
const { onEventsChange, onSelection, onMoved, onRefused, onAction, onZoomLevel } = props
const resources = useMemo(() => toResources(text), [text])
const refusal = useDropRefusal(onRefused)
const board = useRef<HTMLDivElement>(null)
// Hover actions call the latest handler without rebuilding every card's areas.
const action = useRef(onAction)
useEffect(() => {
action.current = onAction
}, [onAction])
const crewName = useCallback(
(id: SuperScheduler.ResourceId) => {
const crew = crewOf(id)
return crew === null ? null : `${text.crews[crew.id]} · ${text.regions[crew.region]}`
},
[text],
)
// Hover card: the crew and its team, the trade, site and zone, the drive, and the deadline margin.
const card = useCallback(
(event: SuperScheduler.Event): HoverCardModel | null => {
const booking = bookings.find((candidate) => candidate.job === String(event.id()))
const job = booking === undefined ? null : jobById(booking.job)
const crew = booking === undefined ? null : crewOf(booking.crew)
if (booking === undefined || job === null || crew === null) return null
const start = parseCivil(booking.start)
const end = parseCivil(booking.end)
const day = start - (start % DAY)
const slack = dueSlack(job, booking.end)
const tight = slack < TIGHT_SLACK
const blocked = conflicts.includes(job.id)
return {
id: job.id,
tone: SKILL_TONES[job.skill],
eyebrow: `${text.crews[crew.id]} · ${text.regions[crew.region]}`,
title: `${job.id} · ${text.types[job.type]}`,
status: blocked
? { label: text.sla.risk, tone: 'danger' }
: job.priority === 'urgent'
? { label: text.priorities.urgent, tone: 'danger' }
: { label: text.card.onTime, tone: 'success' },
time: {
start,
end,
day: formatDay(start, tag),
startLabel: formatClock(start, tag),
endLabel: formatClock(end, tag),
span: formatSpan(end - start, tag),
window: {
start: day + WORKING_HOURS.begin * HOUR,
end: day + WORKING_HOURS.end * HOUR,
},
},
facts: [
{ label: text.fields.site, value: `${text.sites[job.site]} · ${text.zones[job.zone]}` },
{ label: text.fields.skill, value: text.skills[job.skill] },
{
label: text.fields.travel,
value: format(text.card.drive, {
time: formatSpan(ZONE_TRAVEL[job.zone] * MINUTE, tag),
}),
},
{
label: text.fields.technicians,
value: plural(text.technicians, crew.technicians, tag),
},
{
label: text.fields.due,
value: `${formatWhen(job.due, tag)} · ${format(
slack >= 0 ? text.card.spare : text.card.overdue,
{ time: formatSpan(slack, tag) },
)}`,
alert: tight,
},
],
rule: blocked
? { state: 'blocked', text: text.card.offRoad }
: tight
? { state: 'warn', text: format(text.card.tight, { time: formatSpan(slack, tag) }) }
: { state: 'ok', text: format(text.card.fits, { crew: text.crews[crew.id] }) },
// A click selects on this board (Ctrl/⌘ adds), so Enter selects too.
hints: [
{ keys: KEYS.details, label: text.card.select },
{ keys: KEYS.actions, label: common.kit.actions },
{ keys: KEYS.move, label: common.kit.move },
],
}
},
[bookings, conflicts, text, common, tag],
)
const { eventHover, suppressHover } = useEventHover(card)
// Drag verdict: crew and region, the slot, and the dispatch rule's reason when it refuses; a
// slot that finishes less than an hour before the deadline is allowed but flagged.
const dragCard = useMemo(
() =>
createDragCard({
tag,
common,
rowName: crewName,
warn: (info) => {
const job = info.eventId === null ? null : jobById(String(info.eventId))
if (job === null) return null
const slack = parseCivil(job.due) - info.end.getTime()
return slack >= 0 && slack < TIGHT_SLACK
? format(text.card.tight, { time: formatSpan(slack, tag) })
: null
},
}),
[tag, common, text, crewName],
)
// Context menu: rebuilt when the board changes, so its labels name the real crew and slot.
const contextMenu = useMemo(
() =>
createEventMenu({
theme: skinMenuTheme(SLUG),
title: (event) => format(common.kit.menuTitle, { name: String(event.id()) }),
onOpenChange: (open) => suppressHover(open),
entries: (event) => {
const id = String(event.id())
const booking = bookings.find((candidate) => candidate.job === id)
const job = jobById(id)
if (booking === undefined || job === null) return []
const option = earliestOf(job, bookings, booking)
const here =
option !== null && option.crew === booking.crew && option.start === booking.start
return [
{ label: common.kit.openDetails, icon: 'details', run: () => onAction('details', id) },
{
label:
option === null
? text.actions.noEarliest
: here
? text.actions.atEarliest
: format(text.actions.earliest, {
crew: text.crews[option.crew],
time: formatWhen(option.start, tag),
}),
icon: 'slot',
primary: option !== null && !here,
disabled: option === null || here,
run: () => onAction('earliest', id),
},
{
label: format(text.actions.crewDay, { crew: text.crews[booking.crew] }),
icon: 'layers',
run: () => onAction('crew-day', id),
},
'separator',
{ label: text.actions.sendBack, icon: 'pending', run: () => onAction('send-back', id) },
]
},
}),
[bookings, common, text, tag, onAction, suppressHover],
)
// The dispatcher's clock: a cobalt line over the cards, its time in the day header.
const separators = useMemo<SuperScheduler.SeparatorData[]>(
() => [
{
location: NOW,
cssClass: 'fw-sep-now',
// Under the cards: the clock reads in the gaps and never crosses a job's text.
layer: 'BelowEvents',
width: 2,
toolTip: format(text.clock, { time: formatWhen(NOW, tag) }),
},
],
[text, tag],
)
const columns = useMemo<SuperScheduler.RowHeaderColumnData[]>(
() =>
compact
? [{ text: text.columns.crew, width: COMPACT_ROW_HEADER, nonresizable: true }]
: [
{ text: text.columns.crew, width: COLUMN_WIDTHS[0], nonresizable: true },
{ text: text.columns.load, width: COLUMN_WIDTHS[1], nonresizable: true },
],
[compact, text],
)
const config = useMemo<SchedulerRenderProps>(() => {
const escape = SuperScheduler.Util.escapeHtml
const selectionOf = (control: SuperScheduler.Scheduler) =>
control.multiselect.events().map((event) => String(event.id()))
const blocked = new Set(conflicts)
const query = filter.query.trim().toLocaleLowerCase()
const visibleCrews = CREWS.filter(
(crew) =>
(filter.skill === 'all' || crew.skills.includes(filter.skill)) &&
filter.regions.includes(crew.region) &&
crewMatches(crew, query, bookings, text),
)
const visibleIds = new Set<string>(visibleCrews.map((crew) => crew.id))
// Header markup per cell start (the hook runs for every header cell).
const headerCache = new Map<
string,
Pick<SuperScheduler.TimeHeaderRenderHeader, 'html' | 'cssClass' | 'areas'>
>()
const clockLabel = escape(formatClock(NOW_TICKS, tag))
const clockTip = format(text.clock, { time: formatWhen(NOW, tag) })
const dayHeader = (ticks: number) => {
const weekday = escape(formatCivil(ticks, tag, { weekday: 'short' }))
const date = escape(formatCivil(ticks, tag, { day: 'numeric', month: 'short' }))
const midnight = ticks - (ticks % DAY)
const today = NOW_TICKS >= midnight && NOW_TICKS < midnight + DAY
// Today carries the dispatcher's clock beside its date; the line marks the same instant.
const clock = today
? `<span class="fw-clock" title="${escape(clockTip)}">${clockLabel}</span>`
: ''
return {
html: `<span class="fw-th-day"><b>${weekday}</b> ${date}${clock}</span>`,
cssClass: today ? 'fw-th fw-th--day fw-th--today' : 'fw-th fw-th--day',
areas: [] as SuperScheduler.AreaData[],
}
}
const cellHeader = (ticks: number, span: number) => {
const unit = span <= HOUR ? 'hour' : 'hours-2'
const current = NOW_TICKS >= ticks && NOW_TICKS < ticks + span
return {
html: escape(headerLabel(ticks, unit, tag, 'cell')),
cssClass: current ? 'fw-th fw-th--hour fw-th--now' : 'fw-th fw-th--hour',
areas: [] as SuperScheduler.AreaData[],
}
}
// Free crews per hour, cached per cell for this board and filter.
const freeCache = new Map<number, number>()
const freeAt = (from: number, to: number) => {
let value = freeCache.get(from)
if (value === undefined) {
value = crewsFree(visibleCrews, bookings, BLOCKS, civil(from), civil(to))
freeCache.set(from, value)
}
return value
}
const freeHtml = new Map<string, string>()
const loads = new Map(
CREWS.map((crew) => [crew.id, crewLoad(crew.id, bookings, BLOCKS, NOW, WORKING_HOURS)]),
)
const cardCache = new Map<string, { html: string; areas: SuperScheduler.AreaData[] }>()
return {
locale: schedulerLocale,
cssClass: skinClass(SLUG),
startDate: WEEK.start,
days: WEEK.days,
zoomLevels: ZOOM_LEVELS,
zoom: initialZoom,
zoomPosition: 'left',
// Crews are on the road 08:00-18:00: evenings and nights are not drawn.
businessBeginsHour: WORKING_HOURS.begin,
businessEndsHour: WORKING_HOURS.end,
showNonBusiness: false,
useEventBoxes: 'Never',
height: '100%',
treeEnabled: true,
treePreventParentUsage: true,
rowHeaderColumns: columns,
rowHeaderColumnsMergeParents: true,
rowHeaderWidthAutoFit: false,
eventHeight: EVENT_HEIGHT,
rowMarginTop: ROW_MARGIN,
rowMarginBottom: ROW_MARGIN,
allowEventOverlap: false,
conflictHighlight: true,
// Time on site is the job's estimate: dispatchers move jobs, they do not stretch them.
eventResizeHandling: 'Disabled',
// A click selects a job; Ctrl/⌘+click adds more, and a box drawn on the grid selects all inside.
eventClickHandling: 'Select',
allowMultiSelect: true,
rectangleSelectHandling: 'EventSelect',
durationBarVisible: false,
separators,
showToolTip: false,
keyboardEnabled: true,
keyboardTarget: 'component',
keyboardMode: 'Full',
history,
controlRef,
onEventsChange,
// Row heights per kind: the free-crews row and region rows hold no jobs.
onBeforeResHeaderRender: (args) => {
const kind = args.resource['rowKind']
const height =
kind === 'free' ? FREE_ROW_HEIGHT : kind === 'region' ? REGION_ROW_HEIGHT : undefined
if (height === undefined) return
args.resource.minHeight = height
args.resource.emptyHeight = height
args.resource.marginTop = 0
args.resource.marginBottom = 0
},
onBeforeTimeHeaderRender: (args) => {
const { level } = args.header
const ticks = args.header.start.getTime()
const end = args.header.end.getTime()
const key = `${level}:${ticks}:${end - ticks}`
let header = headerCache.get(key)
if (header === undefined) {
header = level === 0 ? dayHeader(ticks) : cellHeader(ticks, end - ticks)
headerCache.set(key, header)
}
args.header.html = header.html
args.header.cssClass = header.cssClass
args.header.areas = header.areas
},
onBeforeRowHeaderRender: (args) => {
const row = args.row
const [first, second] = row.columns
if (row.id === FREE_ROW) {
row.cssClass = 'fw-rh fw-rh--free'
if (first !== undefined)
first.html =
`<span class="fw-rh-free"><b>${escape(text.free.row)}</b>` +
`<small>${escape(text.free.meta)}</small></span>`
return
}
const region = regionOf(row.id)
if (region !== null) {
row.cssClass = `fw-rh fw-rh--region fw-region--${region}`
const count = CREWS.filter((crew) => crew.region === region).length
// A parent row spans the columns (rowHeaderColumnsMergeParents): it shows `row.html`.
row.html =
`<span class="fw-rh-region"><i aria-hidden="true"></i><b>${escape(text.regions[region])}</b>` +
`<small>${count}</small></span>`
return
}
const crew = crewOf(row.id)
if (crew === null) return
const load = loads.get(crew.id) ?? 0
row.cssClass = `fw-rh fw-rh--crew fw-region--${crew.region}`
if (first !== undefined) {
const avatars = crew.members
.map((member) => `<i title="${escape(member)}">${escape(initials(member))}</i>`)
.join('')
const skills = crew.skills
.map(
(skill) =>
`<em class="fw-skill fw-skill--${skill}">${escape(text.skillsShort[skill])}</em>`,
)
.join('')
first.html =
`<span class="fw-rh-crew"><span class="fw-avatars" aria-hidden="true">${avatars}</span>` +
`<span class="fw-rh-crew__name">${escape(text.crews[crew.id])}</span>` +
`<span class="fw-rh-crew__skills">${skills}</span>` +
`<span class="sr-only">${escape(crew.members.join(', '))}</span></span>`
}
if (second !== undefined) {
const level = loadLevel(load)
second.html = `<span class="fw-load fw-load--${level}"><b>${Math.round(load * 100)}%</b></span>`
second.areas = [
{ left: 10, right: 10, bottom: 14, height: 3, cssClass: 'fw-meter' },
{
left: 10,
width: `calc((100% - 20px) * ${load.toFixed(3)})`,
bottom: 14,
height: 3,
cssClass: `fw-meter-fill fw-load--${level}`,
},
]
}
},
// Trade, regions and the live search; region rows stay while one of their crews shows.
onRowFilter: (args) => {
if (args.row.id === FREE_ROW) return
const region = regionOf(args.row.id)
if (region !== null) {
args.visible = visibleCrews.some((crew) => crew.region === region)
return
}
const crew = crewOf(args.row.id)
if (crew !== null) args.visible = visibleIds.has(crew.id)
},
onBeforeCellRender: (args) => {
const cell = args.cell
const from = cell.start.getTime()
const to = cell.end.getTime()
if (cell.resource === FREE_ROW) {
const free = freeAt(from, to)
const total = visibleCrews.length
const level = free === 0 ? 'none' : free === 1 ? 'low' : 'ok'
cell.properties.cssClass = `fw-free fw-free--${level}`
if ((args.control.cellWidth ?? HOUR_WIDTH) < 40) return
const key = `${free}/${total}`
let html = freeHtml.get(key)
if (html === undefined) {
const pips = Array.from(
{ length: total },
(_, index) => `<i${index < free ? ' class="on"' : ''}></i>`,
).join('')
html =
`<span class="fw-free__value"><b>${free}</b><small>/${total}</small></span>` +
`<span class="fw-free__pips" aria-hidden="true">${pips}</span>`
freeHtml.set(key, html)
}
cell.properties.html = html
return
}
if (regionOf(cell.resource) !== null) {
cell.properties.cssClass = 'fw-cell-region'
return
}
const crew = crewOf(cell.resource)
if (crew === null) return
const start = civil(from)
const block = BLOCKS.find(
(candidate) =>
candidate.crew === crew.id && candidate.start < civil(to) && start < candidate.end,
)
if (block === undefined) return
// Time off: disabled cells refuse drops for that crew.
cell.properties.disabled = true
cell.properties.cssClass = `fw-cell-off fw-cell-off--${block.kind}`
// The label sits on the block's first cell, or on the first one after the clock when the
// block already started, so the clock line never crosses it.
const labelFrom = Math.max(parseCivil(block.start), Math.ceil(NOW_TICKS / HOUR) * HOUR)
const labelled =
parseCivil(block.start) >= NOW_TICKS
? start <= block.start
: from <= labelFrom && labelFrom < to
if (labelled) {
// That cell carries the label; it runs over the rest of the block.
cell.properties.cssClass = `fw-cell-off fw-cell-off--${block.kind} fw-cell-off--start`
cell.properties.html = `<span class="fw-off-label">${escape(text.blocks[block.kind])}</span>`
}
},
onBeforeEventRender: (args) => {
const id = String(args.data.id)
const fields = readJobFields(args.data)
const job = jobById(id)
const booking = bookings.find((candidate) => candidate.job === id)
if (fields === null || job === null || booking === undefined) return
const off = blocked.has(id)
const sla = slaState(job, booking, NOW, off)
const slack = dueSlack(job, booking.end)
const key = `${id}|${booking.start}|${booking.crew}|${sla}`
let cached = cardCache.get(key)
if (cached === undefined) {
const urgent = job.priority === 'urgent'
const spare = formatSpan(slack, tag)
const badge =
sla === 'risk' || sla === 'late'
? text.sla[sla]
: format(text.sla[sla], { time: spare })
const tip = sla === 'risk' ? text.card.offRoad : format(text.card.spare, { time: spare })
const html =
`<span class="fw-ev__body">` +
`<span class="fw-ev__l1">${typeGlyph(job.type)}<b class="fw-ev__id">${escape(job.id)}</b>` +
`${urgent ? `<span class="fw-ev__flag" title="${escape(text.priorities.urgent)}">${GLYPH.flag}</span>` : ''}` +
`<span class="fw-ev__site">${escape(text.sites[job.site])}</span></span>` +
`<span class="fw-ev__l2" data-super-scheduler-part="event-meta">` +
`<span class="fw-ev__zone">${escape(text.zones[job.zone])}</span>` +
`<span class="fw-sla fw-sla--${sla}" title="${escape(tip)}">${escape(badge)}</span></span>` +
// The job's length trails the times and drops out on a short card (see fieldwork.css).
`<span class="fw-ev__l3" data-super-scheduler-part="event-meta">` +
`${escape(formatClock(booking.start, tag))}–${escape(formatClock(booking.end, tag))}` +
`<span class="fw-ev__len"> · ${escape(formatSpan(job.minutes * MINUTE, tag))}</span></span></span>`
const driveEnd = civil(parseCivil(booking.start) + ZONE_TRAVEL[job.zone] * MINUTE)
const button = (
right: number,
glyph: string,
tip: string,
run: JobAction,
): SuperScheduler.AreaData => ({
right,
top: 'calc(50% - 12px)',
width: 24,
height: 24,
visibility: 'Hover',
action: 'None',
cssClass: 'fw-act',
html: glyph,
toolTip: tip,
onClick: () => action.current(run, id),
})
const areas: SuperScheduler.AreaData[] = [
{
start: booking.start,
end: driveEnd,
top: 0,
bottom: 0,
cssClass: 'fw-drive',
action: 'Default',
html: GLYPH.van,
toolTip: format(text.card.drive, {
time: formatSpan(ZONE_TRAVEL[job.zone] * MINUTE, tag),
}),
},
button(60, GLYPH.earliest, text.history.earliest, 'earliest'),
button(32, GLYPH.back, text.actions.sendBack, 'send-back'),
button(4, GLYPH.details, text.actions.details, 'details'),
]
cached = { html, areas }
cardCache.set(key, cached)
}
args.data.html = cached.html
args.data.areas = cached.areas
// The text starts where the drive ends: fieldwork.css sizes it from the board's --fw-ppm.
const classes = ['fw-ev', `fw-ev--${job.skill}`, `fw-ev--drive-${ZONE_TRAVEL[job.zone]}`]
if (job.priority === 'urgent') classes.push('fw-ev--urgent')
if (off) classes.push('fw-ev--off')
if (query !== '' && !jobMatches(job, query, text)) classes.push('fw-ev--dim')
// Without a `theme` the control adds no class of its own to selected events; the
// selection redraw re-runs this hook for the jobs that changed.
const self = args.control.events.find(args.data.id)
if (self !== null && args.control.multiselect.isSelected(self))
classes.push('fw-ev--selected', 'ss-ev--selected')
args.data.cssClass = classes.join(' ')
args.data.ariaLabel = `${job.id} · ${text.types[job.type]}, ${text.sites[job.site]}, ${text.zones[job.zone]}${job.priority === 'urgent' ? `, ${text.priorities.urgent}` : ''}`
},
// Runs for moves on the board and for jobs dragged in from the queue (args.external).
onEventMoving: (args) => {
const id = String(args.e.id())
const reason = refusalFor(
controlRef.current,
args.e.data,
id,
args.resource,
args.start,
args.end,
)
refusal.track(id, reason)
if (reason !== null) {
args.allowed = false
args.message = text.rules[reason]
}
},
// Final check before the commit; keyboard moves (Alt+arrows) arrive here without a drag.
onEventMove: (args) => {
const id = String(args.e.id())
const reason = refusalFor(
args.control,
args.e.data,
id,
args.newResource,
args.newStart,
args.newEnd,
)
if (reason !== null) {
args.preventDefault()
refusal.clear()
onRefused(id, reason)
}
},
onEventMoved: (args) => {
refusal.clear()
onMoved(String(args.e.id()), args.external)
},
onEventSelected: () => {
const control = controlRef.current
if (control !== null) onSelection(selectionOf(control))
},
onRectangleSelected: () => {
const control = controlRef.current
if (control !== null) onSelection(selectionOf(control))
},
onZoom: (args) => {
if (args.phase !== 'end') return
// Pixels per minute of the new scale, for the cards' drive inset (CSSOM, never markup).
const minutes = args.scale === 'CellDuration' ? args.cellDuration : 60
board.current?.style.setProperty('--fw-ppm', String(args.cellWidth / minutes))
const level = ZOOM_IDS[args.level]
if (level !== undefined) onZoomLevel(level)
},
}
}, [
bookings,
columns,
conflicts,
controlRef,
filter,
history,
initialZoom,
onEventsChange,
onMoved,
onRefused,
onSelection,
onZoomLevel,
refusal,
schedulerLocale,
separators,
tag,
text,
])
// Row filtering is imperative: the control re-runs onRowFilter for every row.
useEffect(() => {
controlRef.current?.rows.filter(filter)
}, [controlRef, filter])
return (
<div ref={board} className="fw-board h-full [&>div]:h-full">
<SuperSchedulerComponent
{...config}
resources={resources}
events={events}
eventHover={eventHover}
dragCard={dragCard}
contextMenu={contextMenu}
/>
</div>
)
}The archive contains this example’s files and a README. It does not include SuperScheduler Pro or any download key.