Reserva de instrumentos de laboratorio
Reserva un instrumento y la calibración viene incluida. Saca una sesión del servicio técnico y alarga tu medición.
- Laboratorio
- Benchlab
- Slots de renderizado React
- Control de zoom
- Filas de resumen
- Minimapa
- Cruceta
- Barras de progreso
- Escala por minutos
- Tiempo bloqueado
- Temas
- Demo con datos sintéticos
Misión
0 de 3 pasos hechosMiércoles, 9:40 en el laboratorio: el servicio técnico del microscopio confocal ocupa ahora de 9:00 a 12:00, justo encima de una sesión de Biología celular.
Saca la sesión CB-091, en rojo, de la ventana de servicio del confocal. — Pendiente
Arrástrala a las 12:00 o más tarde en el mismo microscopio. Otro modelo de instrumento se rechaza, igual que cualquier hora rayada.
Reserva dos horas de LC-MS el miércoles por la tarde. — Pendiente
Arrastra sobre horas libres en la fila del LC-MS; la app añade delante los 60 minutos de calibración. Empezar a las 14:00 se rechaza: la medición de la mañana acaba a las 13:30.
Alarga tu nueva medición arrastrando su borde derecho. — Pendiente
La calibración mantiene sus 60 minutos. Arrastrar el borde izquierdo se rechaza; el botón +30 min de la tarjeta hace lo mismo que arrastrar.
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.
Benchlab es un laboratorio compartido ficticio: dos microscopios, un LC-MS, un espectrofotómetro, termocicladores de qPCR, un secuenciador y bancadas que usan cuatro grupos de investigación. Casi todos los instrumentos necesitan tiempo antes de medir: el láser del confocal se calienta, el LC-MS se calibra durante una hora y el secuenciador ceba su celda de flujo.
Si la reserva solo registra la medición, la preparación invade el turno anterior y la visita del servicio técnico cae sobre una sesión que nadie movió. El tablero tiene que tratar la preparación como parte de la reserva, dejar fuera de alcance el tiempo no disponible y explicar con claridad por qué una petición no cabe. Las reglas son la política de reservas de este laboratorio, no un sistema de cumplimiento normativo.
Cada instrumento tiene además un certificado de calibración con fecha de caducidad, y el tablero lee cada reserva contra el reloj del laboratorio: lo que ya terminó, lo que se prepara o mide y lo que sigue en cola. Una medición que ha empezado se queda donde está.
Qué vas a hacer
Sacarás una sesión de una ventana de servicio técnico, reservarás dos horas de LC-MS con la calibración añadida automáticamente y alargarás esa medición sin que la calibración cambie.
Dónde termina la librería y empieza tu aplicación.
SuperScheduler aporta
- Escala por horas a 72 px por hora con noches y fin de semana ocultos (businessBeginsHour, businessEndsHour, showNonBusiness: false), zoom libre con pellizco, Ctrl+rueda o Ctrl +/− (zoomGesture, keyboardOptions.zoomKeys) y con el deslizador y la insignia de nivel de detalle de zoom-ui (createZoomSlider, createLodBadge), con umbrales lod que convierten las tarjetas en bloques al alejarse.
- Tres columnas de cabecera de fila (rowHeaderColumns, rowHeaderColumnsMergeParents) pintadas por React (renderRowHeader), una fila resumen fija (frozen: 'top') cuyas celdas cuentan los instrumentos en uso (onBeforeCellRender) y filtro de filas por área (rows.filter, onRowFilter).
- Cabeceras de tiempo propias con marcas de minutos y el reloj del laboratorio (onBeforeTimeHeaderRender con áreas de cabecera), un separador para el reloj y la cruz completa (crosshairType: 'Full') leída al minuto con getCoords.
- Tarjetas de reserva de dos líneas en React (renderEvent) sobre un HTML de respaldo, la preparación como área de evento anclada en el tiempo, un área de acción al pasar el ratón (visibility: 'Hover', action: 'None') y barras de progreso en las reservas en curso (durationBarMode: 'PercentComplete', complete).
- Celdas deshabilitadas para el tiempo no disponible; arrastrar para seleccionar, mover y cambiar la duración con etiquetas exactas de inicio y fin (timeRangeSelectingStartEndEnabled, eventMovingStartEndEnabled, eventResizingStartEndEnabled), sin solapes, mensajes de rechazo en la tarjeta de arrastre, deshacer y rehacer con eventos controlados.
- Tarjetas al pasar el ratón (eventHover), resaltado de conflictos y menús contextuales con clic derecho, pulsación larga o Mayús+F10.
- Sobre la leyenda, el minimapa de super-scheduler/minimap alimentado con los instrumentos en uso por hora durante la semana (una serie sobre un rango fijo), un tono por hora y etiquetas traducidas, cuyo selector desplaza el tablero; la columna de uso dibuja la semana de cada instrumento día a día (renderRowHeader).
El código de este ejemplo decide
- Cuánto tarda cada instrumento en prepararse y cómo una medición seleccionada se convierte en una reserva con la preparación delante.
- El reloj del laboratorio (miércoles 9:40, fijo en la demo): las mediciones empezadas no se mueven y no se puede reservar tiempo pasado.
- Qué cambios se permiten: solo entre instrumentos idénticos, nunca sobre servicio o mantenimiento, mediciones de 30 minutos o más, preparación fija al principio.
- Cada cifra: instrumentos en uso por hora y ahora, la cola del día, el uso semanal de cada instrumento y los certificados de calibración que vencen en una semana.
- La barra del producto, el panel de reserva, la misión y todos los textos de esta página. Sin promesas regulatorias ni de auditoría.
- Los instrumentos en uso por hora durante la semana, las horas en que una reserva cae en una franja de servicio, la hora más ocupada y el uso de cada instrumento día a día.
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: escala por horas y límites del zoom, columnas de cabecera y fila resumen fija, cabeceras de tiempo con marcas de minutos y el reloj, el hook de celdas (tiempo pasado, horas no disponibles, cifras por hora), las tarjetas con su área de preparación, su acción al pasar el ratón y su progreso, y los callbacks donde las reglas rechazan un movimiento, un cambio de duración o una reserva.
/**
* Benchlab instrument board: shared instruments and benches over one week, preparation included,
* read against the lab's clock.
*
* Library: an hour scale with nights and weekends hidden (business hours), a free zoom in pixels
* per hour (zoomGesture, driven by the zoom-ui slider in the product bar), tree rows with three
* row-header columns, a frozen summary row computed in onBeforeCellRender, a separator for the
* lab's clock, the full crosshair, disabled cells for unavailable time, time-anchored event areas
* for the preparation and a hover action area, PercentComplete duration bars for running bookings,
* live start/end labels while selecting, moving and resizing, drag-to-book range selection,
* overlap prevention with conflict highlighting, row filtering, undo history, keyboard, React
* content (row headers, booking cards, the hover card) through `super-scheduler/react-render`,
* the drag card and a context menu.
* Application: how long each instrument prepares, where a booking may go, what has started,
* unavailable windows, calibration certificates, what a new booking needs in front of its run and
* every figure on the board. Those rules live in ./rules and run in the callbacks.
*/
import { useCallback, useEffect, useMemo, type RefObject } from 'react'
import { SuperScheduler } from 'super-scheduler'
import type {
SchedulerBeforeTimeHeaderRenderArgs,
SchedulerEventsChangeArgs,
SchedulerProps,
} 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, parseCivil } from '../../scheduler/civil'
import { headerLabel, usesTwelveHours } from '../../scheduler/header-format'
import { unitOfSpan } from '../../scheduler/live-headers'
import { createEventMenu, type MenuEntry } from '../kit/context-menu'
import { formatClock, formatCivilCached, 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 {
GEOMETRY,
LOD,
SUMMARY_ROW,
ZOOM,
rowHeaderWidth,
civilOf,
isInstrumentId,
readBookingFields,
toResources,
type BookingEvent,
} from './adapter'
import { bookingCard, cardHtml, prepSplit } from './booking-card'
import { cardParts, type CardParts, type CardSize } from './card-parts'
import {
AreaCell,
BookingCard,
InstrumentCell,
QcCell,
SummaryCell,
SummaryFigure,
UseCell,
} from './instrument-slots'
import {
AREA_IDS,
BUSINESS_NOW,
INITIAL_VIEW_START,
INSTRUMENTS,
LAB_HOURS,
WEEK,
type AreaId,
type Block,
type Booking,
type InstrumentId,
} from './model'
import {
blockAt,
elapsedAt,
extendRun,
inThePast,
inUse,
instrumentOf,
lockAt,
moveProblem,
moveToTwin,
nextFreeSlot,
phaseAt,
qcStatus,
twinOf,
utilisation,
type MoveProblem,
} from './rules'
import type { BenchlabText } from './text'
import './tokens.css'
import './lab.css'
/** What the board asks the demo to do (context menu, hover action, keyboard). */
export type BookingAction = 'details' | 'next-slot' | 'extend' | 'twin'
/** One menu step of a longer run. */
export const EXTEND_MINUTES = 30
/** The area filter of the product bar: every area, or one. */
export type AreaFilter = AreaId | 'all'
const NOW = parseCivil(BUSINESS_NOW)
const SLUG = 'lab-instruments'
/** Cards narrower than this drop the run name and the sample count, then everything but the code. */
const COMPACT_CARD = 168
const TINY_CARD = 84
function cardSize(width: number): CardSize {
return width < TINY_CARD ? 'tiny' : width < COMPACT_CARD ? 'compact' : 'full'
}
export interface BenchlabSchedulerProps {
readonly events: BookingEvent[]
/** The same bookings in model form: cards, figures and the menu read them. */
readonly bookings: readonly Booking[]
readonly blocks: readonly Block[]
/** Bookings that overlap unavailable time. */
readonly collisions: readonly string[]
readonly text: BenchlabText
readonly common: DemoCommon
/** BCP 47 tag for labels, and the scheduler locale id. */
readonly tag: string
readonly schedulerLocale: string
/** The booking shown in the side sheet: it gets the selection ring. */
readonly selected: string | null
readonly area: AreaFilter
/** Phones: one row-header column and narrower indents (chosen once by the demo). */
readonly compact: boolean
/** The narrowest zoom in pixels per hour: the whole week fills the board. */
readonly minZoom: number
readonly history: SchedulerHistory
readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
/** A run dragged across free time: the application plans the booking around it. */
readonly onRequest: (instrument: InstrumentId, start: string, end: string) => void
readonly onSelect: (id: string) => void
readonly onMoved: (id: string) => void
readonly onResized: (id: string) => void
readonly onRefused: (id: string, message: string) => void
readonly onAction: (action: BookingAction, id: string) => void
}
/** The menu's label for the identical instrument: where it would go, or why it cannot. */
function twinLabel(
booking: Booking,
bookings: readonly Booking[],
blocks: readonly Block[],
text: BenchlabText,
): string | null {
const twin = twinOf(booking.instrument)
if (twin === null) return null
const move = moveToTwin(booking, bookings, blocks)
const instrument = text.instruments[twin]
return move.ok
? format(text.actions.twin, { instrument })
: format(text.actions.twinBlocked, {
instrument,
reason: move.reason === 'no-twin' ? '' : text.actions.reasons[move.reason],
})
}
/**
* Time headers: the day over hour cells with minute ticks (15 min, and 5 min when an hour is wide
* enough), the hour labels shortened when cells get narrow, and the lab's clock marked on the hour
* it falls in. Labels are the preview's (`headerLabel`), so the swap does not jump. Cached per
* cell and width class: the hook runs once per header cell.
*/
function createHeaderHook(
tag: string,
clockLabel: string,
): (args: SchedulerBeforeTimeHeaderRenderArgs) => void {
const cache = new Map<string, { html: string; areas: SuperScheduler.AreaData[] }>()
/** The lab's clock inside a header cell, as a share of the cell: it follows every zoom. */
const clockTick = (start: number, end: number): SuperScheduler.AreaData[] =>
start <= NOW && NOW < end
? [
{
left: `${((NOW - start) / (end - start)) * 100}%`,
top: 0,
bottom: 0,
width: 1,
cssClass: 'bl-th-now',
},
]
: []
return (args) => {
const start = args.header.start.getTime()
const end = args.header.end.getTime()
const width = args.control.cellWidth ?? GEOMETRY.hour
if (args.header.level === 0) {
// Days, or weeks when the level of detail coarsens the header far out.
const unit = unitOfSpan(end - start, 'group')
const today = unit === 'day' && start <= NOW && NOW < end
const key = `g:${unit}:${start}:${today}`
let entry = cache.get(key)
if (entry === undefined) {
const label = SuperScheduler.Util.escapeHtml(headerLabel(start, unit, tag, 'group'))
const clock = today
? `<span class="bl-th-clock"><span class="bl-th-clock__dot" aria-hidden="true"></span>${SuperScheduler.Util.escapeHtml(`${clockLabel} ${formatClock(NOW, tag)}`)}</span>`
: ''
entry = { html: `<span class="bl-th-day">${label}${clock}</span>`, areas: [] }
cache.set(key, entry)
}
args.header.html = entry.html
args.header.areas = entry.areas
args.header.cssClass = today ? 'bl-th--today' : ''
return
}
// A merged cell of six hours or more is a day: the first one is clipped by the window.
const unit = end - start >= 6 * HOUR ? 'day' : unitOfSpan(end - start, 'cell')
if (unit !== 'hour') {
// Far out the level of detail merges hours into longer cells (a day each): label them so.
const key = `c:${unit}:${start}`
let entry = cache.get(key)
if (entry === undefined) {
const span = ((end - start) / HOUR) * width
entry = {
html: `<span class="bl-th-hour">${SuperScheduler.Util.escapeHtml(headerLabel(start, unit, tag, 'cell', span))}</span>`,
areas: clockTick(start, end),
}
cache.set(key, entry)
}
args.header.html = entry.html
args.header.areas = entry.areas
return
}
// Hour cells: the preview's label from 44 px, the bare 24-hour number below, every third
// hour when cells get narrower than the number.
const full = width >= 44
const hour = new Date(start).getUTCHours()
const labelled = width >= 18 || (hour - LAB_HOURS.begin) % 3 === 0
const fine = width >= 120 ? 'fine' : width >= 36 ? 'quarter' : 'none'
const key = `h:${start}:${full}:${labelled}:${fine}`
let entry = cache.get(key)
if (entry === undefined) {
const text = full ? headerLabel(start, 'hour', tag, 'cell') : String(hour).padStart(2, '0')
const label = labelled
? `<span class="bl-th-hour">${SuperScheduler.Util.escapeHtml(text)}</span>`
: ''
const ticks = fine === 'none' ? '' : `<i class="bl-ticks bl-ticks--${fine}"></i>`
entry = { html: `${label}${ticks}`, areas: clockTick(start, end) }
cache.set(key, entry)
}
args.header.html = entry.html
args.header.areas = entry.areas
}
}
/** Instruments in use per hour cell, computed once per cell start for a given set of bookings. */
function createUsage(bookings: readonly Booking[]): (start: number, end: number) => number {
const cache = new Map<number, number>()
return (start, end) => {
let value = cache.get(start)
if (value === undefined) {
value = inUse(bookings, start, end)
cache.set(start, value)
}
return value
}
}
export function BenchlabScheduler(props: BenchlabSchedulerProps) {
const {
events,
bookings,
blocks,
collisions,
text,
common,
tag,
schedulerLocale,
selected,
area,
compact,
minZoom,
history,
controlRef,
} = props
const { onEventsChange, onRequest, onSelect, onMoved, onResized, onRefused, onAction } = props
const resources = useMemo(() => toResources(text), [text])
// Phones get one row-header column (the instrument).
const rowHeaderColumns = useMemo<SuperScheduler.RowHeaderColumnData[]>(() => {
const [name, qc, use] = compact ? [GEOMETRY.compactColumns[0], 0, 0] : GEOMETRY.columns
return [
{ title: text.columns.instrument, width: name, nonresizable: true },
{ title: text.columns.qc, width: qc, hidden: compact, nonresizable: true },
{ title: text.columns.use, width: use, hidden: compact, nonresizable: true },
]
}, [text, compact])
const headerWidth = rowHeaderWidth(compact)
// A refused drop (other model, unavailable time, short run, started run, overlap) is said on release.
const refusal = useDropRefusal(onRefused)
// Hover card: phase, operator, preparation and run, samples, what comes next, the rule.
const card = useCallback(
(event: SuperScheduler.Event): HoverCardModel | null => {
const booking = bookings.find((candidate) => candidate.id === String(event.id()))
return booking === undefined
? null
: bookingCard(booking, bookings, blocks, text, common, tag)
},
[bookings, blocks, text, common, tag],
)
const { eventHover, closeHover, suppressHover } = useEventHover(card)
// Drag verdict: instrument, clock times, the lab's reason when it refuses, and the preparation
// that travels with the booking (when the run would start at the proposed position).
const dragCard = useMemo<SuperScheduler.DragCardOptions>(() => {
const pattern = usesTwelveHours(tag) ? 'h:mm tt' : 'HH:mm'
const base = createDragCard({
tag,
common,
rowName: (id) => (isInstrumentId(id) ? text.instruments[id] : null),
})
return {
...base,
markerFormat: pattern,
html: (info) => {
const html = base.html?.(info) ?? null
const booking = bookings.find((candidate) => candidate.id === String(info.eventId))
if (html === null || booking === undefined || booking.prepMinutes === 0) return html
if (info.forbidden || info.overlapping) return html
const kind = instrumentOf(booking.instrument).prep.kind
return `${html.slice(0, -'</div>'.length)}${prepSplit(booking.prepMinutes, kind, info.start.getTime(), text, tag)}</div>`
},
}
}, [bookings, text, common, tag])
// Context menu: rebuilt when the week changes, so its labels name the real slot.
const contextMenu = useMemo(
() =>
createEventMenu({
theme: skinMenuTheme(SLUG),
title: (event) => format(common.kit.menuTitle, { name: event.text() }),
onOpenChange: (open) => suppressHover(open),
entries: (event) => {
const id = String(event.id())
const booking = bookings.find((candidate) => candidate.id === id)
if (booking === undefined) return []
const locked = lockAt(booking, BUSINESS_NOW)
const slot = locked === null ? nextFreeSlot(booking, bookings, blocks, WEEK) : null
const longer = extendRun(booking, EXTEND_MINUTES, bookings, blocks)
const twin = locked === null ? twinLabel(booking, bookings, blocks, text) : null
const entries: MenuEntry[] = [
{
label: common.kit.openDetails,
icon: 'details',
keys: KEYS.details,
run: () => onAction('details', id),
},
]
if (locked === null)
entries.push({
label:
slot === null
? text.actions.noSlot
: format(text.actions.nextSlot, { time: formatWhen(slot.start, tag) }),
icon: 'slot',
primary: collisions.includes(id),
disabled: slot === null,
run: () => onAction('next-slot', id),
})
if (locked !== 'done')
entries.push('separator', {
label: longer.ok
? format(text.actions.extend, { time: formatClock(longer.end, tag) })
: format(text.actions.extendBlocked, {
reason: text.actions.reasons[longer.reason],
}),
icon: 'after',
disabled: !longer.ok,
run: () => onAction('extend', id),
})
if (twin !== null)
entries.push({
label: twin,
icon: 'handover',
disabled: !moveToTwin(booking, bookings, blocks).ok,
run: () => onAction('twin', id),
})
return entries
},
}),
[bookings, blocks, collisions, common, text, tag, onAction, suppressHover],
)
// Figures of the frozen row, per hour: instruments with a booking in that hour.
const usage = useMemo(() => createUsage(bookings), [bookings])
const total = INSTRUMENTS.length
const headerHook = useMemo(() => createHeaderHook(tag, text.kpi.clock), [tag, text])
const config = useMemo<SchedulerRenderProps>(() => {
const clockPattern = usesTwelveHours(tag) ? 'h:mm tt' : 'HH:mm'
const colliding = new Set(collisions)
const parts = new Map<string, CardParts>()
const overlapText = (conflicts: readonly SuperScheduler.Event[]) => {
const first = conflicts[0]
return first === undefined ? null : format(common.kit.overlaps, { name: first.text() })
}
const problemText = (problem: MoveProblem) =>
problem === 'other-model'
? text.rules.otherModel
: problem === 'unavailable'
? text.rules.unavailable
: text.rules.tooShort
/** The booking a render or a drag talks about, at the times the control reports. */
const bookingOf = (
data: object & Pick<SuperScheduler.EventData, 'id' | 'resource' | 'start' | 'end'>,
) => {
const fields = readBookingFields(data)
const resource = data.resource
if (fields === null || !isInstrumentId(resource)) return null
const booking: Booking = {
id: String(data.id),
instrument: resource,
...fields,
start: civilOf(data.start),
end: civilOf(data.end),
}
return booking
}
/** Why a booking cannot move to `[start, end)` on `target`, as a sentence, or null. */
const moveRefusal = (booking: Booking, target: InstrumentId, start: string, end: string) => {
const locked = lockAt(booking, BUSINESS_NOW)
if (locked !== null) return text.rules[locked]
if (inThePast(start, BUSINESS_NOW)) return text.rules.past
const found = moveProblem(booking, target, start, end, blocks)
return found === null ? null : problemText(found)
}
/** Why a booking cannot end at `end` (only its end edge moves), as a sentence, or null. */
const resizeRefusal = (booking: Booking, what: 'start' | 'end', start: string, end: string) => {
if (what === 'start') return text.rules.startEdge
if (parseCivil(end) <= NOW) return text.rules.past
const found = moveProblem(booking, booking.instrument, start, end, blocks)
return found === null ? null : problemText(found)
}
return {
locale: schedulerLocale,
cssClass: `${skinClass(SLUG)} bl-board`,
startDate: WEEK.start,
days: WEEK.days,
weekStarts: 1,
scale: 'Hour',
cellWidth: GEOMETRY.hour,
timeHeaders: [{ groupBy: 'Day' }, { groupBy: 'Hour' }],
headerHeight: GEOMETRY.header,
// Pinch and Ctrl+wheel zoom freely between a week at a glance and five-minute detail.
zoomGesture: { min: minZoom, max: ZOOM.max, wheel: 'ctrl' },
// Cards adapt to their width below 40 px per hour, and turn into blocks below 20.
lod: LOD,
// The lab is open 07:00–20:00: nights and the weekend stay hidden.
businessBeginsHour: LAB_HOURS.begin,
businessEndsHour: LAB_HOURS.end,
showNonBusiness: false,
useEventBoxes: 'Never',
height: '100%',
treeEnabled: true,
treePreventParentUsage: true,
treeIndent: compact ? 8 : 14,
rowHeaderColumns,
rowHeaderColumnsMergeParents: true,
rowHeaderWidth: headerWidth,
rowHeaderWidthAutoFit: false,
eventHeight: GEOMETRY.event,
rowMarginTop: GEOMETRY.inset,
rowMarginBottom: GEOMETRY.inset,
eventBorderRadius: 2,
allowEventOverlap: false,
conflictHighlight: true,
// The row and column under the pointer, and exact times while selecting, moving and resizing.
crosshairType: 'Full',
timeRangeSelectingStartEndEnabled: true,
timeRangeSelectingStartEndFormat: clockPattern,
eventMovingStartEndEnabled: true,
eventMovingStartEndFormat: clockPattern,
eventResizingStartEndEnabled: true,
eventResizingStartEndFormat: clockPattern,
// The lab's clock: a hairline at Wednesday 09:40, behind the cards (running ones show their
// progress themselves).
separators: [{ location: BUSINESS_NOW, cssClass: 'bl-now', layer: 'BelowEvents', width: 1 }],
// Selecting free time (pointer drag or keyboard) asks for a booking; plain clicks do not.
timeRangeSelectedHandling: 'Enabled',
// A running booking shows how much of it is behind the clock.
durationBarVisible: true,
durationBarMode: 'PercentComplete',
durationBarHeight: 2,
showToolTip: false,
keyboardEnabled: true,
keyboardTarget: 'component',
keyboardMode: 'Full',
keyboardOptions: { zoomKeys: true },
history,
controlRef,
onEventsChange,
onBeforeTimeHeaderRender: headerHook,
onBeforeRowHeaderRender: (args) => {
const id = args.row.id
args.row.cssClass =
id === SUMMARY_ROW ? 'bl-row--summary' : isInstrumentId(id) ? '' : 'bl-row--area'
},
// The area filter: a group row and its instruments, or everything. The summary row stays.
onRowFilter: (args) => {
const filter = args.filterParam
const data: object = args.row.data
const rowArea = 'area' in data ? data.area : undefined
args.visible = filter === 'all' || args.row.id === SUMMARY_ROW || rowArea === filter
},
// The summary row counts instruments in use per hour; instrument rows tint the time behind
// the lab's clock and disable unavailable time (hatched, drops refused by the library).
onBeforeCellRender: (args) => {
const { cell } = args
const start = cell.start.getTime()
const end = cell.end.getTime()
if (cell.resource === SUMMARY_ROW) {
const count = usage(start, end)
cell.properties.cssClass = `bl-sum bl-sum--${count}`
cell.properties.html = `<span class="bl-sum__n">${count}</span><progress class="bl-seg" max="${total}" value="${count}"></progress>`
return
}
const instrument = cell.resource
if (cell.isParent || !isInstrumentId(instrument)) return
const classes: string[] = []
if (end <= NOW) classes.push('bl-past')
else if (start < NOW)
cell.properties.areas = [
{
left: 0,
top: 0,
bottom: 0,
width: `${((NOW - start) / (end - start)) * 100}%`,
cssClass: 'bl-past-part',
},
]
const block = blockAt(instrument, cell.start.value, cell.end.value, blocks)
if (block !== undefined) {
if (parseCivil(block.start) <= start && end <= parseCivil(block.end)) {
cell.properties.disabled = true
// The window's name, once, in its first hour.
if (parseCivil(block.start) === start)
cell.properties.html = `<span class="bl-block">${SuperScheduler.Util.escapeHtml(text.blockShort[block.kind])}</span>`
} else classes.push('bl-unavailable')
}
cell.properties.cssClass = classes.join(' ')
},
onBeforeEventRender: (args) => {
const booking = bookingOf(args.data)
if (booking === null) return
const id = booking.id
const phase = phaseAt(booking, BUSINESS_NOW)
const alert = colliding.has(id)
const key = `${id}|${booking.start}|${booking.end}|${alert}`
let content = parts.get(key)
if (content === undefined) {
content = cardParts(booking, text, tag, alert)
parts.set(key, content)
}
const minutes = (parseCivil(booking.end) - parseCivil(booking.start)) / MINUTE
const width = (minutes / 60) * (args.control.cellWidth ?? GEOMETRY.hour)
// HTML fallback painted until the React card (renderEvent) mounts: the same markup.
args.data.html = cardHtml(content, cardSize(width))
const classes = ['bl-ev', `bl-ev--${phase}`]
if (booking.group === 'request') classes.push('bl-ev--request')
if (alert) classes.push('ss-ev--late', 'bl-ev--alert')
if (id === selected) classes.push('bl-ev--selected')
args.data.cssClass = classes.join(' ')
args.data.ariaLabel = `${booking.project}, ${text.methods[booking.method]}, ${text.instruments[booking.instrument]}, ${content.time}`
// Running bookings: the share already behind the clock fills the bar at the card's foot.
if (phase === 'prep' || phase === 'run')
args.data.complete = Math.round(elapsedAt(booking, BUSINESS_NOW) * 100)
else args.data.barHidden = true
if (phase === 'done') args.data.resizeDisabled = true
const areas: SuperScheduler.AreaData[] = []
// The preparation is drawn by the library as an area anchored in time at the booking start.
if (booking.prepMinutes > 0)
areas.push({
start: args.data.start,
end: args.data.start.addMinutes(booking.prepMinutes),
top: 0,
bottom: 0,
cssClass: 'bl-prep',
action: 'None',
})
// A hover button on the card does what the menu's "Run 30 min longer" does.
if (
phase !== 'done' &&
width >= 120 &&
extendRun(booking, EXTEND_MINUTES, bookings, blocks).ok
)
areas.push({
right: 4,
top: 7,
width: 56,
height: 22,
visibility: 'Hover',
action: 'None',
cssClass: 'bl-act',
html: SuperScheduler.Util.escapeHtml(text.actions.extendShort),
toolTip: format(text.actions.extend, {
time: formatClock(parseCivil(booking.end) + EXTEND_MINUTES * MINUTE, tag),
}),
onClick: () => onAction('extend', id),
})
args.data.areas = areas
},
// Identical instruments only, never across unavailable time, never into the past, and a
// booking that has started stays put; overlap is refused by the library.
onEventMoving: (args) => {
const booking = bookingOf(args.e.data)
if (booking === null || !isInstrumentId(args.resource)) return
const message = moveRefusal(booking, args.resource, args.start.value, args.end.value)
if (message !== null) {
args.allowed = false
args.message = message
refusal.track(booking.id, message)
return
}
refusal.track(booking.id, overlapText(args.conflicts))
},
// Final check before the commit (also covers keyboard moves).
onEventMove: (args) => {
const booking = bookingOf(args.e.data)
if (booking === null || !isInstrumentId(args.newResource)) return
const message = moveRefusal(
booking,
args.newResource,
args.newStart.value,
args.newEnd.value,
)
if (message !== null) {
args.preventDefault()
refusal.clear()
onRefused(booking.id, message)
}
},
// The preparation belongs to the instrument: only the end of a booking can be dragged, and
// never back behind the lab's clock.
onEventResizing: (args) => {
const booking = bookingOf(args.e.data)
if (booking === null) return
const message = resizeRefusal(booking, args.what, args.start.value, args.end.value)
if (message !== null) {
args.allowed = false
args.message = message
refusal.track(booking.id, message)
return
}
refusal.track(booking.id, overlapText(args.conflicts))
},
onEventResize: (args) => {
const booking = bookingOf(args.e.data)
if (booking === null) return
const message = resizeRefusal(booking, args.what, args.newStart.value, args.newEnd.value)
if (message !== null) {
args.preventDefault()
refusal.clear()
onRefused(booking.id, message)
}
},
onTimeRangeSelected: (args) => {
args.control.clearSelection()
if (args.origin === 'click' || !isInstrumentId(args.resource)) return
onRequest(args.resource, civilOf(args.start), civilOf(args.end))
},
onEventMoved: (args) => {
refusal.clear()
onMoved(String(args.e.id()))
},
onEventResized: (args) => {
refusal.clear()
onResized(String(args.e.id()))
},
// A click (or Enter) docks the booking into the side sheet; the hover card steps aside.
onEventClick: (args) => {
closeHover()
onSelect(String(args.e.id()))
},
}
}, [
history,
controlRef,
bookings,
blocks,
collisions,
compact,
selected,
common,
refusal,
closeHover,
onEventsChange,
onMoved,
onRefused,
onRequest,
onResized,
onSelect,
onAction,
schedulerLocale,
headerHook,
rowHeaderColumns,
headerWidth,
minZoom,
usage,
total,
tag,
text,
])
// React row headers: the summary row's figures, lab areas, and per instrument its preparation,
// calibration certificate and booked share of the week. Rebuilt when bookings change.
const renderRowHeader = useMemo<NonNullable<SchedulerProps['renderRowHeader']>>(() => {
const day = NOW - (NOW % DAY)
// The week day by day for the use column: each day's start, its short name, the clock's day.
const weekStart = parseCivil(WEEK.start)
const weekDays = Array.from({ length: WEEK.days }, (_, index) => civil(weekStart + index * DAY))
const weekday = new Intl.DateTimeFormat(tag, { weekday: 'short', timeZone: 'UTC' })
const dayNames = weekDays.map((start) => weekday.format(new Date(parseCivil(start))))
const today = Math.floor((day - weekStart) / DAY)
const share = new Intl.NumberFormat(tag, { style: 'percent' })
let peak = 0
for (let hour = LAB_HOURS.begin; hour < LAB_HOURS.end; hour += 1)
peak = Math.max(peak, inUse(bookings, day + hour * HOUR, day + (hour + 1) * HOUR))
const now = inUse(bookings, NOW, NOW + 1)
return ({ row, column }) => {
const id = row.id
if (id === SUMMARY_ROW) {
if (column === 1) return <SummaryFigure value={now} label={text.summary.now} />
if (column === 2) return <SummaryFigure value={peak} label={text.summary.peak} />
return (
<SummaryCell
label={text.summary.label}
meta={format(text.summary.meta, { total: INSTRUMENTS.length })}
/>
)
}
if (!isInstrumentId(id)) {
const areaId = AREA_IDS.find((candidate) => candidate === id)
return areaId === undefined ? (
row.name
) : (
<AreaCell
name={text.areas[areaId]}
count={INSTRUMENTS.filter((instrument) => instrument.area === areaId).length}
/>
)
}
const instrument = instrumentOf(id)
if (column === 1) {
const status = qcStatus(instrument, BUSINESS_NOW)
const label = text.qc[status.state]
const detail =
status.state === 'none'
? '—'
: status.state === 'ok'
? format(text.qc.until, {
date: formatCivilCached(instrument.qcDue ?? BUSINESS_NOW, tag, {
day: 'numeric',
month: 'short',
}),
})
: plural(text.qc.inDays, Math.max(0, status.days), tag)
return <QcCell status={status} label={label} detail={detail} />
}
if (column === 2) {
const days = weekDays.map((start) => utilisation(id, bookings, { start, days: 1 }))
const week = utilisation(id, bookings, WEEK)
const label = `${text.columns.use}: ${text.instruments[id]} ${share.format(week)} · ${days
.map((value, index) => `${dayNames[index] ?? ''} ${share.format(value)}`)
.join(', ')}`
return <UseCell value={week} days={days} today={today} label={label} />
}
const minutes = instrument.prep.minutes
return (
<InstrumentCell
name={text.instruments[id]}
hasPrep={minutes > 0}
prep={
minutes === 0
? text.noPrep
: format(text.prepChip, {
minutes: plural(text.minutes, minutes, tag),
kind: text.prepKinds[instrument.prep.kind],
})
}
/>
)
}
}, [bookings, text, tag])
// React booking cards: the same parts as the HTML fallback.
const renderEvent = useMemo<NonNullable<SchedulerProps['renderEvent']>>(
() =>
({ e, data, width }) => {
const fields = readBookingFields(data)
const resource = data.resource
if (fields === null || !isInstrumentId(resource)) return e.text()
const booking: Booking = {
id: String(e.id()),
instrument: resource,
...fields,
start: civilOf(data.start),
end: civilOf(data.end),
}
return (
<BookingCard
parts={cardParts(booking, text, tag, collisions.includes(booking.id))}
size={cardSize(width)}
/>
)
},
[collisions, text, tag],
)
// The area filter runs through the library (onRowFilter above).
useEffect(() => {
const control = controlRef.current
if (control === null || control.disposed()) return
control.rows.filter(area)
}, [area, controlRef, config])
// Imperative and once: a scroll prop would be re-applied on every update.
useEffect(() => {
controlRef.current?.scrollTo(INITIAL_VIEW_START, false, 'left')
}, [controlRef])
return (
<SuperSchedulerComponent
{...config}
resources={resources}
events={events}
renderRowHeader={renderRowHeader}
renderEvent={renderEvent}
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.