Zum Inhalt springen

Planung einer Mietwagenflotte

Ein Kleinwagen fällt am Abholtag aus. Die Miete auf ein anderes Auto legen, die Aufbereitung einhalten und an Tagen ohne freie Flotte den Schalterverkauf stoppen.

  • Mobilität
  • Fleetline
  • Zeilenspalten
  • Summenzeilen
  • Minimap
  • Mehrtägige Ereignisse
  • Filter
  • Ressourcenbaum
  • Detailpanel
  • Theming
  • Demo mit synthetischen Daten
Quellcode laden.zip

Aufgabe

0 von 3 Schritten erledigt

Montag, 12. Oktober, 8:00 Uhr: Bei FL 208 ist über Nacht die Frontscheibe gerissen, die Werkstatt behält ihn bis Freitag. Der Kunde holt um 10:00 Uhr ab.

  1. Legen Sie die Miete R-1093 von FL 208 auf einen anderen Kleinwagen. — Offen

    Ziehen Sie sie nach oben auf FL 206 (ein Kombi geht auch, als kostenloses Upgrade). FL 204 ist nicht rechtzeitig fertig, Transporter und Elektroautos werden abgelehnt.

  2. Der Kunde des Transporters R-1107 behält ihn einen Tag länger: Verlängern Sie die Miete. — Offen

    Klicken Sie auf R-1107 bei FL V05 und nutzen Sie im Panel „Um einen Tag verlängern“. Die Aufbereitung endet weiterhin vor der nächsten Abholung.

  3. Finden Sie die Tage, an denen die ganze Flotte unterwegs ist, und stoppen Sie dort den Schalterverkauf. — Offen

    Wechseln Sie zu Wochen (oder folgen Sie dem roten Abschnitt der Minimap), klicken Sie auf die rote 0 in der Zeile Freie Autos und dann auf „Schalterverkauf stoppen“. Die Kennzahl Ausgebucht in der Leiste öffnet dasselbe Panel per Tastatur.

Etwa 30 Sekunden. Erledigte Schritte werden abgehakt.

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

Fleetline
KleinwagenFL 204ArloFL 206ArloFL 208ArloKombiFL 311Breva TouringFL 315Breva TouringElektroFL E21Volta 60FL E24Volta 50TransporterFL V02Cargo MFL V05Cargo LFL V07Cargo LA. LindqvistCEN · R-1088M. HaddadCEN→APT · R-1101S. MoreauAPT→CEN · R-1120L. OkaforCEN · R-1097P. NovakCEN · R-1126D. BrennanCEN · R-1093ScheibenreparaturI. KowalskiCEN · R-1131C. DuboisCEN→APT · R-1090N. RossiAPT→CEN · R-1110T. AndersenCEN · R-1139J. MensahCEN · R-1104V. PetrovCEN · R-1128Y. ChenCEN · R-1095M. AhmedCEN→APT · R-1115G. LaurentAPT→CEN · R-1145ReifenwechselS. KaurCEN · R-1118K. OseiCEN · R-1099D. HughesCEN · R-1123A. FerreiraCEN · R-1107J. ParkCEN · R-1112E. SchmidtCEN · R-1136JahresinspektionT. BauerCEN · R-1114C. MurphyCEN · R-1116764444544555666877677788Freie Autosganztägig frei12. Okt.19. Okt.26. Okt.2. Nov.Mo., 12.Di., 13.Mi., 14.Do., 15.Fr., 16.Sa., 17.So., 18.Mo., 19.Di., 20.Mi., 21.Do., 22.Fr., 23.Sa., 24.So., 25.Mo., 26.Di., 27.Mi., 28.Do., 29.Fr., 30.Sa., 31.So., 1.Mo., 2.Di., 3.Mi., 4.

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.

Fleetline ist eine fiktive Mietstation mit zehn Fahrzeugen: drei Kleinwagen, zwei Kombis, zwei Elektroautos und drei Transporter. Kunden buchen eine Kategorie und einen Zeitraum; die Station entscheidet, welches Fahrzeug rausgeht, und jede Rückgabe braucht Reinigung und Prüfung (bei Elektroautos auch das Laden) vor der nächsten Abholung.

In einer Tabelle bleibt diese Aufbereitung unsichtbar: Der nächste Kunde steht da, während der Transporter noch gereinigt wird. Die Planung muss die Daten jeder Miete festhalten, eine niedrigere Kategorie oder einen Transporter für eine Kleinwagenbuchung ablehnen, die Aufbereitung nach jeder Rückgabe zeigen, die noch freien Autos pro Tag zählen und dem Schalter sagen, wann er nicht mehr verkaufen soll.

Was Sie tun werden

Sie legen eine gestrandete Miete auf ein freies Auto (oder ein kostenloses Upgrade), verlängern eine Transportermiete im Detailpanel und stoppen mit Wochenansicht, Minimap und der Zeile Freie Autos den Schalterverkauf an den Tagen, an denen die ganze Flotte unterwegs ist.

Wo die Bibliothek endet und Ihre Anwendung beginnt.

SuperScheduler liefert

  • Kategorien mit ihren Fahrzeugen als Ressourcenbaum, mit rowHeaderColumns (Kennzeichen, Modell, Tank- oder Ladeanzeige), die per Klick sortieren (sort, rowSortingMode: LeavesOnly), und einem Zeilenkopf, den man breiter ziehen kann (rowHeaderResizable).
  • Eine fixierte Zeile (frozen: top, cellsDisabled), deren Zellen onBeforeCellRender mit den freien Autos pro Tag füllt, mit einem klickbaren Zellbereich, der die Verfügbarkeit des Tages oder der Woche öffnet.
  • Mehrtägige Balken zu exakten Abhol- und Rückgabezeiten, nur senkrechtes Verschieben (moveHDisabled), Ablehnung von Überschneidungen pro Fahrzeug und conflictHighlight.
  • Zeitverankerte Ereignisbereiche für die Mietkapsel und die Aufbereitung nach der Rückgabe sowie htmlLeft / htmlRight mit Abhol- und Bereitschaftszeit.
  • zoomLevels für Tage und Wochen mit animiertem Wechsel und Strg/⌘ + Mausrad, Zeitköpfe aus onBeforeTimeHeaderRender, ein Separator am Jetzt des Schalters und eine Minimap (super-scheduler/minimap), deren Fenster die Planung verschiebt und zoomt.
  • Zeilenfilter (rows.filter, onRowFilter), die Hover-Karte der Ereignisse (eventHover), eine Ziehkarte mit beiden Kennzeichen und dem Grund der Station, ein Kontextmenü (Rechtsklick oder Umschalt+F10) und der Rückgängig-Verlauf (super-scheduler/history, mit history.push für den Verkaufsstopp).

Der Code dieses Beispiels entscheidet

  • Welches Fahrzeug welche Buchung bedienen darf: dieselbe Kategorie oder ein kostenloses Upgrade vom Kleinwagen auf den Kombi.
  • Die Aufbereitungszeit pro Kategorie und die Konfliktprüfung, die sie vor der nächsten Abholung frei hält.
  • Die Verfügbarkeit pro Tag (ein Auto zählt nur, wenn es von Mitternacht bis Mitternacht frei ist), die ausgebuchten Tage und der Stopp des Schalterverkaufs.
  • Die Kennzahlen des Schalters (vermietet, in der Werkstatt, Abholungen und Rückgaben heute, Auslastung über sieben Tage) und die Auslastungsreihe der Minimap mit ihren Schwellen in Bernstein und Rot.
  • Ein freies Fahrzeug für dieselben Daten, angeboten für eine kollidierende Miete, Verlängerungen im Detailpanel und alle Texte dieser Seite.

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: der Kategorienbaum mit den Spalten Kennzeichen, Modell und Tank, die fixierte Zeile Freie Autos in onBeforeCellRender, die Kapsel- und Aufbereitungsbereiche in onBeforeEventRender, die Prüfungen beim Verschieben, Hover-Karte, Ziehurteil und Kontextmenü sowie die Minimap, die nach dem Mounten des Controls entsteht.

/**
 * Fleetline rental board: a night-mode fleet desk. Vehicles grouped by category over seven weeks,
 * a frozen "Cars available" row, rental capsules with their preparation tail, and a fleet-load
 * minimap.
 *
 * Library: resource tree, rowHeaderColumns (plate, model, fuel) with sort and a resizable row
 * header, a frozen summary row filled by onBeforeCellRender (with a clickable cell area), row
 * filtering, multi-day bars at exact times, vertical-only moves, overlap refusal with conflict
 * highlight, time-anchored areas for the capsule and the preparation, htmlLeft / htmlRight side
 * labels, custom time headers, a separator at the desk's now, the drag card, the event hover card
 * (super-scheduler/react-render), a context menu, undo history, day/week zoom and the minimap.
 * Application: which vehicle may serve which booking, how long preparation takes, which rentals
 * clash, which days are sold out, and what the minimap measures. Those rules live in ./rules.
 */
import {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useSyncExternalStore,
  type RefObject,
} from 'react'
import { SuperScheduler } from 'super-scheduler'
import type { SchedulerEventsChangeArgs } from 'super-scheduler'
import type { SchedulerHistory } from 'super-scheduler/history'
import { createMinimap, type Minimap } from 'super-scheduler/minimap'
import { SuperSchedulerComponent, type SchedulerRenderProps } from 'super-scheduler/react-render'
import { format, plural } from '~/i18n/format'
import { DAY, HOUR, formatCivil, parseCivil } from '../../scheduler/civil'
import { usesTwelveHours } from '../../scheduler/header-format'
import { skinClass, skinMenuTheme } from '../registry'
import { createEventMenu } from '../kit/context-menu'
import { formatClock, formatCivilCached, formatSpan, formatWhen } from '../kit/format'
import { useEventHover, type HoverCardModel, type KeyHint } from '../kit/hover-card'
import { ALT_KEY, KEYS } from '../kit/keys'
import { useDropRefusal } from '../kit/use-drop-refusal'
import { createDragCard } from '../kit/verdict'
import type { DemoCommon } from '../types'
import {
  CATEGORY_TONES,
  GEOMETRY,
  SUMMARY_HEIGHT,
  SUMMARY_ROW,
  civilOf,
  isVehicleId,
  plateOf,
  readFleetFields,
  toResources,
  type FleetEvent,
} from './adapter'
import { CATEGORIES, NOW, PERIOD, VEHICLES, type Category, type FleetItem } from './model'
import {
  PREP_HOURS,
  assignment,
  busySpan,
  clashOf,
  clashes,
  dayIndex,
  extendIssue,
  fleetLoad,
  fleetMask,
  freeOn,
  freeVehicle,
  lowestFree,
  nextOnVehicle,
  readyAt,
  rentalDays,
  vehicleCategory,
  vehiclesOf,
  type Availability,
} from './rules'
import type { FleetlineText, ZoomId } from './text'
import './tokens.css'
import './fleet.css'

/** What the board asks the demo to do (context menu). */
export type FleetAction = 'details' | 'free-vehicle' | 'extend' | 'next'

/** A stretch of days of the period, as day indexes [from, to). */
export interface DaySpan {
  readonly from: number
  readonly to: number
}

/** "R-1093" for a rental, "Windscreen repair" for a workshop slot. */
export function itemName(item: FleetItem, text: FleetlineText): string {
  return item.kind === 'rental' ? item.code : text.services[item.reason]
}

export interface FleetlineSchedulerProps {
  readonly events: FleetEvent[]
  /** The same data read back as the branch's model, for the rules and the minimap. */
  readonly items: readonly FleetItem[]
  /** Daily availability computed from `items` (one bit per vehicle and day). */
  readonly table: Availability
  readonly text: FleetlineText
  readonly common: DemoCommon
  /** BCP 47 tag for labels, and the scheduler locale id. */
  readonly tag: string
  readonly schedulerLocale: string
  /** Level on mount. Later changes go through control.zoom so the view animates from where it is. */
  readonly initialZoom: ZoomId
  /** The level on screen (side labels only show where the day level leaves room for them). */
  readonly zoom: ZoomId
  /** The category the desk filters on, or null for the whole fleet. */
  readonly category: Category | null
  /** Days with walk-in sales closed (day indexes of the period). */
  readonly closed: ReadonlySet<number>
  /** The item shown in the detail sheet: it gets the selection ring. */
  readonly selected: string | null
  /** The span shown in the availability sheet: its summary cells are marked. */
  readonly selectedSpan: DaySpan | null
  readonly history: SchedulerHistory
  readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
  /** Where the minimap mounts (the frame's foot strip). */
  readonly minimapHost: RefObject<HTMLDivElement | null>
  readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
  readonly onSelect: (id: string) => void
  readonly onSpan: (span: DaySpan) => void
  readonly onMoved: (id: string) => void
  /** A drop or a keyboard move the branch refused, with its sentence. */
  readonly onRefused: (id: string, message: string) => void
  readonly onAction: (action: FleetAction, id: string) => void
  readonly onZoomLevel: (level: ZoomId) => void
}

const ZOOM_LEVELS: SuperScheduler.ZoomLevel[] = [
  {
    id: 'days',
    properties: {
      scale: 'Day',
      cellWidth: GEOMETRY.cellWidth.days,
      timeHeaders: [{ groupBy: 'Week' }, { groupBy: 'Day' }],
    },
  },
  {
    id: 'weeks',
    properties: {
      scale: 'Week',
      cellWidth: GEOMETRY.cellWidth.weeks,
      timeHeaders: [{ groupBy: 'Month' }, { groupBy: 'Week' }],
    },
  },
]

const ZOOM_IDS: readonly ZoomId[] = ['days', 'weeks']

/** Minimap colours: amber from 75 % of the fleet busy, red from 90 %. */
const loadTone = (value: number) => (value >= 0.9 ? 'danger' : value >= 0.75 ? 'warn' : 'base')

const NOW_TICKS = parseCivil(NOW)
/**
 * Side labels need this much free time beside a bar at the day level (2.5 px per hour): room for
 * the ready time of one rental and the pickup time of the next.
 */
const SIDE_GAP = 36 * HOUR

/** "10 AM" / "10:00": the shortest clock that still reads as one. */
function shortClock(value: string, tag: string): string {
  const ticks = parseCivil(value)
  return ticks % HOUR === 0 && usesTwelveHours(tag)
    ? formatCivilCached(ticks, tag, { hour: 'numeric' })
    : formatClock(ticks, tag)
}

const escape = (value: string) => SuperScheduler.Util.escapeHtml(value)

/** Fixed icons of the board (trusted markup, classes only). */
const ICON = {
  fuel: '<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 14V3.5A1.5 1.5 0 0 1 4.5 2h4A1.5 1.5 0 0 1 10 3.5V14M2 14h9M10 6h1.5a1 1 0 0 1 1 1v4.5a1 1 0 0 0 2 0V5.5L12.5 3.5M4.5 5.5h4"/></svg>',
  bolt: '<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M9 1.5 3.5 9H8l-1 5.5L12.5 7H8z"/></svg>',
  wrench:
    '<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M10.5 2.2a3.5 3.5 0 0 0-4 4.6L2.3 11a1.4 1.4 0 0 0 2 2l4.2-4.2a3.5 3.5 0 0 0 4.6-4L11 6.9 9.1 5l2.1-2.1a3.5 3.5 0 0 0-.7-.7z"/></svg>',
  sparkle:
    '<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 2v3M8 11v3M2 8h3M11 8h3M4 4l1.6 1.6M10.4 10.4 12 12M12 4l-1.6 1.6M5.6 10.4 4 12"/></svg>',
  up: '<svg class="fl-ico" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 13V3M4 7l4-4 4 4"/></svg>',
} as const

/** The slots of a summary cell: one per vehicle of the (filtered) fleet, lit when free all day. */
function slotsHtml(busy: number, category: Category | null): string {
  let html = ''
  let previous: Category | null = null
  VEHICLES.forEach((vehicle, index) => {
    if (category !== null && vehicle.category !== category) return
    if (previous !== null && previous !== vehicle.category) html += '<b class="fl-slots__gap"></b>'
    previous = vehicle.category
    const free = (busy & (1 << index)) === 0
    html += `<i class="fl-s fl-s--${vehicle.category}${free ? ' is-free' : ''}"></i>`
  })
  return `<span class="fl-slots" aria-hidden="true">${html}</span>`
}

/** A string cache keyed by what the markup depends on: hooks run for every visible cell. */
function createCache<V>(): (key: string, build: () => V) => V {
  const map = new Map<string, V>()
  return (key, build) => {
    let value = map.get(key)
    if (value === undefined) {
      value = build()
      map.set(key, value)
    }
    return value
  }
}

/**
 * onBeforeTimeHeaderRender: stacked weekday and day number, the desk's today and the days with
 * walk-in sales closed under week ranges (day level); months over week ranges (week level).
 */
function createHeaderHook(
  tag: string,
  table: Availability,
  closed: ReadonlySet<number>,
): (args: SuperScheduler.SchedulerBeforeTimeHeaderRenderArgs) => void {
  const cache = createCache<{ readonly html: string; readonly cssClass: string }>()
  const range = new Intl.DateTimeFormat(tag, { day: 'numeric', month: 'short', timeZone: 'UTC' })
  const todayIndex = dayIndex(table, NOW_TICKS)
  return (args) => {
    const { start, end, level } = args.header
    const from = start.getTime()
    const span = end.getTime() - from
    const day = dayIndex(table, from)
    const isClosed = span <= DAY && closed.has(day)
    const entry = cache(`${level}:${from}:${span}:${isClosed ? 1 : 0}`, () => {
      if (level === 0) {
        const label =
          span > 7 * DAY
            ? formatCivilCached(from, tag, { month: 'long', year: 'numeric' })
            : range.formatRange(new Date(from), new Date(from + span - DAY))
        return { html: `<span class="fl-thg">${escape(label)}</span>`, cssClass: 'fl-thg-cell' }
      }
      if (span > DAY) {
        const label = range.formatRange(new Date(from), new Date(from + span - DAY))
        return { html: `<span class="fl-th fl-th--week">${escape(label)}</span>`, cssClass: '' }
      }
      const weekday = formatCivilCached(from, tag, { weekday: 'short' })
      const date = formatCivilCached(from, tag, { day: 'numeric' })
      const classes = ['fl-th-cell']
      if (new Date(from).getUTCDay() % 6 === 0) classes.push('fl-th-cell--we')
      if (day === todayIndex) classes.push('fl-th-cell--today')
      if (isClosed) classes.push('fl-th-cell--closed')
      return {
        html: `<span class="fl-th"><span class="fl-th__wd">${escape(weekday)}</span><span class="fl-th__d">${escape(date)}</span></span>`,
        cssClass: classes.join(' '),
      }
    })
    args.header.html = entry.html
    args.header.cssClass = entry.cssClass
  }
}

/** Narrow screens keep the plate column only (model and fuel are in the hover card and sheet). */
const NARROW = '(max-width: 640px)'
function useNarrowScreen(): boolean {
  return useSyncExternalStore(
    (notify) => {
      const query = window.matchMedia(NARROW)
      query.addEventListener('change', notify)
      return () => query.removeEventListener('change', notify)
    },
    () => window.matchMedia(NARROW).matches,
    () => false,
  )
}

export function FleetlineScheduler(props: FleetlineSchedulerProps) {
  const { events, items, table, text, common, tag, schedulerLocale, initialZoom, zoom } = props
  const { category, closed, selected, selectedSpan, history, controlRef, minimapHost } = props
  const { onEventsChange, onSelect, onSpan, onMoved, onRefused, onAction, onZoomLevel } = props

  const compact = useNarrowScreen()
  const resources = useMemo(() => toResources(text), [text])
  const clashing = useMemo(() => new Set(clashes(items)), [items])
  const refusal = useDropRefusal(onRefused)

  // Free time before and after each item on its vehicle: side labels only where they fit.
  const gaps = useMemo(() => {
    const out = new Map<string, { readonly before: number; readonly after: number }>()
    for (const vehicle of VEHICLES) {
      const own = items
        .filter((item) => item.vehicle === vehicle.id)
        .map((item) => ({ id: item.id, ...busySpan(item) }))
        .sort((a, b) => parseCivil(a.start) - parseCivil(b.start))
      own.forEach((item, index) => {
        const previous = own[index - 1]
        const next = own[index + 1]
        out.set(item.id, {
          before:
            previous === undefined
              ? Number.POSITIVE_INFINITY
              : parseCivil(item.start) - parseCivil(previous.end),
          after:
            next === undefined
              ? Number.POSITIVE_INFINITY
              : parseCivil(next.start) - parseCivil(item.end),
        })
      })
    }
    return out
  }, [items])

  // Rentals only change vehicle on this board: the keyboard moves them up and down.
  const hints = useMemo<KeyHint[]>(
    () => [
      { keys: KEYS.details, label: common.kit.details },
      { keys: KEYS.actions, label: common.kit.actions },
      { keys: [ALT_KEY, '↑↓'], label: common.kit.move },
    ],
    [common],
  )

  // Hover card: the customer and vehicle, the rental against its preparation tail, what comes
  // next, and the category rule (or the clash) that applies.
  const card = useCallback(
    (event: SuperScheduler.Event): HoverCardModel | null => {
      const item = items.find((candidate) => candidate.id === String(event.id()))
      if (item === undefined) return null
      const vehicleCategoryName = text.categories[vehicleCategory(item.vehicle)]
      const vehicle = `${plateOf(item.vehicle)} · ${vehicleCategoryName}`
      const next = nextOnVehicle(item, items)
      const nextText =
        next === undefined
          ? text.noNext
          : `${itemName(next, text)} · ${formatWhen(next.kind === 'rental' ? next.pickup : next.start, tag)}`
      if (item.kind === 'service') {
        const start = parseCivil(item.start)
        const end = parseCivil(item.end)
        return {
          id: item.id,
          tone: 'blocked',
          eyebrow: vehicle,
          title: text.services[item.reason],
          status: { label: text.status.offRoad, tone: 'warning' },
          time: {
            start,
            end,
            startLabel: formatWhen(start, tag),
            endLabel: formatWhen(end, tag),
            span: formatSpan(end - start, tag),
          },
          facts: [{ label: text.fields.next, value: nextText }],
          rule: { state: 'blocked', text: text.rules.fixed },
          hints: [{ keys: KEYS.details, label: common.kit.details }],
        }
      }
      const pickup = parseCivil(item.pickup)
      const back = parseCivil(item.return)
      const ready = parseCivil(readyAt(item))
      const clash = clashOf(item, items)
      const upgraded = assignment(item.vehicle, item.booked) === 'upgrade'
      return {
        id: item.id,
        tone: CATEGORY_TONES[item.booked],
        eyebrow: `${item.code} · ${vehicle}`,
        title: item.customer,
        status:
          clash !== undefined
            ? { label: text.card.clash, tone: 'danger' }
            : upgraded
              ? { label: text.status.upgrade, tone: 'warning' }
              : { label: text.status.ok, tone: 'success' },
        // The bar stands for pickup to ready: the empty tail is the preparation.
        time: {
          start: pickup,
          end: back,
          day: `${plural(text.hours, PREP_HOURS[item.booked], tag)} ${text.prep}`,
          startLabel: formatWhen(pickup, tag),
          endLabel: formatWhen(back, tag),
          span: plural(text.days, rentalDays(item), tag),
          window: { start: pickup, end: ready },
        },
        facts: [
          { label: text.fields.booked, value: text.categories[item.booked] },
          { label: text.fields.route, value: `${item.from} → ${item.to}` },
          { label: text.fields.ready, value: formatWhen(ready, tag) },
          { label: text.fields.next, value: nextText },
        ],
        rule:
          clash !== undefined
            ? {
                state: 'blocked',
                text: format(text.card.clashWith, { other: itemName(clash, text) }),
              }
            : { state: 'ok', text: text.rules.wrongCategory[item.booked] },
        hints,
      }
    },
    [items, text, common, tag, hints],
  )
  const { eventHover, closeHover, suppressHover } = useEventHover(card)

  // Drag verdict: from which plate to which, and the branch's sentence when it refuses; a free
  // upgrade is allowed but flagged, since the branch gives away a bigger car.
  const dragCard = useMemo(
    () =>
      createDragCard({
        tag,
        common,
        rowName: (id) =>
          isVehicleId(id) ? `${plateOf(id)} · ${text.categories[vehicleCategory(id)]}` : null,
        warn: (info) => {
          const rental = items.find((candidate) => candidate.id === String(info.eventId))
          if (rental?.kind !== 'rental' || info.resource === null || !isVehicleId(info.resource))
            return null
          return assignment(info.resource, rental.booked) === 'upgrade'
            ? format(text.card.upgradeWarn, {
                category: text.categories[vehicleCategory(info.resource)],
              })
            : null
        },
      }),
    [tag, common, text, items],
  )

  // Context menu: rebuilt when the plan changes, so its labels name the real vehicle. It wears the
  // product's skin on <body> through its theme.
  const contextMenu = useMemo(
    () =>
      createEventMenu({
        theme: skinMenuTheme('fleet-rentals'),
        title: (event) => {
          const item = items.find((candidate) => candidate.id === String(event.id()))
          return format(common.kit.menuTitle, {
            name: item === undefined ? String(event.id()) : itemName(item, text),
          })
        },
        onOpenChange: (open) => suppressHover(open),
        entries: (event) => {
          const id = String(event.id())
          const item = items.find((candidate) => candidate.id === id)
          if (item === undefined) return []
          const next = nextOnVehicle(item, items)
          const details = {
            label: common.kit.openDetails,
            icon: 'details',
            keys: KEYS.details,
            run: () => onAction('details', id),
          } as const
          const go = {
            label:
              next === undefined
                ? text.noNext
                : format(text.actions.next, {
                    plate: plateOf(item.vehicle),
                    name: itemName(next, text),
                  }),
            icon: 'focus',
            disabled: next === undefined,
            run: () => onAction('next', id),
          } as const
          if (item.kind === 'service') return [details, 'separator', go]
          const free = freeVehicle(item, items)
          return [
            details,
            {
              label:
                free === null
                  ? text.actions.noFreeVehicle
                  : format(text.actions.freeVehicle, { plate: plateOf(free) }),
              icon: 'handover',
              primary: free !== null && clashing.has(id),
              disabled: free === null,
              run: () => onAction('free-vehicle', id),
            },
            {
              label: text.extend.action,
              icon: 'after',
              disabled: extendIssue(item, items) !== null,
              run: () => onAction('extend', id),
            },
            'separator',
            go,
          ]
        },
      }),
    [items, clashing, common, text, onAction, suppressHover],
  )

  // Time headers: stacked weekday and day number, the desk's today, closed days; week ranges under
  // the day level, months and week ranges at the week level.
  const headerHook = useMemo(() => createHeaderHook(tag, table, closed), [tag, table, closed])

  // Summary cells: cached HTML per (free, busy bits, filter, state) key.
  const summaryHtml = useMemo(() => createCache<string>(), [])

  const config = useMemo<SchedulerRenderProps>(() => {
    const mask = fleetMask(category)
    const count = vehiclesOf(category).length
    const refusalOf = (
      data: object,
      resource: SuperScheduler.ResourceId,
      conflicts: number,
    ): string | null => {
      const fields = readFleetFields(data)
      if (fields === null) return null
      if (fields.kind === 'service') return text.rules.fixed
      if (!isVehicleId(resource)) return text.rules.categoryRow
      if (assignment(resource, fields.booked) === null)
        return text.rules.wrongCategory[fields.booked]
      return conflicts > 0 ? text.rules.busy : null
    }
    const inSpan = (from: number, to: number) =>
      selectedSpan !== null && from < selectedSpan.to && selectedSpan.from < to

    return {
      locale: schedulerLocale,
      cssClass: skinClass('fleet-rentals'),
      startDate: PERIOD.start,
      days: PERIOD.days,
      zoomLevels: ZOOM_LEVELS,
      zoom: initialZoom,
      zoomPosition: 'left',
      // The branch plans Monday-to-Sunday weeks, whatever the page language.
      weekStarts: 1,
      height: '100%',
      treeEnabled: true,
      // Category rows group vehicles; nothing is rented to a category row.
      treePreventParentUsage: true,
      rowHeaderColumns: [
        { title: text.columns.vehicle, width: GEOMETRY.columns.vehicle, sort: 'plate' },
        {
          title: text.columns.model,
          width: GEOMETRY.columns.model,
          sort: 'model',
          hidden: compact,
        },
        {
          title: text.columns.energy,
          width: GEOMETRY.columns.energy,
          sort: 'energy',
          hidden: compact,
        },
      ],
      // Category rows span the three columns; sorting reorders vehicles inside their category.
      rowHeaderColumnsMergeParents: true,
      rowSortingMode: 'LeavesOnly',
      rowHeaderResizable: true,
      rowHeaderWidthAutoFit: false,
      rowHeaderWidthMax: 460,
      eventHeight: GEOMETRY.eventHeight,
      rowMarginTop: GEOMETRY.rowMargin,
      rowMarginBottom: GEOMETRY.rowMargin,
      treeIndent: 10,
      // Pickups and returns keep their hour: bars are drawn at exact times, not whole days.
      useEventBoxes: 'Never',
      allowEventOverlap: false,
      conflictHighlight: true,
      durationBarVisible: false,
      // Capsules keep their areas down to 36 px (the default drops them below 80 px).
      lod: { eventFull: 36, eventText: 20 },
      eventHtmlLeftMargin: 5,
      eventHtmlRightMargin: 5,
      showToolTip: false,
      keyboardEnabled: true,
      keyboardTarget: 'component',
      keyboardMode: 'Full',
      // The desk's "now" (the story's Monday morning), as a line across every row.
      separators: [{ location: NOW, layer: 'AboveEvents', width: 2, cssClass: 'fl-now' }],
      history,
      controlRef,
      onEventsChange,

      onBeforeTimeHeaderRender: headerHook,

      // Category and summary rows hold no bars: their own heights, without the lane margins.
      onBeforeResHeaderRender: (args) => {
        const resource = args.resource
        const id = resource.id
        if (id === SUMMARY_ROW || (typeof id === 'string' && id.startsWith('cat-'))) {
          resource.minHeight = id === SUMMARY_ROW ? SUMMARY_HEIGHT : GEOMETRY.groupHeight
          resource.marginTop = 0
          resource.marginBottom = 0
        }
      },

      onBeforeRowHeaderRender: (args) => {
        const row = args.row
        const id = row.id
        const [first, second, third] = row.columns
        if (id === SUMMARY_ROW) {
          row.cssClass = 'fl-rh fl-rh--sum'
          const meta = `<span class="fl-rh-sum__m">${escape(zoom === 'days' ? text.summary.meta : text.summary.lowest)}</span>`
          if (first !== undefined)
            first.html = `<span class="fl-rh-sum"><span class="fl-rh-sum__t">${escape(text.summary.label)}</span>${compact ? meta : ''}</span>`
          if (second !== undefined) second.html = meta
          // Filtered, the row counts one category: its name says so.
          if (third !== undefined)
            third.html =
              category === null
                ? ''
                : `<span class="fl-rh-sum__scope fl-cat--${category}"><i class="fl-dot" aria-hidden="true"></i>${escape(text.categories[category])}</span>`
          return
        }
        if (typeof id === 'string' && id.startsWith('cat-')) {
          const group = CATEGORIES.find((candidate) => `cat-${candidate}` === id)
          if (group === undefined) return
          const total = VEHICLES.filter((vehicle) => vehicle.category === group).length
          const free = freeOn(table, dayIndex(table, NOW_TICKS), fleetMask(group))
          row.cssClass = `fl-rh fl-rh--cat fl-cat--${group}`
          const html = `<span class="fl-rh-cat"><i class="fl-dot" aria-hidden="true"></i><span class="fl-rh-cat__name">${escape(text.categories[group])}</span><span class="fl-rh-cat__free">${escape(format(text.group, { free, count: total }))}</span></span>`
          // Merged across the columns (rowHeaderColumnsMergeParents): the row's own html shows.
          row.html = html
          if (first !== undefined) first.html = html
          return
        }
        if (!isVehicleId(id)) return
        const vehicle = VEHICLES.find((candidate) => candidate.id === id)
        if (vehicle === undefined) return
        row.cssClass = `fl-rh fl-cat--${vehicle.category}`
        if (first !== undefined)
          first.html = `<span class="fl-plate" title="${escape(vehicle.model)}"><span class="fl-plate__eu" aria-hidden="true"></span><span class="fl-plate__txt">${escape(vehicle.plate)}</span></span>`
        if (second !== undefined)
          second.html = `<span class="fl-model"><span class="fl-model__name">${escape(vehicle.model)}</span><span class="fl-model__spec">${escape(text.specs[vehicle.id])}</span></span>`
        if (third !== undefined) {
          const electric = vehicle.category === 'electric'
          const low = vehicle.energy < 30
          const label = `${electric ? text.energy.charge : text.energy.fuel} ${vehicle.energy}%${low ? ` · ${text.energy.low}` : ''}`
          third.html = `<span class="fl-energy${low ? ' fl-energy--low' : ''}" title="${escape(label)}">${electric ? ICON.bolt : ICON.fuel}<span class="fl-meter fl-meter--${Math.round(vehicle.energy / 10)}" aria-hidden="true"><i></i></span><span class="fl-energy__pct">${vehicle.energy}%</span></span>`
        }
      },

      onRowFilter: (args) => {
        const param = args.filterParam
        const id = String(args.row.id)
        if (typeof param !== 'string' || id === SUMMARY_ROW) return
        if (id.startsWith('cat-')) args.visible = id === `cat-${param}`
        else if (isVehicleId(id)) args.visible = vehicleCategory(id) === param
      },

      onBeforeCellRender: (args) => {
        const cell = args.cell
        if (cell.isParent) {
          cell.properties.cssClass = 'fl-groupcell'
          return
        }
        if (cell.resource !== SUMMARY_ROW) return
        const from = dayIndex(table, cell.start.getTime())
        const to = dayIndex(table, cell.end.getTime())
        const single = to - from <= 1
        const lowest = lowestFree(table, from, to, mask)
        const busy = table.busy[lowest.day] ?? 0
        const closedHere = single
          ? closed.has(from)
          : Array.from({ length: to - from }, (_, index) => from + index).some((day) =>
              closed.has(day),
            )
        const level = lowest.free === 0 ? 'out' : lowest.free <= 1 ? 'low' : 'ok'
        const marked = inSpan(from, to)
        const iso = new Date(cell.start.getTime()).toISOString().slice(0, 10)
        const key = `${iso}|${single ? 1 : 0}|${lowest.free}|${busy}|${category ?? ''}|${closedHere ? 1 : 0}`
        const html = summaryHtml(key, () => {
          const caption = closedHere
            ? `<span class="fl-sum__tag fl-sum__tag--closed">${escape(text.summary.closed)}</span>`
            : ''
          return `<span class="fl-sum fl-sum--${level}" data-span="${iso}"><span class="fl-sum__top"><span class="fl-sum__n">${lowest.free}</span>${caption}</span>${slotsHtml(busy, category)}</span>`
        })
        cell.properties.cssClass = `fl-sumcell fl-sumcell--${level}${closedHere ? ' fl-sumcell--closed' : ''}${marked ? ' fl-sumcell--sel' : ''}`
        // The whole cell opens its availability: an area holds the figures and owns the click
        // (the row's cells are disabled).
        cell.properties.areas = [
          {
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            action: 'None',
            html,
            cssClass: 'fl-sum-hit',
            toolTip: format(text.summary.tip, { free: lowest.free, count }),
            onClick: () => onSpan({ from, to }),
          },
        ]
      },

      onBeforeEventRender: (args) => {
        const data = args.data
        const fields = readFleetFields(data)
        if (fields === null) return
        const id = String(data.id)
        const classes = ['fl-ev']
        if (fields.kind === 'service') {
          classes.push('fl-ev--svc')
          const until = formatWhen(civilOf(data.end), tag)
          data.html = `<span class="fl-card"><span class="fl-card__l1">${ICON.wrench}<span class="fl-card__who">${escape(text.services[fields.reason])}</span></span><span class="fl-card__l2">${escape(`${text.fields.until} ${until}`)}</span></span>`
          data.areas = [{ left: 0, right: 0, top: 0, bottom: 0, cssClass: 'fl-cap fl-cap--svc' }]
        } else {
          const resource = data.resource
          const upgraded =
            resource !== undefined &&
            isVehicleId(resource) &&
            assignment(resource, fields.booked) === 'upgrade'
          const pickup = civilOf(data.start)
          const badge = upgraded
            ? `<span class="fl-upg">${ICON.up}${escape(text.upgrade)}</span>`
            : ''
          const route =
            fields.from === fields.to
              ? `<span class="fl-route">${fields.from}</span>`
              : `<span class="fl-route fl-route--oneway">${fields.from}<i>→</i>${fields.to}</span>`
          data.html = `<span class="fl-card"><span class="fl-card__l1"><span class="fl-card__who">${escape(fields.customer)}</span>${badge}</span><span class="fl-card__l2">${route}<span class="fl-card__code">${escape(fields.code)}</span></span></span>`
          data.ariaLabel = `${fields.code}, ${fields.customer}, ${plural(text.days, rentalDays({ pickup, return: fields.returnAt }), tag)}`
          // The capsule is the rental (pickup to return); the tail after it is the preparation,
          // both anchored to their times, so they follow zoom and moves.
          const electric = fields.booked === 'electric'
          data.areas = [
            { start: pickup, end: fields.returnAt, top: 0, bottom: 0, cssClass: 'fl-cap' },
            {
              start: fields.returnAt,
              end: data.end,
              top: 7,
              bottom: 7,
              cssClass: `fl-prep${electric ? ' fl-prep--charge' : ''}`,
              // Charging or cleaning, where the day level leaves room for the icon.
              ...(zoom === 'days' ? { html: electric ? ICON.bolt : ICON.sparkle } : {}),
            },
          ]
          if (upgraded) classes.push('fl-ev--upg')
          if (clashing.has(id)) classes.push('fl-ev--clash')
          // Pickup and ready times beside the bar, where the day level leaves room for them.
          const gap = gaps.get(id)
          if (zoom === 'days' && gap !== undefined) {
            const ready = civilOf(data.end)
            if (gap.before >= SIDE_GAP)
              data.htmlLeft = `<span class="fl-side fl-side--l" title="${escape(format(text.card.pickupAt, { time: formatClock(pickup, tag) }))}">${escape(shortClock(pickup, tag))}</span>`
            if (gap.after >= SIDE_GAP)
              data.htmlRight = `<span class="fl-side fl-side--r" title="${escape(format(text.card.readyAt, { time: formatClock(ready, tag) }))}">${escape(shortClock(ready, tag))}</span>`
          }
        }
        classes.push(`fl-tone--${fields.kind === 'service' ? 'svc' : fields.booked}`)
        if (id === selected) classes.push('ss-ev--selected')
        data.cssClass = classes.join(' ')
      },

      // Only the row can change (moveHDisabled): check the category; the library checks overlaps,
      // and its reason is kept so a refused release is announced too.
      onEventMoving: (args) => {
        const id = String(args.e.id())
        const message = refusalOf(args.e.data, args.resource, args.conflicts.length)
        refusal.track(id, message)
        if (message !== null && message !== text.rules.busy) {
          args.allowed = false
          args.message = message
        }
      },

      // Final check before the commit (also covers keyboard moves).
      onEventMove: (args) => {
        const id = String(args.e.id())
        const message = refusalOf(args.e.data, args.newResource, 0)
        if (message !== null) {
          args.preventDefault()
          refusal.clear()
          onRefused(id, message)
        }
      },

      onEventMoved: (args) => {
        refusal.clear()
        onMoved(String(args.e.id()))
      },
      // A click (or Enter) docks the item into the detail sheet; the hover card steps aside.
      onEventClick: (args) => {
        closeHover()
        onSelect(String(args.e.id()))
      },

      onZoom: (args) => {
        if (args.phase !== 'end') return
        const level = ZOOM_IDS[args.level]
        if (level !== undefined) onZoomLevel(level)
      },
    }
  }, [
    category,
    clashing,
    closeHover,
    closed,
    compact,
    controlRef,
    gaps,
    headerHook,
    history,
    initialZoom,
    onEventsChange,
    onMoved,
    onRefused,
    onSelect,
    onSpan,
    onZoomLevel,
    refusal,
    schedulerLocale,
    selected,
    selectedSpan,
    summaryHtml,
    table,
    tag,
    text,
    zoom,
  ])

  // The category filter runs through the control's own row filter (rows.filter + onRowFilter).
  useEffect(() => {
    const control = controlRef.current
    if (control === null || control.disposed()) return
    control.rows.filter(category)
  }, [controlRef, category])

  // The minimap needs the mounted control; it goes with it.
  const minimap = useRef<Minimap | null>(null)
  const latest = useRef({ items, category })
  useEffect(() => {
    latest.current = { items, category }
    minimap.current?.refresh()
  }, [items, category])

  useEffect(() => {
    const control = controlRef.current
    const host = minimapHost.current
    if (control === null || host === null) return
    const date = (value: SuperScheduler.Date) =>
      formatCivil(value.getTime(), tag, { day: 'numeric', month: 'short' })
    const widget = createMinimap(control, host, {
      height: 28,
      peak: 'absolute',
      max: 1,
      // One value per bucket: the share of the fleet (or the filtered category) that is out, in
      // preparation or in the workshop.
      series: (range) => {
        const values = new Float32Array(range.buckets)
        const start = range.start.getTime()
        const { items: current, category: filter } = latest.current
        for (let index = 0; index < values.length; index++) {
          const from = start + index * range.bucketMs
          values[index] = fleetLoad(current, from, from + range.bucketMs, filter)
        }
        return values
      },
      tone: loadTone,
      marks: { today: false, months: true, past: false },
      labels: {
        label: text.minimap.label,
        zoom: text.minimap.zoom,
        valueText: (start, end) => format(text.minimap.range, { from: date(start), to: date(end) }),
      },
    })
    minimap.current = widget
    return () => {
      widget.dispose()
      minimap.current = null
    }
  }, [controlRef, minimapHost, tag, text])

  return (
    <SuperSchedulerComponent
      {...config}
      resources={resources}
      events={events}
      eventHover={eventHover}
      dragCard={dragCard}
      contextMenu={contextMenu}
    />
  )
}

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