Despacho de servicio técnico
Entra un trabajo urgente en la cola. Encuentra la cuadrilla que puede atenderlo a tiempo.
- Servicio técnico
- Fieldwork
- Arrastrar desde fuera
- Filas de resumen
- Minimapa
- Búsqueda en vivo
- Multiselección
- Áreas activas
- Filtros
- Panel de detalle
- Temas
- Demo con datos sintéticos
Misión
0 de 3 pasos hechosLunes, 08:40: acaba de entrar J-5107, una reparación urgente de climatización en una clínica de la zona C1, que vence a las 14:00. Y la furgoneta de la cuadrilla S2 se ha averiado esta mañana.
Muestra solo las cuadrillas y los trabajos de climatización. — Pendiente
Usa «Climatización» en la barra. El filtro se aplica a las filas del tablero y a la cola.
Arrastra J-5107 de la cola a la cuadrilla C1, entre las 10:00 y las 12:00. — Pendiente
Las demás cuadrillas lo rechazan: otro oficio, otra región o demasiado tarde. «Asignar» en la ficha muestra el primer hueco libre de cada cuadrilla, desplazamiento incluido.
La furgoneta de la cuadrilla S2 se ha averiado: selecciona sus dos trabajos y devuélvelos a la cola. — Pendiente
Vuelve a mostrar todos los oficios, haz clic en J-5110, Ctrl/⌘+clic en J-5111 (o arrastra un recuadro sobre los dos) y usa «Devolver a la cola».
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.
Fieldwork es una empresa ficticia de servicio técnico con seis cuadrillas en tres regiones. Cada cuadrilla tiene sus oficios (climatización, electricidad, fontanería), trabaja de 08:00 a 18:00, sale de la base de su región y solo cubre esa región. Los trabajos llegan con una estimación, un lugar, una zona y una hora límite, y algunos son urgentes.
La mañana de quien despacha es una cola y un tablero. Soltar un trabajo en la cuadrilla equivocada cuesta una visita; pasarse de la hora límite incumple un acuerdo de servicio; una furgoneta parada deja tirado todo lo que lleva detrás. El tablero tiene que decir, mientras se arrastra el trabajo, si una cuadrilla puede atenderlo y por qué no, ofrecer la misma comprobación sin ratón y mostrar cuánto tiempo ocupa de verdad cada trabajo, desplazamiento incluido.
Qué vas a hacer
Reducirás el tablero a un oficio, colocarás un trabajo urgente en la única cuadrilla que llega a tiempo y devolverás a la cola los trabajos de una cuadrilla parada en un solo paso.
Dónde termina la librería y empieza tu aplicación.
SuperScheduler aporta
- Fichas de la cola arrastradas al tablero con SuperScheduler.Scheduler.makeDraggable, comprobadas fotograma a fotograma en onEventMoving y confirmadas en onEventMoved (args.external).
- rowHeaderColumns con avatares de los técnicos, chips de oficio, franja de región y la carga de la cuadrilla, y una fila congelada arriba cuyas celdas de onBeforeCellRender cuentan las cuadrillas libres por hora.
- Tarjetas de dos líneas desde onBeforeEventRender con un área de desplazamiento anclada al tiempo al inicio, distintivos de plazo y acciones al pasar el ratón como áreas con visibility: 'Hover'.
- rows.filter y onRowFilter para oficio, región y la búsqueda en vivo; multiselect con rectangleSelectHandling: 'EventSelect'; celdas deshabilitadas para las ausencias.
- zoomLevels de día y semana con showNonBusiness: false, separators para el reloj de despacho, la tarjeta de arrastre, la tarjeta flotante, un menú contextual y createHistory de super-scheduler/history.
- El minimapa (super-scheduler/minimap) con un rango fijo sobre la semana de despacho, alimentado con la serie horaria propia de la aplicación; su selector también funciona como deslizador desde el teclado.
El código de este ejemplo decide
- Qué cuadrilla puede hacer cada trabajo: oficio, región, horario, ausencias y hora límite, contando el desplazamiento desde la base.
- La propia cola: todo trabajo que no está en el tablero, así que devolver trabajos es una sola actualización de estado.
- Los plazos: la cuenta atrás antes de que un trabajo en cola tenga que salir, el margen que deja una asignación y qué cuenta como en riesgo.
- El panel Asignar: el primer hueco libre de cada cuadrilla según las reglas, sin rutas entre trabajos.
- Cada cifra: trabajos sin asignar, trabajos en riesgo, cuadrillas en ruta, carga de hoy y cuadrillas libres por hora.
- La carga de la flota que dibuja el minimapa: tiempo reservado sobre el tiempo en ruta de las cuadrillas, hora a hora y día a día, con los umbrales de carga alta y completa de los medidores.
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: escalas, las columnas de cabecera de fila, la fila de cuadrillas libres, las tarjetas con su desplazamiento y su plazo, los filtros, la selección múltiple, las ausencias como celdas deshabilitadas y los callbacks que comprueban cada hueco, también al soltar desde la cola.
/**
* 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>
)
}El archivo contiene los ficheros de este ejemplo y un README. No incluye SuperScheduler Pro ni ninguna clave de descarga.