Planificación de aulas de formación
La matrícula superó el aula. Selecciona ambas sesiones, mira qué está libre para las dos, muévelas juntas y conserva la vista.
- Formación
- Morrow
- Multiselección
- Columnas de fila
- Vistas guardadas
- Filas de resumen
- Minimapa
- Búsqueda en vivo
- Filtros
- Menú contextual
- Temas
- Demo con datos sintéticos
Misión
0 de 3 pasos hechosAlfabetización de datos tiene ya 20 personas inscritas y Birch tiene 16 plazas. Las dos sesiones, martes y jueves por la mañana, tienen que cambiar de aula.
Selecciona las dos sesiones de Alfabetización de datos en Birch. — Pendiente
Haz clic en una y Ctrl/⌘+clic en la otra. Las aulas libres y con plazas para ambas se marcan como «Libre».
Arrástralas juntas al aula que sirve para las dos. — Pendiente
Arrastra cualquiera de las sesiones seleccionadas hasta Delta y la otra la sigue. Cedar se rechaza: sin proyector y con 12 plazas.
Guarda esta vista y vuelve a abrirla desde el menú Vistas. — Pendiente
Vistas → Guardar la vista actual, elige otra vista predefinida y luego la tuya.
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.
Morrow es un centro de formación de empresa ficticio con cuatro aulas, dos talleres y cuatro formadores. Los cursos se imparten en medias jornadas durante dos semanas; cada sesión necesita un aula con el equipamiento adecuado y plazas suficientes, y un formador que no esté dando otra clase ni ausente.
Cuando las matrículas de última hora superan el aforo de un aula, coordinación necesita un aula libre en todas las sesiones, adecuada al curso y que mantenga las sesiones juntas. Comprobarlo a ojo en diez días es lento y fácil de fallar: el cuadrante tiene que responderlo a partir de una selección y dejar a un clic la disposición habitual de cada coordinador.
Qué vas a hacer
Seleccionarás las dos sesiones de un curso, verás qué aulas y formadores comparten disponibilidad con ellas, las moverás juntas al aula que encaja y guardarás la vista para recuperarla después.
Dónde termina la librería y empieza tu aplicación.
SuperScheduler aporta
- Filas agrupadas con cuatro rowHeaderColumns (aula, plazas, iconos de equipamiento, horas) que se ordenan (sort), cambian de ancho (rowHeaderColumnsResizable) y de orden (rowHeaderColumnsReorderable); onBeforeRowHeaderRender localiza cada celda por el display de su columna.
- Selección múltiple con clic y Ctrl/⌘+clic que guarda el control (multiselect.events()), arrastre con rechazo de solapes y crosshairType: 'Full'.
- Búsqueda en vivo con control.events.filter() y onEventFilter, filtrado de filas con control.rows.filter() y onRowFilter, y clases de celda con onBeforeCellRender.
- Tarjetas escritas en onBeforeEventRender con una regla de plazas dibujada como área del evento; números de semana escritos con onBeforeTimeHeaderRender tras la etiqueta de cada lunes.
- Rejillas de horas y de medias jornadas sin noches ni fines de semana, navegación con teclado y anuncios.
- getViewState y applyViewState de super-scheduler/views (zoom, scroll, grupos plegados, anchos y orden de columnas en JSON), la tarjeta al pasar el ratón, la tarjeta de arrastre, un menú contextual y el historial de deshacer de super-scheduler/history.
- Una fila de resumen fija (frozen: 'top', cellsDisabled) con las aulas libres de cada bloque, pintada por onBeforeCellRender; bajo la rejilla, el minimapa de super-scheduler/minimap alimentado con la serie propia del centro sobre un rango fijo, un tono por día y etiquetas traducidas, cuyo selector desplaza el horario.
El código de este ejemplo decide
- Reglas de ejemplo entre recursos: equipamiento, plazas y disponibilidad del formador en cada sesión.
- Disponibilidad compartida: las aulas y formadores libres y adecuados para todas las sesiones seleccionadas.
- Mover las demás sesiones seleccionadas con la arrastrada: onEventMove entrega el grupo a la aplicación, que lo aplica como un solo cambio y un solo paso de deshacer.
- Lo que lee la búsqueda (curso, código, formador, aula), el filtro de plazas, el filtro «Libres para la selección» y las horas de clase de cada formador, derivadas de las sesiones.
- La mejor aula libre para una sesión o una selección: adecuada y libre para todas, la más pequeña primero.
- Dónde se guardan las vistas (aquí, en memoria durante la visita), la leyenda y los números de semana del horario, y todos los textos de esta página.
- El registro: horas de aula reservadas por día frente a las horas lectivas de las aulas, los días en que una sesión supera su aula, el día más lleno y las aulas libres de cada bloque.
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: columnas de cabecera de fila ordenables, redimensionables y reordenables, la selección múltiple, las comprobaciones de movimiento y el movimiento en grupo, la búsqueda en vivo, la tarjeta al pasar el ratón, el veredicto de arrastre y el menú contextual, el resaltado de disponibilidad en onBeforeCellRender y el filtro que recibe rows.filter().
/**
* Morrow timetable: classrooms, workshops and instructors over two teaching weeks.
*
* Library: grouped rows with four rowHeaderColumns (sortable through `sort`, resizable and
* reorderable: rowHeaderColumnsResizable, rowHeaderColumnsReorderable), a frozen summary row
* (`frozen: 'top'`, painted by onBeforeCellRender), hour and half-day grids
* with nights and weekends hidden, week numbers in the time header (onBeforeTimeHeaderRender),
* the full crosshair, multi-selection (Ctrl/⌘+click), row filtering (rows.filter and
* onRowFilter), live search (events.filter and onEventFilter), cell styling (onBeforeCellRender),
* cards with a seats rule (event areas), the drag card, the event hover card
* (super-scheduler/react-render), a context menu, undo history, keyboard and announcements.
* Application (example logic): which room suits which course, when an instructor is free, which
* rooms and instructors share availability with the selected sessions, the best free room, how
* many rooms are free in each block, and moving the other selected sessions along with a dragged
* one. See ./rules.
*/
import { useCallback, useEffect, useMemo, useSyncExternalStore, type RefObject } from 'react'
import type {
SchedulerBeforeTimeHeaderRenderArgs,
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, parseCivil, type CivilDateTime } from '../../scheduler/civil'
import { toneClass } from '../../scheduler/tones'
import { createEventMenu } from '../kit/context-menu'
import { formatClock, formatDay, formatSpan } from '../kit/format'
import { useEventHover, type HoverCardModel } from '../kit/hover-card'
import { KEYS } from '../kit/keys'
import { createSpanHeaderHook } from '../kit/span-header-hook'
import { useDropRefusal } from '../kit/use-drop-refusal'
import { createDragCard } from '../kit/verdict'
import { skinClass, skinMenuTheme } from '../registry'
import type { DemoCommon } from '../types'
import {
CELL_WIDTH,
FREE_ROW,
GEOMETRY,
courseTone,
civilOf,
isInstructorId,
isRoomId,
itemLabels,
readCentreFields,
toResources,
type CentreEvent,
} from './adapter'
import {
COURSE_CODES,
COURSE_KIT,
INITIAL_VIEW_START,
PERIOD,
TEACHING_HOURS,
type CentreItem,
type RoomId,
type Session,
} from './model'
import {
bestRoom,
companionLandings,
matchesSearch,
instructorIssue,
roomFree,
roomIssue,
roomOf,
seatLoad,
sessionIssues,
sharedAvailability,
withinTeachingHours,
} from './rules'
import type { MorrowText, SeatFilter, ZoomId } from './text'
import {
PERIOD_HOURS,
createCardHtml,
createFreeCells,
createRowCells,
isColumnId,
weekBadge,
} from './timetable-html'
import type { MorrowFilters } from './views'
import './tokens.css'
import './morrow.css'
/** The toolbar's filters, handed to `control.rows.filter()` and read back in onRowFilter. */
export class RowFilter {
constructor(
readonly minSeats: number,
/** Rows to keep (shared availability plus the rows of the selection), or null for all. */
readonly only: ReadonlySet<string> | null,
) {}
}
/** What the board asks the demo to do (context menu). */
export type SessionAction = 'details' | 'best-room' | 'sittings'
/** Where one session of a group move lands. */
export interface Move {
readonly id: string
readonly room: RoomId
readonly start: CivilDateTime
readonly end: CivilDateTime
}
export interface MorrowSchedulerProps {
readonly events: CentreEvent[]
/** The same data read back as the centre's model, for the rules. */
readonly items: readonly CentreItem[]
/** Ids of the selected sessions (mirrors the control's multiselect). */
readonly selected: readonly string[]
readonly filters: MorrowFilters
/** The live search query (empty: every session). */
readonly search: string
readonly text: MorrowText
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 or saved views. */
readonly initialZoom: ZoomId
readonly history: SchedulerHistory
readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
readonly onSelectionChange: (ids: readonly string[]) => void
/** One session moved by the library. */
readonly onMoved: (id: string) => void
/** A selected session was dropped: it and the other selected sessions land together. */
readonly onGroupMove: (moves: readonly Move[]) => void
/** A drop or a keyboard move the centre refused, with its sentence. */
readonly onRefused: (id: string, message: string) => void
readonly onAction: (action: SessionAction, id: string) => void
readonly onZoomLevel: (level: ZoomId) => void
}
const ZOOM_LEVELS: SuperScheduler.ZoomLevel[] = [
{
id: 'hours',
properties: {
scale: 'Hour',
cellWidth: CELL_WIDTH.hours,
timeHeaders: [{ groupBy: 'Day' }, { groupBy: 'Hour' }],
},
},
// Morning and afternoon blocks: 8:00-12:00 and 12:00-16:00.
{
id: 'week',
properties: {
scale: 'CellDuration',
cellDuration: 240,
cellWidth: CELL_WIDTH.week,
timeHeaders: [{ groupBy: 'Day' }, { groupBy: 'Cell' }],
},
},
]
const ZOOM_IDS: readonly ZoomId[] = ['hours', 'week']
/** The query of the live search, handed to `control.events.filter()`. */
export class SearchFilter {
constructor(readonly query: string) {}
}
const MIN_SEATS = { all: 0, '16': 16, '24': 24 } as const satisfies Record<SeatFilter, number>
export function MorrowScheduler(props: MorrowSchedulerProps) {
const {
events,
items,
selected,
filters,
search,
text,
common,
tag,
schedulerLocale,
initialZoom,
} = props
const { history, controlRef } = props
const { onEventsChange, onSelectionChange, onMoved, onGroupMove, onRefused, onAction } = props
const { onZoomLevel } = props
const resources = useMemo(() => toResources(text), [text])
const issues = useMemo(() => sessionIssues(items), [items])
const dropRefusal = useDropRefusal(onRefused)
// Hover card: the room against what the course needs, the instructor, and the rule that fails
// or holds.
const card = useCallback(
(event: SuperScheduler.Event): HoverCardModel | null => {
const item = items.find((candidate) => candidate.id === String(event.id()))
if (item === undefined) return null
const start = parseCivil(item.start)
const end = parseCivil(item.end)
const midnight = start - (start % DAY)
const time = {
start,
end,
day: formatDay(start, tag),
startLabel: formatClock(start, tag),
endLabel: formatClock(end, tag),
span: formatSpan(end - start, tag),
window: {
start: midnight + TEACHING_HOURS.begin * HOUR,
end: midnight + TEACHING_HOURS.end * HOUR,
},
}
if (item.kind === 'away') {
return {
id: item.id,
tone: 'blocked',
eyebrow: text.instructors[item.instructor],
title: text.away[item.reason],
time,
facts: [],
rule: { state: 'blocked', text: text.rules.fixed },
}
}
const room = roomOf(item.room)
const issue = issues.get(item.id) ?? null
const kit = COURSE_KIT[item.course]
const people = plural(text.people, item.attendees, tag)
return {
id: item.id,
tone: courseTone(item.course),
eyebrow: `${COURSE_CODES[item.course]} · ${text.rooms[item.room]} · ${plural(text.seatCount, room.seats, tag)}`,
title: text.courses[item.course],
status:
issue === null
? { label: text.card.chips.ok, tone: 'success' }
: { label: text.card.chips[issue], tone: 'danger' },
time,
facts: [
{ label: text.fields.instructor, value: text.instructors[item.instructor] },
{ label: text.fields.attendees, value: people, alert: issue === 'seats' },
{
label: text.card.needs,
value: kit === null ? text.card.anyRoom : text.kits[kit],
alert: issue === 'kit',
},
],
rule:
issue === 'seats'
? {
state: 'blocked',
text: format(text.card.seatsRule, {
people,
seats: plural(text.seatCount, room.seats, tag),
room: text.rooms[item.room],
}),
}
: issue === 'kit' && kit !== null
? { state: 'blocked', text: text.rules.kit[kit] }
: issue === 'teaching' || issue === 'away'
? { state: 'blocked', text: text.rules[issue] }
: { state: 'ok', text: format(text.card.fits, { room: text.rooms[item.room] }) },
// A click selects on this board (Ctrl/⌘ adds), so Enter selects too.
hints: [
{ keys: KEYS.details, label: text.card.select },
{ keys: KEYS.actions, label: common.kit.actions },
{ keys: KEYS.move, label: common.kit.move },
],
}
},
[items, issues, text, common, tag],
)
const { eventHover, suppressHover } = useEventHover(card)
// Context menu: rebuilt when the plan changes, so its labels name the real room.
const contextMenu = useMemo(
() =>
createEventMenu({
theme: skinMenuTheme('training-rooms'),
title: (event) => {
const item = items.find((candidate) => candidate.id === String(event.id()))
return format(common.kit.menuTitle, {
name: item?.kind === 'session' ? text.courses[item.course] : String(event.id()),
})
},
onOpenChange: (open) => suppressHover(open),
entries: (event) => {
const id = String(event.id())
const session = items.find(
(item): item is Session => item.kind === 'session' && item.id === id,
)
if (session === undefined) return []
const room = bestRoom([session], items)
const here = room === session.room
return [
{ label: common.kit.openDetails, icon: 'details', run: () => onAction('details', id) },
{
label:
room === null
? text.actions.noRoom
: here
? text.actions.inBestRoom
: format(text.actions.bestRoom, { room: text.rooms[room] }),
icon: 'after',
primary: room !== null && !here && issues.has(id),
disabled: room === null || here,
run: () => onAction('best-room', id),
},
'separator',
{
label: format(text.actions.sittings, { course: text.courses[session.course] }),
icon: 'layers',
run: () => onAction('sittings', id),
},
]
},
}),
[items, issues, common, text, onAction, suppressHover],
)
// Shared availability of the selection, and the time spans the grid highlights for it.
const selection = useMemo(
() =>
items.filter(
(item): item is Session => item.kind === 'session' && selected.includes(item.id),
),
[items, selected],
)
const shared = useMemo(() => sharedAvailability(selection, items), [selection, items])
const fitRows = useMemo(() => new Set<string>([...shared.rooms, ...shared.instructors]), [shared])
const selectedSpans = useMemo(
() => selection.map((session) => [parseCivil(session.start), parseCivil(session.end)] as const),
[selection],
)
// The frozen row's blocks: rooms free, the selection's blocks highlighted, the shared rooms stamped.
const freeCells = useMemo(
() => createFreeCells({ items, text, tag }, new Set(shared.rooms)),
[items, text, tag, shared],
)
// Drag verdict: the room, the slot and the centre's reason when it refuses; dragging one of the
// selected sessions warns that the others move with it.
const dragCard = useMemo(
() =>
createDragCard({
tag,
common,
rowName: (id) =>
isRoomId(id) ? text.rooms[id] : isInstructorId(id) ? text.instructors[id] : null,
warn: (info) => {
const id = String(info.eventId)
const others = selection.some((session) => session.id === id) ? selection.length - 1 : 0
return others > 0 ? plural(text.card.companions, others, tag) : null
},
}),
[tag, common, text, selection],
)
// Instructor rows show when each instructor teaches, derived from the sessions on room rows.
const teaching = useMemo(() => {
const spans = new Map<string, (readonly [number, number])[]>()
for (const item of items) {
if (item.kind !== 'session') continue
spans.set(item.instructor, [
...(spans.get(item.instructor) ?? []),
[parseCivil(item.start), parseCivil(item.end)] as const,
])
}
return spans
}, [items])
const compact = useNarrowScreen()
// Day and hour labels from the shared Intl texts (same as the preview), and each Monday's week
// number after its label.
const headerHook = useMemo(() => {
const labels = createSpanHeaderHook(tag, (span, level) =>
level === 'group' ? 'day' : span >= 4 * HOUR ? 'hours-4' : 'hour',
)
return (args: SchedulerBeforeTimeHeaderRenderArgs) => {
labels(args)
if (args.header.level !== 0) return
const week = weekBadge(args.header.start.getTime(), args.header.end.getTime(), text)
if (week === null) return
args.header.html = `${args.header.html}${week.html}`
args.header.toolTip = week.tip
}
}, [tag, text])
// Four columns, each named by the cell it shows (`display`), so the hook finds them after the
// visitor reorders them. Phones keep the name only; the rest is in the details panel.
const rowHeaderColumns = useMemo<SuperScheduler.RowHeaderColumnData[]>(
() => [
{
title: text.columns.resource,
display: 'name',
sort: 'name',
width: compact ? 112 : GEOMETRY.columns.name,
},
{
title: text.columns.seats,
display: 'seats',
sort: 'seats',
width: GEOMETRY.columns.seats,
hidden: compact,
},
{ title: text.columns.kit, display: 'kit', width: GEOMETRY.columns.kit, hidden: compact },
{
title: text.columns.booked,
display: 'booked',
width: GEOMETRY.columns.booked,
toolTip: format(text.columns.bookedTip, { total: PERIOD_HOURS }),
hidden: compact,
},
],
[text, compact],
)
// What the grid prints, rebuilt when the plan changes and cached inside.
const paint = useMemo(() => {
const context = { items, text, tag }
return { card: createCardHtml(context), row: createRowCells(context) }
}, [items, text, tag])
const config = useMemo<SchedulerRenderProps>(() => {
const sessions = new Map(
items.flatMap((item) => (item.kind === 'session' ? [[item.id, item] as const] : [])),
)
// The selected sessions that follow a dragged one (only when the dragged one is selected too).
const companionsOf = (id: string, room: RoomId, start: string) => {
const dragged = sessions.get(id)
return dragged !== undefined && selection.some((session) => session.id === id)
? companionLandings(dragged, room, start, selection)
: []
}
// Why the centre refuses this landing, for the dragged session and each companion, or null.
const refusal = (
data: object,
resource: SuperScheduler.ResourceId,
start: CivilDateTime,
end: CivilDateTime,
): string | null => {
const fields = readCentreFields(data)
if (fields === null) return null
if (fields.kind === 'away') return text.rules.fixed
if (!isRoomId(resource)) return text.rules.notRoom
const id = 'id' in data ? String(data.id) : ''
const companions = companionsOf(id, resource, start)
const moving = new Set([id, ...companions.map((landing) => landing.session.id)])
const landings = [
{ ...fields, room: resource, start, end, companion: false },
...companions.map((landing) => ({ ...landing.session, ...landing, companion: true })),
]
for (const landing of landings) {
if (!withinTeachingHours(landing)) return text.rules.hours
const room = roomIssue(landing.course, landing.attendees, landing.room)
const kit = COURSE_KIT[landing.course]
if (room === 'kit' && kit !== null) return text.rules.kit[kit]
if (room === 'seats') return text.rules.seats
// The library checks overlaps for the dragged session only; companions are checked here.
if (landing.companion && !roomFree(landing.room, landing, items, moving))
return text.rules.roomTaken
const instructor = instructorIssue(landing.instructor, landing, items, moving)
if (instructor !== null) return text.rules[instructor]
}
return null
}
const known = new Map(items.map((item) => [item.id, item]))
return {
locale: schedulerLocale,
startDate: PERIOD.start,
days: PERIOD.days,
zoomLevels: ZOOM_LEVELS,
zoom: initialZoom,
zoomPosition: 'left',
// Courses run 8:00 to 16:00 on weekdays: nights and weekends are hidden.
businessBeginsHour: TEACHING_HOURS.begin,
businessEndsHour: TEACHING_HOURS.end,
showNonBusiness: false,
height: '100%',
cssClass: `mr-board ${skinClass('training-rooms')}`,
treeEnabled: true,
treePreventParentUsage: true,
rowHeaderColumns,
rowHeaderColumnsResizable: true,
rowHeaderColumnsReorderable: true,
rowHeaderWidthAutoFit: false,
eventHeight: GEOMETRY.eventHeight,
rowMarginTop: GEOMETRY.rowMargin,
rowMarginBottom: GEOMETRY.rowMargin,
crosshairType: 'Full',
useEventBoxes: 'Never',
allowEventOverlap: false,
conflictHighlight: true,
// Click selects; Ctrl/⌘+click adds to the selection (the control keeps it in multiselect).
eventClickHandling: 'Select',
allowMultiSelect: true,
durationBarVisible: false,
showToolTip: false,
keyboardEnabled: true,
keyboardTarget: 'component',
keyboardMode: 'Full',
history,
controlRef,
onEventsChange,
onBeforeTimeHeaderRender: headerHook,
// Each cell is written from its column's id, wherever the visitor moved the column.
onBeforeRowHeaderRender: (args) => {
const id = String(args.row.id)
const cells = paint.row(id, fitRows.has(id))
if (cells === null) return
const specs = controlRef.current?.rowHeaderColumns ?? rowHeaderColumns
args.row.columns.forEach((column, index) => {
const display = specs[index]?.display
// A group row has a single cell spanning the columns: it shows the group's name.
const key = args.row.columns.length === 1 ? 'name' : display
if (isColumnId(key)) column.html = cells[key]
})
args.row.cssClass =
id === FREE_ROW
? 'mr-row--free'
: args.row.data.children !== undefined
? 'mr-row--group'
: fitRows.has(id)
? 'mr-rh--fit'
: ''
},
onBeforeCellRender: (args) => {
const { cell } = args
if (cell.isParent) return
const from = cell.start.getTime()
const to = cell.end.getTime()
const hit = (spans: readonly (readonly [number, number])[] | undefined) =>
spans?.some(([start, end]) => start < to && from < end) === true
if (cell.resource === FREE_ROW) {
const painted = freeCells(from, to, hit(selectedSpans))
cell.properties.html = painted.html
cell.properties.cssClass = painted.cssClass
return
}
const classes: string[] = []
if (hit(teaching.get(String(cell.resource)))) classes.push('mr-cell--teaching')
if (fitRows.has(String(cell.resource)) && hit(selectedSpans)) classes.push('mr-cell--fit')
cell.properties.cssClass = classes.join(' ')
},
onBeforeEventRender: (args) => {
const fields = readCentreFields(args.data)
const id = String(args.data.id)
const item = known.get(id)
if (fields === null || item === undefined) return
// The control may hold a newer room and times than React (a drop lands first).
const start = civilOf(args.data.start)
const end = civilOf(args.data.end)
const resource = args.data.resource
const live: CentreItem =
item.kind === 'session' && resource !== undefined && isRoomId(resource)
? { ...item, room: resource, start, end }
: { ...item, start, end }
args.data.html = paint.card(live)
if (live.kind === 'away') {
args.data.cssClass = 'mr-ev mr-ev--away'
return
}
const classes = ['mr-ev', 'mr-ev--session', toneClass(courseTone(live.course))]
if (issues.has(id)) classes.push('mr-ev--issue')
// The control tracks the selection; the app draws it, since several sessions can be selected.
if (selected.includes(id)) classes.push('mr-ev--selected')
args.data.cssClass = classes.join(' ')
// The seats rule along the card's foot: enrolled over seats, red past the room's size.
const load = seatLoad(live)
args.data.areas = [
{
left: 0,
bottom: 0,
height: 3,
width: `${Math.round(Math.min(1, load) * 1000) / 10}%`,
nonFloating: true,
cssClass: load > 1 ? 'mr-seatbar mr-seatbar--over' : 'mr-seatbar',
toolTip: format(text.card.seatsTip, {
people: plural(text.people, live.attendees, tag),
seats: plural(text.seatCount, roomOf(live.room).seats, tag),
}),
},
]
},
// Live search: sessions whose course, code, instructor or room start with the query's words.
onEventFilter: (args) => {
const filter = args.filterParam
if (!(filter instanceof SearchFilter)) return
const item = known.get(String(args.e.id()))
args.visible = item !== undefined && matchesSearch(itemLabels(item, text), filter.query)
},
// Room suitability, instructor availability and teaching hours for every session that moves.
onEventMoving: (args) => {
const id = String(args.e.id())
const message = refusal(args.e.data, args.resource, civilOf(args.start), civilOf(args.end))
dropRefusal.track(id, message)
if (message !== null) {
args.allowed = false
args.message = message
}
},
// Final check before the commit (also covers keyboard moves). A selected session takes the
// others with it: the app applies the whole group as one change and one undo step.
onEventMove: (args) => {
const id = String(args.e.id())
const start = civilOf(args.newStart)
const end = civilOf(args.newEnd)
const message = refusal(args.e.data, args.newResource, start, end)
if (message !== null) {
args.preventDefault()
dropRefusal.clear()
onRefused(id, message)
return
}
if (!isRoomId(args.newResource)) return
const companions = companionsOf(id, args.newResource, start)
if (companions.length === 0) return
args.preventDefault()
dropRefusal.clear()
onGroupMove([
{ id, room: args.newResource, start, end },
...companions.map((landing) => ({
id: landing.session.id,
room: landing.room,
start: landing.start,
end: landing.end,
})),
])
},
onEventMoved: (args) => {
dropRefusal.clear()
onMoved(String(args.e.id()))
},
onEventSelected: () => {
const control = controlRef.current
if (control !== null)
onSelectionChange(control.multiselect.events().map((event) => String(event.id())))
},
onRowFilter: (args) => {
const filter = args.filterParam
if (!(filter instanceof RowFilter)) return
const id = args.row.id
if (isRoomId(id))
args.visible =
roomOf(id).seats >= filter.minSeats && (filter.only === null || filter.only.has(id))
else if (isInstructorId(id)) args.visible = filter.only === null || filter.only.has(id)
},
onZoom: (args) => {
if (args.phase !== 'end') return
const level = ZOOM_IDS[args.level]
if (level !== undefined) onZoomLevel(level)
},
}
}, [
controlRef,
dropRefusal,
fitRows,
freeCells,
headerHook,
paint,
rowHeaderColumns,
initialZoom,
issues,
items,
history,
onEventsChange,
onGroupMove,
onMoved,
onRefused,
onSelectionChange,
onZoomLevel,
schedulerLocale,
selected,
selectedSpans,
selection,
tag,
teaching,
text,
])
// Filters go through the library's row filtering; the rows of the selection always stay.
const rowFilter = useMemo(() => {
const keep =
filters.freeOnly && selection.length > 0
? new Set([
...fitRows,
...selection.flatMap((session) => [session.room, session.instructor]),
])
: null
return new RowFilter(MIN_SEATS[filters.seats], keep)
}, [filters, selection, fitRows])
useEffect(() => {
controlRef.current?.rows.filter(rowFilter)
}, [controlRef, rowFilter])
// The live search goes through the library's event filtering; an empty query clears it.
useEffect(() => {
const query = search.trim()
controlRef.current?.events.filter(query === '' ? null : new SearchFilter(query))
}, [controlRef, search])
// Imperative and once: the board opens on the Monday of week 46.
useEffect(() => {
controlRef.current?.scrollTo(INITIAL_VIEW_START, false, 'left')
}, [controlRef])
return (
<SuperSchedulerComponent
{...config}
resources={resources}
events={events}
eventHover={eventHover}
dragCard={dragCard}
contextMenu={contextMenu}
/>
)
}
const NARROW = '(max-width: 639px)'
/** True on phone-sized screens (the stage is then too narrow for three header columns). */
function useNarrowScreen(): boolean {
return useSyncExternalStore(
(notify) => {
const query = window.matchMedia(NARROW)
query.addEventListener('change', notify)
return () => query.removeEventListener('change', notify)
},
() => window.matchMedia(NARROW).matches,
() => false,
)
}El archivo contiene los ficheros de este ejemplo y un README. No incluye SuperScheduler Pro ni ninguna clave de descarga.