Zum Inhalt springen

Planung von Fertigungsaufträgen

Die Wartung wurde vorgezogen. Verschieben Sie den Auftrag und halten Sie die Arbeitsfolge ein.

  • Fertigung
  • Forge
  • Summenzeilen
  • Fortschrittsbalken
  • Abhängigkeiten
  • Minimap
  • Zoom-Regler
  • Fadenkreuz
  • Gesperrte Zeiten
  • Theming
  • Demo mit synthetischen Daten
Quellcode laden.zip

Aufgabe

0 von 3 Schritten erledigt

Dienstag, 06:20 Uhr, Frühschicht: Der Spindelservice der CNC-Fräse 2 wurde vorgezogen und läuft gerade, genau über dem für 08:00 Uhr geplanten Fräsgang von WO-4471.

  1. Holen Sie „WO-4471 · Fräsen“ aus dem Spindelservice der CNC-Fräse 2. — Offen

    Ziehen Sie den Arbeitsgang auf 12:00 Uhr an derselben Maschine, wenn der Service endet. Schraffierte Zellen lehnen ab, und die Drehmaschine ist keine Fräse.

  2. Verschieben Sie den roten Drehgang, sodass er nach dem Fräsen beginnt. — Offen

    Legen Sie „WO-4471 · Drehen“ um 17:00 Uhr auf der Drehmaschine ab. Die rote Verknüpfung wird grau, sobald die Reihenfolge stimmt.

  3. Sehen Sie sich mit dem Auslastungsstreifen den Donnerstag an. — Offen

    Ziehen Sie das hervorgehobene Fenster im Streifen unter der Tafel nach rechts, oder fokussieren Sie es und nutzen Sie die Pfeiltasten.

Etwa 30 Sekunden. Erledigte Schritte werden abgehakt.

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

Forge
ZerspanungCNC-Fräse 151%CNC-Fräse 257%Drehmaschine59%MontageZelle A56%Zelle B55%EndbearbeitungLackierkabine60%Prüflabor39%OP10 WO-4471 GetriebegehäuseFräsen · 120 StückOP10 WO-4475 VentilkörperFräsen · 80 StückOP10 WO-4477 AbdeckplatteFräsen · 300 StückOP10 WO-4482 LagerdeckelFräsen · 60 StückOP20 WO-4471 GetriebegehäuseDrehen · 120 StückOP20 WO-4475 VentilkörperDrehen · 80 StückOP20 WO-4476 AntriebswelleDrehen · 90 StückOP20 WO-4478 MotorflanschDrehen · 250 StückOP20 WO-4479 KupplungsnabeDrehen · 180 StückOP30 WO-4471 GetriebegehäuseMontage · 120 StückOP30 WO-4473 HydraulikblockMontage · 60 StückOP30 WO-4476 AntriebswelleMontage · 90 StückOP50 WO-4472 PumpenhalterPrüfen · 400 StückOP50 WO-4473 HydraulikblockPrüfen · 60 StückOP30 WO-4474 SpindelhülsePrüfen · 200 StückOP50 WO-4476 AntriebswellePrüfen · 90 StückOP40 WO-4477 AbdeckplattePrüfen · 300 StückOP30 WO-4480 SchaltschrankPrüfen · 20 StückOP40 WO-4472 PumpenhalterLackieren · 400 StückOP40 WO-4473 HydraulikblockLackieren · 60 StückOP40 WO-4476 AntriebswelleLackieren · 90 StückOP30 WO-4477 AbdeckplatteLackieren · 300 StückOP20 WO-4480 SchaltschrankLackieren · 20 StückOP20 WO-4474 SpindelhülseMontage · 200 StückOP20 WO-4477 AbdeckplatteMontage · 300 StückOP30 WO-4478 MotorflanschMontage · 250 StückOP10 WO-4478 MotorflanschFräsen · 250 StückOP10 WO-4479 KupplungsnabeFräsen · 180 StückOP10 WO-4481 BremsträgerFräsen · 75 Stück71%43%57%67%67%83%83%100%100%86%57%43%43%57%57%57%43%57%71%71%43%33%50%50%50%67%67%57%Linienlastpro StundeDienstag, 20. OktoberMittwoch, 21. Oktober03:0004:0005:0006:0007:0008:0009:0010:0011:0012:0013:0014:0015:0016:0017:0018:0019:0020:0021:0022:0023:0000:0001:0002:0003:0004:0005:0006: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.

Forge ist ein fiktiver Lohnfertiger für Zerspanung: zwei CNC-Fräsen und eine Drehmaschine, zwei Montagezellen, eine Lackierkabine und ein Prüflabor, betrieben von vier Teams in drei Schichten. Jeder Auftrag folgt einem Arbeitsplan (Fräsen, Drehen, Montage, Lackieren, Prüfen), und kein Arbeitsgang darf beginnen, bevor der vorherige endet.

Wartung wartet nicht auf den Plan. Wird der Spindelservice der CNC-Fräse 2 vorgezogen, muss der dort geplante Fräsgang weichen, und was im Arbeitsplan folgt, beginnt womöglich zu früh. Eine Planungstafel muss unmögliche Verschiebungen ablehnen, Begonnenes an seinem Platz lassen, Arbeitsgänge außerhalb der Reihenfolge zeigen und sichtbar machen, wo die Woche schon voll ist.

Was Sie tun werden

Sie verschieben einen Fräsgang aus einem Wartungsfenster, bringen den Drehgang zurück in die Reihenfolge und springen über den Auslastungsstreifen zur nächsten Wartung am Donnerstag.

Wo die Bibliothek endet und Ihre Anwendung beginnt.

SuperScheduler liefert

  • Ein Baum aus Linien und Maschinen mit rowHeaderColumns (Maschine, OEE, Auslastungsbalken) und eine fixierte Zeile oben, deren Bereiche aus onBeforeCellRender die Linienauslastung pro Stunde zeichnen.
  • Drei Kopfzeilen: Tag, Schichtbänder als Bereiche aus onBeforeTimeHeaderRender und Stunden; separators bei jedem Schichtwechsel und an der Werksuhr, dazu crosshairType: 'Full'.
  • Zweizeilige Karten aus onBeforeEventRender: ein zeitverankerter Rüstbereich, Fortschritt mit durationBarMode: 'PercentComplete' und Hover-Aktionen als Bereiche mit visibility: 'Hover'.
  • Deaktivierte Wartungszellen, Vetos pro Frame in onEventMoving mit der Drag-Karte, conflictHighlight und Ende-Anfang-Verknüpfungen mit linkShape: 'RightAngled'.
  • rows.filter für die Linienauswahl, createZoomSlider aus super-scheduler/zoom-ui, die Minimap aus super-scheduler/minimap und der Viewport-Zustand aus super-scheduler/hooks.

Der Code dieses Beispiels entscheidet

  • Welcher Maschinentyp welchen Arbeitsgang ausführt, die Schichten, der Wartungskalender und die Werksuhr, die Begonnenes sperrt.
  • Der Arbeitsplan jedes Auftrags und die Prüfung, die einen zu früh beginnenden Arbeitsgang markiert.
  • Jede Kennzahl: Linienauslastung pro Stunde, Maschinenauslastung und geplante OEE aus den Standardraten, verspätete Aufträge, markierte Arbeitsgänge.
  • Feste Laufzeiten (keine Änderung der Dauer), das Detailpanel, die Aufgabe und alle Texte.

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: Spalten im Zeilenkopf, Schichtkopf, Auslastungszeile, Karten mit Rüstbereich und Fortschritt, Ablehnungen, Verknüpfungen, Zoom-Regler und Auslastungsstreifen.

/**
 * Forge shop-floor board: a frozen line-load row over production lines and their machines, one
 * week of three shifts, each work order's operations linked in sequence, and a plant-load strip
 * underneath.
 *
 * Library: tree rows with rowHeaderColumns, a frozen summary row painted by onBeforeCellRender,
 * three time header rows (day, shift bands as header areas, hours), separators, the crosshair,
 * two-line cards with time-anchored setup areas, PercentComplete progress bars and hover actions,
 * disabled cells, right-angled finish-to-start links, rows.filter, the zoom slider
 * (super-scheduler/zoom-ui), the minimap (super-scheduler/minimap), viewport state
 * (super-scheduler/hooks), the event hover card and the drag card (super-scheduler/react-render),
 * conflict highlighting and a context menu. Application: which machine runs which operation, the
 * plant clock, maintenance windows, what counts as out of sequence, due dates and every figure.
 * Those rules live in ./rules.
 */
import { useCallback, useEffect, useMemo, useRef, type RefObject } from 'react'
import { SuperScheduler } from 'super-scheduler'
import type { SchedulerEventsChangeArgs } from 'super-scheduler'
import type { SchedulerHistory } from 'super-scheduler/history'
import { subscribeScheduler } from 'super-scheduler/hooks'
import { createMinimap, type Minimap } from 'super-scheduler/minimap'
import { SuperSchedulerComponent, type SchedulerRenderProps } from 'super-scheduler/react-render'
import { createZoomSlider } from 'super-scheduler/zoom-ui'
import { format, plural } from '~/i18n/format'
import { DAY, HOUR, civil, formatCivil, parseCivil } from '../../scheduler/civil'
import { headerLabel } from '../../scheduler/header-format'
import { createEventMenu } from '../kit/context-menu'
import { formatClock, formatDay, formatSpan, formatWhen } from '../kit/format'
import { defaultHints, 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 {
  LOAD_ROW,
  civilOf,
  isOperationEvent,
  lineOf,
  machineOf,
  opCode,
  readOperationFields,
  toResources,
  type OperationEvent,
} from './adapter'
import {
  BUSINESS_NOW,
  INITIAL_VIEW_START,
  MACHINES,
  MAINTENANCE,
  ORDERS,
  SHIFTS,
  WEEK,
  type LineId,
  type Operation,
} from './model'
import {
  LOAD_DANGER,
  LOAD_WARN,
  dueSlack,
  hasStarted,
  loadLevel,
  loadSeries,
  maintenanceAt,
  nextValidSlot,
  phaseAt,
  plantLoad,
  progressAt,
  setupEnd,
  shiftAt,
  slotRefusal,
  type PlantFigures,
  type Refusal,
  type SequenceIssue,
} from './rules'
import {
  COLUMN_WIDTHS,
  COMPACT_ROW_HEADER,
  EVENT_HEIGHT,
  HEADER_HEIGHTS,
  HOUR_WIDTH,
  LINE_ROW_HEIGHT,
  LOAD_ROW_HEIGHT,
  ROW_MARGIN,
} from './geometry'
import type { ForgeText } from './text'
import 'super-scheduler/styles.css'
import '../../scheduler/skin.css'
import './tokens.css'
import './forge.css'

const SLUG = 'manufacturing-orders'
const NOW = parseCivil(BUSINESS_NOW)
const WEEK_RANGE = { from: `${WEEK.start}T00:00:00`, to: `${WEEK.end}T00:00:00` } as const

/** The zoom slider's bounds and marks (week, shifts, hours), in pixels per hour. */
const ZOOM = { min: 8, max: 96, detents: [9, 22, HOUR_WIDTH] } as const

/** What the board asks the demo to do (context menu, hover actions). */
export type OperationAction = 'details' | 'next-slot' | 'next-operation'

/** The routing-preserving slot an operation could move to (menu and sheet share it). */
export function nextSlotOf(
  operation: Operation,
  operations: readonly Operation[],
): { start: string; end: string } | null {
  const machine = machineOf(operation.machine)
  if (machine === null || hasStarted(operation, NOW)) return null
  return nextValidSlot(operation, machine, MAINTENANCE, operations, WEEK_RANGE, BUSINESS_NOW)
}

export interface ForgeSchedulerProps {
  readonly events: OperationEvent[]
  /** The same operations in model form: figures and the load strip are computed from them. */
  readonly operations: readonly Operation[]
  readonly figures: PlantFigures
  readonly issues: readonly SequenceIssue[]
  /** Operations that sit on a maintenance window. */
  readonly conflicts: readonly string[]
  /** The line selector (null: all lines). */
  readonly line: LineId | null
  /** Narrow stage: the row header keeps the machine column only. */
  readonly compact: boolean
  readonly text: ForgeText
  readonly common: DemoCommon
  /** BCP 47 tag for labels, and the scheduler locale id. */
  readonly tag: string
  readonly schedulerLocale: string
  /** The operation shown in the detail sheet: it gets the selection ring. */
  readonly selected: string | null
  readonly history: SchedulerHistory
  readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
  /** Where the product bar keeps the zoom slider and the footer the load strip. */
  readonly zoomHost: RefObject<HTMLDivElement | null>
  readonly stripHost: RefObject<HTMLDivElement | null>
  readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
  readonly onSelect: (id: string) => void
  readonly onMoved: (id: string) => void
  readonly onRefused: (id: string, refusal: Refusal) => void
  readonly onAction: (action: OperationAction, id: string) => void
  /** The visible range once scrolling settles (civil ISO strings). */
  readonly onViewport: (start: string, end: string) => void
}

/** Every operation the control holds right now, in the shape the rules read. */
function operationsIn(
  control: SuperScheduler.Scheduler,
): Pick<Operation, 'id' | 'machine' | 'start' | 'end'>[] {
  return control.events.list.flatMap((event) => {
    const machine = event.resource === undefined ? null : machineOf(event.resource)
    if (machine === null || !isOperationEvent(event)) return []
    return [
      {
        id: String(event.id),
        machine: machine.id,
        start: civilOf(event.start),
        end: civilOf(event.end),
      },
    ]
  })
}

/** Checks one proposed slot of an operation against the plant's rules. */
function refusalFor(
  control: SuperScheduler.Scheduler | null,
  data: object,
  id: string,
  resource: SuperScheduler.ResourceId,
  start: SuperScheduler.Date,
  end: SuperScheduler.Date,
): Refusal | null {
  const fields = readOperationFields(data)
  const machine = machineOf(resource)
  if (control === null || fields === null || machine === null) return null
  return slotRefusal(
    { id, kind: fields.kind, start: civil(start.ticks), end: civil(end.ticks) },
    machine,
    MAINTENANCE,
    operationsIn(control),
    BUSINESS_NOW,
  )
}

/**
 * Shift segments inside `[from, to)`, day by day: the night shift shows on both ends of each day.
 * A header cell is one day, or several when the level of detail coarsens the header (zoomed out).
 */
function shiftSegments(
  from: number,
  to: number,
): { id: (typeof SHIFTS)[number]['id']; from: number; to: number }[] {
  const segments: { id: (typeof SHIFTS)[number]['id']; from: number; to: number }[] = []
  for (let day = from - (((from % DAY) + DAY) % DAY); day < to; day += DAY) {
    for (const shift of SHIFTS) {
      for (const offset of [0, -24]) {
        const start = Math.max(from, day + Math.max(0, shift.start + offset) * HOUR)
        const end = Math.min(to, day + Math.min(24, shift.end + offset) * HOUR)
        if (end > start) segments.push({ id: shift.id, from: start, to: end })
      }
    }
  }
  return segments.sort((a, b) => a.from - b.from)
}

const percent = (value: number) => `${Math.round(value * 10000) / 100}%`

/**
 * Brings one order's cards and links forward (`fg-traced`) and lets the rest step back, or clears
 * it. Class writes on hover enter and leave only, never per pointer frame.
 */
function trace(root: HTMLElement | null, order: string | null): void {
  if (root === null) return
  for (const element of root.querySelectorAll('.fg-traced')) element.classList.remove('fg-traced')
  root.toggleAttribute('data-tracing', order !== null)
  if (order === null) return
  for (const element of root.querySelectorAll(`.fg-o-${order}`)) element.classList.add('fg-traced')
}

// Small glyphs drawn in cards and hover actions (trusted markup, classes only).
const GLYPH = {
  details:
    '<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="2" y="2" width="12" height="12" rx="2"/><path d="M10 2v12M4.5 6h3M4.5 9h3"/></svg>',
  slot: '<svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="9" r="5"/><path d="M7 6.5V9l1.6 1.2M5.5 2h3M13 5.5l1.8 1.8L13 9"/></svg>',
  lock: '<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="3.5" y="7" width="9" height="6.5" rx="1.2"/><path d="M5.5 7V5.2a2.5 2.5 0 0 1 5 0V7"/></svg>',
  done: '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3.5 8.5 3 3 6-7"/></svg>',
} as const

export function ForgeScheduler(props: ForgeSchedulerProps) {
  const {
    events,
    operations,
    figures,
    issues,
    conflicts,
    line,
    compact,
    text,
    common,
    tag,
    schedulerLocale,
    selected,
    history,
    controlRef,
    zoomHost,
    stripHost,
  } = props
  const { onEventsChange, onSelect, onMoved, onRefused, onAction, onViewport } = props

  const resources = useMemo(() => toResources(text), [text])
  const refusal = useDropRefusal(onRefused)
  const minimap = useRef<Minimap | null>(null)
  const board = useRef<HTMLDivElement>(null)
  // Hover actions call the latest handler without rebuilding every card's areas.
  const action = useRef(onAction)
  useEffect(() => {
    action.current = onAction
  }, [onAction])
  const name = useCallback(
    (operation: Pick<Operation, 'order' | 'kind'>) =>
      `${operation.order} · ${text.operations[operation.kind]}`,
    [text],
  )

  // Hover card: the part, the machine, the routing on both sides, the due date and the rule.
  const card = useCallback(
    (event: SuperScheduler.Event): HoverCardModel | null => {
      const operation = operations.find((candidate) => candidate.id === String(event.id()))
      const machine = operation === undefined ? null : machineOf(operation.machine)
      const order = ORDERS.find((candidate) => candidate.id === operation?.order)
      if (operation === undefined || machine === null || order === undefined) return null
      const previous = operations.find((candidate) => candidate.id === operation.after)
      const next = operations.find((candidate) => candidate.after === operation.id)
      const late = issues.some((issue) => issue.operation === operation.id)
      const window = maintenanceAt(MAINTENANCE, machine.id, operation.start, operation.end)
      const phase = phaseAt(operation, NOW)
      const start = parseCivil(operation.start)
      const end = parseCivil(operation.end)
      const slack = dueSlack(order, operations)
      const day = start - (start % DAY)
      const setup = setupEnd(operation) - start
      return {
        id: operation.id,
        tone: 'slate',
        eyebrow: `${opCode(operation.step)} · ${text.parts[operation.order]} · ${plural(text.pieces, order.quantity, tag)}`,
        title: name(operation),
        status:
          window !== null
            ? { label: text.card.onMaintenance, tone: 'danger' }
            : late
              ? { label: text.card.outOfSequence, tone: 'danger' }
              : phase === 'planned'
                ? previous === undefined
                  ? { label: text.phases.planned }
                  : { label: text.status.ready, tone: 'success' }
                : { label: text.phases[phase], tone: phase === 'done' ? undefined : 'success' },
        time: {
          start,
          end,
          day: formatDay(start, tag),
          startLabel: formatClock(start, tag),
          endLabel: formatClock(end, tag),
          span: formatSpan(end - start, tag),
          window: { start: day, end: day + DAY },
        },
        facts: [
          {
            label: text.fields.machine,
            value: `${text.machines[machine.id]} · ${machine.code}`,
          },
          { label: text.fields.setup, value: formatSpan(setup, tag) },
          { label: text.fields.follows, value: previous === undefined ? '—' : name(previous) },
          { label: text.card.next, value: next === undefined ? '—' : name(next) },
          {
            label: text.card.due,
            value:
              slack === null
                ? formatWhen(order.due, tag)
                : `${formatWhen(order.due, tag)} · ${format(slack >= 0 ? text.card.spare : text.card.overdue, { time: formatSpan(slack, tag) })}`,
            alert: slack !== null && slack < 0,
          },
        ],
        rule:
          window !== null
            ? {
                state: 'blocked',
                text: format(text.card.maintenanceRule, {
                  window: text.maintenance[window.kind],
                  start: formatClock(window.start, tag),
                  end: formatClock(window.end, tag),
                }),
              }
            : late && previous !== undefined
              ? { state: 'blocked', text: format(text.card.early, { other: name(previous) }) }
              : hasStarted(operation, NOW)
                ? {
                    state: 'warn',
                    text: format(text.rules.started, { time: formatWhen(operation.start, tag) }),
                  }
                : { state: 'ok', text: text.rules.wrongMachine[operation.kind] },
        hints: defaultHints(common, { move: !hasStarted(operation, NOW) }),
      }
    },
    [operations, issues, text, common, tag, name],
  )
  const { eventHover, closeHover, suppressHover } = useEventHover(card)

  // Drag verdict: the plant's refusals, and warnings when the routing or the due date would break.
  const dragCard = useMemo(
    () =>
      createDragCard({
        tag,
        common,
        rowName: (id) => {
          const machine = machineOf(id)
          return machine === null ? null : text.machines[machine.id]
        },
        warn: (info) => {
          const operation = operations.find((candidate) => candidate.id === String(info.eventId))
          if (operation === undefined) return null
          const previous = operations.find((candidate) => candidate.id === operation.after)
          if (previous !== undefined && info.start.getTime() < parseCivil(previous.end))
            return format(text.card.early, { other: name(previous) })
          const next = operations.find(
            (candidate) =>
              candidate.after === operation.id && parseCivil(candidate.start) < info.end.getTime(),
          )
          if (next !== undefined) return format(text.card.cascade, { other: name(next) })
          const order = ORDERS.find((candidate) => candidate.id === operation.order)
          return order !== undefined && info.end.getTime() > parseCivil(order.due)
            ? text.card.pastDue
            : null
        },
      }),
    [tag, common, text, operations, name],
  )

  // The load strip reads the latest operations through a ref and redraws when they change.
  const latest = useRef(operations)
  useEffect(() => {
    latest.current = operations
    minimap.current?.refresh()
  }, [operations])

  // Context menu: rebuilt when the plan 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 operation = operations.find((candidate) => candidate.id === id)
          if (operation === undefined) return []
          const slot = nextSlotOf(operation, operations)
          const next = operations.find((candidate) => candidate.after === id)
          return [
            {
              label: common.kit.openDetails,
              icon: 'details',
              keys: KEYS.details,
              run: () => onAction('details', id),
            },
            {
              label:
                slot === null
                  ? text.actions.noSlot
                  : format(text.actions.nextSlot, { time: formatWhen(slot.start, tag) }),
              icon: 'slot',
              primary: true,
              disabled: slot === null || slot.start === operation.start,
              run: () => onAction('next-slot', id),
            },
            ...(next === undefined
              ? []
              : [
                  'separator' as const,
                  {
                    label: format(text.actions.nextOperation, {
                      operation: text.operations[next.kind],
                    }),
                    icon: 'after' as const,
                    run: () => onAction('next-operation', id),
                  },
                ]),
          ]
        },
      }),
    [operations, common, text, tag, onAction, suppressHover],
  )

  // Each order's routing is a chain of right-angled finish-to-start links; late ones are red.
  const links = useMemo<SuperScheduler.LinkData[]>(() => {
    const late = new Set(issues.map((issue) => issue.operation))
    return events.flatMap((event) =>
      event.after === undefined
        ? []
        : [
            {
              id: `${event.after}->${String(event.id)}`,
              from: event.after,
              to: event.id,
              type: 'FinishToStart',
              cssClass: late.has(String(event.id))
                ? `fg-link fg-o-${event.order} ss-link--late`
                : `fg-link fg-o-${event.order}`,
            },
          ],
    )
  }, [events, issues])

  // Plant clock, shift changes: hairlines through the grid (the clock above the cards).
  const separators = useMemo<SuperScheduler.SeparatorData[]>(() => {
    const start = parseCivil(`${WEEK.start}T00:00:00`)
    const changes: SuperScheduler.SeparatorData[] = []
    for (let day = 0; day < WEEK.days; day++) {
      for (const shift of SHIFTS) {
        changes.push({
          location: civil(start + day * DAY + shift.start * HOUR),
          cssClass: `fg-sep fg-sep--${shift.id}`,
          layer: 'BelowEvents',
          width: 1,
        })
      }
    }
    changes.push({
      location: BUSINESS_NOW,
      cssClass: 'fg-sep fg-sep--now',
      layer: 'AboveEvents',
      width: 2,
      toolTip: format(text.kpis.clock, { time: formatWhen(BUSINESS_NOW, tag) }),
    })
    return changes
  }, [text, tag])

  const columns = useMemo<SuperScheduler.RowHeaderColumnData[]>(
    () =>
      compact
        ? [{ text: text.columns.machine, width: COMPACT_ROW_HEADER, nonresizable: true }]
        : [
            { text: text.columns.machine, width: COLUMN_WIDTHS[0], nonresizable: true },
            { text: text.columns.oee, width: COLUMN_WIDTHS[1], nonresizable: true },
            { text: text.columns.load, width: COLUMN_WIDTHS[2], nonresizable: true },
          ],
    [compact, text],
  )

  const config = useMemo<SchedulerRenderProps>(() => {
    const flagged = new Set([...issues.map((issue) => issue.operation), ...conflicts])
    const escape = SuperScheduler.Util.escapeHtml
    const byId = new Map(operations.map((operation) => [operation.id, operation]))
    const lineMachines = line === null ? MACHINES : MACHINES.filter((m) => m.line === line)
    const messageFor = (reason: Refusal, data: object) => {
      const fields = readOperationFields(data)
      if (reason === 'machine') return fields === null ? '' : text.rules.wrongMachine[fields.kind]
      return text.rules[reason]
    }

    // Header markup per cell start, built once per plan (the hook runs for every header cell).
    const headerCache = new Map<
      string,
      Pick<SuperScheduler.TimeHeaderRenderHeader, 'html' | 'cssClass' | 'areas'>
    >()
    const nowShift = shiftAt(NOW)
    const nowLabel = escape(formatClock(NOW, tag))
    const nowTip = format(text.kpis.clock, { time: formatWhen(BUSINESS_NOW, tag) })
    const dayHeader = (ticks: number, span: number) => {
      const weekday = escape(formatCivil(ticks, tag, { weekday: 'short' }))
      const date = escape(formatCivil(ticks, tag, { day: 'numeric', month: 'short' }))
      // Zoomed out, the cell covers several days: it reads as their range.
      const last = escape(formatCivil(ticks + span - 1, tag, { day: 'numeric', month: 'short' }))
      const areas: SuperScheduler.AreaData[] =
        NOW >= ticks && NOW < ticks + span
          ? [
              {
                left: `calc(${percent((NOW - ticks) / span)} - 30px)`,
                width: 60,
                top: 4,
                bottom: 4,
                cssClass: 'fg-now-tag',
                html: nowLabel,
                toolTip: nowTip,
              },
            ]
          : []
      return {
        html:
          span > DAY
            ? `<span class="fg-th-day">${date} – ${last}</span>`
            : `<span class="fg-th-day"><b>${weekday}</b> ${date}</span>`,
        cssClass: 'fg-th fg-th--day',
        areas,
      }
    }
    const bandHeader = (ticks: number, span: number) => ({
      html: '',
      cssClass: 'fg-th fg-th--bands',
      areas: shiftSegments(ticks, ticks + span).map((segment): SuperScheduler.AreaData => {
        const current = NOW >= segment.from && NOW < segment.to && nowShift.shift.id === segment.id
        const midnight = segment.from - (((segment.from % DAY) + DAY) % DAY)
        // The small hours close the night shift that started the day before: label them at their end.
        const tail =
          segment.from === midnight && segment.to < midnight + DAY && segment.id === 'night'
        const hours = `${formatCivil(segment.from, tag, { hour: '2-digit', hourCycle: 'h23' })}–${formatCivil(segment.to, tag, { hour: '2-digit', hourCycle: 'h23' })}`
        return {
          left: percent((segment.from - ticks) / span),
          width: percent((segment.to - segment.from) / span),
          top: 0,
          bottom: 0,
          cssClass: `fg-band fg-band--${segment.id}${tail ? ' fg-band--tail' : ''}${current ? ' fg-band--now' : ''}`,
          html: `<span class="fg-band__name">${escape(text.shifts[segment.id])}</span><span class="fg-band__hours">${escape(hours)}</span>`,
          toolTip: `${text.shifts[segment.id]} · ${hours}`,
        }
      }),
    })
    const hourHeader = (ticks: number, span: number, narrow: boolean) => {
      // Coarsened to days when zoomed far out: each cell names its day.
      if (span >= DAY)
        return {
          html: `<span>${escape(formatCivil(ticks, tag, { weekday: 'short', day: 'numeric' }))}</span>`,
          cssClass: 'fg-th fg-th--hour fg-th--shift-start',
          areas: [] as SuperScheduler.AreaData[],
        }
      const hour = (((ticks % DAY) + DAY) % DAY) / HOUR
      const shiftStart = SHIFTS.some((shift) => shift.start % 24 === hour)
      const label = narrow && !shiftStart ? '' : headerLabel(ticks, 'hour', tag, 'cell')
      const current = NOW >= ticks && NOW < ticks + span
      const classes = ['fg-th', 'fg-th--hour']
      if (shiftStart) classes.push('fg-th--shift-start')
      if (current) classes.push('fg-th--now')
      if (ticks < NOW) classes.push('fg-th--past')
      return {
        html: label === '' ? '' : `<span>${escape(label)}</span>`,
        cssClass: classes.join(' '),
        areas: current
          ? [
              {
                left: percent((NOW - ticks) / span),
                width: 2,
                top: 0,
                bottom: 0,
                cssClass: 'fg-now-tick',
              },
            ]
          : [],
      }
    }

    // Line load per hour: cached per cell start for this plan and line selection.
    const loadCache = new Map<number, number>()
    const loadAt = (from: number, to: number) => {
      let value = loadCache.get(from)
      if (value === undefined) {
        value = plantLoad(operations, MAINTENANCE, lineMachines, from, to)
        loadCache.set(from, value)
      }
      return value
    }
    const loadAreas = new Map<string, SuperScheduler.AreaData[]>()

    // Cards: markup and areas cached per operation state, so an unchanged card is not rebuilt.
    const cardCache = new Map<string, { html: string; areas: SuperScheduler.AreaData[] }>()

    return {
      locale: schedulerLocale,
      cssClass: skinClass(SLUG),
      startDate: WEEK.start,
      days: WEEK.days,
      scale: 'Hour',
      cellWidth: HOUR_WIDTH,
      zoomGesture: { min: ZOOM.min, max: ZOOM.max, scales: false },
      timeHeaders: [
        { groupBy: 'Day', height: HEADER_HEIGHTS[0] },
        { groupBy: 'Day', height: HEADER_HEIGHTS[1] },
        { groupBy: 'Hour', height: HEADER_HEIGHTS[2] },
      ],
      // Three shifts: every hour is production time, so nothing is shaded as non-business.
      cellsMarkBusiness: false,
      useEventBoxes: 'Never',
      height: '100%',
      treeEnabled: true,
      treePreventParentUsage: true,
      rowHeaderColumns: columns,
      rowHeaderColumnsMergeParents: true,
      rowHeaderWidthAutoFit: false,
      eventHeight: EVENT_HEIGHT,
      rowMarginTop: ROW_MARGIN,
      rowMarginBottom: ROW_MARGIN,
      allowEventOverlap: false,
      // Run time follows quantity and cycle time: planners move operations, they do not stretch them.
      eventResizeHandling: 'Disabled',
      conflictHighlight: true,
      durationBarVisible: true,
      durationBarMode: 'PercentComplete',
      durationBarHeight: 3,
      linkShape: 'RightAngled',
      // Under the cards: a routing reads between plates, never across their text.
      linkLayer: 'Below',
      crosshairType: 'Full',
      separators,
      showToolTip: false,
      keyboardEnabled: true,
      keyboardTarget: 'component',
      keyboardMode: 'Full',
      history,
      controlRef,
      onEventsChange,

      // Row heights per kind: the load row and line rows hold no cards.
      onBeforeResHeaderRender: (args) => {
        const kind = args.resource['rowKind']
        const height =
          kind === 'load' ? LOAD_ROW_HEIGHT : kind === 'line' ? LINE_ROW_HEIGHT : undefined
        if (height === undefined) return
        args.resource.minHeight = height
        args.resource.emptyHeight = height
        args.resource.marginTop = 0
        args.resource.marginBottom = 0
      },

      // The corner names the header rows beside it: day and shift (the hours speak for themselves).
      onBeforeCornerRender: (args) => {
        args.html =
          `<span class="fg-corner" aria-hidden="true"><span>${escape(text.axis.day)}</span>` +
          `<span>${escape(text.axis.shift)}</span></span>`
      },

      onBeforeTimeHeaderRender: (args) => {
        const { level } = args.header
        const ticks = args.header.start.getTime()
        const span = args.header.end.getTime() - ticks
        const narrow = (args.control.cellWidth ?? HOUR_WIDTH) < 30
        const key = `${level}:${ticks}:${span}:${narrow ? 'n' : 'w'}`
        let header = headerCache.get(key)
        if (header === undefined) {
          header =
            level === 0
              ? dayHeader(ticks, span)
              : level === 1
                ? bandHeader(ticks, span)
                : hourHeader(ticks, span, narrow)
          headerCache.set(key, header)
        }
        args.header.html = header.html
        args.header.cssClass = header.cssClass
        args.header.areas = header.areas
      },

      onBeforeRowHeaderRender: (args) => {
        const row = args.row
        const [first, second, third] = row.columns
        if (row.id === LOAD_ROW) {
          row.cssClass = 'fg-rh fg-rh--load'
          if (first !== undefined)
            first.html =
              `<span class="fg-rh-load"><b>${escape(text.load.row)}</b>` +
              `<small>${escape(line === null ? text.lineFilter.all : text.lines[line])} · ${escape(text.load.perHour)}</small></span>`
          if (third !== undefined)
            third.html =
              `<span class="fg-rh-legend" aria-hidden="true"><i class="fg-rh-legend__warn"></i>${Math.round(LOAD_WARN * 100)}` +
              `<i class="fg-rh-legend__danger"></i>${Math.round(LOAD_DANGER * 100)}</span>`
          return
        }
        const lineId = lineOf(row.id)
        if (lineId !== null) {
          row.cssClass = compact ? 'fg-rh fg-rh--line fg-rh--compact' : 'fg-rh fg-rh--line'
          const count = MACHINES.filter((machine) => machine.line === lineId).length
          const load = figures.lines[lineId]
          // A parent row spans the columns (rowHeaderColumnsMergeParents): it shows `row.html`.
          row.html =
            `<span class="fg-rh-line"><b>${escape(text.lines[lineId])}</b>` +
            `<small>${escape(plural(text.machinesCount, count, tag))}</small>` +
            `<span class="fg-rh-line__load fg-lvl--${loadLevel(load)}">${Math.round(load * 100)}%</span></span>`
          return
        }
        const machine = machineOf(row.id)
        if (machine === null) return
        const figure = figures.machines[machine.id]
        row.cssClass = `fg-rh fg-rh--machine fg-rh--${figure.state}`
        if (first !== undefined)
          first.html =
            `<span class="fg-rh-m"><i class="fg-led fg-led--${figure.state}" title="${escape(text.states[figure.state])}"></i>` +
            `<span class="fg-rh-m__name">${escape(text.machines[machine.id])}</span>` +
            `<span class="fg-rh-m__meta">${escape(machine.code)} · ${escape(text.crews[machine.crew])}</span>` +
            `<span class="sr-only">${escape(text.states[figure.state])}</span></span>`
        if (second !== undefined)
          second.html = `<span class="fg-num">${Math.round(figure.oee * 100)}%</span>`
        if (third !== undefined) {
          third.html = `<span class="fg-rh-meter fg-lvl--${loadLevel(figure.load)}"><b>${Math.round(figure.load * 100)}%</b></span>`
          third.areas = [
            { left: 10, right: 46, top: 'calc(50% - 2px)', height: 4, cssClass: 'fg-meter-track' },
            {
              left: 10,
              width: `calc((100% - 56px) * ${figure.load.toFixed(3)})`,
              top: 'calc(50% - 2px)',
              height: 4,
              cssClass: `fg-meter-fill fg-lvl--${loadLevel(figure.load)}`,
            },
          ]
        }
      },

      onRowFilter: (args) => {
        const filter = args.filterParam
        if (filter === null || filter === undefined || args.row.id === LOAD_ROW) return
        const lineId = lineOf(args.row.id)
        const machine = machineOf(args.row.id)
        args.visible = lineId === filter || machine?.line === filter
      },

      onBeforeCellRender: (args) => {
        const cell = args.cell
        const from = cell.start.getTime()
        const to = cell.end.getTime()
        if (cell.resource === LOAD_ROW) {
          const value = loadAt(from, to)
          const level = loadLevel(value)
          const past = to <= NOW ? ' fg-lc--past' : ''
          if ((args.control.cellWidth ?? HOUR_WIDTH) < 26) {
            cell.properties.cssClass = `fg-lc fg-lc--heat fg-lvl--${level}${past}`
            return
          }
          const pct = Math.round(value * 100)
          cell.properties.cssClass = `fg-lc fg-lvl--${level}${past}`
          cell.properties.html = `<span class="fg-lc__value">${pct}<small>%</small></span>`
          const key = `${pct}`
          let areas = loadAreas.get(key)
          if (areas === undefined) {
            areas = [
              { left: 5, right: 5, bottom: 6, height: 3, cssClass: 'fg-lc__track' },
              {
                left: 5,
                width: `calc((100% - 10px) * ${value.toFixed(3)})`,
                bottom: 6,
                height: 3,
                cssClass: `fg-lc__fill fg-lvl--${level}`,
              },
            ]
            loadAreas.set(key, areas)
          }
          cell.properties.areas = areas
          return
        }
        if (lineOf(cell.resource) !== null) {
          cell.properties.cssClass = to <= NOW ? 'fg-cell-line fg-cell--past' : 'fg-cell-line'
          return
        }
        const machine = machineOf(cell.resource)
        if (machine === null) return
        const classes: string[] = []
        if (to <= NOW) classes.push('fg-cell--past')
        const hour = (((from % DAY) + DAY) % DAY) / HOUR
        if (hour >= 22 || hour < 6) classes.push('fg-cell--night')
        const cellStart = civil(from)
        const window = maintenanceAt(MAINTENANCE, machine.id, cellStart, civil(to))
        if (window !== null) {
          // Maintenance windows become disabled cells: the library refuses drops on them.
          cell.properties.disabled = true
          classes.push('fg-cell--maint')
          if (cellStart <= window.start) {
            // The first cell carries the label; it runs over the rest of the window.
            classes.push('fg-cell--maint-start')
            cell.properties.html = `<span class="fg-maint-label">${escape(text.maintenance[window.kind])}</span>`
          }
        }
        cell.properties.cssClass = classes.join(' ')
      },

      onBeforeEventRender: (args) => {
        const id = String(args.data.id)
        const operation = byId.get(id)
        const fields = readOperationFields(args.data)
        if (operation === undefined || fields === null) return
        const order = ORDERS.find((candidate) => candidate.id === operation.order)
        const phase = phaseAt(operation, NOW)
        const started = phase !== 'planned'
        const late = flagged.has(id)
        const key = `${id}|${operation.start}|${operation.machine}|${phase}`
        let cached = cardCache.get(key)
        if (cached === undefined) {
          const glyph = phase === 'done' ? GLYPH.done : started ? GLYPH.lock : ''
          const hours = formatSpan(parseCivil(operation.end) - parseCivil(operation.start), tag)
          const html =
            `<span class="fg-ev__body">` +
            `<span class="fg-ev__l1"><b class="fg-ev__op">${opCode(operation.step)}</b>` +
            `<span class="fg-ev__wo">${escape(operation.order)}</span>` +
            `<span class="fg-ev__part">${escape(text.parts[operation.order])}</span>` +
            `${glyph === '' ? '' : `<span class="fg-ev__glyph">${glyph}</span>`}</span>` +
            `<span class="fg-ev__l2" data-super-scheduler-part="event-meta">` +
            `<span class="fg-ev__kind">${escape(text.operations[operation.kind])}</span>` +
            `<span>${escape(plural(text.pieces, order?.quantity ?? 0, tag))}</span>` +
            `<span>${escape(hours)}</span></span></span>`
          const areas: SuperScheduler.AreaData[] = [
            {
              start: operation.start,
              end: civil(setupEnd(operation)),
              top: 0,
              bottom: 0,
              cssClass: 'fg-setup',
              action: 'Default',
            },
          ]
          if (!started)
            areas.push(
              {
                right: 32,
                top: 'calc(50% - 12px)',
                width: 24,
                height: 24,
                visibility: 'Hover',
                action: 'None',
                cssClass: 'fg-act',
                html: GLYPH.slot,
                toolTip: text.historyNextSlot,
                onClick: () => action.current('next-slot', id),
              },
              {
                right: 5,
                top: 'calc(50% - 12px)',
                width: 24,
                height: 24,
                visibility: 'Hover',
                action: 'None',
                cssClass: 'fg-act',
                html: GLYPH.details,
                toolTip: text.actions.details,
                onClick: () => action.current('details', id),
              },
            )
          cached = { html, areas }
          cardCache.set(key, cached)
        }
        args.data.html = cached.html
        args.data.areas = cached.areas
        args.data.complete = Math.round(progressAt(operation, NOW) * 100)
        args.data.moveDisabled = started
        const classes = ['fg-ev', `fg-ev--${phase}`, `fg-o-${operation.order}`]
        if (late) classes.push('ss-ev--late', 'fg-ev--late')
        if (id === selected) classes.push('fg-ev--selected')
        args.data.cssClass = classes.join(' ')
        args.data.ariaLabel = `${opCode(operation.step)} ${name(operation)}, ${text.phases[phase]}${late ? `, ${text.card.outOfSequence}` : ''}`
      },

      onEventMoving: (args) => {
        const id = String(args.e.id())
        const reason = refusalFor(
          controlRef.current,
          args.e.data,
          id,
          args.resource,
          args.start,
          args.end,
        )
        refusal.track(id, reason)
        if (reason !== null) {
          args.allowed = false
          args.message = messageFor(reason, args.e.data)
        }
      },

      // Final check before the commit; keyboard moves (Alt+arrows) arrive here without a drag.
      onEventMove: (args) => {
        const id = String(args.e.id())
        const reason = refusalFor(
          args.control,
          args.e.data,
          id,
          args.newResource,
          args.newStart,
          args.newEnd,
        )
        if (reason !== null) {
          args.preventDefault()
          refusal.clear()
          onRefused(id, reason)
        }
      },

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

      // Hovering a card traces its order: the other orders' cards and links step back.
      onEventMouseEnter: (args) => {
        const fields = readOperationFields(args.e.data)
        trace(board.current, fields === null ? null : fields.order)
      },
      onEventMouseLeave: () => trace(board.current, null),
    }
  }, [
    columns,
    compact,
    conflicts,
    controlRef,
    figures,
    history,
    selected,
    closeHover,
    issues,
    line,
    name,
    onEventsChange,
    onMoved,
    onRefused,
    onSelect,
    operations,
    refusal,
    schedulerLocale,
    separators,
    tag,
    text,
  ])

  // Imperative and once: a scroll prop would be re-applied on every update.
  useEffect(() => {
    controlRef.current?.scrollTo(INITIAL_VIEW_START, false, 'left')
  }, [controlRef])

  // The line selector filters the machine rows (the line-load row follows the same lines).
  useEffect(() => {
    controlRef.current?.rows.filter(line)
  }, [controlRef, line])

  // The visible range, published once scrolling (or a minimap drag) settles.
  useEffect(() => {
    const control = controlRef.current
    if (control === null) return
    return subscribeScheduler(control, 'viewport', (viewport) =>
      onViewport(civil(viewport.start.ticks), civil(viewport.end.ticks)),
    )
  }, [controlRef, onViewport])

  // The zoom slider lives in the product bar; it drives the same animated zoom as a pinch.
  useEffect(() => {
    const control = controlRef.current
    const host = zoomHost.current
    if (control === null || host === null) return
    const slider = createZoomSlider(control, host, {
      min: ZOOM.min,
      max: ZOOM.max,
      scale: 'log',
      detents: ZOOM.detents,
      label: text.zoom.label,
    })
    return () => slider.dispose()
  }, [controlRef, zoomHost, text])

  useEffect(() => {
    const control = controlRef.current
    const host = stripHost.current
    if (control === null || host === null) return
    // The brush reports exact instants (with milliseconds): format their ticks.
    const when = (date: SuperScheduler.Date) =>
      formatCivil(date.ticks, tag, { weekday: 'short', hour: 'numeric', minute: '2-digit' })
    const created = createMinimap(control, host, {
      height: 26,
      // Absolute scale: a full bar means every available machine is busy.
      peak: 'absolute',
      max: 1,
      series: (range) =>
        loadSeries(
          latest.current,
          MAINTENANCE,
          MACHINES,
          range.start.ticks,
          range.bucketMs,
          range.buckets,
        ),
      tone: (value) => loadLevel(value),
      // A fixed week of fixtures: the plant clock is drawn by the board, not the strip.
      marks: { today: false, months: false, past: false },
      labels: {
        label: text.load.label,
        zoom: text.load.zoom,
        valueText: (start, end) =>
          text.load.range.replace('{start}', when(start)).replace('{end}', when(end)),
      },
    })
    minimap.current = created
    return () => {
      created.dispose()
      minimap.current = null
    }
  }, [controlRef, stripHost, tag, text])

  return (
    <div ref={board} className="fg-board h-full [&>div]:h-full">
      <SuperSchedulerComponent
        {...config}
        resources={resources}
        events={events}
        links={links}
        eventHover={eventHover}
        dragCard={dragCard}
        contextMenu={contextMenu}
      />
    </div>
  )
}

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