Zum Inhalt springen

Gerätebuchung im Labor

Wer ein Gerät bucht, bekommt die Kalibrierung mit. Eine Sitzung aus dem Servicefenster holen, dann den eigenen Lauf verlängern.

  • Labor
  • Benchlab
  • React-Render-Slots
  • Zoom-Regler
  • Summenzeilen
  • Minimap
  • Fadenkreuz
  • Fortschrittsbalken
  • Minutenraster
  • Gesperrte Zeiten
  • Theming
  • Demo mit synthetischen Daten
Quellcode laden.zip

Aufgabe

0 von 3 Schritten erledigt

Mittwoch, 9:40 Uhr im Labor: Der Herstellerservice am Konfokalmikroskop liegt jetzt von 9:00 bis 12:00 – genau über einer Sitzung der Zellbiologie.

  1. Holen Sie die rote Sitzung CB-091 aus dem Servicefenster des Konfokalmikroskops. — Offen

    Ziehen Sie sie auf 12:00 oder später am selben Mikroskop. Ein anderes Gerätemodell wird abgelehnt, ebenso jede schraffierte Stunde.

  2. Buchen Sie zwei Stunden LC-MS am Mittwochnachmittag. — Offen

    Ziehen Sie über freie Stunden in der LC-MS-Zeile; die App setzt die 60 Minuten Kalibrierung davor. Ein Start um 14:00 wird abgelehnt: Der Vormittagslauf endet um 13:30.

  3. Verlängern Sie Ihren neuen Lauf am rechten Rand. — Offen

    Die Kalibrierung behält ihre 60 Minuten. Ziehen am linken Rand wird abgelehnt; die Schaltfläche +30 min auf der Karte tut dasselbe wie das Ziehen.

Etwa 30 Sekunden. Erledigte Schritte werden abgehakt.

Tastatur: Raster fokussieren, dann Pfeiltasten, Eingabe und Alt+Pfeile zum Verschieben.

Benchlab
MikroskopieKonfokalmikroskop13%Weitfeldmikroskop10%AnalytikLC-MS18%UV-Vis-Spektralphotometer6%MolekularbiologieqPCR-Cycler 16%qPCR-Cycler 29%Sequenzierer36%ArbeitsplätzeNasslabor-Platz 112%Nasslabor-Platz 28%Sicherheitswerkbank11%CB-091 Lebendzell-Imaging10:30–12:30 Uhr n=6PX-220 Peptid-Mapping10:00–13:30 Uhr n=18PX-214 Metaboliten-Panel09:00–12:00 Uhr n=24CB-088 Fluoreszenz-Screen13:15–15:15 Uhr n=8CB-091 Fluoreszenz-Screen07:45–09:15 Uhr n=8GN-140 Genotypisierung10:00–12:00 Uhr n=96TL-02 Praktikum13:00–17:00 Uhr n=12CB-091 Zellkultur09:15–11:15 Uhr n=4TL-03 Zellkultur13:45–16:00 Uhr n=6PX-220 Klonierung08:00–09:30 Uhr n=8GN-131 Amplikon-Lauf09:00–16:00 Uhr n=48GN-140 Amplikon-Lauf09:45–16:45 Uhr n=48PX-214 Proteinassay11:15–12:15 Uhr n=30GN-131 Genotypisierung13:00–15:00 Uhr n=961355646541000012221Geräte in BetriebMittwoch, 21. OktoberDonnerstag, 22. Oktober07:0008:0009:0010:0011:0012:0013:0014:0015:0016:0017:0018:0019:0007:0008:0009:0010:0011:0012:00

Vorschau des ersten BildesLive: die echte Pro-Engine, in Ihrem BrowserEtwa 30 Sekunden. Erledigte Schritte werden abgehakt. Tastatur: Raster fokussieren, dann Pfeiltasten, Eingabe und Alt+Pfeile zum Verschieben.

Die Ausgangslage.

Benchlab ist ein fiktives Gemeinschaftslabor: zwei Mikroskope, ein LC-MS, ein Spektralphotometer, qPCR-Cycler, ein Sequenzierer und Arbeitsplätze für vier Forschungsgruppen. Die meisten Geräte brauchen Vorlauf: Der Laser des Konfokalmikroskops wärmt sich auf, das LC-MS kalibriert eine Stunde, der Sequenzierer primt seine Flusszelle.

Wenn eine Buchung nur den Lauf erfasst, frisst die Vorbereitung den vorherigen Slot, und der Servicebesuch des Herstellers landet auf einer Sitzung, die niemand verschoben hat. Das Board muss die Vorbereitung als Teil der Buchung behandeln, nicht verfügbare Zeit unerreichbar machen und klar sagen, warum eine Anfrage nicht passt. Die Regeln sind die eigene Buchungspolitik dieses Labors, kein Compliance-System.

Jedes Gerät hat außerdem ein Kalibrierzertifikat mit Ablaufdatum, und das Board liest jede Buchung gegen die Laboruhr: was fertig ist, was sich vorbereitet oder läuft und was noch geplant ist. Ein begonnener Lauf bleibt, wo er ist.

Was Sie tun werden

Sie holen eine Sitzung aus einem Servicefenster, buchen zwei Stunden LC-MS mit automatisch vorangestellter Kalibrierung und verlängern diesen Lauf, ohne dass sich die Kalibrierung ändert.

Wo die Bibliothek endet und Ihre Anwendung beginnt.

SuperScheduler liefert

  • Eine Stundenskala mit 72 px pro Stunde, Nächte und Wochenende ausgeblendet (businessBeginsHour, businessEndsHour, showNonBusiness: false), freier Zoom per Pinch, Strg+Mausrad oder Strg +/− (zoomGesture, keyboardOptions.zoomKeys) und per Schieberegler und Detailstufen-Badge aus zoom-ui (createZoomSlider, createLodBadge), mit lod-Schwellen, die Karten weit herausgezoomt zu Blöcken machen.
  • Drei Zeilenkopf-Spalten (rowHeaderColumns, rowHeaderColumnsMergeParents), gefüllt von React (renderRowHeader), eine fixierte Summenzeile (frozen: 'top'), deren Zellen die Geräte in Betrieb zählen (onBeforeCellRender), und ein Zeilenfilter nach Bereich (rows.filter, onRowFilter).
  • Eigene Zeitköpfe mit Minutenstrichen und der Laboruhr (onBeforeTimeHeaderRender mit Kopf-Areas), ein Separator für die Uhr und das volle Fadenkreuz (crosshairType: 'Full'), minutengenau gelesen mit getCoords.
  • Zweizeilige Buchungskarten aus React (renderEvent) über einem HTML-Fallback, die Vorbereitung als zeitlich verankerte Event-Area, eine Hover-Aktion (visibility: 'Hover', action: 'None') und Fortschrittsbalken auf laufenden Buchungen (durationBarMode: 'PercentComplete', complete).
  • Deaktivierte Zellen für nicht verfügbare Zeit; per Ziehen auswählen, verschieben und Dauer ändern mit exakten Start- und Endmarken (timeRangeSelectingStartEndEnabled, eventMovingStartEndEnabled, eventResizingStartEndEnabled), ohne Überschneidung, Ablehnungsmeldungen auf der Drag-Karte, Rückgängig und Wiederholen mit kontrollierten Ereignissen.
  • Hover-Karten (eventHover), Konfliktmarkierung und Kontextmenüs per Rechtsklick, langem Drücken oder Umschalt+F10.
  • Über der Legende die Minimap aus super-scheduler/minimap, gespeist mit den Geräten in Betrieb pro Stunde über die Woche (eine Reihe über einen festen Zeitraum), einem Ton pro Stunde und übersetzten Beschriftungen, deren Schieber die Tafel bewegt; die Lastspalte zeichnet die Woche jedes Geräts Tag für Tag (renderRowHeader).

Der Code dieses Beispiels entscheidet

  • Wie lange jedes Gerät Vorlauf braucht und wie aus einem gewählten Lauf eine Buchung mit vorangestellter Vorbereitung wird.
  • Die Laboruhr (Mittwoch 9:40, fest für die Demo): Begonnene Läufe bleiben, wo sie sind, und vergangene Zeit lässt sich nicht buchen.
  • Welche Änderungen erlaubt sind: nur zwischen identischen Geräten, nie über Service oder Wartung, Läufe ab 30 Minuten, Vorbereitung fest am Anfang.
  • Jede Zahl: Geräte in Betrieb pro Stunde und jetzt, die heutige Warteschlange, die Wochenlast je Gerät und Kalibrierzertifikate, die innerhalb einer Woche ablaufen.
  • Die Produktleiste, das Buchungspanel, die Mission und alle Texte dieser Seite. Keine regulatorischen oder Audit-Versprechen.
  • Die Geräte in Betrieb pro Stunde über die Woche, die Stunden, in denen eine Buchung in einem Servicefenster liegt, die vollste Stunde und die Last jedes Geräts Tag für Tag.

Der Code hinter dieser Demo.

Das sind die Dateien, die diese Seite ausführt, keine vereinfachte Kopie. Sie kompilieren gegen die öffentlichen Exporte von SuperScheduler Pro.

tsx.zip

Die Integration: Stundenskala und Zoomgrenzen, Zeilenkopf-Spalten und fixierte Summenzeile, Zeitköpfe mit Minutenstrichen und Laboruhr, der Zell-Hook (Zeit hinter der Uhr, nicht verfügbare Stunden, Zahlen pro Stunde), die Karten mit Vorbereitungsbereich, Hover-Aktion und Fortschritt und die Callbacks, in denen die Regeln eine Verschiebung, eine Längenänderung oder eine Buchung ablehnen.

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

Das Archiv enthält die Dateien dieses Beispiels und eine README. SuperScheduler Pro und Download-Schlüssel sind nicht enthalten.