Planificación de una flota de alquiler
Un compacto queda inmovilizado el día de la recogida. Pasa su alquiler a otro coche, respeta la limpieza y cierra la venta en mostrador los días en que no queda flota.
- Movilidad
- Fleetline
- Columnas de fila
- Filas de resumen
- Minimapa
- Eventos de varios días
- Filtros
- Árbol de recursos
- Panel de detalle
- Temas
- Demo con datos sintéticos
Misión
0 de 3 pasos hechosLunes 12 de octubre, 8:00: al FL 208 se le agrietó el parabrisas anoche y el taller lo tiene hasta el viernes. Su cliente lo recoge a las 10:00.
Mueve el alquiler R-1093 de FL 208 a otro compacto. — Pendiente
Arrástralo hacia arriba hasta FL 206 (un familiar también vale, como mejora gratuita). FL 204 no estará listo a tiempo, y las furgonetas y los eléctricos se rechazan.
El cliente de la furgoneta R-1107 se la queda un día más: amplía el alquiler. — Pendiente
Haz clic en R-1107, en FL V05, y usa «Ampliar un día» en el panel. La limpieza sigue terminando antes de la siguiente recogida.
Encuentra los días en que sale toda la flota y cierra en ellos la venta en mostrador. — Pendiente
Cambia a Semanas (o sigue el tramo rojo del minimapa), haz clic en el 0 rojo de la fila Coches disponibles y pulsa «Cerrar venta en mostrador». La cifra Agotado de la barra abre el mismo panel desde el teclado.
Unos 30 segundos. Los pasos se marcan a medida que los completas.
Teclado: enfoca la rejilla y usa las flechas, Intro y Alt+flechas para mover.
Vista previa del primer fotogramaEn vivo: el motor Pro real, funcionando en tu navegadorUnos 30 segundos. Los pasos se marcan a medida que los completas. Teclado: enfoca la rejilla y usa las flechas, Intro y Alt+flechas para mover.
La situación.
Fleetline es una oficina de alquiler ficticia con diez vehículos: tres compactos, dos familiares, dos eléctricos y tres furgonetas. El cliente reserva una categoría y unas fechas; la oficina decide qué vehículo sale, y cada devolución necesita limpieza y revisión (y carga, en los eléctricos) antes de la siguiente recogida.
En una hoja de cálculo esa preparación no se ve: el siguiente cliente llega mientras la furgoneta todavía se está limpiando. El cuadrante tiene que mantener fijas las fechas de cada alquiler, rechazar una categoría inferior o una furgoneta para una reserva de compacto, mostrar la preparación tras cada devolución, contar los coches que quedan libres cada día y avisar al mostrador de cuándo dejar de vender.
Qué vas a hacer
Moverás un alquiler varado a un coche libre (o a una mejora gratuita), ampliarás un alquiler de furgoneta desde su panel de detalle y usarás la vista de semanas, el minimapa y la fila de coches disponibles para cerrar la venta en mostrador los días en que sale toda la flota.
Dónde termina la librería y empieza tu aplicación.
SuperScheduler aporta
- Categorías con sus vehículos como árbol de recursos, con rowHeaderColumns (matrícula, modelo y un indicador de combustible o carga) que se ordenan con un clic (sort, rowSortingMode: LeavesOnly) y una cabecera de filas que se puede ensanchar (rowHeaderResizable).
- Una fila fija (frozen: top, cellsDisabled) cuyas celdas rellena onBeforeCellRender con los coches libres de cada día, con un área de celda que abre la disponibilidad de ese día o esa semana.
- Barras de varios días a la hora exacta de recogida y devolución, movimiento solo vertical (moveHDisabled), rechazo de solapes por vehículo y conflictHighlight.
- Áreas de evento ancladas al tiempo para la cápsula del alquiler y la preparación tras la devolución, y etiquetas htmlLeft / htmlRight con la hora de recogida y la de vuelta a punto.
- zoomLevels de días y semanas con cambio animado y Ctrl/⌘ + rueda, cabeceras de tiempo con onBeforeTimeHeaderRender, un separador en el ahora del mostrador y un minimapa (super-scheduler/minimap) cuya ventana desplaza y amplía el cuadrante.
- Filtro de filas (rows.filter, onRowFilter), la tarjeta flotante de cada evento (eventHover), una tarjeta de arrastre que nombra las dos matrículas y el motivo de la oficina, un menú contextual (clic derecho o Mayús+F10) y el historial para deshacer (super-scheduler/history, con history.push para el cierre de ventas).
El código de este ejemplo decide
- Qué vehículo puede atender cada reserva: la misma categoría o una mejora gratuita de compacto a familiar.
- El tiempo de preparación por categoría y la comprobación que lo mantiene libre de la siguiente recogida.
- La disponibilidad por día (un coche solo cuenta si está libre de medianoche a medianoche), los días agotados y el cierre de la venta en mostrador.
- Las cifras del mostrador (en alquiler, en taller, recogidas y devoluciones de hoy, ocupación a siete días) y la serie de carga que dibuja el minimapa, con sus umbrales ámbar y rojo.
- Un vehículo libre para las mismas fechas, ofrecido a un alquiler en conflicto, las ampliaciones desde el panel de detalle y todos los textos de esta página.
El código de esta demo.
Son los archivos que ejecuta esta página, no una copia simplificada. Compilan contra los exports públicos de SuperScheduler Pro.
La integración: el árbol de categorías con sus columnas de matrícula, modelo y combustible, la fila fija de coches disponibles en onBeforeCellRender, las áreas de cápsula y preparación en onBeforeEventRender, las comprobaciones al mover, la tarjeta flotante, el veredicto de arrastre y el menú contextual, y el minimapa creado al montarse el control.
/**
* 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}
/>
)
}El archivo contiene los ficheros de este ejemplo y un README. No incluye SuperScheduler Pro ni ninguna clave de descarga.