Saltar al contenido

Planificación de atraques

Un buque llega doce horas tarde. Mueve su ventana de atraque y lleva con ella el remolcador y las grúas.

  • Logística
  • Harborworks
  • Filas de resumen
  • Dependencias
  • Minimapa
  • Eventos de varios días
  • Columnas de fila
  • Cruceta
  • Áreas activas
  • Temas
  • Demo con datos sintéticos

Misión

0 de 3 pasos hechos

Miércoles, 06:00: el Atlas Meridian avisa de un retraso de 12 horas. Ahora puede atracar el jueves a las 00:00.

  1. Mueve la ventana roja del Atlas Meridian en el Muelle 1 al jueves a las 00:00. — Pendiente

    Arrástrala tres guardias (12 horas) a la derecha. El Muelle 2 no tiene calado y el Muelle 3 es corto: los dos la rechazan.

  2. Lleva su remolcador y sus grúas a la nueva ventana. — Pendiente

    Haz clic en la ventana y pulsa Realinear operaciones en el panel, o arrastra cada operación en rojo.

  3. Resuelve la última operación en rojo. — Pendiente

    La STS 2 tiene mantenimiento el jueves por la tarde. Arrastra su operación a la STS 3 y tres guardias a la derecha, al jueves a las 02:00.

Unos 30 segundos. Los pasos se marcan a medida que los completas.

Teclado: enfoca la rejilla y usa las flechas, Intro y Alt+flechas para mover.

Harborworks
Servicios náuticosRemolcador Petrel70 tRemolcador Alca60 tMuelleMuelle 1340 m · 16 mMuelle 2300 m · 14 mMuelle 3220 m · 12 mGrúasSTS 1Muelles 1–2STS 2Muelles 1–2STS 3Muelles 1–2Grúa móvil 4Muelle 3Sella TraderHW-2413 · 148 mFjord LanternHW-2416 · 186 mMarisolHW-2417 · 182 mSella Trader310 movimientosMarisol420 movimientosCape SolanoHW-2414 · 212 mOrinoco StarHW-2418 · 262 mCape Solano780 movimientosOrinoco Star1180 movimientosAtlas MeridianMarisolKestrel BayAtlas MeridianHW-2415 · 300 mKestrel BayHW-2419 · 176 mAtlas Meridian1040 movimientosKestrel Bay610 movimientosAtlas Meridian800 movimientosRevisiónFjord LanternOrinoco Star67%33%17%33%67%67%67%67%67%33%50%33%33%50%83%100%100%100%83%50%33%0%0%0%0%Ocupación del muellepor guardiamiércoles, 21 de octubrejueves, 22 de octubreviernes, 23 de octubresábado, 24 de octubredomingo, 25 de octubre00:0004:0008:0012:0016:0020:0000:0004:0008:0012:0016:0020:0000:0004:0008:0012:0016:0020:0000:0004:0008:0012:0016:0020:0000:00

Vista previa del primer fotogramaEn vivo: el motor Pro real, funcionando en tu navegadorUnos 30 segundos. Los pasos se marcan a medida que los completas. Teclado: enfoca la rejilla y usa las flechas, Intro y Alt+flechas para mover.

La situación.

Harborworks es una terminal ficticia con tres muelles, tres grúas pórtico, una grúa móvil y dos remolcadores. El planificador de atraques trabaja las 24 horas: cada escala necesita un muelle con eslora y calado suficientes, un remolcador que acerque el buque y grúas que alcancen ese muelle.

Los retrasos son lo normal. Cuando un buque comunica una nueva hora de llegada, su ventana se mueve y todo lo que depende de ella también: el remolque, las manos de estiba y a veces el buque siguiente. Un tablero que solo muestra barras esconde esa cascada; este dibuja los vínculos, marca lo que ya no encaja y mantiene a la vista la ocupación del muelle.

Qué vas a hacer

Moverás un buque retrasado a su nueva hora de atraque, realinearás su remolcador y sus grúas con un solo comando y resolverás la grúa que coincide con un mantenimiento.

Dónde termina la librería y empieza tu aplicación.

SuperScheduler aporta

  • Árbol de recursos agrupado con rowHeaderColumns: qué hace cada equipo a la hora de la terminal y sus indicadores (eslora y calado de un muelle, carga de trabajo de una grúa, tiro de un remolcador).
  • Una fila fija arriba (frozen: 'top', cellsDisabled) que onBeforeCellRender llena con la ocupación del muelle por guardia, hora o día, recalculada tras cada cambio.
  • Tres filas de cabecera de tiempo (timeHeaders con su altura); onBeforeTimeHeaderRender dibuja la tercera: la curva de marea, con pleamares y bajamares como áreas de cabecera.
  • Barras largas a la hora exacta (useEventBoxes: 'Never') que se mueven por celdas completas (eventMoveByCell), con un área anclada en el tiempo (start, end) sobre las horas en que el buque aún no puede atracar, botones al pasar el ratón (visibility: 'Hover', action: 'None') y etiquetas htmlRight junto a los remolques.
  • Vínculos inicio-inicio y fin-inicio dibujados a partir de tus datos, un separador a la hora de la terminal y crosshairType: 'Full'.
  • Niveles de zoom de horas a días, el minimapa con un selector de vista, prevención de solapes, historial y movimientos con teclado.
  • Tarjetas al pasar el ratón y tarjeta de arrastre (super-scheduler/react-render), conflictHighlight y un menú contextual con la piel del producto (theme del Menu).

El código de este ejemplo decide

  • Qué buque cabe en qué muelle (eslora y calado) y qué grúa alcanza qué muelle: los rechazos en onEventMoving.
  • Qué es un conflicto: una ventana antes de su ETB, una grúa fuera de su ventana, un remolque que no termina al atracar.
  • El comando de realinear: una función pura que mueve las operaciones vinculadas y registra un único paso de deshacer.
  • Las cifras de la terminal: buques atracados y en fondeo, ocupación del muelle en las próximas 24 horas, el modelo de marea y la serie de ocupación que alimenta el minimapa.
  • Las tarjetas de casco, carga y remolque, la leyenda que destaca un tipo de barra y las acciones: primer muelle libre, realinear, pasar una operación a otra grúa.

El código de esta demo.

Son los archivos que ejecuta esta página, no una copia simplificada. Compilan contra los exports públicos de SuperScheduler Pro.

tsx.zip

La integración: niveles de zoom con tres filas de cabecera, rowHeaderColumns, la fila fija de ocupación, el separador a la hora de la terminal, vínculos construidos desde los datos, la tarjeta al pasar el ratón, el veredicto de arrastre que vuelve a evaluar la cadena del buque en la posición propuesta, el menú contextual y los callbacks donde las reglas de la terminal rechazan un movimiento.

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

El archivo contiene los ficheros de este ejemplo y un README. No incluye SuperScheduler Pro ni ninguna clave de descarga.