Fleet rental planning
A compact is grounded on pickup day. Hand its rental to another car, keep the cleaning slot and stop walk-in sales on the days the fleet runs out.
- Mobility
- Fleetline
- Row columns
- Summary rows
- Minimap
- Multi-day events
- Filters
- Resource tree
- Detail panel
- Theming
- Demo with synthetic data
Mission
0 of 3 steps doneMonday 12 October, 8:00 AM: FL 208’s windscreen cracked overnight and the workshop has it until Friday. Its customer picks up at 10:00 AM.
Move rental R-1093 from FL 208 to another compact. — To do
Drag it up to FL 206 (an estate is accepted too, as a free upgrade). FL 204 is not ready in time, and vans or electric cars are refused.
The customer of van rental R-1107 keeps it one more day: extend it. — To do
Click R-1107 on FL V05 and use “Extend by one day” in the panel. The cleaning still ends before the next pickup.
Find the days when the whole fleet is out and stop walk-in sales on them. — To do
Switch to Weeks (or follow the minimap’s red stretch), click the red 0 in the Cars available row and press “Stop walk-in sales”. The Sold out figure in the bar opens the same panel from the keyboard.
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.
Fleetline is a fictional rental branch with ten vehicles: three compacts, two estates, two electric cars and three vans. Customers book a category and dates; the branch decides which vehicle goes out, and every return needs cleaning and checks (and charging, for the electric cars) before the next pickup.
A spreadsheet hides that turnaround: the next customer arrives while the van is still being cleaned. The board has to keep each rental’s dates fixed, refuse a downgrade or a van for a compact booking, show the preparation after every return, count the cars still free each day and tell the desk when to stop selling walk-ins.
What you will do
You will move a stranded rental to a free car (or a free upgrade), extend a van rental from its detail panel, and use the week view, the minimap and the Cars available row to close walk-in sales on the days the whole fleet is out.
Where the library ends and your application begins.
SuperScheduler provides
- Categories and their vehicles as a resource tree, with rowHeaderColumns (a licence plate, the model, a fuel or charge meter) that sort with a click (sort, rowSortingMode: LeavesOnly) and a row header you can widen (rowHeaderResizable).
- A frozen row (frozen: top, cellsDisabled) whose cells onBeforeCellRender fills with the cars free each day, with a clickable cell area that opens that day’s or week’s availability.
- Multi-day bars at exact pickup and return times, vertical-only moves (moveHDisabled), overlap refusal per vehicle and conflictHighlight.
- Time-anchored event areas for the rental capsule and the preparation after a return, and htmlLeft / htmlRight labels with the pickup and ready times.
- Day and week zoomLevels with an animated switch and Ctrl/⌘ + wheel, time headers from onBeforeTimeHeaderRender, a separator at the desk’s now and a minimap (super-scheduler/minimap) whose window pans and zooms the board.
- Row filtering (rows.filter, onRowFilter), the event hover card (eventHover), a drag card that names both plates and the branch’s reason, a context menu (right click or Shift+F10) and undo history (super-scheduler/history, with history.push for the sales stop).
This example’s code decides
- Which vehicle may serve which booking: the same category, or a free upgrade from compact to estate.
- Preparation time per category, and the clash check that keeps it clear of the next pickup.
- Availability per day (a car counts only when it is free from midnight to midnight), the sold-out days and the walk-in sales stop.
- The desk’s figures (on rent, workshop, pickups and returns today, seven-day utilisation) and the fleet-load series the minimap draws, with its amber and red thresholds.
- A free vehicle for the same dates, offered for a clashing rental, extensions from the detail panel, and every label on this page.
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: the category tree with its plate, model and fuel columns, the frozen Cars available row in onBeforeCellRender, the capsule and preparation areas in onBeforeEventRender, the move checks, the hover card, drag verdict and context menu, and the minimap created once the control is mounted.
/**
* Fleetline rental board: a night-mode fleet desk. Vehicles grouped by category over seven weeks,
* a frozen "Cars available" row, rental capsules with their preparation tail, and a fleet-load
* minimap.
*
* Library: resource tree, rowHeaderColumns (plate, model, fuel) with sort and a resizable row
* header, a frozen summary row filled by onBeforeCellRender (with a clickable cell area), row
* filtering, multi-day bars at exact times, vertical-only moves, overlap refusal with conflict
* highlight, time-anchored areas for the capsule and the preparation, htmlLeft / htmlRight side
* labels, custom time headers, a separator at the desk's now, the drag card, the event hover card
* (super-scheduler/react-render), a context menu, undo history, day/week zoom and the minimap.
* Application: which vehicle may serve which booking, how long preparation takes, which rentals
* clash, which days are sold out, and what the minimap measures. Those rules live in ./rules.
*/
import {
useCallback,
useEffect,
useMemo,
useRef,
useSyncExternalStore,
type RefObject,
} from 'react'
import { SuperScheduler } from 'super-scheduler'
import type { SchedulerEventsChangeArgs } from 'super-scheduler'
import type { SchedulerHistory } from 'super-scheduler/history'
import { createMinimap, type Minimap } from 'super-scheduler/minimap'
import { SuperSchedulerComponent, type SchedulerRenderProps } from 'super-scheduler/react-render'
import { format, plural } from '~/i18n/format'
import { DAY, HOUR, formatCivil, parseCivil } from '../../scheduler/civil'
import { usesTwelveHours } from '../../scheduler/header-format'
import { skinClass, skinMenuTheme } from '../registry'
import { createEventMenu } from '../kit/context-menu'
import { formatClock, formatCivilCached, formatSpan, formatWhen } from '../kit/format'
import { useEventHover, type HoverCardModel, type KeyHint } from '../kit/hover-card'
import { ALT_KEY, KEYS } from '../kit/keys'
import { useDropRefusal } from '../kit/use-drop-refusal'
import { createDragCard } from '../kit/verdict'
import type { DemoCommon } from '../types'
import {
CATEGORY_TONES,
GEOMETRY,
SUMMARY_HEIGHT,
SUMMARY_ROW,
civilOf,
isVehicleId,
plateOf,
readFleetFields,
toResources,
type FleetEvent,
} from './adapter'
import { CATEGORIES, NOW, PERIOD, VEHICLES, type Category, type FleetItem } from './model'
import {
PREP_HOURS,
assignment,
busySpan,
clashOf,
clashes,
dayIndex,
extendIssue,
fleetLoad,
fleetMask,
freeOn,
freeVehicle,
lowestFree,
nextOnVehicle,
readyAt,
rentalDays,
vehicleCategory,
vehiclesOf,
type Availability,
} from './rules'
import type { FleetlineText, ZoomId } from './text'
import './tokens.css'
import './fleet.css'
/** What the board asks the demo to do (context menu). */
export type FleetAction = 'details' | 'free-vehicle' | 'extend' | 'next'
/** A stretch of days of the period, as day indexes [from, to). */
export interface DaySpan {
readonly from: number
readonly to: number
}
/** "R-1093" for a rental, "Windscreen repair" for a workshop slot. */
export function itemName(item: FleetItem, text: FleetlineText): string {
return item.kind === 'rental' ? item.code : text.services[item.reason]
}
export interface FleetlineSchedulerProps {
readonly events: FleetEvent[]
/** The same data read back as the branch's model, for the rules and the minimap. */
readonly items: readonly FleetItem[]
/** Daily availability computed from `items` (one bit per vehicle and day). */
readonly table: Availability
readonly text: FleetlineText
readonly common: DemoCommon
/** BCP 47 tag for labels, and the scheduler locale id. */
readonly tag: string
readonly schedulerLocale: string
/** Level on mount. Later changes go through control.zoom so the view animates from where it is. */
readonly initialZoom: ZoomId
/** The level on screen (side labels only show where the day level leaves room for them). */
readonly zoom: ZoomId
/** The category the desk filters on, or null for the whole fleet. */
readonly category: Category | null
/** Days with walk-in sales closed (day indexes of the period). */
readonly closed: ReadonlySet<number>
/** The item shown in the detail sheet: it gets the selection ring. */
readonly selected: string | null
/** The span shown in the availability sheet: its summary cells are marked. */
readonly selectedSpan: DaySpan | null
readonly history: SchedulerHistory
readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
/** Where the minimap mounts (the frame's foot strip). */
readonly minimapHost: RefObject<HTMLDivElement | null>
readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
readonly onSelect: (id: string) => void
readonly onSpan: (span: DaySpan) => void
readonly onMoved: (id: string) => void
/** A drop or a keyboard move the branch refused, with its sentence. */
readonly onRefused: (id: string, message: string) => void
readonly onAction: (action: FleetAction, id: string) => void
readonly onZoomLevel: (level: ZoomId) => void
}
const ZOOM_LEVELS: SuperScheduler.ZoomLevel[] = [
{
id: 'days',
properties: {
scale: 'Day',
cellWidth: GEOMETRY.cellWidth.days,
timeHeaders: [{ groupBy: 'Week' }, { groupBy: 'Day' }],
},
},
{
id: 'weeks',
properties: {
scale: 'Week',
cellWidth: GEOMETRY.cellWidth.weeks,
timeHeaders: [{ groupBy: 'Month' }, { groupBy: 'Week' }],
},
},
]
const ZOOM_IDS: readonly ZoomId[] = ['days', 'weeks']
/** Minimap colours: amber from 75 % of the fleet busy, red from 90 %. */
const loadTone = (value: number) => (value >= 0.9 ? 'danger' : value >= 0.75 ? 'warn' : 'base')
const NOW_TICKS = parseCivil(NOW)
/**
* Side labels need this much free time beside a bar at the day level (2.5 px per hour): room for
* the ready time of one rental and the pickup time of the next.
*/
const SIDE_GAP = 36 * HOUR
/** "10 AM" / "10:00": the shortest clock that still reads as one. */
function shortClock(value: string, tag: string): string {
const ticks = parseCivil(value)
return ticks % HOUR === 0 && usesTwelveHours(tag)
? formatCivilCached(ticks, tag, { hour: 'numeric' })
: formatClock(ticks, tag)
}
const escape = (value: string) => SuperScheduler.Util.escapeHtml(value)
/** Fixed icons of the board (trusted markup, classes only). */
const ICON = {
fuel: '<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 14V3.5A1.5 1.5 0 0 1 4.5 2h4A1.5 1.5 0 0 1 10 3.5V14M2 14h9M10 6h1.5a1 1 0 0 1 1 1v4.5a1 1 0 0 0 2 0V5.5L12.5 3.5M4.5 5.5h4"/></svg>',
bolt: '<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M9 1.5 3.5 9H8l-1 5.5L12.5 7H8z"/></svg>',
wrench:
'<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M10.5 2.2a3.5 3.5 0 0 0-4 4.6L2.3 11a1.4 1.4 0 0 0 2 2l4.2-4.2a3.5 3.5 0 0 0 4.6-4L11 6.9 9.1 5l2.1-2.1a3.5 3.5 0 0 0-.7-.7z"/></svg>',
sparkle:
'<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 2v3M8 11v3M2 8h3M11 8h3M4 4l1.6 1.6M10.4 10.4 12 12M12 4l-1.6 1.6M5.6 10.4 4 12"/></svg>',
up: '<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 13V3M4 7l4-4 4 4"/></svg>',
} as const
/** The slots of a summary cell: one per vehicle of the (filtered) fleet, lit when free all day. */
function slotsHtml(busy: number, category: Category | null): string {
let html = ''
let previous: Category | null = null
VEHICLES.forEach((vehicle, index) => {
if (category !== null && vehicle.category !== category) return
if (previous !== null && previous !== vehicle.category) html += '<b class="fl-slots__gap"></b>'
previous = vehicle.category
const free = (busy & (1 << index)) === 0
html += `<i class="fl-s fl-s--${vehicle.category}${free ? ' is-free' : ''}"></i>`
})
return `<span class="fl-slots" aria-hidden="true">${html}</span>`
}
/** A string cache keyed by what the markup depends on: hooks run for every visible cell. */
function createCache<V>(): (key: string, build: () => V) => V {
const map = new Map<string, V>()
return (key, build) => {
let value = map.get(key)
if (value === undefined) {
value = build()
map.set(key, value)
}
return value
}
}
/**
* onBeforeTimeHeaderRender: stacked weekday and day number, the desk's today and the days with
* walk-in sales closed under week ranges (day level); months over week ranges (week level).
*/
function createHeaderHook(
tag: string,
table: Availability,
closed: ReadonlySet<number>,
): (args: SuperScheduler.SchedulerBeforeTimeHeaderRenderArgs) => void {
const cache = createCache<{ readonly html: string; readonly cssClass: string }>()
const range = new Intl.DateTimeFormat(tag, { day: 'numeric', month: 'short', timeZone: 'UTC' })
const todayIndex = dayIndex(table, NOW_TICKS)
return (args) => {
const { start, end, level } = args.header
const from = start.getTime()
const span = end.getTime() - from
const day = dayIndex(table, from)
const isClosed = span <= DAY && closed.has(day)
const entry = cache(`${level}:${from}:${span}:${isClosed ? 1 : 0}`, () => {
if (level === 0) {
const label =
span > 7 * DAY
? formatCivilCached(from, tag, { month: 'long', year: 'numeric' })
: range.formatRange(new Date(from), new Date(from + span - DAY))
return { html: `<span class="fl-thg">${escape(label)}</span>`, cssClass: 'fl-thg-cell' }
}
if (span > DAY) {
const label = range.formatRange(new Date(from), new Date(from + span - DAY))
return { html: `<span class="fl-th fl-th--week">${escape(label)}</span>`, cssClass: '' }
}
const weekday = formatCivilCached(from, tag, { weekday: 'short' })
const date = formatCivilCached(from, tag, { day: 'numeric' })
const classes = ['fl-th-cell']
if (new Date(from).getUTCDay() % 6 === 0) classes.push('fl-th-cell--we')
if (day === todayIndex) classes.push('fl-th-cell--today')
if (isClosed) classes.push('fl-th-cell--closed')
return {
html: `<span class="fl-th"><span class="fl-th__wd">${escape(weekday)}</span><span class="fl-th__d">${escape(date)}</span></span>`,
cssClass: classes.join(' '),
}
})
args.header.html = entry.html
args.header.cssClass = entry.cssClass
}
}
/** Narrow screens keep the plate column only (model and fuel are in the hover card and sheet). */
const NARROW = '(max-width: 640px)'
function useNarrowScreen(): boolean {
return useSyncExternalStore(
(notify) => {
const query = window.matchMedia(NARROW)
query.addEventListener('change', notify)
return () => query.removeEventListener('change', notify)
},
() => window.matchMedia(NARROW).matches,
() => false,
)
}
export function FleetlineScheduler(props: FleetlineSchedulerProps) {
const { events, items, table, text, common, tag, schedulerLocale, initialZoom, zoom } = props
const { category, closed, selected, selectedSpan, history, controlRef, minimapHost } = props
const { onEventsChange, onSelect, onSpan, onMoved, onRefused, onAction, onZoomLevel } = props
const compact = useNarrowScreen()
const resources = useMemo(() => toResources(text), [text])
const clashing = useMemo(() => new Set(clashes(items)), [items])
const refusal = useDropRefusal(onRefused)
// Free time before and after each item on its vehicle: side labels only where they fit.
const gaps = useMemo(() => {
const out = new Map<string, { readonly before: number; readonly after: number }>()
for (const vehicle of VEHICLES) {
const own = items
.filter((item) => item.vehicle === vehicle.id)
.map((item) => ({ id: item.id, ...busySpan(item) }))
.sort((a, b) => parseCivil(a.start) - parseCivil(b.start))
own.forEach((item, index) => {
const previous = own[index - 1]
const next = own[index + 1]
out.set(item.id, {
before:
previous === undefined
? Number.POSITIVE_INFINITY
: parseCivil(item.start) - parseCivil(previous.end),
after:
next === undefined
? Number.POSITIVE_INFINITY
: parseCivil(next.start) - parseCivil(item.end),
})
})
}
return out
}, [items])
// Rentals only change vehicle on this board: the keyboard moves them up and down.
const hints = useMemo<KeyHint[]>(
() => [
{ keys: KEYS.details, label: common.kit.details },
{ keys: KEYS.actions, label: common.kit.actions },
{ keys: [ALT_KEY, '↑↓'], label: common.kit.move },
],
[common],
)
// Hover card: the customer and vehicle, the rental against its preparation tail, what comes
// next, and the category rule (or the clash) that applies.
const card = useCallback(
(event: SuperScheduler.Event): HoverCardModel | null => {
const item = items.find((candidate) => candidate.id === String(event.id()))
if (item === undefined) return null
const vehicleCategoryName = text.categories[vehicleCategory(item.vehicle)]
const vehicle = `${plateOf(item.vehicle)} · ${vehicleCategoryName}`
const next = nextOnVehicle(item, items)
const nextText =
next === undefined
? text.noNext
: `${itemName(next, text)} · ${formatWhen(next.kind === 'rental' ? next.pickup : next.start, tag)}`
if (item.kind === 'service') {
const start = parseCivil(item.start)
const end = parseCivil(item.end)
return {
id: item.id,
tone: 'blocked',
eyebrow: vehicle,
title: text.services[item.reason],
status: { label: text.status.offRoad, tone: 'warning' },
time: {
start,
end,
startLabel: formatWhen(start, tag),
endLabel: formatWhen(end, tag),
span: formatSpan(end - start, tag),
},
facts: [{ label: text.fields.next, value: nextText }],
rule: { state: 'blocked', text: text.rules.fixed },
hints: [{ keys: KEYS.details, label: common.kit.details }],
}
}
const pickup = parseCivil(item.pickup)
const back = parseCivil(item.return)
const ready = parseCivil(readyAt(item))
const clash = clashOf(item, items)
const upgraded = assignment(item.vehicle, item.booked) === 'upgrade'
return {
id: item.id,
tone: CATEGORY_TONES[item.booked],
eyebrow: `${item.code} · ${vehicle}`,
title: item.customer,
status:
clash !== undefined
? { label: text.card.clash, tone: 'danger' }
: upgraded
? { label: text.status.upgrade, tone: 'warning' }
: { label: text.status.ok, tone: 'success' },
// The bar stands for pickup to ready: the empty tail is the preparation.
time: {
start: pickup,
end: back,
day: `${plural(text.hours, PREP_HOURS[item.booked], tag)} ${text.prep}`,
startLabel: formatWhen(pickup, tag),
endLabel: formatWhen(back, tag),
span: plural(text.days, rentalDays(item), tag),
window: { start: pickup, end: ready },
},
facts: [
{ label: text.fields.booked, value: text.categories[item.booked] },
{ label: text.fields.route, value: `${item.from} → ${item.to}` },
{ label: text.fields.ready, value: formatWhen(ready, tag) },
{ label: text.fields.next, value: nextText },
],
rule:
clash !== undefined
? {
state: 'blocked',
text: format(text.card.clashWith, { other: itemName(clash, text) }),
}
: { state: 'ok', text: text.rules.wrongCategory[item.booked] },
hints,
}
},
[items, text, common, tag, hints],
)
const { eventHover, closeHover, suppressHover } = useEventHover(card)
// Drag verdict: from which plate to which, and the branch's sentence when it refuses; a free
// upgrade is allowed but flagged, since the branch gives away a bigger car.
const dragCard = useMemo(
() =>
createDragCard({
tag,
common,
rowName: (id) =>
isVehicleId(id) ? `${plateOf(id)} · ${text.categories[vehicleCategory(id)]}` : null,
warn: (info) => {
const rental = items.find((candidate) => candidate.id === String(info.eventId))
if (rental?.kind !== 'rental' || info.resource === null || !isVehicleId(info.resource))
return null
return assignment(info.resource, rental.booked) === 'upgrade'
? format(text.card.upgradeWarn, {
category: text.categories[vehicleCategory(info.resource)],
})
: null
},
}),
[tag, common, text, items],
)
// Context menu: rebuilt when the plan changes, so its labels name the real vehicle. It wears the
// product's skin on <body> through its theme.
const contextMenu = useMemo(
() =>
createEventMenu({
theme: skinMenuTheme('fleet-rentals'),
title: (event) => {
const item = items.find((candidate) => candidate.id === String(event.id()))
return format(common.kit.menuTitle, {
name: item === undefined ? String(event.id()) : itemName(item, text),
})
},
onOpenChange: (open) => suppressHover(open),
entries: (event) => {
const id = String(event.id())
const item = items.find((candidate) => candidate.id === id)
if (item === undefined) return []
const next = nextOnVehicle(item, items)
const details = {
label: common.kit.openDetails,
icon: 'details',
keys: KEYS.details,
run: () => onAction('details', id),
} as const
const go = {
label:
next === undefined
? text.noNext
: format(text.actions.next, {
plate: plateOf(item.vehicle),
name: itemName(next, text),
}),
icon: 'focus',
disabled: next === undefined,
run: () => onAction('next', id),
} as const
if (item.kind === 'service') return [details, 'separator', go]
const free = freeVehicle(item, items)
return [
details,
{
label:
free === null
? text.actions.noFreeVehicle
: format(text.actions.freeVehicle, { plate: plateOf(free) }),
icon: 'handover',
primary: free !== null && clashing.has(id),
disabled: free === null,
run: () => onAction('free-vehicle', id),
},
{
label: text.extend.action,
icon: 'after',
disabled: extendIssue(item, items) !== null,
run: () => onAction('extend', id),
},
'separator',
go,
]
},
}),
[items, clashing, common, text, onAction, suppressHover],
)
// Time headers: stacked weekday and day number, the desk's today, closed days; week ranges under
// the day level, months and week ranges at the week level.
const headerHook = useMemo(() => createHeaderHook(tag, table, closed), [tag, table, closed])
// Summary cells: cached HTML per (free, busy bits, filter, state) key.
const summaryHtml = useMemo(() => createCache<string>(), [])
const config = useMemo<SchedulerRenderProps>(() => {
const mask = fleetMask(category)
const count = vehiclesOf(category).length
const refusalOf = (
data: object,
resource: SuperScheduler.ResourceId,
conflicts: number,
): string | null => {
const fields = readFleetFields(data)
if (fields === null) return null
if (fields.kind === 'service') return text.rules.fixed
if (!isVehicleId(resource)) return text.rules.categoryRow
if (assignment(resource, fields.booked) === null)
return text.rules.wrongCategory[fields.booked]
return conflicts > 0 ? text.rules.busy : null
}
const inSpan = (from: number, to: number) =>
selectedSpan !== null && from < selectedSpan.to && selectedSpan.from < to
return {
locale: schedulerLocale,
cssClass: skinClass('fleet-rentals'),
startDate: PERIOD.start,
days: PERIOD.days,
zoomLevels: ZOOM_LEVELS,
zoom: initialZoom,
zoomPosition: 'left',
// The branch plans Monday-to-Sunday weeks, whatever the page language.
weekStarts: 1,
height: '100%',
treeEnabled: true,
// Category rows group vehicles; nothing is rented to a category row.
treePreventParentUsage: true,
rowHeaderColumns: [
{ title: text.columns.vehicle, width: GEOMETRY.columns.vehicle, sort: 'plate' },
{
title: text.columns.model,
width: GEOMETRY.columns.model,
sort: 'model',
hidden: compact,
},
{
title: text.columns.energy,
width: GEOMETRY.columns.energy,
sort: 'energy',
hidden: compact,
},
],
// Category rows span the three columns; sorting reorders vehicles inside their category.
rowHeaderColumnsMergeParents: true,
rowSortingMode: 'LeavesOnly',
rowHeaderResizable: true,
rowHeaderWidthAutoFit: false,
rowHeaderWidthMax: 460,
eventHeight: GEOMETRY.eventHeight,
rowMarginTop: GEOMETRY.rowMargin,
rowMarginBottom: GEOMETRY.rowMargin,
treeIndent: 10,
// Pickups and returns keep their hour: bars are drawn at exact times, not whole days.
useEventBoxes: 'Never',
allowEventOverlap: false,
conflictHighlight: true,
durationBarVisible: false,
// Capsules keep their areas down to 36 px (the default drops them below 80 px).
lod: { eventFull: 36, eventText: 20 },
eventHtmlLeftMargin: 5,
eventHtmlRightMargin: 5,
showToolTip: false,
keyboardEnabled: true,
keyboardTarget: 'component',
keyboardMode: 'Full',
// The desk's "now" (the story's Monday morning), as a line across every row.
separators: [{ location: NOW, layer: 'AboveEvents', width: 2, cssClass: 'fl-now' }],
history,
controlRef,
onEventsChange,
onBeforeTimeHeaderRender: headerHook,
// Category and summary rows hold no bars: their own heights, without the lane margins.
onBeforeResHeaderRender: (args) => {
const resource = args.resource
const id = resource.id
if (id === SUMMARY_ROW || (typeof id === 'string' && id.startsWith('cat-'))) {
resource.minHeight = id === SUMMARY_ROW ? SUMMARY_HEIGHT : GEOMETRY.groupHeight
resource.marginTop = 0
resource.marginBottom = 0
}
},
onBeforeRowHeaderRender: (args) => {
const row = args.row
const id = row.id
const [first, second, third] = row.columns
if (id === SUMMARY_ROW) {
row.cssClass = 'fl-rh fl-rh--sum'
const meta = `<span class="fl-rh-sum__m">${escape(zoom === 'days' ? text.summary.meta : text.summary.lowest)}</span>`
if (first !== undefined)
first.html = `<span class="fl-rh-sum"><span class="fl-rh-sum__t">${escape(text.summary.label)}</span>${compact ? meta : ''}</span>`
if (second !== undefined) second.html = meta
// Filtered, the row counts one category: its name says so.
if (third !== undefined)
third.html =
category === null
? ''
: `<span class="fl-rh-sum__scope fl-cat--${category}"><i class="fl-dot" aria-hidden="true"></i>${escape(text.categories[category])}</span>`
return
}
if (typeof id === 'string' && id.startsWith('cat-')) {
const group = CATEGORIES.find((candidate) => `cat-${candidate}` === id)
if (group === undefined) return
const total = VEHICLES.filter((vehicle) => vehicle.category === group).length
const free = freeOn(table, dayIndex(table, NOW_TICKS), fleetMask(group))
row.cssClass = `fl-rh fl-rh--cat fl-cat--${group}`
const html = `<span class="fl-rh-cat"><i class="fl-dot" aria-hidden="true"></i><span class="fl-rh-cat__name">${escape(text.categories[group])}</span><span class="fl-rh-cat__free">${escape(format(text.group, { free, count: total }))}</span></span>`
// Merged across the columns (rowHeaderColumnsMergeParents): the row's own html shows.
row.html = html
if (first !== undefined) first.html = html
return
}
if (!isVehicleId(id)) return
const vehicle = VEHICLES.find((candidate) => candidate.id === id)
if (vehicle === undefined) return
row.cssClass = `fl-rh fl-cat--${vehicle.category}`
if (first !== undefined)
first.html = `<span class="fl-plate" title="${escape(vehicle.model)}"><span class="fl-plate__eu" aria-hidden="true"></span><span class="fl-plate__txt">${escape(vehicle.plate)}</span></span>`
if (second !== undefined)
second.html = `<span class="fl-model"><span class="fl-model__name">${escape(vehicle.model)}</span><span class="fl-model__spec">${escape(text.specs[vehicle.id])}</span></span>`
if (third !== undefined) {
const electric = vehicle.category === 'electric'
const low = vehicle.energy < 30
const label = `${electric ? text.energy.charge : text.energy.fuel} ${vehicle.energy}%${low ? ` · ${text.energy.low}` : ''}`
third.html = `<span class="fl-energy${low ? ' fl-energy--low' : ''}" title="${escape(label)}">${electric ? ICON.bolt : ICON.fuel}<span class="fl-meter fl-meter--${Math.round(vehicle.energy / 10)}" aria-hidden="true"><i></i></span><span class="fl-energy__pct">${vehicle.energy}%</span></span>`
}
},
onRowFilter: (args) => {
const param = args.filterParam
const id = String(args.row.id)
if (typeof param !== 'string' || id === SUMMARY_ROW) return
if (id.startsWith('cat-')) args.visible = id === `cat-${param}`
else if (isVehicleId(id)) args.visible = vehicleCategory(id) === param
},
onBeforeCellRender: (args) => {
const cell = args.cell
if (cell.isParent) {
cell.properties.cssClass = 'fl-groupcell'
return
}
if (cell.resource !== SUMMARY_ROW) return
const from = dayIndex(table, cell.start.getTime())
const to = dayIndex(table, cell.end.getTime())
const single = to - from <= 1
const lowest = lowestFree(table, from, to, mask)
const busy = table.busy[lowest.day] ?? 0
const closedHere = single
? closed.has(from)
: Array.from({ length: to - from }, (_, index) => from + index).some((day) =>
closed.has(day),
)
const level = lowest.free === 0 ? 'out' : lowest.free <= 1 ? 'low' : 'ok'
const marked = inSpan(from, to)
const iso = new Date(cell.start.getTime()).toISOString().slice(0, 10)
const key = `${iso}|${single ? 1 : 0}|${lowest.free}|${busy}|${category ?? ''}|${closedHere ? 1 : 0}`
const html = summaryHtml(key, () => {
const caption = closedHere
? `<span class="fl-sum__tag fl-sum__tag--closed">${escape(text.summary.closed)}</span>`
: ''
return `<span class="fl-sum fl-sum--${level}" data-span="${iso}"><span class="fl-sum__top"><span class="fl-sum__n">${lowest.free}</span>${caption}</span>${slotsHtml(busy, category)}</span>`
})
cell.properties.cssClass = `fl-sumcell fl-sumcell--${level}${closedHere ? ' fl-sumcell--closed' : ''}${marked ? ' fl-sumcell--sel' : ''}`
// The whole cell opens its availability: an area holds the figures and owns the click
// (the row's cells are disabled).
cell.properties.areas = [
{
left: 0,
right: 0,
top: 0,
bottom: 0,
action: 'None',
html,
cssClass: 'fl-sum-hit',
toolTip: format(text.summary.tip, { free: lowest.free, count }),
onClick: () => onSpan({ from, to }),
},
]
},
onBeforeEventRender: (args) => {
const data = args.data
const fields = readFleetFields(data)
if (fields === null) return
const id = String(data.id)
const classes = ['fl-ev']
if (fields.kind === 'service') {
classes.push('fl-ev--svc')
const until = formatWhen(civilOf(data.end), tag)
data.html = `<span class="fl-card"><span class="fl-card__l1">${ICON.wrench}<span class="fl-card__who">${escape(text.services[fields.reason])}</span></span><span class="fl-card__l2">${escape(`${text.fields.until} ${until}`)}</span></span>`
data.areas = [{ left: 0, right: 0, top: 0, bottom: 0, cssClass: 'fl-cap fl-cap--svc' }]
} else {
const resource = data.resource
const upgraded =
resource !== undefined &&
isVehicleId(resource) &&
assignment(resource, fields.booked) === 'upgrade'
const pickup = civilOf(data.start)
const badge = upgraded
? `<span class="fl-upg">${ICON.up}${escape(text.upgrade)}</span>`
: ''
const route =
fields.from === fields.to
? `<span class="fl-route">${fields.from}</span>`
: `<span class="fl-route fl-route--oneway">${fields.from}<i>→</i>${fields.to}</span>`
data.html = `<span class="fl-card"><span class="fl-card__l1"><span class="fl-card__who">${escape(fields.customer)}</span>${badge}</span><span class="fl-card__l2">${route}<span class="fl-card__code">${escape(fields.code)}</span></span></span>`
data.ariaLabel = `${fields.code}, ${fields.customer}, ${plural(text.days, rentalDays({ pickup, return: fields.returnAt }), tag)}`
// The capsule is the rental (pickup to return); the tail after it is the preparation,
// both anchored to their times, so they follow zoom and moves.
const electric = fields.booked === 'electric'
data.areas = [
{ start: pickup, end: fields.returnAt, top: 0, bottom: 0, cssClass: 'fl-cap' },
{
start: fields.returnAt,
end: data.end,
top: 7,
bottom: 7,
cssClass: `fl-prep${electric ? ' fl-prep--charge' : ''}`,
// Charging or cleaning, where the day level leaves room for the icon.
...(zoom === 'days' ? { html: electric ? ICON.bolt : ICON.sparkle } : {}),
},
]
if (upgraded) classes.push('fl-ev--upg')
if (clashing.has(id)) classes.push('fl-ev--clash')
// Pickup and ready times beside the bar, where the day level leaves room for them.
const gap = gaps.get(id)
if (zoom === 'days' && gap !== undefined) {
const ready = civilOf(data.end)
if (gap.before >= SIDE_GAP)
data.htmlLeft = `<span class="fl-side fl-side--l" title="${escape(format(text.card.pickupAt, { time: formatClock(pickup, tag) }))}">${escape(shortClock(pickup, tag))}</span>`
if (gap.after >= SIDE_GAP)
data.htmlRight = `<span class="fl-side fl-side--r" title="${escape(format(text.card.readyAt, { time: formatClock(ready, tag) }))}">${escape(shortClock(ready, tag))}</span>`
}
}
classes.push(`fl-tone--${fields.kind === 'service' ? 'svc' : fields.booked}`)
if (id === selected) classes.push('ss-ev--selected')
data.cssClass = classes.join(' ')
},
// Only the row can change (moveHDisabled): check the category; the library checks overlaps,
// and its reason is kept so a refused release is announced too.
onEventMoving: (args) => {
const id = String(args.e.id())
const message = refusalOf(args.e.data, args.resource, args.conflicts.length)
refusal.track(id, message)
if (message !== null && message !== text.rules.busy) {
args.allowed = false
args.message = message
}
},
// Final check before the commit (also covers keyboard moves).
onEventMove: (args) => {
const id = String(args.e.id())
const message = refusalOf(args.e.data, args.newResource, 0)
if (message !== null) {
args.preventDefault()
refusal.clear()
onRefused(id, message)
}
},
onEventMoved: (args) => {
refusal.clear()
onMoved(String(args.e.id()))
},
// A click (or Enter) docks the item into the detail sheet; the hover card steps aside.
onEventClick: (args) => {
closeHover()
onSelect(String(args.e.id()))
},
onZoom: (args) => {
if (args.phase !== 'end') return
const level = ZOOM_IDS[args.level]
if (level !== undefined) onZoomLevel(level)
},
}
}, [
category,
clashing,
closeHover,
closed,
compact,
controlRef,
gaps,
headerHook,
history,
initialZoom,
onEventsChange,
onMoved,
onRefused,
onSelect,
onSpan,
onZoomLevel,
refusal,
schedulerLocale,
selected,
selectedSpan,
summaryHtml,
table,
tag,
text,
zoom,
])
// The category filter runs through the control's own row filter (rows.filter + onRowFilter).
useEffect(() => {
const control = controlRef.current
if (control === null || control.disposed()) return
control.rows.filter(category)
}, [controlRef, category])
// The minimap needs the mounted control; it goes with it.
const minimap = useRef<Minimap | null>(null)
const latest = useRef({ items, category })
useEffect(() => {
latest.current = { items, category }
minimap.current?.refresh()
}, [items, category])
useEffect(() => {
const control = controlRef.current
const host = minimapHost.current
if (control === null || host === null) return
const date = (value: SuperScheduler.Date) =>
formatCivil(value.getTime(), tag, { day: 'numeric', month: 'short' })
const widget = createMinimap(control, host, {
height: 28,
peak: 'absolute',
max: 1,
// One value per bucket: the share of the fleet (or the filtered category) that is out, in
// preparation or in the workshop.
series: (range) => {
const values = new Float32Array(range.buckets)
const start = range.start.getTime()
const { items: current, category: filter } = latest.current
for (let index = 0; index < values.length; index++) {
const from = start + index * range.bucketMs
values[index] = fleetLoad(current, from, from + range.bucketMs, filter)
}
return values
},
tone: loadTone,
marks: { today: false, months: true, past: false },
labels: {
label: text.minimap.label,
zoom: text.minimap.zoom,
valueText: (start, end) => format(text.minimap.range, { from: date(start), to: date(end) }),
},
})
minimap.current = widget
return () => {
widget.dispose()
minimap.current = null
}
}, [controlRef, minimapHost, tag, text])
return (
<SuperSchedulerComponent
{...config}
resources={resources}
events={events}
eventHover={eventHover}
dragCard={dragCard}
contextMenu={contextMenu}
/>
)
}The archive contains this example’s files and a README. It does not include SuperScheduler Pro or any download key.