Planificación de producción audiovisual
Un rodaje se alarga. Mueve la edición que dependía de él, entiende por qué y vuelve atrás.
- Producción audiovisual
- Framehouse
- Dependencias
- Hitos
- Barras de progreso
- Control de zoom
- Minimapa
- Columnas de fila
- Reglas de movimiento
- Deshacer y rehacer
- Temas
- Demo con datos sintéticos
Misión
0 de 3 pasos hechosMiércoles, 12:30: el spot de cocina necesita más tiempo en el plató B.
Arrastra el final de «Spot de cocina · Rodaje» de la pista S2 hasta la tarde. — Pendiente
Agarra el borde derecho del clip en curso del plató B. El montaje offline que lo espera se marca en rojo.
Mueve el montaje offline en rojo para después del rodaje. — Pendiente
Llévalo al jueves por la mañana, a E1 o E2. Un plató lo rechaza, y también cualquier hora detrás del cabezal.
Deshaz tu último cambio. — Pendiente
Usa la flecha de deshacer de la barra del producto o Ctrl/⌘+Z con el tablero enfocado.
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.
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.
Framehouse es una productora ficticia con dos platós, dos unidades de cámara, dos salas de edición, una sala de etalonaje y una sala de mezcla. Producción reparte tres clientes en la misma semana y cada fase espera a la anterior: no hay montaje offline antes de terminar el rodaje, ni etalonaje antes de cerrar el montaje, ni entrega antes de la última sesión.
En una hoja de cálculo la semana parece correcta hasta que un rodaje se alarga. El tablero tiene que leerse como las herramientas que el equipo ya usa, mostrar qué rompe ese retraso, rechazar los movimientos sin sentido (un rodaje en la sala de mezcla, una edición detrás del cabezal) y permitir deshacer cualquier cambio con facilidad.
Qué vas a hacer
Alargarás un rodaje en curso, verás cómo la edición que depende de él se marca en rojo, la moverás a una sala libre después del rodaje y desharás un cambio con una sola tecla.
Dónde termina la librería y empieza tu aplicación.
SuperScheduler aporta
- Cabeceras de pista con rowHeaderColumns y onBeforeRowHeaderRender, con el candado dibujado como un área de la cabecera de fila (action: ‘None’, onClick).
- Clips de dos líneas desde onBeforeEventRender: html, cssClass, durationBarMode: ‘PercentComplete’ con complete, áreas al pasar el ratón (visibility: ‘Hover’), un área anclada en el tiempo (start, end) para el solape en retraso y entregas como type: ‘Milestone’ con etiquetas htmlRight.
- zoomLevels de día y semana, un deslizador de zoom libre y un indicador de nivel de detalle de super-scheduler/zoom-ui (createZoomSlider, createLodBadge), y una regla de timecode desde onBeforeTimeHeaderRender.
- El cabezal como separator, crosshairType: ‘Full’ y vínculos fin-inicio con linkShape: ‘RightAngled’.
- Arrastrar y redimensionar con vetos en cada fotograma (onEventMoving, onEventResizing), la tarjeta de arrastre, conflictHighlight, deshacer y rehacer de super-scheduler/history y eventos controlados (onEventsChange).
- El minimapa (super-scheduler/minimap) con un rango fijo sobre la semana de producción, alimentado con la serie horaria propia de la aplicación y un tono por hora; su selector también funciona como deslizador desde el teclado.
El código de este ejemplo decide
- Qué fase cabe en qué pista, qué sesiones dependen de cuáles y cuándo una sesión o una entrega va con retraso.
- La regla del cabezal: lo terminado es historia y lo que está en curso solo puede durar más o menos.
- Los candados de pista, los colores de departamento, los contadores en vivo, el inspector, la misión y todos los textos de esta página.
- Quién está en jornada: el equipo que aporta cada pista, las horas extra al terminar la jornada, las horas que retiene una sesión con retraso y el día punta en horas-persona.
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.
La integración: niveles de zoom, la regla, clips ricos con áreas, hitos, el separador del cabezal, los candados de pista y los callbacks donde las reglas deciden si un cambio se permite.
/**
* Framehouse planning board: an edit suite for one production week. Tracks are rooms and crews,
* clips are sessions coloured by department, deliveries are milestones and the playhead marks the
* studio's now.
*
* Library: hour-scale zoom levels, the time-header, row-header and event render hooks (rich
* clips, track headers with columns and a lock area, a timecode ruler), areas (hover actions, a
* time-anchored late overlap), percent-complete bars, milestones with side labels, a separator as
* the playhead, the full crosshair, right-angled dependency links, drag and resize with per-frame
* vetoes, the drag card, the event hover card (super-scheduler/react-render), conflict
* highlighting, a context menu and undo history. Application: which track takes which phase,
* what is fixed or locked, what the playhead allows, what counts as late and when the crew's day
* turns into overtime. Those rules live in ./rules and run inside the callbacks below.
*/
import { useCallback, useEffect, useMemo, type RefObject } from 'react'
import type { SchedulerEventsChangeArgs, SuperScheduler } 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, HOUR, civil, parseCivil } from '../../scheduler/civil'
import { headerLabel } from '../../scheduler/header-format'
import { unitOfSpan } from '../../scheduler/live-headers'
import { createEventMenu } from '../kit/context-menu'
import { formatClock, formatDay, formatWhen } from '../kit/format'
import { defaultHints } 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 {
CLIP_HEIGHT,
CLIP_INSET,
HEADER_ROW,
NARROW_HEADER_WIDTH,
TRACK_COLUMNS,
TRACK_DEPARTMENT,
TRACK_HEADER_WIDTH,
ZOOM_WIDTH,
timecode,
departmentOf,
readSessionFields,
roomOf,
sessionName,
toResources,
type SessionEvent,
} from './adapter'
import { useClipHover, type ClipCardModel } from './clip-card'
import {
binHtml,
clipHtml,
createHtmlCache,
crewHtml,
dayHtml,
deliveryLabelHtml,
hourOf,
iconHtml,
lockIconHtml,
columnIconHtml,
playheadHtml,
rulerHtml,
rulerStep,
tickStep,
trackHtml,
} from './clips'
import {
BUSINESS_HOURS,
CLIENTS,
INITIAL_VIEW_START,
NOW,
ROOMS,
WEEK,
type RoomId,
type Session,
} from './model'
import {
CREW_DAY_END,
TRACKS_PROGRESS,
moveRefusal,
progressAt,
resizeRefusal,
slotAfterDependency,
timeState,
type DependencyIssue,
type EditRefusal,
} from './rules'
import { ZOOM_IDS, type FramehouseText, type ZoomId } from './text'
import './tokens.css'
import './framehouse.css'
/** What the board asks the demo to do (context menu, hover actions, track headers). */
export type SessionAction = 'details' | 'start-after' | 'toggle-links' | 'toggle-lock'
export interface FramehouseSchedulerProps {
readonly events: SessionEvent[]
/** The same sessions in model form: cards, rules and the menu read them. */
readonly sessions: readonly Session[]
readonly issues: readonly DependencyIssue[]
readonly text: FramehouseText
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
/** Tracks locked in their headers: their clips do not move and nothing lands on them. */
readonly lockedTracks: ReadonlySet<RoomId>
/** Narrow stage: the crew column steps aside. */
readonly narrow: boolean
/** Pixels per hour of the week view, measured for this stage (see weekWidthFor). */
readonly weekWidth: number
/** The product skin: a class for the scheduler root (hover cards copy it) and the menu theme. */
readonly skin: { readonly cssClass: string; readonly menuTheme: string }
/** The session shown in the inspector: 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, end: SuperScheduler.Date) => void
readonly onRefused: (id: string, message: string) => void
readonly onAction: (action: SessionAction, id: string) => void
readonly onToggleLock: (room: RoomId) => void
/** A zoom settled (switch, slider, pinch, keys) at this many px per hour. */
readonly onZoomEnd: (pxPerHour: number) => void
}
const NOW_TICKS = parseCivil(NOW)
/** Clips narrower than this keep their whole body for dragging: no hover action. */
const HOVER_ACTION_MIN_WIDTH = 72
/** Deliveries from Friday 14:00 on put their label on the left of the diamond (inside the week). */
const LABEL_LEFT_FROM = parseCivil(`${WEEK.end}T00:00:00`) - DAY + 14 * HOUR
const WEEK_START = parseCivil(WEEK.start)
function ticksOf(value: SuperScheduler.Date): number {
return value.ticks
}
/** The classes of a track cell, built once per combination (the hook runs for every cell). */
const CELL_CLASSES = new Map<number, string>()
function cellClass(past: boolean, locked: boolean, overtime: boolean): string {
const key = (past ? 1 : 0) + (locked ? 2 : 0) + (overtime ? 4 : 0)
let value = CELL_CLASSES.get(key)
if (value === undefined) {
value = [past && 'fh-cell--past', locked && 'fh-cell--locked', overtime && 'fh-cell--overtime']
.filter((name) => name !== false)
.join(' ')
CELL_CLASSES.set(key, value)
}
return value
}
export function FramehouseScheduler(props: FramehouseSchedulerProps) {
const {
events,
sessions,
issues,
text,
common,
tag,
schedulerLocale,
initialZoom,
showLinks,
lockedTracks,
narrow,
weekWidth,
skin,
selected,
history,
controlRef,
} = props
const { onEventsChange, onSelect, onMoved, onResized, onRefused, onAction, onToggleLock } = props
const { onZoomEnd } = props
const resources = useMemo(() => toResources(text), [text])
const name = useCallback(
(session: Pick<Session, 'project' | 'phase'>) => sessionName(session, text),
[text],
)
const byId = useMemo(() => new Map(sessions.map((session) => [session.id, session])), [sessions])
const late = useMemo(() => new Set(issues.map((issue) => issue.session)), [issues])
// A refused drop is said once the pointer is released.
const refusal = useDropRefusal(onRefused)
/** One sentence per refusal reason; the track code fills the lock message. */
const refusalText = useCallback(
(reason: EditRefusal, session: Pick<Session, 'phase'>, room: RoomId): string => {
switch (reason) {
case 'fixed':
return session.phase === 'delivery' ? text.rules.delivery : text.rules.locked
case 'track-locked': {
const locked = lockedTracks.has(room) ? room : null
const code = roomOf(locked ?? room)?.code ?? ''
return format(text.rules.trackLocked, { code })
}
case 'wrapped':
return text.rules.wrapped
case 'rolling':
return text.rules.rolling
case 'past':
return text.rules.past
case 'wrong-room':
return text.rules.wrongRoom[session.phase]
}
},
[text, lockedTracks],
)
// Finish-to-start links come from the business model, not from the scheduler.
const links = useMemo<SuperScheduler.LinkData[]>(() => {
if (!showLinks) return []
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)) ? 'fh-link fh-link--late' : 'fh-link',
},
],
)
}, [events, late, showLinks])
// The clip card: in and out points, the day with the playhead, dependencies and the rule.
const card = useCallback(
(event: SuperScheduler.Event): ClipCardModel | null => {
const session = byId.get(String(event.id()))
const room = session === undefined ? null : roomOf(session.room)
// The clip open in the inspector needs no card: the sheet already says it all.
if (session === undefined || room === null || session.id === selected) return null
const department = departmentOf(session.phase)
const before = session.after === undefined ? undefined : byId.get(session.after)
const after = sessions.filter((candidate) => candidate.after === session.id)
const isLate = late.has(session.id)
const start = parseCivil(session.start)
const end = parseCivil(session.end)
const day = start - (start % DAY)
const open = day + BUSINESS_HOURS.begin * HOUR
const span = (BUSINESS_HOURS.end - BUSINESS_HOURS.begin) * HOUR
const state = timeState(session, NOW)
const delivery = session.phase === 'delivery'
const client = CLIENTS.find((candidate) => candidate.project === session.project)?.name ?? ''
return {
id: session.id,
department,
eyebrow: `${text.departments[department]} · ${client}`,
title: name(session),
state: isLate
? { label: text.card.late, tone: 'late' }
: session.locked === true
? { label: delivery ? text.card.due : text.card.locked, tone: 'fixed' }
: state === 'wrapped'
? { label: text.card.wrapped, tone: 'wrapped' }
: state === 'rolling'
? { label: text.card.rolling, tone: 'rolling' }
: before === undefined
? null
: { label: text.card.onTrack, tone: 'ok' },
points: delivery
? [
{ label: text.card.due, value: formatWhen(start, tag) },
{ label: text.fields.track, value: room.code },
]
: [
{ label: text.card.in, value: formatWhen(start, tag) },
{ label: text.card.out, value: formatClock(end, tag) },
{ label: text.fields.duration, value: timecode(end - start) },
],
strip: {
from: (start - open) / span,
to: (end - open) / span,
playhead:
NOW_TICKS >= open && NOW_TICKS <= open + span ? (NOW_TICKS - open) / span : null,
start: formatDay(start, tag),
end: formatClock(open + span, tag),
},
progress: TRACKS_PROGRESS.has(session.phase)
? { label: text.fields.progress, value: progressAt(session, NOW) }
: null,
facts: [
{ label: text.fields.track, value: `${room.code} · ${text.rooms[room.id]}` },
{
label: text.fields.dependsOn,
value: before === undefined ? '—' : name(before),
alert: isLate,
},
{
label: text.card.unblocks,
value: after.length === 0 ? '—' : after.map((next) => name(next)).join(', '),
},
],
rule:
session.locked === true
? { state: 'blocked', text: delivery ? text.rules.delivery : text.rules.locked }
: lockedTracks.has(session.room)
? { state: 'blocked', text: format(text.rules.trackLocked, { code: room.code }) }
: isLate && before !== undefined
? {
state: 'blocked',
text: format(text.card.lateRule, {
other: name(before),
time: formatClock(before.end, tag),
}),
}
: state === 'wrapped'
? { state: 'warn', text: text.rules.wrapped }
: { state: 'ok', text: text.rules.wrongRoom[session.phase] },
hints: defaultHints(common, {
move: session.locked !== true && state === 'upcoming' && !lockedTracks.has(session.room),
}),
}
},
[byId, sessions, late, lockedTracks, selected, text, common, tag, name],
)
const { eventHover, closeHover, suppressHover } = useClipHover(card)
// Drag verdict: the rules refuse, a broken dependency (either way) warns.
const dragCard = useMemo(
() =>
createDragCard({
tag,
common,
rowName: (id) => {
const room = roomOf(id)
return room === null ? null : `${room.code} · ${text.rooms[room.id]}`
},
warn: (info) => {
const session = byId.get(String(info.eventId))
if (session === undefined) return null
const before = session.after === undefined ? undefined : byId.get(session.after)
if (before !== undefined && info.start.getTime() < parseCivil(before.end))
return format(text.card.early, { other: name(before) })
const next = sessions.find(
(candidate) =>
candidate.after === session.id && parseCivil(candidate.start) < info.end.getTime(),
)
return next === undefined ? null : format(text.card.cascade, { other: name(next) })
},
}),
[tag, common, text, byId, sessions, name],
)
// Context menu: rebuilt when the plan changes, so its labels name the real consequence.
const contextMenu = useMemo(
() =>
createEventMenu({
theme: skin.menuTheme,
title: (event) => format(common.kit.menuTitle, { name: event.text() }),
onOpenChange: (open) => suppressHover(open),
entries: (event) => {
const id = String(event.id())
const session = byId.get(id)
const room = session === undefined ? null : roomOf(session.room)
if (session === undefined || room === null) return []
const before = session.after === undefined ? undefined : byId.get(session.after)
const slot = slotAfterDependency(session, sessions)
const movable =
session.locked !== true &&
timeState(session, NOW) === 'upcoming' &&
!lockedTracks.has(session.room)
return [
{
label: text.actions.inspect,
icon: 'details',
keys: KEYS.details,
run: () => onAction('details', id),
},
...(before === undefined || !movable
? []
: [
{
label: format(slot === null ? text.actions.roomBusy : text.actions.startAfter, {
other: name(before),
}),
icon: 'after' as const,
primary: late.has(id),
disabled:
slot === null ||
slot.start === session.start ||
parseCivil(slot.start) < NOW_TICKS,
run: () => onAction('start-after', id),
},
]),
'separator',
{
label: format(
lockedTracks.has(room.id) ? text.actions.unlockTrack : text.actions.lockTrack,
{ code: room.code },
),
icon: 'layers',
run: () => onAction('toggle-lock', id),
},
{
label: showLinks ? text.actions.hideLinks : text.actions.showLinks,
icon: 'link',
run: () => onAction('toggle-links', id),
},
]
},
}),
[
byId,
sessions,
late,
lockedTracks,
showLinks,
skin,
common,
text,
name,
onAction,
suppressHover,
],
)
const columns = useMemo<SuperScheduler.RowHeaderColumnData[]>(
() =>
narrow
? [
{ name: text.columns.track, width: TRACK_COLUMNS.narrowTrack, nonresizable: true },
{ name: text.columns.lock, width: TRACK_COLUMNS.lock, nonresizable: true },
]
: [
{ name: text.columns.track, width: TRACK_COLUMNS.track, nonresizable: true },
{ name: text.columns.crew, width: TRACK_COLUMNS.crew, nonresizable: true },
{ name: text.columns.lock, width: TRACK_COLUMNS.lock, nonresizable: true },
],
[narrow, text],
)
const config = useMemo<SchedulerRenderProps>(() => {
// Both views on the hour scale: only the width of an hour changes, so a pinch or the slider
// glide between them without a change of grid.
const zoomLevels: SuperScheduler.ZoomLevel[] = ZOOM_IDS.map((id) => ({
id,
properties: { scale: 'Hour', cellWidth: id === 'week' ? weekWidth : ZOOM_WIDTH[id] },
}))
const clips = createHtmlCache()
const headers = createHtmlCache()
const rows = createHtmlCache(200)
// Tracks with a session rolling at the playhead: their code chip lights up.
const live = new Set<RoomId>(
sessions.filter((session) => timeState(session, NOW) === 'rolling').map((s) => s.room),
)
const sessionRefusal = (
data: object,
id: string,
room: SuperScheduler.ResourceId,
start: SuperScheduler.Date,
): string | null => {
const session = byId.get(id)
const target = roomOf(room)
if (session === undefined || target === null || readSessionFields(data) === null) return null
const reason = moveRefusal(
session,
{ room: target.id, kind: target.kind, start: civil(ticksOf(start)) },
{ now: NOW, lockedTracks },
)
return reason === null ? null : refusalText(reason, session, target.id)
}
const sizeRefusal = (
id: string,
start: SuperScheduler.Date,
end: SuperScheduler.Date,
): string | null => {
const session = byId.get(id)
if (session === undefined) return null
const reason = resizeRefusal(
session,
{ start: civil(ticksOf(start)), end: civil(ticksOf(end)) },
{ now: NOW, lockedTracks },
)
return reason === null ? null : refusalText(reason, session, session.room)
}
const overlapRefusal = (conflicts: readonly SuperScheduler.Event[]): string | null => {
const first = conflicts[0]
return first === undefined ? null : format(common.kit.overlaps, { name: first.text() })
}
return {
locale: schedulerLocale,
cssClass: skin.cssClass,
startDate: WEEK.start,
days: 5,
scale: 'Hour',
// The ruler writes its own labels (onBeforeTimeHeaderRender): an empty format tells the
// level of detail that hour cells always fit, so the ruler keeps its hours when zoomed out.
timeHeaders: [{ groupBy: 'Day' }, { groupBy: 'Hour', format: '' }],
headerHeight: HEADER_ROW,
zoomLevels,
zoom: initialZoom,
zoomPosition: 'left',
zoomGesture: { min: 4, max: 160 },
// Detail down to 12 px per hour, compact clips below, an overview strip under 6 px.
lod: { zoomedOut: 12 * 24, shading: 6 * 24 },
// Nights stay hidden: the board shows the studio's working day only.
businessBeginsHour: BUSINESS_HOURS.begin,
businessEndsHour: BUSINESS_HOURS.end,
showNonBusiness: false,
useEventBoxes: 'Never',
height: '100%',
treeEnabled: true,
treePreventParentUsage: true,
treeIndent: 0,
rowHeaderColumns: columns,
rowHeaderColumnsMergeParents: true,
rowHeaderWidth: narrow ? NARROW_HEADER_WIDTH : TRACK_HEADER_WIDTH,
rowHeaderWidthAutoFit: false,
eventHeight: CLIP_HEIGHT,
rowMarginTop: CLIP_INSET,
rowMarginBottom: CLIP_INSET,
eventBorderRadius: 4,
eventHtmlRightMargin: 6,
eventHtmlLeftMargin: 6,
durationBarVisible: true,
durationBarMode: 'PercentComplete',
durationBarHeight: 3,
linkShape: 'RightAngled',
linkLayer: 'Below',
crosshairType: 'Full',
separators: [{ location: NOW, layer: 'AboveEvents', width: 2, cssClass: 'fh-playhead' }],
allowEventOverlap: false,
conflictHighlight: true,
showToolTip: false,
keyboardEnabled: true,
keyboardTarget: 'component',
keyboardMode: 'Full',
history,
controlRef,
onEventsChange,
// Day row: date and production day. Ruler row: labels on major ticks, the playhead's tag.
onBeforeTimeHeaderRender: (args) => {
const header = args.header
const start = ticksOf(header.start)
const span = ticksOf(header.end) - start
const px = args.control.cellWidth ?? weekWidth
if (header.level === 0) {
const day = Math.floor((start - WEEK_START) / DAY) + 1
header.html = headers(`d:${start}:${span}`, () =>
span <= DAY
? dayHtml(headerLabel(start, 'day', tag, 'group'), day)
: rulerHtml(headerLabel(start, unitOfSpan(span, 'group'), tag, 'group')),
)
return
}
if (span > HOUR) {
// Zoomed far out the engine merges hours into days (a business day spans 12 hours).
const unit = span >= 6 * HOUR && span <= DAY ? 'day' : unitOfSpan(span, 'cell')
header.html = headers(`c:${start}:${span}:${px < 30 ? 'n' : 'w'}`, () =>
rulerHtml(headerLabel(start, unit, tag, 'cell', px)),
)
return
}
// Every hour carries its label; the zoom decides which ones show (data-ruler on the
// board, written on zoom frames without re-running this hook).
header.cssClass = 'fh-ruler'
header.html = headers(`h:${start}`, () =>
rulerHtml(headerLabel(start, 'hour', tag, 'cell'), tickStep(hourOf(start))),
)
if (NOW_TICKS >= start && NOW_TICKS < start + span) {
header.cssClass += ' fh-ruler--now'
header.areas = [
{
left: `${((NOW_TICKS - start) / span) * 100}%`,
top: 0,
bottom: 0,
width: 72,
cssClass: 'fh-ph-area',
html: headers(`p:${tag}`, () => playheadHtml(formatClock(NOW_TICKS, tag))),
},
]
}
},
// Narrow columns are titled with a glyph; their names stay for assistive tech.
onBeforeRowHeaderColumnRender: (args) => {
const name = args.column.data.name
if (name === text.columns.lock)
args.column.html = headers(`lock:${name}`, () => columnIconHtml('lock', name))
else if (name === text.columns.crew)
args.column.html = headers(`crew:${name}`, () => columnIconHtml('person', name))
},
onBeforeRowHeaderRender: (args) => {
const row = args.row
const room = roomOf(row.id)
if (room === null) {
const count = ROOMS.filter((candidate) => candidate.group === row.id).length
row.cssClass = 'fh-rh fh-rh--bin'
const html = rows(`b:${String(row.id)}:${row.name}`, () => binHtml(row.name, count))
row.html = html
const first = row.columns[0]
if (first !== undefined) first.html = html
return
}
const department = TRACK_DEPARTMENT[room.kind]
const locked = lockedTracks.has(room.id)
const lit = live.has(room.id)
row.cssClass = `fh-rh fh-rh--track${locked ? ' fh-rh--locked' : ''}`
const [first, second, third] = row.columns
if (first !== undefined)
first.html = rows(`t:${room.id}:${lit ? 1 : 0}:${text.rooms[room.id]}`, () =>
trackHtml(room.code, department, text.rooms[room.id], lit),
)
const lockColumn = narrow ? second : third
if (!narrow && second !== undefined) {
const label = plural(text.crew, room.crew, tag)
second.html = rows(`c:${room.id}:${label}`, () => crewHtml(room.crew, label))
}
if (lockColumn !== undefined) {
lockColumn.html = ''
lockColumn.areas = [
{
left: 8,
top: (CLIP_HEIGHT + 2 * CLIP_INSET - 24) / 2,
width: 24,
height: 24,
action: 'None',
cssClass: locked ? 'fh-lock fh-lock--on' : 'fh-lock',
html: lockIconHtml(locked),
toolTip: format(locked ? text.actions.unlockTrack : text.actions.lockTrack, {
code: room.code,
}),
onClick: () => onToggleLock(room.id),
},
]
}
},
// The past is shaded up to the playhead; a locked track is hatched.
onBeforeCellRender: (args) => {
const cell = args.cell
const room = roomOf(cell.resource)
if (room === null) {
cell.properties.cssClass = 'fh-cell--bin'
return
}
const past = ticksOf(cell.end) <= NOW_TICKS
const locked = lockedTracks.has(room.id)
// After the crew's day the studio pays overtime: the same warm tint as the crew strip.
const overtime = (ticksOf(cell.start) % DAY) / HOUR >= CREW_DAY_END
cell.properties.cssClass = cellClass(past, locked, overtime)
},
onBeforeEventRender: (args) => {
const data = args.data
const fields = readSessionFields(data)
if (fields === null) return
const id = String(data.id)
const room = data.resource === undefined ? null : roomOf(data.resource)
const start = ticksOf(data.start)
const end = ticksOf(data.end)
const range = { start: civil(start), end: civil(end) }
const department = departmentOf(fields.phase)
const state = timeState(range, NOW)
const isLate = late.has(id)
const trackLocked = room !== null && lockedTracks.has(room.id)
const classes = [
'fh-clip',
`fh-dept-${department}`,
`fh-phase-${fields.phase}`,
`fh-${state}`,
]
if (isLate) classes.push('fh-clip--late')
if (trackLocked) classes.push('fh-clip--locked')
if (id === selected) classes.push('fh-clip--selected')
data.cssClass = classes.join(' ')
const title = text.projects[fields.project]
const phase = text.phases[fields.phase]
data.ariaLabel = `${name(fields)}, ${room === null ? '' : `${room.code}, `}${formatWhen(start, tag)}${isLate ? `, ${text.card.late}` : ''}`
if (fields.phase === 'delivery') {
data['type'] = 'Milestone'
data['width'] = 20
data.html = ''
data.barHidden = true
const label = clips(`m:${id}:${start}:${isLate ? 1 : 0}:${tag}`, () =>
deliveryLabelHtml(title, formatWhen(start, tag), isLate ? text.card.late : null),
)
// Late in the week the label reads leftwards, inside the board.
if (start >= LABEL_LEFT_FROM) data.htmlLeft = label
else data.htmlRight = label
return
}
data.html = clips(
`e:${id}:${end - start}:${state}:${isLate ? 1 : 0}:${trackLocked ? 1 : 0}:${title}:${phase}`,
() =>
clipHtml({
title,
phase,
duration: timecode(end - start),
flag: isLate ? text.card.late : null,
rolling: state === 'rolling',
locked: trackLocked,
}),
)
if (TRACKS_PROGRESS.has(fields.phase)) data.complete = progressAt(range, NOW)
else data.barHidden = true
if (trackLocked) {
data.moveDisabled = true
data.resizeDisabled = true
}
const areas: SuperScheduler.AreaData[] = []
// The part of a late clip that overlaps the session it waits for, anchored in time.
const before = fields.after === undefined ? undefined : byId.get(fields.after)
if (isLate && before !== undefined) {
areas.push({
start: range.start,
end: civil(Math.min(end, parseCivil(before.end))),
top: 0,
bottom: 0,
cssClass: 'fh-clash',
action: 'Default',
})
}
// One hover action, clear of the resize edge and only on clips wide enough to keep a
// grip: the fix for a late clip, the inspector for the others.
const width = ((end - start) / HOUR) * (args.control.cellWidth ?? weekWidth)
if (width >= HOVER_ACTION_MIN_WIDTH) {
const fix = isLate && before !== undefined && fields.locked !== true
areas.push({
right: 7,
top: 3,
width: 18,
height: 18,
visibility: 'Hover',
action: 'None',
cssClass: fix ? 'fh-hover-act fh-hover-act--fix' : 'fh-hover-act',
html: iconHtml(fix ? 'after' : 'inspect'),
toolTip: fix
? format(text.actions.startAfter, { other: name(before) })
: text.actions.inspect,
onClick: () => {
closeHover()
if (fix) onAction('start-after', id)
else onSelect(id)
},
})
}
data.areas = areas
},
// Track locks, the playhead and room compatibility are application rules; overlap is
// enforced by the library.
onEventMoving: (args) => {
const id = String(args.e.id())
const reason = sessionRefusal(args.e.data, id, args.resource, args.start)
if (reason !== null) {
args.allowed = false
args.message = reason
refusal.track(id, reason)
return
}
refusal.track(id, overlapRefusal(args.conflicts))
},
onEventResizing: (args) => {
const id = String(args.e.id())
const reason = sizeRefusal(id, args.start, args.end)
if (reason !== null) {
args.allowed = false
args.message = reason
refusal.track(id, reason)
return
}
refusal.track(id, overlapRefusal(args.conflicts))
},
// Final checks before the commit (also cover keyboard moves and resizes).
onEventMove: (args) => {
const id = String(args.e.id())
const reason = sessionRefusal(args.e.data, id, args.newResource, args.newStart)
if (reason !== null) {
args.preventDefault()
refusal.clear()
onRefused(id, reason)
}
},
onEventResize: (args) => {
const id = String(args.e.id())
const reason = sizeRefusal(id, args.newStart, args.newEnd)
if (reason !== null) {
args.preventDefault()
refusal.clear()
onRefused(id, reason)
}
},
onEventMoved: (args) => {
refusal.clear()
onMoved(String(args.e.id()))
},
onEventResized: (args) => {
refusal.clear()
onResized(String(args.e.id()), args.newEnd)
},
// A click (or Enter) docks the clip into the inspector; the hover card steps aside.
onEventClick: (args) => {
closeHover()
onSelect(String(args.e.id()))
},
onZoom: (args) => {
syncRuler(args.control, args.cellWidth)
if (args.phase === 'end') onZoomEnd(args.cellWidth)
},
}
}, [
history,
controlRef,
byId,
sessions,
late,
lockedTracks,
narrow,
weekWidth,
columns,
skin,
selected,
common,
refusal,
refusalText,
closeHover,
onEventsChange,
onMoved,
onRefused,
onResized,
onSelect,
onAction,
onToggleLock,
onZoomEnd,
schedulerLocale,
tag,
text,
name,
initialZoom,
])
// Imperative and once: a scroll prop would be re-applied on every update.
useEffect(() => {
const control = controlRef.current
if (control === null) return
control.scrollTo(INITIAL_VIEW_START, false, 'left')
syncRuler(control, control.cellWidth ?? weekWidth)
}, [controlRef, weekWidth])
return (
<SuperSchedulerComponent
{...config}
resources={resources}
events={events}
links={links}
eventHover={eventHover}
dragCard={dragCard}
contextMenu={contextMenu}
/>
)
}
/**
* Which ruler labels show at a zoom: written as `data-ruler` on the board's wrapper, only when it
* changes. A DOM attribute, so a pinch or the slider re-render nothing.
*/
function syncRuler(control: SuperScheduler.Scheduler, pxPerHour: number): void {
const board = control.nav.top?.closest<HTMLElement>('.fh-live')
if (board === null || board === undefined) return
const step = String(rulerStep(pxPerHour))
if (board.dataset['ruler'] !== step) board.dataset['ruler'] = step
}El archivo contiene los ficheros de este ejemplo y un README. No incluye SuperScheduler Pro ni ninguna clave de descarga.