Planification des postes à quai
Un navire arrive avec douze heures de retard. Déplacez sa fenêtre d’accostage, puis entraînez son remorqueur et ses grues.
- Logistique
- Harborworks
- Lignes de synthèse
- Dépendances
- Minimap
- Événements sur plusieurs jours
- Colonnes de ligne
- Réticule
- Zones actives
- Thèmes
- Démo avec données fictives
Mission
0 étapes faites sur 3Mercredi, 06:00 : l’Atlas Meridian annonce 12 heures de retard. Il peut désormais accoster jeudi à 00:00.
Déplacez la fenêtre rouge de l’Atlas Meridian sur le poste 1 à jeudi 00:00. — À faire
Glissez-la de trois quarts (12 heures) vers la droite. Le poste 2 manque de fond et le poste 3 de longueur : tous deux la refusent.
Ramenez son remorqueur et ses grues dans la nouvelle fenêtre. — À faire
Cliquez sur la fenêtre puis sur Réaligner les opérations dans le panneau, ou glissez chaque opération rouge.
Réglez la dernière opération en rouge. — À faire
Le STS 2 est en maintenance jeudi après-midi. Glissez son opération sur le STS 3 et de trois quarts vers la droite, à jeudi 02:00.
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.
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.
Harborworks est un terminal fictif avec trois postes à quai, trois portiques, une grue mobile et deux remorqueurs. Le planificateur travaille en continu : chaque escale demande un poste assez long et assez profond pour le navire, un remorqueur pour l’amener à quai et des grues capables d’atteindre ce poste.
Les retards sont la règle. Quand un navire annonce une nouvelle heure d’arrivée, sa fenêtre se déplace, et tout ce qui en dépend doit suivre : le remorquage, les équipes de manutention, parfois le navire suivant. Un planning qui ne montre que des barres masque cette cascade ; celui-ci dessine les liens, signale ce qui ne tient plus et garde l’occupation du quai sous les yeux.
Ce que vous allez faire
Vous déplacerez un navire en retard vers sa nouvelle heure d’accostage, réalignerez son remorqueur et ses grues en une commande et réglerez la grue qui tombe sur une maintenance.
Où s’arrête la bibliothèque et où commence votre application.
SuperScheduler fournit
- Arbre de ressources groupé avec rowHeaderColumns : ce que fait chaque équipement à l’heure du terminal et ses jauges (longueur et profondeur d’un poste, charge maximale d’une grue, traction d’un remorqueur).
- Une ligne figée en haut (frozen: 'top', cellsDisabled) que onBeforeCellRender remplit avec l’occupation du quai par quart, heure ou jour, recalculée après chaque modification.
- Trois lignes d’en-tête de temps (timeHeaders avec leur hauteur) ; onBeforeTimeHeaderRender dessine la troisième : la courbe de marée, avec pleines et basses mers en zones d’en-tête.
- Des barres longues à l’heure exacte (useEventBoxes: 'Never') déplacées par cellules entières (eventMoveByCell), avec une zone ancrée dans le temps (start, end) sur les heures où le navire ne peut pas encore accoster, des boutons au survol (visibility: 'Hover', action: 'None') et des libellés htmlRight à côté des remorquages.
- Des liens début-début et fin-début tirés de vos données, un séparateur à l’heure du terminal et crosshairType: 'Full'.
- Des niveaux de zoom des heures aux jours, la minicarte avec sa fenêtre, la prévention des chevauchements, l’historique et les déplacements au clavier.
- Des cartes au survol et la carte de glisser (super-scheduler/react-render), conflictHighlight et un menu contextuel à l’habillage du produit (theme du Menu).
Le code de cet exemple décide
- Quel navire tient à quel poste (longueur et tirant d’eau) et quelle grue atteint quel poste : les refus dans onEventMoving.
- Ce qu’est un conflit : une fenêtre avant son ETB, une grue hors de sa fenêtre, un remorquage qui ne finit pas à l’accostage.
- La commande de réalignement : une fonction pure qui déplace les opérations liées et enregistre une seule étape d’annulation.
- Les chiffres du terminal : navires à quai et au mouillage, occupation du quai sur les 24 prochaines heures, le modèle de marée et la série d’occupation qui alimente la minicarte.
- Les cartes de coque, de manutention et de remorquage, la légende qui fait ressortir un type de barre et les actions : premier poste libre, réaligner, confier une opération à une autre grue.
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.
L’intégration : niveaux de zoom à trois lignes d’en-tête, rowHeaderColumns, la ligne d’occupation figée, le séparateur à l’heure du terminal, les liens construits à partir des données, la carte au survol, le verdict de glisser qui réévalue la chaîne du navire à la position proposée, le menu contextuel et les callbacks où les règles du terminal refusent un dépôt.
/**
* Harborworks berth plan: tugs, berths and cranes over two weeks of vessel calls, round the clock.
*
* Library: grouped resource tree with row-header columns, a frozen summary row, a three-row time
* header (days, watches, tide) written by onBeforeTimeHeaderRender, long events at exact times
* with time-anchored and hover areas, drag/resize with conflict highlighting, links, a separator
* at the terminal clock, the full crosshair, zoom levels, keyboard and undo history, the event
* hover card and the drag card (super-scheduler/react-render), and a context menu. Application:
* which ship fits which berth, which crane reaches which berth, what counts as a conflict, the
* tide, quay occupancy and the chain that follows a ship (tug, berth window, cranes). Those rules
* live in ./rules and run in the callbacks below; ./board-paint writes the markup.
*/
import { useCallback, useEffect, useMemo, useState, type RefObject } from 'react'
import { SuperScheduler } from 'super-scheduler'
import type { SchedulerEventsChangeArgs } from 'super-scheduler'
import type { SchedulerHistory } from 'super-scheduler/history'
import { SuperSchedulerComponent, type SchedulerRenderProps } from 'super-scheduler/react-render'
import { format, plural } from '../../i18n/format'
import { DAY, civil, parseCivil } from '../../scheduler/civil'
import { createHeaderHook } from '../../scheduler/live-headers'
import { toneClass } from '../../scheduler/tones'
import { createEventMenu, type MenuEntry } from '../kit/context-menu'
import { formatWhen } from '../kit/format'
import { useEventHover, type HoverCardModel } from '../kit/hover-card'
import { KEYS } from '../kit/keys'
import { useDropRefusal } from '../kit/use-drop-refusal'
import { createDragCard } from '../kit/verdict'
import type { DemoCommon } from '../types'
import { skinClass, skinMenuTheme } from '../registry'
import {
BOARD,
SUMMARY_ID,
callById,
groupMembers,
isAssetId,
readOperationFields,
toResources,
toneOf,
type OperationEvent,
} from './adapter'
import {
assetHtml,
assetState,
capacityHtml,
cardHtml,
clock,
earlyUntil,
occupancyPainter,
tideHeader,
tugSide,
watchLabel,
} from './board-paint'
import { chainHtml, chainItems, operationCard } from './call-card'
import { GROUP_IDS, INITIAL_VIEW_START, NOW, PLAN, type Operation, type VesselCall } from './model'
import {
berthById,
earliestWindow,
handOverCrane,
issuesIf,
moveRefusal,
realignCall,
windowOf,
type Issue,
type MoveRefusal,
} from './rules'
import type { HarborText, ZoomId } from './text'
/** What the board asks the demo to do (context menu, keyboard). */
export type OperationAction = 'details' | 'earliest' | 'realign' | 'hand-over' | 'toggle-links'
export interface HarborSchedulerProps {
readonly events: OperationEvent[]
/** The same events as business objects, for rules that look at other operations. */
readonly operations: readonly Operation[]
readonly calls: readonly VesselCall[]
readonly issues: readonly Issue[]
readonly text: HarborText
readonly common: DemoCommon
/** BCP 47 tag for labels, and the scheduler locale id. */
readonly tag: string
readonly schedulerLocale: string
/** Level on mount. Later changes go through control.zoom so the view animates from where it is. */
readonly initialZoom: ZoomId
readonly showLinks: boolean
/** The operation shown in the side sheet: it gets the selection ring. */
readonly selected: string | null
readonly history: SchedulerHistory
readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
readonly onSelect: (id: string) => void
readonly onMoved: (id: string) => void
readonly onResized: (id: string, edge: 'start' | 'end') => void
readonly onRefused: (id: string, message: string) => void
readonly onAction: (action: OperationAction, id: string) => void
readonly onZoomLevel: (level: ZoomId) => void
/** Narrow stages drop the capacity column. */
readonly narrow: boolean
}
/** Three header rows at every level: the period, its cells, and the tide under them. */
function headerRows(
group: SuperScheduler.GroupBy,
cell: SuperScheduler.GroupBy,
format?: string,
): SuperScheduler.TimeHeaderData[] {
return [
{ groupBy: group, height: BOARD.header.day },
// A declared format tells the level-of-detail planner how wide the label really is.
{ groupBy: cell, height: BOARD.header.watch, ...(format === undefined ? {} : { format }) },
{ groupBy: 'Cell', height: BOARD.header.tide, format: 'HH' },
]
}
/** Four-hour watches by default; hours to plan a berthing, days to see the fortnight. */
const ZOOM_LEVELS: SuperScheduler.ZoomLevel[] = [
{
id: 'hours',
// The planner measures 'HH'; the hook writes 04:00, which fits the cell.
properties: { scale: 'Hour', cellWidth: 50, timeHeaders: headerRows('Day', 'Hour', 'HH') },
},
{
id: 'watches',
properties: {
scale: 'CellDuration',
cellDuration: 240,
cellWidth: BOARD.cellWidth,
timeHeaders: headerRows('Day', 'Cell', 'HH:mm'),
},
},
{
id: 'days',
properties: { scale: 'Day', cellWidth: 168, timeHeaders: headerRows('Week', 'Day') },
},
]
const KIND_CLASS = { berth: 'ship', crane: 'cargo', tug: 'tug', maintenance: 'maint' } as const
const ICONS = {
earliest:
'<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="5" r="2"/><path d="M12 7v14M5 13a7 7 0 0 0 14 0M8 10h8"/></svg>',
realign:
'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>',
'hand-over':
'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 17h12M12 13l4 4-4 4M20 7H8M12 3 8 7l4 4"/></svg>',
} as const
/** A hover button on a bar (`visibility: 'Hover'`): the press is the area's, not a drag. */
function hoverAction(
icon: keyof typeof ICONS,
label: string,
right: number,
run: () => void,
): SuperScheduler.AreaData {
return {
right,
top: 7,
width: 26,
height: 26,
visibility: 'Hover',
action: 'None',
cssClass: 'hw-act',
html: ICONS[icon],
toolTip: label,
onClick: (args) => {
args.preventDefault()
run()
},
}
}
const ZOOM_IDS: readonly ZoomId[] = ['hours', 'watches', 'days']
/** A refusal message with the numbers of the ship and the berth it was dropped on. */
function refusalMessage(
reason: MoveRefusal,
call: VesselCall | null,
target: SuperScheduler.ResourceId,
text: HarborText,
tag: string,
): string {
const berth = berthById(String(target))
const number = (value: number) =>
new Intl.NumberFormat(tag, { maximumFractionDigits: 1 }).format(value)
return format(text.rules[reason], {
length: number(call?.length ?? 0),
draft: number(call?.draft ?? 0),
berthLength: number(berth?.length ?? 0),
berthDraft: number(berth?.draft ?? 0),
})
}
/** Menu label for the earliest berth window: where it would go, or why it stays. */
export function earliestLabel(
op: Operation,
ops: readonly Operation[],
calls: readonly VesselCall[],
text: HarborText,
tag: string,
): { label: string; enabled: boolean } {
const next = earliestWindow(op.id, ops, calls, PLAN)
if (next === null) return { label: text.actions.noBerth, enabled: false }
if (next.asset === op.asset && next.start === op.start)
return { label: text.actions.atEarliest, enabled: false }
return {
label: format(text.actions.earliest, {
time: formatWhen(next.start, tag),
berth: text.assets[next.asset],
}),
enabled: true,
}
}
/** Menu label for handing a crane operation to another crane. */
export function handOverLabel(
op: Operation,
ops: readonly Operation[],
text: HarborText,
tag: string,
): { label: string; enabled: boolean } {
const next = handOverCrane(op.id, ops)
return next === null
? { label: text.actions.noCrane, enabled: false }
: {
label: format(text.actions.handOver, {
crane: text.assets[next.asset],
time: formatWhen(next.start, tag),
}),
enabled: true,
}
}
/**
* The hover buttons of each bar for one plan, cached per operation: realign and earliest berth on
* a ship's window, hand-over on a crane operation. Long-range calls have none.
*/
function barActionsFor(
operations: readonly Operation[],
calls: readonly VesselCall[],
text: HarborText,
tag: string,
onAction: (action: OperationAction, id: string) => void,
): (op: Operation) => SuperScheduler.AreaData[] {
const cache = new Map<string, SuperScheduler.AreaData[]>()
return (op) => {
const cached = cache.get(op.id)
if (cached !== undefined) return cached
const areas: SuperScheduler.AreaData[] = []
const call = callById(op.call)
if (call !== null && call.planned !== true) {
if (op.kind === 'berth') {
let right = 20
if (realignCall(call.id, operations, calls).moved.length > 0) {
areas.push(
hoverAction('realign', text.actions.realign, right, () => onAction('realign', op.id)),
)
right += 30
}
const earliest = earliestLabel(op, operations, calls, text, tag)
if (earliest.enabled)
areas.push(
hoverAction('earliest', earliest.label, right, () => onAction('earliest', op.id)),
)
} else if (op.kind === 'crane') {
const handOver = handOverLabel(op, operations, text, tag)
if (handOver.enabled)
areas.push(
hoverAction('hand-over', handOver.label, 6, () => onAction('hand-over', op.id)),
)
}
}
cache.set(op.id, areas)
return areas
}
}
export function HarborScheduler(props: HarborSchedulerProps) {
const {
events,
operations,
calls,
issues,
text,
common,
tag,
schedulerLocale,
initialZoom,
showLinks,
selected,
history,
controlRef,
narrow,
} = props
const { onEventsChange, onSelect, onMoved, onResized, onRefused, onAction, onZoomLevel } = props
const resources = useMemo(() => toResources(text), [text])
// Header labels depend on the level's scale. A zoom animation lands on the new scale after the
// headers of its last frames were drawn, so each settled level gets a fresh hook: a new hook
// makes the control label its headers again.
const [level, setLevel] = useState<ZoomId>(initialZoom)
const timeHeaders = useMemo(() => {
const shared = createHeaderHook(tag)
const hook = (args: SuperScheduler.SchedulerBeforeTimeHeaderRenderArgs) => {
const header = args.header
const start = header.start.getTime()
const end = header.end.getTime()
// The third row is the tide under the cells, whatever their length.
if (header.level === 2) {
tideHeader(header, start, end, args.control.cellWidth ?? BOARD.cellWidth, text, tag)
header.cssClass = 'hw-th-tide'
return
}
shared(args)
header.cssClass = header.level === 0 ? 'hw-th-day' : 'hw-th-cell'
// Watches and hours read as a control room writes them: 04:00.
if (header.level === 1 && end - start < DAY) header.html = watchLabel(start, tag)
}
return { level, hook }
}, [level, tag, text]).hook
// A refused drop (berth size, crane reach, asset kind, overlap) is said on release.
const refusal = useDropRefusal(onRefused)
// The occupancy row is computed from the berth windows in state, cached per cell.
const paintOccupancy = useMemo(
() => occupancyPainter(operations.filter((op) => op.kind === 'berth')),
[operations],
)
// Hover buttons of the bars, decided once per plan (the earliest berth search is not free).
const barActions = useMemo(
() => barActionsFor(operations, calls, text, tag, onAction),
[operations, calls, text, tag, onAction],
)
// Links come from the business model: tugs finish before berthing, cranes start after it.
const links = useMemo<SuperScheduler.LinkData[]>(() => {
if (!showLinks) return []
const flagged = new Set(issues.map((issue) => issue.op))
const windows = new Map(
events.flatMap((event) =>
event.kind === 'berth' && event.call !== undefined ? [[event.call, event.id]] : [],
),
)
return events.flatMap((event): SuperScheduler.LinkData[] => {
const window = event.call === undefined ? undefined : windows.get(event.call)
if (window === undefined || (event.kind !== 'tug' && event.kind !== 'crane')) return []
const late = flagged.has(String(event.id)) ? { cssClass: 'ss-link--late' } : {}
return event.kind === 'tug'
? [
{
id: `${String(event.id)}->${String(window)}`,
from: event.id,
to: window,
type: 'FinishToStart',
...late,
},
]
: [
{
id: `${String(window)}->${String(event.id)}`,
from: window,
to: event.id,
type: 'StartToStart',
...late,
},
]
})
}, [events, issues, showLinks])
// Hover card: the ship, its fit, ETB, and the chain of operations that follows it.
const card = useCallback(
(event: SuperScheduler.Event): HoverCardModel | null => {
const op = operations.find((candidate) => candidate.id === String(event.id()))
return op === undefined ? null : operationCard(op, operations, issues, text, common, tag)
},
[operations, issues, text, common, tag],
)
const { eventHover, closeHover, suppressHover } = useEventHover(card)
// Drag verdict: the terminal's refusal, or what the drop would leave behind, and the chain of
// the ship re-evaluated at the proposed position (a red dot is a link that would stop fitting).
const dragCard = useMemo<SuperScheduler.DragCardOptions>(() => {
const proposed = (info: SuperScheduler.DragCardInfo) => {
const op = operations.find((candidate) => candidate.id === String(info.eventId))
if (op?.call === undefined || info.resource === null || !isAssetId(info.resource)) return null
const placement = {
asset: info.resource,
start: civil(info.start.getTime()),
end: civil(info.end.getTime()),
}
return { op, placement, issues: issuesIf(op.id, placement, operations, calls) }
}
const base = createDragCard({
tag,
common,
rowName: (id) => (isAssetId(id) ? text.assets[id] : null),
warn: (info) => {
const next = proposed(info)
if (next === null) return null
const { op } = next
const own = next.issues.find((issue) => issue.op === op.id)
const call = callById(op.call)
if (op.kind === 'berth') {
if (own?.kind === 'before-etb' && call !== null)
return format(text.card.etbRule, { time: formatWhen(call.etb, tag) })
const behind = next.issues.filter((issue) => issue.op !== op.id).length
return behind === 0 ? null : plural(text.card.behindWarn, behind, tag)
}
if (own === undefined || call === null) return null
if (op.kind === 'tug') {
const window = windowOf(call.id, operations)
return format(text.card.tugWarn, {
time: window === null ? '—' : formatWhen(window.start, tag),
})
}
// A crane out of reach never gets here: moveRefusal refuses it.
return own.kind === 'outside-window'
? format(text.card.outsideWarn, { vessel: call.vessel })
: null
},
})
return {
...base,
html: (info) => {
const html = base.html?.(info) ?? null
if (html === null || info.forbidden || info.overlapping) return html
const next = proposed(info)
if (next === null) return html
const moved = operations.map((op) =>
op.id === next.op.id ? { ...op, ...next.placement } : op,
)
const chain = chainHtml(chainItems(next.op, moved, next.issues, text), text)
return chain === '' ? html : `${html.slice(0, -'</div>'.length)}${chain}</div>`
},
}
}, [operations, calls, text, common, tag])
// Context menu: rebuilt when the plan changes, so its labels name the real consequence.
const contextMenu = useMemo(
() =>
createEventMenu({
theme: skinMenuTheme('port-berths'),
title: (event) => format(common.kit.menuTitle, { name: event.text() }),
onOpenChange: (open) => suppressHover(open),
entries: (event) => {
const id = String(event.id())
const op = operations.find((candidate) => candidate.id === id)
if (op === undefined) return []
const entries: MenuEntry[] = [
{
label: common.kit.openDetails,
icon: 'details',
keys: KEYS.details,
run: () => onAction('details', id),
},
]
const call = callById(op.call)
if (op.kind === 'berth') {
const earliest = earliestLabel(op, operations, calls, text, tag)
entries.push({
label: earliest.label,
icon: 'slot',
primary: issues.some((issue) => issue.op === id && issue.kind === 'before-etb'),
disabled: !earliest.enabled,
run: () => onAction('earliest', id),
})
} else if (op.kind === 'crane') {
const handOver = handOverLabel(op, operations, text, tag)
entries.push({
label: handOver.label,
icon: 'handover',
disabled: !handOver.enabled,
run: () => onAction('hand-over', id),
})
}
if (call !== null && call.planned !== true) {
const count = realignCall(call.id, operations, calls).moved.length
entries.push({
label:
count === 0 ? text.actions.aligned : plural(text.actions.realignCount, count, tag),
icon: 'link',
primary: count > 0,
disabled: count === 0,
run: () => onAction('realign', id),
})
}
entries.push('separator', {
label: showLinks ? text.actions.hideLinks : text.actions.showLinks,
icon: 'layers',
run: () => onAction('toggle-links', id),
})
return entries
},
}),
[operations, calls, issues, showLinks, common, text, tag, onAction, suppressHover],
)
const config = useMemo<SchedulerRenderProps>(() => {
const flagged = new Set(issues.map((issue) => issue.op))
const overlapText = (conflicts: readonly SuperScheduler.Event[]) => {
const first = conflicts[0]
return first === undefined ? null : format(common.kit.overlaps, { name: first.text() })
}
const vessels = new Map(calls.map((call) => [call.id, call]))
const groupCounts = new Map<SuperScheduler.ResourceId, number>(
GROUP_IDS.map((group) => [group, groupMembers(group).length]),
)
const escape = SuperScheduler.Util.escapeHtml
return {
locale: schedulerLocale,
startDate: PLAN.start,
days: PLAN.days,
// ISO weeks in every locale, as the static preview draws them.
weekStarts: 1,
zoomLevels: ZOOM_LEVELS,
zoom: initialZoom,
zoomPosition: 'left',
// Exact times (a window from 06:30 stays at 06:30); drags move by whole cells.
useEventBoxes: 'Never',
eventMoveByCell: true,
height: '100%',
cssClass: skinClass('port-berths'),
treeEnabled: true,
treePreventParentUsage: true,
rowHeaderColumns: [
{ text: text.columns.asset, width: narrow ? BOARD.narrowColumn : BOARD.assetColumn },
{ text: text.columns.capacity, width: BOARD.capacityColumn, hidden: narrow },
],
rowHeaderWidth: narrow ? BOARD.narrowColumn : BOARD.rowHeaderWidth,
rowHeaderWidthAutoFit: false,
treeIndent: BOARD.treeIndent,
// The last visible column title sits beside the tide row: it carries the row's key.
onBeforeRowHeaderColumnRender: (args) => {
const title = args.column.data.text
if (title !== (narrow ? text.columns.asset : text.columns.capacity)) return
args.column.html =
`<span class="hw-colhead"><span>${escape(title)}</span>` +
`<span class="hw-colhead__tide" aria-hidden="true">${escape(text.tide.row)}</span></span>`
},
eventHeight: BOARD.eventHeight,
rowMarginTop: BOARD.rowMarginTop,
rowMarginBottom: BOARD.rowMarginBottom,
allowEventOverlap: false,
conflictHighlight: true,
durationBarVisible: false,
crosshairType: 'Full',
// The terminal clock: a fixed instant of the scenario, not the visitor's clock.
separators: [
{
location: NOW,
layer: 'AboveEvents',
width: 2,
cssClass: 'hw-now',
toolTip: `${text.chrome.clock} ${clock(parseCivil(NOW), tag)}`,
},
],
showToolTip: false,
keyboardEnabled: true,
keyboardTarget: 'component',
keyboardMode: 'Full',
history,
controlRef,
onEventsChange,
onBeforeRowHeaderRender: (args) => {
const row = args.row
const id = row.id
const [first, second] = row.columns
if (first === undefined) return
const name = String(row.name)
if (id === SUMMARY_ID) {
row.cssClass = 'hw-row hw-row--summary'
first.html = `<span class="hw-rh"><span class="hw-rh__name">${escape(name)}</span><span class="hw-rh__meta">${escape(text.summary.rowMeta[level])}</span></span>`
if (second !== undefined) second.html = ''
return
}
if (!isAssetId(id)) {
row.cssClass = 'ss-rh--group hw-row hw-row--group'
const count = groupCounts.get(id)
// Parent rows span both columns (merged): their header is the row's own html.
row.html = `<span class="hw-group">${escape(name)}<span class="hw-group__count">${count ?? ''}</span></span>`
first.html = row.html
return
}
row.cssClass = `hw-row hw-row--${id.startsWith('berth') ? 'berth' : id.startsWith('tug') ? 'tug' : 'crane'}`
first.html = assetHtml(name, assetState(id, operations, text))
if (second !== undefined) second.html = capacityHtml(id, text, tag)
},
onBeforeCellRender: (args) => {
const cell = args.cell
if (cell.resource !== SUMMARY_ID) return
const painted = paintOccupancy(
cell.start.getTime(),
cell.end.getTime(),
args.control.cellWidth ?? BOARD.cellWidth,
text,
tag,
)
cell.properties.html = painted.html
cell.properties.cssClass = painted.css
},
onBeforeEventRender: (args) => {
const data = args.data
const fields = readOperationFields(data)
if (fields === null || data.resource === undefined || !isAssetId(data.resource)) return
const id = String(data.id)
const op: Operation = {
id,
kind: fields.kind,
asset: data.resource,
start: civil(data.start.getTime()),
end: civil(data.end.getTime()),
...(fields.call === undefined ? {} : { call: fields.call }),
...(fields.moves === undefined ? {} : { moves: fields.moves }),
}
const call = fields.call === undefined ? undefined : vessels.get(fields.call)
const early = earlyUntil(op)
const isFlagged = flagged.has(id)
const isSelected = id === selected
data.html = cardHtml(
op,
{ flagged: isFlagged, selected: isSelected, early: early !== null },
text,
tag,
)
const classes = ['hw-ev', `hw-ev--${KIND_CLASS[op.kind]}`, toneClass(toneOf(fields))]
if (call?.planned === true) classes.push('hw-planned')
if (isFlagged) classes.push('hw-conflict')
if (isSelected) classes.push('hw-selected')
data.cssClass = classes.join(' ')
if (op.kind === 'tug') data.htmlRight = tugSide(op)
const areas: SuperScheduler.AreaData[] = []
// The hours the window is open before the ship can be there.
if (early !== null)
areas.push({
start: op.start,
end: civil(early),
top: 0,
bottom: 0,
cssClass: 'hw-early',
toolTip: format(text.card.early, { time: formatWhen(early, tag) }),
})
areas.push(...barActions(op))
data.areas = areas
data.ariaLabel = isFlagged
? `${String(data.text)}, ${text.kinds[op.kind]}, ${text.card.conflict}`
: `${String(data.text)}, ${text.kinds[op.kind]}`
},
// Berth size, crane reach and asset kinds are terminal rules; overlap is enforced by the library.
onEventMoving: (args) => {
const id = String(args.e.id())
const fields = readOperationFields(args.e.data)
if (fields === null) return
const reason = moveRefusal(fields, String(args.resource), calls, operations)
if (reason !== null) {
const message = refusalMessage(reason, callById(fields.call), args.resource, text, tag)
args.allowed = false
args.message = message
refusal.track(id, message)
return
}
refusal.track(id, overlapText(args.conflicts))
},
onEventResizing: (args) => {
refusal.track(String(args.e.id()), overlapText(args.conflicts))
},
// Final check before the commit (also covers keyboard moves).
onEventMove: (args) => {
const fields = readOperationFields(args.e.data)
if (fields === null) return
const reason = moveRefusal(fields, String(args.newResource), calls, operations)
if (reason !== null) {
args.preventDefault()
refusal.clear()
onRefused(
String(args.e.id()),
refusalMessage(reason, callById(fields.call), args.newResource, text, tag),
)
}
},
onEventMoved: (args) => {
refusal.clear()
onMoved(String(args.e.id()))
},
onEventResized: (args) => {
refusal.clear()
onResized(String(args.e.id()), args.what)
},
// A click (or Enter) docks the operation into the side sheet; the hover card steps aside.
onEventClick: (args) => {
closeHover()
onSelect(String(args.e.id()))
},
onZoom: (args) => {
if (args.phase !== 'end') return
const next = ZOOM_IDS[args.level]
if (next === undefined) return
setLevel(next)
onZoomLevel(next)
},
}
}, [
history,
controlRef,
issues,
calls,
operations,
selected,
narrow,
level,
paintOccupancy,
barActions,
common,
refusal,
closeHover,
onEventsChange,
onMoved,
onRefused,
onResized,
onSelect,
onZoomLevel,
schedulerLocale,
tag,
text,
initialZoom,
])
// Imperative and once: a scroll prop would be re-applied on every update.
useEffect(() => {
controlRef.current?.scrollTo(INITIAL_VIEW_START, false, 'left')
}, [controlRef])
return (
<SuperSchedulerComponent
{...config}
onBeforeTimeHeaderRender={timeHeaders}
resources={resources}
events={events}
links={links}
eventHover={eventHover}
dragCard={dragCard}
contextMenu={contextMenu}
/>
)
}L’archive contient les fichiers de cet exemple et un README. Elle n’inclut ni SuperScheduler Pro ni aucune clé de téléchargement.