Aller au contenu

Ordonnancement des ordres de fabrication

La maintenance a été avancée. Déplacez l’ordre et gardez ses opérations dans le bon ordre.

  • Industrie
  • Forge
  • Lignes de synthèse
  • Barres de progression
  • Dépendances
  • Minimap
  • Curseur de zoom
  • Réticule
  • Créneaux bloqués
  • Thèmes
  • Démo avec données fictives

Mission

0 étapes faites sur 3

Mardi, 6 h 20, poste du matin : la révision de broche de la fraiseuse CNC 2 a été avancée et elle est en cours, en plein sur le fraisage de WO-4471 prévu à 8 h.

  1. Sortez « WO-4471 · Fraisage » de la révision de broche de la fraiseuse CNC 2. — À faire

    Faites-le glisser à 12 h sur la même machine, à la fin de la révision. Les cellules hachurées le refusent, et le tour n’est pas une fraiseuse.

  2. Déplacez le tournage en rouge pour qu’il commence après la fin du fraisage. — À faire

    Déposez « WO-4471 · Tournage » à 17 h sur le tour. Le lien rouge redevient gris quand la séquence est respectée.

  3. Utilisez la bande de charge de l’atelier pour regarder jeudi. — À faire

    Faites glisser vers la droite la fenêtre en surbrillance de la bande sous le planning, ou donnez-lui le focus et utilisez les flèches.

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

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

Forge
UsinageFraiseuse CNC 151%Fraiseuse CNC 257%Tour59%AssemblageCellule A56%Cellule B55%FinitionCabine peinture60%Labo qualité39%OP10 WO-4471 Carter de réducteurFraisage · 120 piècesOP10 WO-4475 Corps de vanneFraisage · 80 piècesOP10 WO-4477 Plaque de recouvrementFraisage · 300 piècesOP10 WO-4482 Chapeau de palierFraisage · 60 piècesOP20 WO-4471 Carter de réducteurTournage · 120 piècesOP20 WO-4475 Corps de vanneTournage · 80 piècesOP20 WO-4476 Arbre de transmissionTournage · 90 piècesOP20 WO-4478 Flasque moteurTournage · 250 piècesOP20 WO-4479 Moyeu d’accouplementTournage · 180 piècesOP30 WO-4471 Carter de réducteurAssemblage · 120 piècesOP30 WO-4473 Bloc hydrauliqueAssemblage · 60 piècesOP30 WO-4476 Arbre de transmissionAssemblage · 90 piècesOP50 WO-4472 Support de pompeContrôle · 400 piècesOP50 WO-4473 Bloc hydrauliqueContrôle · 60 piècesOP30 WO-4474 Douille de brocheContrôle · 200 piècesOP50 WO-4476 Arbre de transmissionContrôle · 90 piècesOP40 WO-4477 Plaque de recouvrementContrôle · 300 piècesOP30 WO-4480 Armoire de commandeContrôle · 20 piècesOP40 WO-4472 Support de pompePeinture · 400 piècesOP40 WO-4473 Bloc hydrauliquePeinture · 60 piècesOP40 WO-4476 Arbre de transmissionPeinture · 90 piècesOP30 WO-4477 Plaque de recouvrementPeinture · 300 piècesOP20 WO-4480 Armoire de commandePeinture · 20 piècesOP20 WO-4474 Douille de brocheAssemblage · 200 piècesOP20 WO-4477 Plaque de recouvrementAssemblage · 300 piècesOP30 WO-4478 Flasque moteurAssemblage · 250 piècesOP10 WO-4478 Flasque moteurFraisage · 250 piècesOP10 WO-4479 Moyeu d’accouplementFraisage · 180 piècesOP10 WO-4481 Support de freinFraisage · 75 pièces71%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%Charge de lignepar heuremardi 20 octobremercredi 21 octobre03: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

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

La situation.

Forge est un atelier fictif d’usinage à façon : deux fraiseuses CNC et un tour, deux cellules d’assemblage, une cabine de peinture et un laboratoire qualité, tenus par quatre équipes en trois postes. Chaque ordre suit une gamme (fraisage, tournage, assemblage, peinture, contrôle) et aucune opération ne peut commencer avant la fin de la précédente.

La maintenance n’attend pas le plan. Quand la révision de broche de la fraiseuse CNC 2 est avancée, le fraisage prévu dessus doit bouger, et ce qui le suit dans la gamme risque de commencer trop tôt. Le planning doit refuser les déplacements impossibles, laisser en place ce qui a déjà commencé, montrer les opérations hors séquence et signaler où la semaine est déjà pleine.

Ce que vous allez faire

Vous sortirez un fraisage d’une fenêtre de maintenance, remettrez son tournage dans la séquence et utiliserez la bande de charge pour aller jusqu’à la maintenance suivante, jeudi.

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

SuperScheduler fournit

  • Un arbre de lignes et de machines avec rowHeaderColumns (machine, TRS, jauge de charge) et une ligne figée en haut dont les zones de onBeforeCellRender dessinent la charge de ligne par heure.
  • Trois rangs d’en-tête : jour, bandes de poste écrites en zones par onBeforeTimeHeaderRender, et heures ; des separators à chaque changement de poste et à l’horloge de l’atelier, et crosshairType: 'Full'.
  • Des cartes sur deux lignes depuis onBeforeEventRender : une zone de réglage ancrée dans le temps, l’avancement avec durationBarMode: 'PercentComplete' et des actions au survol en zones visibility: 'Hover'.
  • Des cellules de maintenance désactivées, des vetos image par image dans onEventMoving avec la carte de glisser, conflictHighlight et des liens fin-début tracés avec linkShape: 'RightAngled'.
  • rows.filter pour le sélecteur de ligne, createZoomSlider de super-scheduler/zoom-ui, la minimap de super-scheduler/minimap et l’état du viewport de super-scheduler/hooks.

Le code de cet exemple décide

  • Quel type de machine exécute chaque opération, les postes, le calendrier de maintenance et l’horloge de l’atelier qui bloque ce qui a déjà commencé.
  • La gamme de chaque ordre et la vérification qui signale une opération qui commence trop tôt.
  • Chaque chiffre : charge de ligne par heure, charge machine et TRS planifié selon les cadences standard, ordres en retard, opérations signalées.
  • Des durées fixes (pas de redimensionnement), le panneau de détail, la mission et tous les libellés.

Le code de cette démo.

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

tsx.zip

L’intégration : les colonnes d’en-tête de ligne, l’en-tête des postes, la ligne de charge, les cartes avec leur réglage et leur avancement, les refus, les liens, le curseur de zoom et la bande de charge.

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

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