Planification de salles de formation
Les inscriptions dépassent la salle. Sélectionnez les deux sessions, voyez ce qui est libre pour les deux, déplacez-les ensemble et gardez la vue.
- Formation
- Morrow
- Multisélection
- Colonnes de ligne
- Vues enregistrées
- Lignes de synthèse
- Minimap
- Recherche instantanée
- Filtres
- Menu contextuel
- Thèmes
- Démo avec données fictives
Mission
0 étapes faites sur 3Culture des données compte désormais 20 inscrits et Birch n’a que 16 places. Les deux sessions, mardi et jeudi matin, doivent changer de salle.
Sélectionnez les deux sessions de Culture des données dans Birch. — À faire
Cliquez sur l’une, puis Ctrl/⌘+clic sur l’autre. Les salles libres et assez grandes pour les deux sont marquées « Libre ».
Faites-les glisser ensemble dans la salle qui convient aux deux. — À faire
Faites glisser l’une des sessions sélectionnées jusqu’à Delta : l’autre suit. Cedar est refusée : pas de projecteur et 12 places.
Enregistrez cette vue, puis rouvrez-la depuis le menu Vues. — À faire
Vues → Enregistrer la vue actuelle, choisissez une vue prédéfinie, puis la vôtre.
Environ 30 secondes. Les étapes se cochent au fur et à mesure.
Clavier : placez le focus sur la grille, puis flèches, Entrée et Alt+flèches pour déplacer.
Aperçu de la première imageEn direct : le vrai moteur Pro, dans votre navigateurEnviron 30 secondes. Les étapes se cochent au fur et à mesure. Clavier : placez le focus sur la grille, puis flèches, Entrée et Alt+flèches pour déplacer.
La situation.
Morrow est un centre de formation d’entreprise fictif avec quatre salles, deux ateliers et quatre formateurs. Les cours ont lieu par demi-journées sur deux semaines ; chaque session demande une salle avec le bon équipement et assez de places, et un formateur qui n’est ni en cours ailleurs ni absent.
Quand des inscriptions tardives dépassent la capacité d’une salle, la coordination cherche une salle libre à chaque session, adaptée au cours, et qui garde les sessions ensemble. Le vérifier à l’œil sur dix jours est lent et source d’erreurs : le planning doit répondre à partir d’une sélection et garder la disposition habituelle de chacun à un clic.
Ce que vous allez faire
Vous allez sélectionner les deux sessions d’un cours, voir les salles et formateurs qui partagent leur disponibilité, les déplacer ensemble dans la salle qui convient, puis enregistrer la vue pour la rouvrir plus tard.
Où s’arrête la bibliothèque et où commence votre application.
SuperScheduler fournit
- Lignes groupées avec quatre rowHeaderColumns (salle, places, icônes d’équipement, heures) que l’on trie (sort), redimensionne (rowHeaderColumnsResizable) et réordonne (rowHeaderColumnsReorderable) ; onBeforeRowHeaderRender retrouve chaque cellule par le display de sa colonne.
- Sélection multiple au clic et Ctrl/⌘+clic conservée par le contrôle (multiselect.events()), glisser-déposer avec refus des chevauchements et crosshairType: 'Full'.
- Recherche en direct via control.events.filter() et onEventFilter, filtrage des lignes via control.rows.filter() et onRowFilter, et classes de cellule via onBeforeCellRender.
- Cartes écrites dans onBeforeEventRender avec une règle de places dessinée en zone d’événement ; numéros de semaine écrits par onBeforeTimeHeaderRender après le libellé de chaque lundi.
- Grilles en heures et en demi-journées sans nuits ni week-ends, navigation au clavier et annonces.
- getViewState et applyViewState de super-scheduler/views (zoom, défilement, groupes repliés, largeurs et ordre des colonnes en JSON), la carte au survol, la carte de glisser-déposer, un menu contextuel et l’historique d’annulation de super-scheduler/history.
- Une ligne de synthèse figée (frozen: 'top', cellsDisabled) avec les salles libres de chaque créneau, peinte par onBeforeCellRender ; sous la grille, la minicarte de super-scheduler/minimap alimentée par la série du centre sur une plage fixe, un ton par jour et des libellés traduits, dont le curseur déplace l’emploi du temps.
Le code de cet exemple décide
- Règles d’exemple entre ressources : équipement, places et disponibilité du formateur pour chaque session.
- Disponibilité partagée : les salles et formateurs libres et adaptés à toutes les sessions sélectionnées.
- Déplacer les autres sessions sélectionnées avec celle que l’on fait glisser : onEventMove confie tout le groupe à l’application, qui l’applique en un seul changement et une seule étape d’annulation.
- Ce que lit la recherche (cours, code, formateur, salle), le filtre de places, le filtre « Libres pour la sélection » et les heures de cours des formateurs, déduites des sessions.
- La meilleure salle libre pour une session ou une sélection : adaptée et libre pour toutes, la plus petite d’abord.
- Où les vues sont conservées (ici, en mémoire pendant la visite), la légende et les numéros de semaine de l’emploi du temps, et tous les textes de cette page.
- Le registre : heures de salle réservées par jour rapportées aux heures d’enseignement des salles, les jours où une session dépasse sa salle, le jour le plus chargé et les salles libres de chaque créneau.
Le code de cette démo.
Ce sont les fichiers exécutés par cette page, pas une copie simplifiée. Ils compilent avec les exports publics de SuperScheduler Pro.
L’intégration : colonnes d’en-tête de ligne triables, redimensionnables et réordonnables, sélection multiple, contrôles de déplacement et déplacement groupé, recherche en direct, carte au survol, verdict de glisser-déposer et menu contextuel, mise en évidence des disponibilités dans onBeforeCellRender et filtre passé à 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,
)
}L’archive contient les fichiers de cet exemple et un README. Elle n’inclut ni SuperScheduler Pro ni aucune clé de téléchargement.