Aller au contenu

Réservation de courts dans un club sportif

En pleine matinée, le filet d’un court de padel lâche. Déplacez le stage, fermez le court et gardez chaque coach dans son service.

  • Sport
  • Court Club
  • Lignes de synthèse
  • Minimap
  • Menu contextuel
  • Zones actives
  • Filtres
  • Règles de déplacement
  • Créneaux bloqués
  • Annuler et rétablir
  • Thèmes
  • Démo avec données fictives

Mission

0 étapes faites sur 3

Samedi, 10 h 45 : le filet du Padel 2 doit être réparé de 11 h 30 à 13 h, et le stage de padel y est réservé.

  1. Déplacez le stage de padel du Padel 2 vers le Padel 3. — À faire

    Faites-le glisser d’une ligne vers le bas. Le Padel 1 est occupé à cette heure, un court de tennis est refusé et le service de Noor se termine à 13 h.

  2. Fermez le Padel 2 de 11 h 30 à 13 h pour la réparation. — À faire

    Glissez sur le créneau libre du Padel 2 et choisissez « Bloquer pour maintenance » dans le menu qui s’ouvre.

  3. Passez le cours de yoga de midi en Salle B au Pilates. — À faire

    Clic droit sur le cours (ou donnez-lui le focus et appuyez sur Maj+F10), ouvrez Activité et choisissez Pilates.

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.

Court Club
Court 117 %Court 218 %Court 318 %Padel 125 %Padel 220 %Padel 315 %Studio A10 %Studio B10 %Coach Iris50 %Coach Mateo30 %Coach Noor59 %Tennis●●●●Tennis●●○○Tennis●●●●Tennis●●●●Tennis●●●○Tennis●●○○Tennis●●○○Pickleball●●●●Tennis●○○○Padel●●●●Padel●●●●Padel●●●●Padel●●●●Padel●●●●Padel●●●○Padel●●●●Padel●●○○Vélo10/12Yoga9/14Pilates11/14En serviceEn serviceEn serviceEn serviceEn service4533121332344345666655Courts librespar demi-heuresamedi 17 octobre07:0007:3008:0008:3009:0009:3010:0010:3011:0011:3012:0012:3013:0013:3014:0014:3015:0015:3016:0016:3017:0017:30

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.

Court Club est un club fictif de raquette et de fitness avec trois courts de tennis, trois courts de padel, une salle de vélo et une salle de tapis. Les membres réservent à la demi-heure, et les coachs donnent cours sur toute surface de leur sport, mais seulement pendant leur service.

À l’accueil, le week-end change à chaque minute : un filet casse, un cours passe du yoga au Pilates, un court doit être balayé. Le planning doit refuser un cours de padel sur terre battue, un coach à deux endroits à la fois et une réservation par-dessus une autre, et proposer les bonnes commandes là où regarde la personne à l’accueil.

Ce que vous allez faire

Vous allez déplacer un cours de padel vers un court libre, fermer le court en panne pour sa réparation depuis un menu contextuel et changer l’activité d’un cours en salle, chaque refus étant expliqué.

Où s’arrête la bibliothèque et où commence votre application.

SuperScheduler fournit

  • Des zoomLevels à la demi-heure et à l’heure limités aux heures d’ouverture (showNonBusiness : false), une bascule animée et un navigateur de jours construit sur scrollTo et l’abonnement au viewport (super-scheduler/hooks).
  • Des rowHeaderColumns pour le court (une vignette dessinée comme ses lignes), son toit ou son éclairage et son taux d’occupation ; le filtrage des lignes par sport (rows.filter, onRowFilter).
  • Une ligne figée « Courts libres » (frozen : top, cellsDisabled) remplie par onBeforeCellRender, dont les zones de cellule ouvrent le menu du créneau sur le premier court libre.
  • Des tuiles franches via onBeforeEventRender : joueurs en points sur la capacité, initiales du coach, prix, et actions au survol en zones (visibility : Hover, action : None et ContextMenu).
  • Glisser et redimensionner avec refus des chevauchements par ligne, conflictHighlight et une carte de glisser avec la raison du club ; un séparateur sur le « maintenant » de l’accueil et son étiquette dans l’en-tête (zones d’en-tête).
  • Des menus contextuels SuperScheduler.Menu sur les réservations et le temps sélectionné (contextMenuSelection, onTimeRangeSelected), avec sous-menus, options désactivées, Maj+F10 et le thème de menu du skin ; la carte de survol (eventHover) et l’historique d’annulation (super-scheduler/history).
  • La minicarte (super-scheduler/minimap) sur une plage fixe couvrant le week-end, alimentée par la série propre de l’application par demi-heure ; sa fenêtre se pilote aussi au clavier, comme un curseur.

Le code de cet exemple décide

  • Quelle surface accueille quelle activité, l’éclairage et le coucher du soleil sur les courts extérieurs, et la phrase de chaque refus.
  • Les contrôles des coachs d’une ligne à l’autre : de service, et pas déjà en cours ailleurs.
  • Les prix (une location à l’heure selon la surface, un cours par joueur), les chiffres de l’accueil (courts libres, occupation et recette du jour) et les courts libres par demi-heure.
  • Ce que fait chaque commande du menu, quelles durées tiennent avant la réservation suivante, le coucher du soleil ou la fermeture, et un autre court libre pour une réservation.
  • Le skin, les barres autour du planning et tous les textes de cette page.
  • Les courts occupés par demi-heure que dessine la minicarte (le même compte que la ligne Courts libres), le pic, et les demi-heures en ambre au dernier court libre ou en rouge quand tout est pris.

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.

tsx.zip

L’intégration : deux niveaux de grille sur les heures d’ouverture, les colonnes court, toit et occupation, la ligne des courts libres dans onBeforeCellRender, les tuiles et leurs zones de survol dans onBeforeEventRender, les contrôles au déplacement et au redimensionnement, et les deux menus remplis à l’ouverture à partir des réservations du moment.

/**
 * Court Club booking board: courts, studios and the coaches' rota over one weekend, with a frozen
 * "Courts free" row and chunky booking tiles.
 *
 * Library: half-hour and hourly grids over opening hours, rowHeaderColumns (court, roof and lights,
 * booked share), a frozen summary row filled by onBeforeCellRender whose cell areas open the slot
 * menu, row filtering, time headers with a "now" tag (header areas) and a separator at the desk's
 * now, drag/resize with per-frame vetoes, the drag card, per-row overlap refusal with conflict
 * highlight, hover actions as event areas, the event hover card (super-scheduler/react-render),
 * SuperScheduler.Menu context menus with submenus in the skin's menu theme, undo history and the
 * keyboard (Shift+F10 opens the menus).
 * Application: which surface hosts which activity, sunset on unlit courts, whether the coach is on
 * duty and free, which other court is free, prices and the desk's figures. Those rules live in
 * ./rules.
 */
import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useState,
  useSyncExternalStore,
  type RefObject,
} from 'react'
import { SuperScheduler } from 'super-scheduler'
import type { SchedulerEventsChangeArgs } from 'super-scheduler'
import type { SchedulerHistory } from 'super-scheduler/history'
import { subscribeScheduler } from 'super-scheduler/hooks'
import { SuperSchedulerComponent, type SchedulerRenderProps } from 'super-scheduler/react-render'
import { format, plural } from '~/i18n/format'
import {
  DAY,
  HOUR,
  MINUTE,
  formatCivil,
  minutesBetween,
  overlaps,
  parseCivil,
  type CivilDateTime,
} from '../../scheduler/civil'
import { headerLabel, usesTwelveHours } from '../../scheduler/header-format'
import { toneClass } from '../../scheduler/tones'
import { skinClass, skinMenuTheme } from '../registry'
import { formatClock, formatDay, formatSpan } from '../kit/format'
import { defaultHints, useEventHover, type HoverCardModel } from '../kit/hover-card'
import { KEYS } from '../kit/keys'
import { useDropRefusal } from '../kit/use-drop-refusal'
import { createDragCard } from '../kit/verdict'
import type { DemoCommon } from '../types'
import {
  GEOMETRY,
  SUMMARY_ROW,
  civilOf,
  isRowId,
  isVenueId,
  itemLabel,
  itemTone,
  readClubFields,
  rowMetrics,
  toResources,
  type ClubEvent,
} from './adapter'
import {
  CAPACITY,
  COACH_IDS,
  COACH_ROWS,
  COURT_IDS,
  NOW,
  OPENING_HOURS,
  VENUES,
  WEEKEND,
  type Activity,
  type ClubItem,
  type CoachId,
  type RowId,
  type VenueId,
} from './model'
import {
  ACTIVITIES_BY_VENUE,
  LENGTHS,
  afterDark,
  bookingRevenue,
  canHost,
  classesInShift,
  coachIssue,
  coachLoad,
  freeCourts,
  freeVenue,
  lengthIssue,
  sunset,
  venueConflicts,
  venueKind,
  venueOccupancy,
  type Length,
} from './rules'
import type { CourtClubText, SportId, ZoomId } from './text'
import './tokens.css'
import './skin.css'

/** Menu and sheet commands. The demo applies them to its React state, the single source of truth. */
export interface ClubActions {
  readonly details: (id: string) => void
  readonly freeCourt: (id: string) => void
  readonly switchActivity: (id: string, activity: Activity) => void
  readonly setLength: (id: string, minutes: Length) => void
  readonly cancel: (id: string) => void
  readonly reopen: (id: string) => void
  readonly block: (venue: VenueId, start: CivilDateTime, end: CivilDateTime) => void
  readonly hire: (venue: VenueId, start: CivilDateTime, end: CivilDateTime) => void
}

export interface CourtClubSchedulerProps {
  readonly events: ClubEvent[]
  /** The same data read back as the club's model, for the rules. */
  readonly items: readonly ClubItem[]
  readonly text: CourtClubText
  readonly common: DemoCommon
  /** BCP 47 tag for labels, and the scheduler locale id. */
  readonly tag: string
  readonly schedulerLocale: string
  /** Level on mount. Later changes go through control.zoom so the view animates from where it is. */
  readonly initialZoom: ZoomId
  /** The level on screen (the summary row's caption follows it). */
  readonly zoom: ZoomId
  /** The family of venues the desk filters on, or null for all. */
  readonly sport: SportId | null
  /** The item shown in the detail sheet: it gets the selection ring. */
  readonly selected: string | null
  readonly history: SchedulerHistory
  readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
  /** Receives the booking menu, so the detail sheet's "Options" button can open it too. */
  readonly menuRef: RefObject<SuperScheduler.Menu | null>
  readonly actions: ClubActions
  readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
  readonly onSelect: (id: string) => void
  readonly onMoved: (id: string) => void
  readonly onResized: (id: string) => void
  /** A drop or a keyboard move the club refused, with its sentence. */
  readonly onRefused: (id: string, message: string) => void
  readonly onZoomLevel: (level: ZoomId) => void
  /** The day at the left of the view (`YYYY-MM-DD`), published once scrolling settles. */
  readonly onDay: (day: string) => void
}

const ZOOM_LEVELS: SuperScheduler.ZoomLevel[] = [
  {
    id: 'half-hours',
    properties: {
      scale: 'CellDuration',
      cellDuration: 30,
      cellWidth: GEOMETRY.halfHour,
      timeHeaders: [{ groupBy: 'Day' }, { groupBy: 'Cell' }],
    },
  },
  {
    id: 'hours',
    properties: {
      scale: 'Hour',
      cellWidth: GEOMETRY.hour,
      timeHeaders: [{ groupBy: 'Day' }, { groupBy: 'Hour' }],
    },
  },
]

const ZOOM_IDS: readonly ZoomId[] = ['half-hours', 'hours']

const NOW_TICKS = parseCivil(NOW)

/** Venues of each family the sport filter knows. */
export const SPORT_VENUES: Readonly<Record<SportId, readonly VenueId[]>> = {
  tennis: ['court-1', 'court-2', 'court-3'],
  padel: ['padel-1', 'padel-2', 'padel-3'],
  studios: ['studio-a', 'studio-b'],
}

/** Rows that start a new family of venues get a court line above them. */
const SECTION_STARTS: ReadonlySet<string> = new Set<RowId>(['padel-1', 'studio-a', 'coach-iris'])

const escape = (value: string) => SuperScheduler.Util.escapeHtml(value)

/** Menu icons (lucide geometry), in the kit's menu anatomy (`ss-menu__icon`). */
const ICONS = {
  details:
    '<rect x="3" y="3" width="18" height="18" rx="3"/><path d="M15 3v18"/><path d="M7 9h4M7 13h4"/>',
  court:
    '<path d="M8 3 4 7l4 4"/><path d="M4 7h16"/><path d="m16 21 4-4-4-4"/><path d="M20 17H4"/>',
  activity:
    '<path d="m17 2 4 4-4 4"/><path d="M3 11v-1a4 4 0 0 1 4-4h14"/><path d="m7 22-4-4 4-4"/><path d="M21 13v1a4 4 0 0 1-4 4H3"/>',
  length: '<circle cx="12" cy="13" r="8"/><path d="M12 9v4l2.5 2"/><path d="M9 2h6"/>',
  cancel: '<circle cx="12" cy="12" r="9"/><path d="m15 9-6 6M9 9l6 6"/>',
  reopen: '<rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 7.5-2"/>',
  block: '<rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>',
  hire: '<path d="M16 20v-1.5a3.5 3.5 0 0 0-3.5-3.5h-5A3.5 3.5 0 0 0 4 18.5V20"/><circle cx="10" cy="8" r="3.5"/><path d="M19 8v6M16 11h6"/>',
} as const

type Icon = keyof typeof ICONS

/** Trusted menu markup: a fixed icon, the escaped label and optional keycaps. */
function itemHtml(icon: Icon, label: string, keys: readonly string[] = []): string {
  const svg = `<svg class="ss-menu__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICONS[icon]}</svg>`
  const hint =
    keys.length === 0
      ? ''
      : `<span class="ss-menu__hint" aria-hidden="true">${keys
          .map((key) => `<kbd class="keycap keycap--sm keycap--muted">${escape(key)}</kbd>`)
          .join('')}</span>`
  return `${svg}<span class="ss-menu__label">${escape(label)}</span>${hint}`
}

/** Board glyphs (trusted markup, classes only). */
const GLYPH = {
  roof: '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M2 8 8 3l6 5M4 7v6h8V7"/></svg>',
  bulb: '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6 12.5h4M6.5 14.5h3M8 1.5a4.5 4.5 0 0 0-2.6 8.2c.4.3.6.7.6 1.1v.2h4v-.2c0-.4.2-.8.6-1.1A4.5 4.5 0 0 0 8 1.5z"/></svg>',
  sunset:
    '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M1.5 12.5h13M4 12.5a4 4 0 0 1 8 0M8 3v3M2.8 6.8 4.6 8.3M13.2 6.8 11.4 8.3"/></svg>',
  more: '<svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="3.5" cy="8" r="1.3"/><circle cx="8" cy="8" r="1.3"/><circle cx="12.5" cy="8" r="1.3"/></svg>',
  swap: '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M5 2.5 2.5 5 5 7.5M2.5 5h10M11 8.5l2.5 2.5L11 13.5M13.5 11h-10"/></svg>',
  cone: '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6.5 2h3l3.5 11.5h-10zM5 8h6M2 13.5h12"/></svg>',
} as const

/** The coach's initial, in a disc. */
function avatar(coach: CoachId, text: CourtClubText): string {
  const name = text.coaches[coach]
  return `<span class="cc-avatar" title="${escape(name)}">${escape(name.slice(0, 1))}</span>`
}

/** A string cache keyed by what the markup depends on: hooks run for every visible cell. */
function createCache<V>(): (key: string, build: () => V) => V {
  const map = new Map<string, V>()
  return (key, build) => {
    let value = map.get(key)
    if (value === undefined) {
      value = build()
      map.set(key, value)
    }
    return value
  }
}

/** "11:30 AM – 1:00 PM" / "11:30 – 13:00" in the page's language. */
export function timeRange(start: string, end: string, tag: string): string {
  const options: Intl.DateTimeFormatOptions = usesTwelveHours(tag)
    ? { hour: 'numeric', minute: '2-digit' }
    : { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }
  return `${formatCivil(start, tag, options)} – ${formatCivil(end, tag, options)}`
}

/** "11:30–1" / "11:30–13:00": the shortest range a tile can carry. */
function shortRange(start: string, end: string, tag: string): string {
  if (!usesTwelveHours(tag)) return timeRange(start, end, tag).replace(' – ', '–')
  const clock = (value: string) => {
    const ticks = parseCivil(value)
    const hour = new Date(ticks).getUTCHours() % 12 || 12
    const minutes = new Date(ticks).getUTCMinutes()
    return minutes === 0 ? String(hour) : `${hour}:${String(minutes).padStart(2, '0')}`
  }
  return `${clock(start)}–${clock(end)}`
}

/**
 * onBeforeTimeHeaderRender: the day as a scoreboard label; whole hours big and half hours as ":30";
 * the half hour (or hour) holding the desk's now carries a "now" tag where 10:45 falls, as a header
 * area positioned in percent of the cell (geometry through the CSSOM).
 */
function createHeaderHook(
  tag: string,
  text: CourtClubText,
): (args: SuperScheduler.SchedulerBeforeTimeHeaderRenderArgs) => void {
  const cache = createCache<{ readonly html: string; readonly cssClass: string }>()
  // "10:45" without its day period: the header around it already says the hour.
  const nowLabel = usesTwelveHours(tag)
    ? `${new Date(NOW_TICKS).getUTCHours() % 12 || 12}:${String(new Date(NOW_TICKS).getUTCMinutes()).padStart(2, '0')}`
    : formatClock(NOW_TICKS, tag)
  return (args) => {
    const { start, end, level } = args.header
    const from = start.getTime()
    const to = end.getTime()
    const entry = cache(`${level}:${from}:${to}`, () => {
      if (level === 0) {
        const weekday = formatCivil(from, tag, { weekday: 'long' })
        const date = formatCivil(from, tag, { day: 'numeric', month: 'long' })
        return {
          html: `<span class="cc-thd"><b>${escape(weekday)}</b><span>${escape(date)}</span></span>`,
          cssClass: 'cc-thd-cell',
        }
      }
      const past = to <= NOW_TICKS ? ' cc-th-cell--past' : ''
      const half = new Date(from).getUTCMinutes() === 30 && to - from <= 30 * MINUTE
      const label = half
        ? `<span class="cc-th cc-th--half">:30</span>`
        : `<span class="cc-th">${escape(headerLabel(from, 'hour', tag, 'cell'))}</span>`
      return { html: label, cssClass: `cc-th-cell${past}` }
    })
    args.header.html = entry.html
    args.header.cssClass = entry.cssClass
    // The tag rides the day row (its own label sits at the far left), where the now falls in the
    // day's opening hours: the hour labels below stay readable.
    if (level === 0 && from <= NOW_TICKS && NOW_TICKS < to) {
      const day = from - (from % DAY)
      const open = Math.max(from, day + OPENING_HOURS.begin * HOUR)
      const close = Math.min(to, day + OPENING_HOURS.end * HOUR)
      const share = ((NOW_TICKS - open) / (close - open)) * 100
      args.header.areas = [
        {
          left: `calc(${share}% - 26px)`,
          width: 52,
          top: 5,
          bottom: 5,
          cssClass: 'cc-now-tag',
          html: `<span>${escape(nowLabel)}</span>`,
          toolTip: `${text.now} · ${nowLabel}`,
        },
      ]
    }
  }
}

/** What the menus need when they open; refreshed by the board after every render. */
interface MenuContext {
  readonly items: CourtClubSchedulerProps['items']
  readonly text: CourtClubSchedulerProps['text']
  readonly actions: ClubActions
  readonly tag: string
  readonly clearSelection: () => void
  /** A menu opened or closed: the hover card stays away meanwhile. */
  readonly onOpenChange: (open: boolean) => void
}

/**
 * Both menus are created once, outside render, in the skin's menu theme (so they wear the club's
 * tokens on <body>). What they offer is decided when they open, from the context the board hands
 * over after each render.
 */
function createClubMenus() {
  let context: MenuContext | null = null
  const theme = skinMenuTheme('sports-club-courts')
  const selection = new SuperScheduler.Menu({
    theme,
    showMenuTitle: true,
    onShow: (args) => {
      const source = args.source
      if (
        !(source instanceof SuperScheduler.Selection) ||
        source.resource === undefined ||
        !isVenueId(source.resource) ||
        context === null
      ) {
        args.preventDefault()
        return
      }
      const { items: current, text: t, actions: run, tag: lang } = context
      const venue = source.resource
      const start = civilOf(source.start)
      const end = civilOf(source.end)
      const free = venueConflicts(venue, { start, end }, current).length === 0
      const courts = venueKind(venue) !== 'bikes' && venueKind(venue) !== 'mats'
      context.onOpenChange(true)
      args.menu.menuTitle = `${t.rows[venue]} · ${timeRange(start, end, lang)}`
      args.menu.items = [
        {
          html: itemHtml('block', t.menu.block),
          disabled: !free,
          cssClass: 'ss-menu--brand',
          onClick: () => run.block(venue, start, end),
        },
        {
          html: itemHtml('hire', t.menu.hire),
          disabled: !free || afterDark(venue, { start, end }),
          hidden: !courts,
          onClick: () => run.hire(venue, start, end),
        },
      ]
    },
    // A held selection would linger under the next booking: clear it whatever was chosen.
    onHide: () => {
      context?.clearSelection()
      context?.onOpenChange(false)
    },
  })
  const booking = new SuperScheduler.Menu({
    theme,
    showMenuTitle: true,
    onShow: (args) => {
      const source = args.source
      const fields = source instanceof SuperScheduler.Event ? readClubFields(source.data) : null
      // The rota has no commands: no menu for shifts.
      if (
        !(source instanceof SuperScheduler.Event) ||
        fields === null ||
        fields.kind === 'shift' ||
        context === null
      ) {
        args.preventDefault()
        return
      }
      const { items: current, text: t, actions: run, tag: lang } = context
      const id = String(source.id())
      const item = current.find((candidate) => candidate.id === id)
      if (item === undefined || item.kind === 'shift') {
        args.preventDefault()
        return
      }
      context.onOpenChange(true)
      const { title, detail } = itemLabel(fields, t)
      args.menu.menuTitle = detail === '' ? title : `${title} · ${detail}`
      const details = {
        html: itemHtml('details', t.actions.details, KEYS.details),
        onClick: () => run.details(id),
      }
      if (item.kind === 'block') {
        args.menu.items = [
          details,
          {
            html: itemHtml('reopen', t.menu.endBlock),
            cssClass: 'ss-menu--brand',
            onClick: () => run.reopen(id),
          },
        ]
        return
      }
      const choices: readonly Activity[] = ACTIVITIES_BY_VENUE[venueKind(item.venue)]
      const length = minutesBetween(item.start, item.end)
      const court = freeVenue(item, current)
      args.menu.items = [
        details,
        {
          html: itemHtml(
            'court',
            court === null
              ? t.actions.noFreeCourt
              : format(t.actions.freeCourt, { venue: t.rows[court] }),
          ),
          disabled: court === null,
          ...(court === null ? {} : { cssClass: 'ss-menu--brand' }),
          onClick: () => run.freeCourt(id),
        },
        { text: '-' },
        {
          html: itemHtml('activity', t.menu.activity),
          disabled: choices.length < 2,
          items: choices.map((activity) => ({
            html: `<span class="ss-menu__label">${escape(t.activities[activity])}</span>`,
            disabled: activity === item.activity,
            ...(activity === item.activity ? { cssClass: 'cc-menu__current' } : {}),
            onClick: () => run.switchActivity(id, activity),
          })),
        },
        {
          html: itemHtml('length', t.menu.length),
          // Each length is checked against the venue, sunset, the coach and closing time first.
          items: LENGTHS.map((minutes) => {
            const issue = minutes === length ? null : lengthIssue(item, minutes, current)
            const label = escape(plural(t.minutes, minutes, lang))
            const why =
              issue === null
                ? ''
                : `<span class="cc-menu__why">${escape(t.menuReasons[issue])}</span>`
            return {
              html: `<span class="ss-menu__label">${label}</span>${why}`,
              disabled: minutes === length || issue !== null,
              ...(minutes === length ? { cssClass: 'cc-menu__current' } : {}),
              onClick: () => run.setLength(id, minutes),
            }
          }),
        },
        { text: '-' },
        {
          html: itemHtml('cancel', t.menu.cancel),
          cssClass: 'cc-menu__danger',
          onClick: () => run.cancel(id),
        },
      ]
    },
    onHide: () => context?.onOpenChange(false),
  })
  return {
    selection,
    booking,
    setContext: (next: MenuContext) => {
      context = next
    },
  }
}

/** Narrow screens keep the court column only (roof, lights and the booked share are in the card). */
const NARROW = '(max-width: 640px)'
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,
  )
}

export function CourtClubScheduler(props: CourtClubSchedulerProps) {
  const { events, items, text, common, tag, schedulerLocale, initialZoom, zoom, sport } = props
  const { selected, history, controlRef, menuRef, actions } = props
  const { onEventsChange, onSelect, onMoved, onResized, onRefused, onZoomLevel, onDay } = props

  const compact = useNarrowScreen()
  const resources = useMemo(() => toResources(text), [text])
  const refusal = useDropRefusal(onRefused)
  const money = useMemo(
    () =>
      new Intl.NumberFormat(tag, { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 }),
    [tag],
  )

  // Hover card: the venue and its surface, players and price, the coach's shift, and the rule that
  // keeps it there.
  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 + OPENING_HOURS.begin * HOUR,
          end: midnight + OPENING_HOURS.end * HOUR,
        },
      }
      const percent = new Intl.NumberFormat(tag, { style: 'percent', maximumFractionDigits: 0 })
      const { title, detail } = itemLabel(item, text)
      if (item.kind === 'shift') {
        return {
          id: item.id,
          tone: itemTone('shift', undefined),
          eyebrow: text.rows[COACH_ROWS[item.coach]],
          title,
          time,
          facts: [
            {
              label: text.fields.load,
              value: `${plural(text.card.classes, classesInShift(item, items), tag)} · ${percent.format(coachLoad(item.coach, items))}`,
            },
          ],
          rule: { state: 'ok', text: text.card.rotaRule },
          hints: defaultHints(common, { move: false, actions: false }),
        }
      }
      const surface = text.surfaces[venueKind(item.venue)]
      if (item.kind === 'block') {
        return {
          id: item.id,
          tone: itemTone('block', item.venue),
          eyebrow: `${text.rows[item.venue]} · ${surface}`,
          title,
          status: { label: text.card.closed, tone: 'danger' },
          time,
          facts: [{ label: text.fields.reason, value: text.blocks[item.reason] }],
          rule: { state: 'blocked', text: text.card.closedRule },
          hints: defaultHints(common, { move: false }),
        }
      }
      const shift =
        item.coach === undefined
          ? undefined
          : items.find(
              (candidate) =>
                candidate.kind === 'shift' &&
                candidate.coach === item.coach &&
                overlaps(candidate.start, candidate.end, item.start, item.end),
            )
      const hosts: readonly Activity[] = ACTIVITIES_BY_VENUE[venueKind(item.venue)]
      // German writes sports with a capital; the other languages lower-case them mid-sentence.
      const names = hosts.map((activity) =>
        tag.startsWith('de') ? text.activities[activity] : text.activities[activity].toLowerCase(),
      )
      const capacity = CAPACITY[venueKind(item.venue)]
      return {
        id: item.id,
        tone: itemTone('booking', item.venue),
        eyebrow: `${text.rows[item.venue]} · ${surface}`,
        title: detail === '' ? title : `${title} · ${detail}`,
        status: { label: text.formats[item.format] },
        time,
        facts: [
          {
            label: text.fields.players,
            value: format(text.card.players, { players: item.players, capacity }),
          },
          { label: text.fields.price, value: money.format(bookingRevenue(item)) },
          ...(shift === undefined
            ? []
            : [{ label: text.fields.rota, value: timeRange(shift.start, shift.end, tag) }]),
          { label: text.card.booked, value: percent.format(venueOccupancy(item.venue, items)) },
        ],
        rule:
          item.coach !== undefined && shift !== undefined
            ? {
                state: 'ok',
                text: format(text.card.onDuty, {
                  coach: text.coaches[item.coach],
                  time: timeRange(shift.start, shift.end, tag),
                }),
              }
            : {
                state: 'ok',
                text: format(text.card.hosts, {
                  activities: new Intl.ListFormat(tag, { type: 'conjunction' }).format(names),
                }),
              },
        hints: defaultHints(common),
      }
    },
    [items, text, common, tag, money],
  )
  const { eventHover, closeHover, suppressHover } = useEventHover(card)

  // Drag verdict: the venue, the new slot and length, and the club's sentence when it refuses.
  const dragCard = useMemo(
    () =>
      createDragCard({
        tag,
        common,
        rowName: (id) => (isRowId(id) ? text.rows[id] : null),
      }),
    [tag, common, text],
  )

  const [menus] = useState(createClubMenus)
  useLayoutEffect(() => {
    menus.setContext({
      items,
      text,
      actions,
      tag,
      clearSelection: () => controlRef.current?.clearSelection(),
      onOpenChange: suppressHover,
    })
  }, [menus, items, text, actions, tag, controlRef, suppressHover])

  // Hand the booking menu to the demo; close any open menu when the board goes away.
  useEffect(() => {
    menuRef.current = menus.booking
    return () => {
      menuRef.current = null
      menus.booking.hide()
      menus.selection.hide()
    }
  }, [menus, menuRef])

  // Live metrics for the row headers: booked share of each venue, teaching share of each coach.
  const metrics = useMemo(() => rowMetrics(items, text), [items, text])
  // Where each booking could go instead (the hover action), computed once per change.
  const alternatives = useMemo(() => {
    const out = new Map<string, VenueId>()
    for (const item of items) {
      if (item.kind !== 'booking') continue
      const venue = freeVenue(item, items)
      if (venue !== null) out.set(item.id, venue)
    }
    return out
  }, [items])
  // Each coach's shifts on the first day, for their row header.
  const rota = useMemo(() => {
    const first = parseCivil(`${WEEKEND.start}T00:00:00`)
    const out = new Map<CoachId, string>()
    for (const coach of COACH_IDS) {
      const spans = items
        .filter(
          (item) =>
            item.kind === 'shift' && item.coach === coach && parseCivil(item.start) < first + DAY,
        )
        .map((item) => shortRange(item.start, item.end, tag))
      out.set(coach, spans.join(' · '))
    }
    return out
  }, [items, tag])

  const headerHook = useMemo(() => createHeaderHook(tag, text), [tag, text])
  const freeHtml = useMemo(() => createCache<string>(), [])

  const config = useMemo<SchedulerRenderProps>(() => {
    const venuesInView = sport === null ? COURT_IDS : SPORT_VENUES[sport]
    const sunsetClock = formatClock(sunset(`${WEEKEND.start}T00:00:00`), tag)
    const refusalOf = (
      data: object,
      resource: SuperScheduler.ResourceId | undefined,
      start: CivilDateTime,
      end: CivilDateTime,
    ): string | null => {
      const message = moveRefusal(data, resource, start, end, items, text)
      if (message !== null) return message
      if (resource !== undefined && isVenueId(resource) && afterDark(resource, { start, end }))
        return format(text.rules.dark, { time: sunsetClock })
      return null
    }

    return {
      locale: schedulerLocale,
      cssClass: skinClass('sports-club-courts'),
      startDate: WEEKEND.start,
      days: WEEKEND.days,
      zoomLevels: ZOOM_LEVELS,
      zoom: initialZoom,
      zoomPosition: 'left',
      // The club is closed at night: only opening hours are on the board. Weekends are business days.
      businessBeginsHour: OPENING_HOURS.begin,
      businessEndsHour: OPENING_HOURS.end,
      businessWeekends: true,
      showNonBusiness: false,
      useEventBoxes: 'Never',
      height: '100%',
      rowHeaderColumns: [
        { title: text.columns.venue, width: GEOMETRY.columns.venue },
        {
          title: '',
          width: GEOMETRY.columns.traits,
          toolTip: text.columns.traits,
          hidden: compact,
        },
        { title: text.columns.booked, width: GEOMETRY.columns.booked, hidden: compact },
      ],
      rowHeaderWidthAutoFit: false,
      eventHeight: GEOMETRY.eventHeight,
      rowMarginTop: GEOMETRY.rowMargin,
      rowMarginBottom: GEOMETRY.rowMargin,
      allowEventOverlap: false,
      conflictHighlight: true,
      durationBarVisible: false,
      showToolTip: false,
      contextMenu: menus.booking,
      contextMenuSelection: menus.selection,
      keyboardEnabled: true,
      keyboardTarget: 'component',
      keyboardMode: 'Full',
      // The desk's now (the story's Saturday 10:45), as a line across every row.
      separators: [{ location: NOW, layer: 'AboveEvents', width: 2, cssClass: 'cc-now' }],
      history,
      controlRef,
      onEventsChange,

      onBeforeTimeHeaderRender: headerHook,

      onBeforeRowHeaderRender: (args) => {
        const row = args.row
        const id = String(row.id)
        const [first, second, third] = row.columns
        const section = SECTION_STARTS.has(id) ? ' cc-rh--section' : ''
        if (id === SUMMARY_ROW) {
          row.cssClass = 'cc-rh cc-rh--sum'
          if (first !== undefined)
            first.html = `<span class="cc-sumhead"><b>${escape(text.summary.label)}</b><span>${escape(zoom === 'hours' ? text.summary.metaHour : text.summary.meta)}</span></span>`
          if (second !== undefined) second.html = ''
          if (third !== undefined) third.html = ''
          return
        }
        if (isVenueId(row.id)) {
          const venue = VENUES.find((candidate) => candidate.id === row.id)
          if (venue === undefined) return
          row.cssClass = `cc-rh cc-rh--venue${section}`
          if (first !== undefined)
            first.html = `<span class="cc-court"><span class="cc-swatch cc-swatch--${venue.kind}" aria-hidden="true"></span><span class="cc-court__text"><span class="cc-court__name">${escape(text.rows[venue.id])}</span><span class="cc-court__surface">${escape(text.surfaces[venue.kind])}</span></span></span>`
          if (second !== undefined) {
            const traits: { readonly glyph: 'roof' | 'bulb' | 'sunset'; readonly label: string }[] =
              venue.indoor
                ? [{ glyph: 'roof', label: text.traits.indoor }]
                : venue.lights
                  ? [{ glyph: 'bulb', label: text.traits.lights }]
                  : [{ glyph: 'sunset', label: text.traits.dark }]
            second.html = `<span class="cc-traits">${traits
              .map(
                (trait) =>
                  `<span class="cc-trait cc-trait--${trait.glyph}" title="${escape(trait.label)}">${GLYPH[trait.glyph]}<span class="sr-only">${escape(trait.label)}</span></span>`,
              )
              .join('')}</span>`
          }
          if (third !== undefined) {
            const share = venueOccupancy(venue.id, items)
            third.html = `<span class="cc-booked" title="${escape(text.occupancyLabel)}"><b>${escape(metrics.get(venue.id) ?? '')}</b><i class="cc-meter cc-meter--${Math.min(10, Math.round(share * 20))}" aria-hidden="true"></i></span>`
          }
          return
        }
        const coach = COACH_IDS.find((candidate) => COACH_ROWS[candidate] === id)
        if (coach === undefined) return
        row.cssClass = `cc-rh cc-rh--coach${section}`
        if (first !== undefined)
          first.html = `<span class="cc-court">${avatar(coach, text)}<span class="cc-court__text"><span class="cc-court__name">${escape(text.rows[COACH_ROWS[coach]])}</span><span class="cc-court__surface">${escape(rota.get(coach) ?? '')}</span></span></span>`
        if (second !== undefined) second.html = ''
        if (third !== undefined)
          third.html = `<span class="cc-booked cc-booked--coach" title="${escape(text.occupancyLabel)}"><b>${escape(metrics.get(id) ?? '')}</b></span>`
      },

      onRowFilter: (args) => {
        const param = args.filterParam
        const id = String(args.row.id)
        if (typeof param !== 'string' || !isVenueId(id)) return
        const family = param === 'tennis' || param === 'padel' || param === 'studios' ? param : null
        if (family !== null) args.visible = SPORT_VENUES[family].includes(id)
      },

      onBeforeCellRender: (args) => {
        const cell = args.cell
        const from = cell.start.getTime()
        const to = cell.end.getTime()
        const past = to <= NOW_TICKS
        const id = String(cell.resource)
        if (id !== SUMMARY_ROW) {
          const kind = isVenueId(id) ? venueKind(id) : 'coach'
          cell.properties.cssClass = `cc-cell cc-cell--${kind}${past ? ' cc-cell--past' : ''}${SECTION_STARTS.has(id) ? ' cc-cell--section' : ''}`
          return
        }
        // The frozen row: how many of the courts in view are free for the whole cell.
        const free = freeCourts(items, from, to, venuesInView)
        const at = new Date(from).toISOString().slice(0, 16)
        const key = `${at}|${venuesInView.join(',')}|${free.join(',')}`
        const html = freeHtml(key, () => {
          const pips = venuesInView
            .map(
              (venue) =>
                `<i class="cc-pip cc-pip--${venueKind(venue)}${free.includes(venue) ? ' is-free' : ''}"></i>`,
            )
            .join('')
          return `<span class="cc-free cc-free--${free.length === 0 ? 'none' : free.length === 1 ? 'one' : 'some'}" data-at="${at}"><b>${free.length}</b><span class="cc-pips" aria-hidden="true">${pips}</span></span>`
        })
        cell.properties.cssClass = `cc-sumcell${past ? ' cc-sumcell--past' : ''}`
        const target = free[0]
        cell.properties.areas = [
          {
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            html,
            cssClass:
              target === undefined || past ? 'cc-free-hit' : 'cc-free-hit cc-free-hit--book',
            toolTip:
              target === undefined
                ? text.summary.full
                : format(text.summary.tip, {
                    free: free.length,
                    count: venuesInView.length,
                    court: text.rows[target],
                  }),
            action: 'None',
            // A free count books its first free court: the slot menu opens there.
            ...(target === undefined || past
              ? {}
              : {
                  onClick: () => {
                    const control = args.control
                    control.selectTimeRange(cell.start, cell.end, target, true)
                    menus.selection.show(
                      new SuperScheduler.Selection(cell.start, cell.end, target),
                      { owner: control },
                    )
                  },
                }),
          },
        ]
      },

      onBeforeEventRender: (args) => {
        const data = args.data
        const fields = readClubFields(data)
        if (fields === null) return
        const id = String(data.id)
        const resource = data.resource
        const tone = toneClass(itemTone(fields.kind, resource))
        const classes = ['cc-ev', `cc-ev--${fields.kind}`, tone]
        const start = civilOf(data.start)
        const end = civilOf(data.end)
        if (fields.kind === 'block') {
          // A half-hour closure keeps the cone only: the reason is in its hover card and name.
          data.html = `<span class="cc-tape"><span class="cc-tape__label">${GLYPH.cone}<span class="cc-tape__text">${escape(text.blocks[fields.reason])}</span></span></span>`
          data.ariaLabel = `${text.blocks[fields.reason]}, ${timeRange(start, end, tag)}`
        } else if (fields.kind === 'shift') {
          data.html = `<span class="cc-shift">${avatar(fields.coach, text)}<span>${escape(text.onDuty)}</span><span class="cc-shift__time">${escape(shortRange(start, end, tag))}</span></span>`
        } else {
          classes.push(`cc-ev--${fields.format}`)
          const venue = resource !== undefined && isVenueId(resource) ? resource : null
          const capacity = venue === null ? 4 : CAPACITY[venueKind(venue)]
          const studio = capacity > 4
          const players = studio
            ? `<span class="cc-count">${fields.players}<small>/${capacity}</small></span>`
            : `<span class="cc-dots" aria-hidden="true">${Array.from({ length: capacity }, (_, index) => `<i${index < fields.players ? ' class="on"' : ''}></i>`).join('')}</span>`
          const price =
            venue === null
              ? 0
              : bookingRevenue({
                  kind: 'booking',
                  id,
                  venue,
                  activity: fields.activity,
                  format: fields.format,
                  players: fields.players,
                  start,
                  end,
                })
          const coach = fields.coach === undefined ? '' : avatar(fields.coach, text)
          data.html = `<span class="cc-tile"><span class="cc-tile__l1"><span class="cc-tile__act">${escape(text.activities[fields.activity])}</span>${coach}<span class="cc-tile__price">${escape(money.format(price))}</span></span><span class="cc-tile__l2"><span class="cc-tile__time">${escape(shortRange(start, end, tag))}</span>${players}</span></span>`
          data.ariaLabel = `${text.activities[fields.activity]}, ${text.formats[fields.format]}, ${timeRange(start, end, tag)}, ${format(text.card.players, { players: fields.players, capacity })}`
          // Hover actions: the booking's menu, and the free court it could move to.
          const alternative = alternatives.get(id)
          data.areas = [
            {
              right: 5,
              top: 5,
              width: 24,
              height: 24,
              visibility: 'Hover',
              action: 'ContextMenu',
              menu: menus.booking,
              cssClass: 'cc-act',
              html: GLYPH.more,
              toolTip: text.actions.more,
            },
            ...(alternative === undefined
              ? []
              : [
                  {
                    right: 33,
                    top: 5,
                    width: 24,
                    height: 24,
                    visibility: 'Hover' as const,
                    action: 'None' as const,
                    cssClass: 'cc-act',
                    html: GLYPH.swap,
                    toolTip: format(text.actions.freeCourt, { venue: text.rows[alternative] }),
                    onClick: () => actions.freeCourt(id),
                  },
                ]),
          ]
        }
        if (id === selected) classes.push('ss-ev--selected')
        data.cssClass = classes.join(' ')
      },

      // Surface, sunset and coach rules run on every shadow change; overlap inside a row is the
      // library's, and its reason is kept so a refused release is announced too.
      onEventMoving: (args) => {
        const id = String(args.e.id())
        const message = refusalOf(
          args.e.data,
          args.resource,
          civilOf(args.start),
          civilOf(args.end),
        )
        refusal.track(id, message ?? (args.conflicts.length > 0 ? text.rules.occupied : null))
        if (message !== null) {
          args.allowed = false
          args.message = message
        }
      },

      // Final check before the commit (also covers keyboard moves).
      onEventMove: (args) => {
        const id = String(args.e.id())
        const message = refusalOf(
          args.e.data,
          args.newResource,
          civilOf(args.newStart),
          civilOf(args.newEnd),
        )
        if (message !== null) {
          args.preventDefault()
          refusal.clear()
          onRefused(id, message)
        }
      },

      onEventResizing: (args) => {
        const id = String(args.e.id())
        const message = refusalOf(
          args.e.data,
          args.e.resource(),
          civilOf(args.start),
          civilOf(args.end),
        )
        refusal.track(id, message ?? (args.conflicts.length > 0 ? text.rules.occupied : null))
        if (message !== null) {
          args.allowed = false
          args.message = message
        }
      },

      onEventResize: (args) => {
        const id = String(args.e.id())
        const message = refusalOf(
          args.e.data,
          args.e.resource(),
          civilOf(args.newStart),
          civilOf(args.newEnd),
        )
        if (message !== null) {
          args.preventDefault()
          refusal.clear()
          onRefused(id, message)
        }
      },

      onEventMoved: (args) => {
        refusal.clear()
        onMoved(String(args.e.id()))
      },
      onEventResized: (args) => {
        refusal.clear()
        onResized(String(args.e.id()))
      },
      // A click (or Enter) docks the item into the detail sheet; the hover card steps aside.
      onEventClick: (args) => {
        closeHover()
        onSelect(String(args.e.id()))
      },

      // Coach rows show the rota and the top row counts: nothing is booked on them.
      onTimeRangeSelecting: (args) => {
        if (!isVenueId(args.resource)) args.allowed = false
      },

      // Dragging across free time offers the slot's commands straight away.
      onTimeRangeSelected: (args) => {
        if (args.origin !== 'drag' || !isVenueId(args.resource)) return
        menus.selection.show(new SuperScheduler.Selection(args.start, args.end, args.resource), {
          owner: args.control,
        })
      },

      onZoom: (args) => {
        if (args.phase !== 'end') return
        const level = ZOOM_IDS[args.level]
        if (level !== undefined) onZoomLevel(level)
      },
    }
  }, [
    actions,
    alternatives,
    closeHover,
    compact,
    controlRef,
    freeHtml,
    headerHook,
    history,
    initialZoom,
    items,
    menus,
    metrics,
    money,
    onEventsChange,
    onMoved,
    onRefused,
    onResized,
    onSelect,
    onZoomLevel,
    refusal,
    rota,
    schedulerLocale,
    selected,
    sport,
    tag,
    text,
    zoom,
  ])

  // The sport filter runs through the control's own row filter (rows.filter + onRowFilter).
  useEffect(() => {
    const control = controlRef.current
    if (control === null || control.disposed()) return
    control.rows.filter(sport)
  }, [controlRef, sport])

  // The day navigator follows the view, once scrolling settles.
  useEffect(() => {
    const control = controlRef.current
    if (control === null) return
    return subscribeScheduler(control, 'viewport', (state) => {
      // The day holding the middle of the view (hidden nights make the edges ambiguous).
      const middle = (parseCivil(civilOf(state.start)) + parseCivil(civilOf(state.end))) / 2
      onDay(new Date(middle).toISOString().slice(0, 10))
    })
  }, [controlRef, onDay])

  return (
    <SuperSchedulerComponent
      {...config}
      resources={resources}
      events={events}
      eventHover={eventHover}
      dragCard={dragCard}
    />
  )
}

/**
 * Why the club refuses `data` at `resource` from `start` to `end`, or null. Blocks and the rota are
 * fixed; a booking needs a surface for its activity and, for a class, a coach on duty and free.
 */
function moveRefusal(
  data: object,
  resource: SuperScheduler.ResourceId | undefined,
  start: CivilDateTime,
  end: CivilDateTime,
  items: readonly ClubItem[],
  text: CourtClubText,
): string | null {
  const fields = readClubFields(data)
  if (fields === null) return null
  if (fields.kind !== 'booking') return text.rules.fixed
  if (resource === undefined || !isVenueId(resource)) return text.rules.coachRow
  if (!canHost(resource, fields.activity)) return text.rules.wrongVenue[fields.activity]
  if (fields.coach === undefined) return null
  const id = 'id' in data ? String(data.id) : undefined
  const issue = coachIssue(fields.coach, { ...(id === undefined ? {} : { id }), start, end }, items)
  if (issue === 'off-duty') return text.rules.offDuty
  if (issue === 'double-booked') return text.rules.doubleBooked
  return null
}

L’archive contient les fichiers de cet exemple et un README. Elle n’inclut ni SuperScheduler Pro ni aucune clé de téléchargement.