Training room scheduling
Enrolment outgrew the room. Select both sittings, see what is free for both, move them together and keep the view.
- Training
- Morrow
- Multi-selection
- Row columns
- Saved views
- Summary rows
- Minimap
- Live search
- Filters
- Context menu
- Theming
- Demo with synthetic data
Mission
0 of 3 steps doneData literacy now has 20 people enrolled and Birch has 16 seats. Both sittings, Tuesday and Thursday morning, have to move.
Select both Data literacy sessions in Birch. — To do
Click one, then Ctrl/⌘+click the other. Rooms that are free and big enough for both are marked “Free”.
Drag them together into the room that fits both. — To do
Drag either selected session down to Delta and the other follows. Cedar is refused: no projector and 12 seats.
Save this view, then reopen it from the Views menu. — To do
Views → Save current view, pick a preset, then choose your saved view.
About 30 seconds. Steps tick off as you complete them.
Keyboard: focus the grid, then use arrow keys, Enter and Alt+arrows to move.
Preview of the first frameLive: the real Pro engine, running in your browserAbout 30 seconds. Steps tick off as you complete them. Keyboard: focus the grid, then use arrow keys, Enter and Alt+arrows to move.
The situation.
Morrow is a fictional corporate training centre with four classrooms, two workshops and four instructors. Courses run in half-day blocks over two weeks; each sitting needs a room with the right equipment and enough seats, and an instructor who is not teaching elsewhere or away.
When late enrolments push a course past its room’s capacity, the coordinators need a room that is free at every sitting, suits the course and keeps the sittings together. Checking that by eye across ten days is slow and easy to get wrong: the board has to answer it from a selection, and keep each coordinator’s usual layout one click away.
What you will do
You will select both sittings of a course, see the rooms and instructors that share availability with them, move them together into the room that fits, and save the view to reopen it later.
Where the library ends and your application begins.
SuperScheduler provides
- Grouped rows with four rowHeaderColumns (room, seats, equipment icons, booked hours) that sort (sort), resize (rowHeaderColumnsResizable) and reorder (rowHeaderColumnsReorderable); onBeforeRowHeaderRender finds each cell by its column's display id.
- Click and Ctrl/⌘+click multi-selection kept by the control (multiselect.events()), drag with overlap refusal and crosshairType: 'Full'.
- Live search through control.events.filter() and onEventFilter, row filtering through control.rows.filter() and onRowFilter, and cell classes through onBeforeCellRender.
- Cards written in onBeforeEventRender with a seats rule drawn as an event area; week numbers written by onBeforeTimeHeaderRender after each Monday’s label.
- Hour and half-day grids with nights and weekends hidden, keyboard navigation and announcements.
- getViewState and applyViewState from super-scheduler/views (zoom, scroll, collapsed groups, column widths and order as JSON), the event hover card, the drag card, a context menu and undo history from super-scheduler/history.
- A frozen summary row (frozen: 'top', cellsDisabled) with the rooms free in each block, painted by onBeforeCellRender; under the grid, the minimap of super-scheduler/minimap fed with the centre's own series over a fixed range, a tone per day and translated labels, its brush moving the timetable.
This example’s code decides
- Example rules between resources: equipment, seats and instructor availability for each session.
- Shared availability: the rooms and instructors free and suitable for every selected session.
- Moving the other selected sessions with the dragged one: onEventMove hands the whole group to the app, which applies it as one change and one undo step.
- What the search reads (course, code, instructor, room), the seat filter, the “Free for selection” filter, and the instructors’ teaching time derived from the sessions.
- The best free room for a session or a whole selection: suitable and free for all of them, the smallest first.
- Where views are stored (here, in memory for the visit), the timetable’s key and week numbers, and every label on this page.
- The register: room hours booked per day over the hours the rooms can teach, the days a session outgrew its room, the busiest day, and the rooms free in each block.
The code behind this demo.
These are the files this page runs, not a simplified copy. They compile against the public SuperScheduler Pro exports.
The integration: sortable, resizable and reorderable row-header columns, multi-selection, the move checks and the group move of the selected sessions, the live search, the hover card, drag verdict and context menu, the availability highlight in onBeforeCellRender and the filter handed to 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,
)
}The archive contains this example’s files and a README. It does not include SuperScheduler Pro or any download key.