Aller au contenu

Réservation d’instruments de laboratoire

Réservez un instrument, l’étalonnage est compris. Sortez une séance d’une visite de maintenance, puis allongez votre mesure.

  • Laboratoire
  • Benchlab
  • Slots de rendu React
  • Curseur de zoom
  • Lignes de synthèse
  • Minimap
  • Réticule
  • Barres de progression
  • Échelle à la minute
  • Créneaux bloqués
  • Thèmes
  • Démo avec données fictives

Mission

0 étapes faites sur 3

Mercredi, 9:40 au labo : la maintenance du fabricant sur le microscope confocal occupe désormais 9:00–12:00, juste sur une séance de Biologie cellulaire.

  1. Sortez la séance CB-091, en rouge, de la fenêtre de maintenance du confocal. — À faire

    Glissez-la à 12:00 ou plus tard sur le même microscope. Un autre modèle d’instrument est refusé, tout comme les heures hachurées.

  2. Réservez deux heures de LC-MS mercredi après-midi. — À faire

    Glissez sur des heures libres de la ligne LC-MS ; l’app ajoute les 60 minutes d’étalonnage devant. Un début à 14:00 est refusé : la mesure du matin finit à 13:30.

  3. Allongez votre nouvelle mesure en tirant son bord droit. — À faire

    L’étalonnage garde ses 60 minutes. Tirer le bord gauche est refusé ; le bouton +30 min de la carte fait la même chose que le glisser.

Environ 30 secondes. Les étapes se cochent au fur et à mesure.

Clavier : placez le focus sur la grille, puis flèches, Entrée et Alt+flèches pour déplacer.

Benchlab
MicroscopieMicroscope confocal13%Microscope à champ large10%AnalyseLC-MS18%Spectrophotomètre UV-Vis6%Biologie moléculaireThermocycleur qPCR 16%Thermocycleur qPCR 29%Séquenceur36%PaillassesPaillasse humide 112%Paillasse humide 28%Poste de sécurité microbiologique11%CB-091 Cellules vivantes10:30 – 12:30 n=6PX-220 Cartographie peptidique10:00 – 13:30 n=18PX-214 Panel de métabolites09:00 – 12:00 n=24CB-088 Criblage en fluorescence13:15 – 15:15 n=8CB-091 Criblage en fluorescence07:45 – 09:15 n=8GN-140 Génotypage10:00 – 12:00 n=96TL-02 TP d’enseignement13:00 – 17:00 n=12CB-091 Culture cellulaire09:15 – 11:15 n=4TL-03 Culture cellulaire13:45 – 16:00 n=6PX-220 Clonage08:00 – 09:30 n=8GN-131 Amplicons09:00 – 16:00 n=48GN-140 Amplicons09:45 – 16:45 n=48PX-214 Dosage de protéines11:15 – 12:15 n=30GN-131 Génotypage13:00 – 15:00 n=961355646541000012221Instruments utilisésmercredi 21 octobrejeudi 22 octobre07:0008:0009:0010:0011:0012:0013:0014:0015:0016:0017:0018:0019:0007:0008:0009:0010:0011:0012:00

Aperçu de la première imageEn direct : le vrai moteur Pro, dans votre navigateurEnviron 30 secondes. Les étapes se cochent au fur et à mesure. Clavier : placez le focus sur la grille, puis flèches, Entrée et Alt+flèches pour déplacer.

La situation.

Benchlab est un laboratoire partagé fictif : deux microscopes, un LC-MS, un spectrophotomètre, des thermocycleurs qPCR, un séquenceur et des paillasses utilisés par quatre équipes. La plupart des instruments demandent du temps avant une mesure : le laser du confocal chauffe, le LC-MS s’étalonne pendant une heure, le séquenceur amorce sa cuve à flux.

Si la réservation n’enregistre que la mesure, la préparation empiète sur le créneau précédent et la visite du fournisseur tombe sur une séance que personne n’a déplacée. Le planning doit traiter la préparation comme une partie de la réservation, mettre le temps indisponible hors de portée et dire clairement pourquoi une demande ne rentre pas. Ces règles sont la politique de réservation de ce laboratoire, pas un système de conformité.

Chaque instrument porte aussi un certificat d’étalonnage avec une date d’expiration, et le planning lit chaque réservation à l’heure du labo : ce qui est terminé, ce qui se prépare ou mesure, ce qui attend encore. Une mesure commencée reste où elle est.

Ce que vous allez faire

Vous sortirez une séance d’une fenêtre de maintenance, réserverez deux heures de LC-MS avec l’étalonnage ajouté pour vous, puis allongerez cette mesure sans changer l’étalonnage.

Où s’arrête la bibliothèque et où commence votre application.

SuperScheduler fournit

  • Une échelle horaire à 72 px par heure, nuits et week-end masqués (businessBeginsHour, businessEndsHour, showNonBusiness: false), un zoom libre au pincement, Ctrl+molette ou Ctrl +/− (zoomGesture, keyboardOptions.zoomKeys) et par le curseur et le badge de niveau de détail de zoom-ui (createZoomSlider, createLodBadge), avec des seuils lod qui changent les cartes en blocs de loin.
  • Trois colonnes d’en-tête de ligne (rowHeaderColumns, rowHeaderColumnsMergeParents) rendues par React (renderRowHeader), une ligne de synthèse figée (frozen: 'top') dont les cellules comptent les instruments utilisés (onBeforeCellRender), et des lignes filtrées par zone (rows.filter, onRowFilter).
  • Des en-têtes de temps sur mesure avec graduations des minutes et l’horloge du labo (onBeforeTimeHeaderRender avec des zones d’en-tête), un séparateur pour l’horloge et le réticule complet (crosshairType: 'Full') lu à la minute avec getCoords.
  • Des cartes de réservation sur deux lignes en React (renderEvent) au-dessus d’un HTML de secours, la préparation en zone d’événement ancrée dans le temps, une zone d’action au survol (visibility: 'Hover', action: 'None') et des barres de progression sur les réservations en cours (durationBarMode: 'PercentComplete', complete).
  • Des cellules désactivées pour le temps indisponible ; glisser pour sélectionner, déplacer et redimensionner avec des étiquettes exactes de début et de fin (timeRangeSelectingStartEndEnabled, eventMovingStartEndEnabled, eventResizingStartEndEnabled), sans chevauchement, des messages de refus sur la carte de glisser, annuler et rétablir avec des événements contrôlés.
  • Cartes au survol (eventHover), mise en évidence des conflits et menus contextuels au clic droit, à l’appui long ou avec Maj+F10.
  • Au-dessus de la légende, la minicarte de super-scheduler/minimap alimentée par les instruments utilisés par heure sur la semaine (une série sur une plage fixe), un ton par heure et des libellés traduits, dont le curseur déplace le tableau ; la colonne d’usage dessine la semaine de chaque instrument jour par jour (renderRowHeader).

Le code de cet exemple décide

  • Combien de temps chaque instrument se prépare, et comment une mesure sélectionnée devient une réservation avec la préparation devant.
  • L’horloge du labo (mercredi 9:40, fixe pour la démo) : une mesure commencée ne bouge plus, et le temps passé ne se réserve pas.
  • Les changements permis : seulement entre instruments identiques, jamais sur un entretien ou une maintenance, des mesures de 30 minutes ou plus, la préparation fixée au début.
  • Chaque chiffre : instruments utilisés par heure et maintenant, la file du jour, l’usage hebdomadaire de chaque instrument et les certificats d’étalonnage qui expirent dans la semaine.
  • La barre du produit, le panneau de réservation, la mission et tous les textes de cette page. Aucune promesse réglementaire ni d’audit.
  • Les instruments utilisés par heure sur la semaine, les heures où une réservation tombe dans un créneau de service, l’heure la plus chargée et l’usage de chaque instrument jour par jour.

Le code de cette démo.

Ce sont les fichiers exécutés par cette page, pas une copie simplifiée. Ils compilent avec les exports publics de SuperScheduler Pro.

tsx.zip

L’intégration : échelle horaire et bornes du zoom, colonnes d’en-tête et ligne de synthèse figée, en-têtes de temps avec graduations et horloge du labo, le hook des cellules (temps passé, heures indisponibles, chiffres par heure), les cartes avec leur zone de préparation, leur action au survol et leur progression, et les callbacks où les règles refusent un déplacement, un redimensionnement ou une réservation.

/**
 * 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}
    />
  )
}

L’archive contient les fichiers de cet exemple et un README. Elle n’inclut ni SuperScheduler Pro ni aucune clé de téléchargement.