Planung von Schulungsräumen
Die Anmeldungen sprengen den Raum. Beide Termine wählen, sehen, was für beide frei ist, zusammen verschieben und die Ansicht behalten.
- Weiterbildung
- Morrow
- Mehrfachauswahl
- Zeilenspalten
- Gespeicherte Ansichten
- Summenzeilen
- Minimap
- Live-Suche
- Filter
- Kontextmenü
- Theming
- Demo mit synthetischen Daten
Aufgabe
0 von 3 Schritten erledigtFür Datenkompetenz sind jetzt 20 Personen angemeldet, Birch hat 16 Plätze. Beide Termine, Dienstag- und Donnerstagvormittag, müssen umziehen.
Wählen Sie beide Termine von Datenkompetenz in Birch aus. — Offen
Einen anklicken, den anderen mit Strg/⌘+Klick. Räume, die für beide frei und groß genug sind, tragen die Marke „Frei“.
Ziehen Sie beide zusammen in den Raum, der für beide passt. — Offen
Einen der ausgewählten Termine auf Delta ziehen, der andere folgt. Cedar wird abgelehnt: kein Beamer, 12 Plätze.
Speichern Sie diese Ansicht und öffnen Sie sie über das Menü Ansichten wieder. — Offen
Ansichten → Aktuelle Ansicht speichern, eine Vorlage wählen und dann Ihre gespeicherte Ansicht.
Etwa 30 Sekunden. Erledigte Schritte werden abgehakt.
Tastatur: Raster fokussieren, dann Pfeiltasten, Eingabe und Alt+Pfeile zum Verschieben.
Vorschau des ersten BildesLive: die echte Pro-Engine, in Ihrem BrowserEtwa 30 Sekunden. Erledigte Schritte werden abgehakt. Tastatur: Raster fokussieren, dann Pfeiltasten, Eingabe und Alt+Pfeile zum Verschieben.
Die Ausgangslage.
Morrow ist ein fiktives betriebliches Schulungszentrum mit vier Seminarräumen, zwei Werkstätten und vier Trainern. Kurse laufen über zwei Wochen in Halbtagsblöcken; jeder Termin braucht einen Raum mit passender Ausstattung und genug Plätzen sowie einen Trainer, der weder anderswo unterrichtet noch abwesend ist.
Wenn späte Anmeldungen die Kapazität eines Raums übersteigen, sucht die Koordination einen Raum, der zu allen Terminen frei ist, zum Kurs passt und die Termine zusammenhält. Das per Augenmaß über zehn Tage zu prüfen, ist langsam und fehleranfällig: Die Planung muss es aus einer Auswahl beantworten und die gewohnte Ansicht jeder Koordinatorin einen Klick entfernt halten.
Was Sie tun werden
Sie wählen beide Termine eines Kurses aus, sehen, welche Räume und Trainer gemeinsam verfügbar sind, verschieben beide zusammen in den passenden Raum und speichern die Ansicht, um sie später wieder zu öffnen.
Wo die Bibliothek endet und Ihre Anwendung beginnt.
SuperScheduler liefert
- Gruppierte Zeilen mit vier rowHeaderColumns (Raum, Plätze, Ausstattungs-Icons, Stunden), die sich sortieren (sort), in der Breite ändern (rowHeaderColumnsResizable) und umordnen (rowHeaderColumnsReorderable) lassen; onBeforeRowHeaderRender findet jede Zelle über das display ihrer Spalte.
- Mehrfachauswahl per Klick und Strg/⌘+Klick, die das Control hält (multiselect.events()), Ziehen mit Ablehnung von Überschneidungen und crosshairType: 'Full'.
- Live-Suche über control.events.filter() und onEventFilter, Zeilenfilter über control.rows.filter() und onRowFilter und Zellklassen über onBeforeCellRender.
- Karten aus onBeforeEventRender mit einer Platzleiste als Event-Area; Kalenderwochen, die onBeforeTimeHeaderRender hinter jeden Montag schreibt.
- Stunden- und Halbtagsraster ohne Nächte und Wochenenden, Tastaturbedienung und Ansagen.
- getViewState und applyViewState aus super-scheduler/views (Zoom, Scrollposition, eingeklappte Gruppen, Spaltenbreiten und -reihenfolge als JSON), die Hover-Karte, die Drag-Karte, ein Kontextmenü und der Undo-Verlauf aus super-scheduler/history.
- Eine fixierte Summenzeile (frozen: 'top', cellsDisabled) mit den freien Räumen je Block, gezeichnet von onBeforeCellRender; unter dem Raster die Minimap aus super-scheduler/minimap mit der eigenen Reihe des Zentrums über einen festen Zeitraum, einem Ton pro Tag und übersetzten Beschriftungen, deren Schieber den Stundenplan bewegt.
Der Code dieses Beispiels entscheidet
- Beispielregeln zwischen Ressourcen: Ausstattung, Plätze und Verfügbarkeit der Trainer für jede Sitzung.
- Gemeinsame Verfügbarkeit: die Räume und Trainer, die für alle ausgewählten Sitzungen frei und geeignet sind.
- Die anderen ausgewählten Sitzungen mit der gezogenen verschieben: onEventMove übergibt die ganze Gruppe an die App, die sie als eine Änderung und einen Undo-Schritt anwendet.
- Was die Suche liest (Kurs, Code, Trainer, Raum), der Platzfilter, der Filter „Frei für Auswahl“ und die Unterrichtszeiten der Trainer, abgeleitet aus den Sitzungen.
- Der beste freie Raum für eine Sitzung oder eine Auswahl: geeignet und für alle frei, der kleinste zuerst.
- Wo Ansichten gespeichert werden (hier im Speicher für den Besuch), die Legende und die Kalenderwochen des Stundenplans und alle Texte dieser Seite.
- Das Register: gebuchte Raumstunden pro Tag gemessen an den Unterrichtsstunden der Räume, die Tage, an denen ein Termin seinen Raum sprengt, der vollste Tag und die freien Räume je Block.
Der Code hinter dieser Demo.
Das sind die Dateien, die diese Seite ausführt, keine vereinfachte Kopie. Sie kompilieren gegen die öffentlichen Exporte von SuperScheduler Pro.
Die Integration: sortierbare, in der Breite änderbare und umordenbare Zeilenkopf-Spalten, Mehrfachauswahl, die Prüfungen beim Verschieben und das Verschieben in der Gruppe, die Live-Suche, Hover-Karte, Drag-Urteil und Kontextmenü, die Verfügbarkeitsmarkierung in onBeforeCellRender und der Filter für 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,
)
}Das Archiv enthält die Dateien dieses Beispiels und eine README. SuperScheduler Pro und Download-Schlüssel sind nicht enthalten.