Aller au contenu

Planification des ressources d’une agence créative

Une graphiste est surréservée. Confiez deux tâches à un collègue d’un seul glisser, vérifiez ce qu’elles débloquent, puis annulez.

  • Agence créative
  • Studio North
  • Lignes de synthèse
  • Minimap
  • Barres de progression
  • Slots de rendu React
  • Dépendances
  • Multisélection
  • Curseur de zoom
  • Colonnes de ligne
  • Thèmes
  • Démo avec données fictives

Mission

0 étapes faites sur 3

Vendredi, 14:00 au studio : Mira est chargée à 120 % sur ce sprint, deux tâches Kestrel chevauchent son packaging Fernhill.

  1. Sélectionnez « Finalisation du logo » et « Visuels clés » sur la ligne de Mira. — À faire

    Cliquez sur la première, puis Ctrl/⌘+clic sur la seconde. Le panneau résume la sélection et les dépendances de la campagne apparaissent.

  2. Glissez l’une des deux vers Jonas : elles bougent ensemble. — À faire

    Les dates ne changent pas et les liens suivent. La charge de Mira descend à 70 %. Les déposer sur un rédacteur est refusé ; le bouton de passation d’une carte confie une tâche au designer le moins chargé.

  3. Annulez la réaffectation. — À faire

    Une seule étape ramène les deux tâches : la flèche de la barre d’outils, ou Ctrl/⌘+Z quand le planning a le focus.

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.

Studio North
StratégieInes Varga70%DesignMira Okafor120%Jonas Brandt20%Leo Marchetti30%RédactionSaskia Moreau60%Theo Lindqvist40%ProductionAda Kowalczyk0%ClientRevues clientAudit de marqueKestrel Cycles · TerminéeInsights acheteursFernhill Tea · 80 % faitAtelier commissairesLarkspur Museum · 2 jours ouvrésFinalisation du logoKestrel Cycles · 50 % faitVisuels clésKestrel Cycles · 3 jours ouvrésDesign du packagingFernhill Tea · 25 % faitAccrochesKestrel Cycles · 30 % faitTextes d’expositionLarkspur Museum · 4 jours ouvrésRevue clientKestrel Cycles · 1 jour ouvréKit de lancementKestrel Cycles · 3 jours ouvrésScripts du filmFernhill Tea · 5 jours ouvrésFilm de lancementFernhill Tea · 5 jours ouvrésTeaser animéLarkspur Museum · 3 jours ouvrésSérie d’affichesLarkspur Museum · 4 jours ouvrésMise à jour du portfolioStudio North · Terminée29%29%14%57%57%57%86%57%57%43%43%29%43%Capacité de l’équipe19 oct.26 oct.2 nov.lun. 19mar. 20mer. 21jeu. 22ven. 23lun. 26mar. 27mer. 28jeu. 29ven. 30lun. 2mar. 3mer. 4

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.

Studio North est une agence fictive où stratèges, graphistes, rédacteurs et une productrice travaillent en même temps sur trois campagnes clients. Chaque campagne est une chaîne de tâches : pas de visuels clés avant que le logo soit finalisé, pas de kit de lancement avant la validation de la revue par le client.

Dans un tableur, les problèmes apparaissent trop tard : une graphiste réservée sur deux campagnes à la fois, une revue qui ne peut pas bouger, une tâche confiée à quelqu’un qui ne peut pas la faire. Le planning doit montrer la charge de chacun, garder les dépendances visibles quand le travail change de mains et rendre un rééquilibrage facile à annuler.

Chaque client a sa couleur sur tout le planning, et le plan se lit le vendredi après-midi : ce qui est fait, ce qui avance, et qui porte plus qu’une semaine pleine. Un jour rouge sur la ligne de quelqu’un signifie deux tâches le même jour.

Ce que vous allez faire

Vous sélectionnerez deux tâches, les confierez à un autre graphiste d’un seul glisser, verrez la colonne de charge se rééquilibrer pendant que les liens suivent, puis annulerez tout le déplacement en une étape.

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

SuperScheduler fournit

  • Une échelle en jours, week-ends masqués (showNonBusiness: false, eventMoveSkipNonBusiness), un zoom au pincement, Ctrl+molette ou Ctrl +/− (zoomGesture, keyboardOptions.zoomKeys) et par le curseur de zoom-ui (createZoomSlider), avec des seuils lod ; le sélecteur de semaine fait défiler le planning (scrollTo) et suit le sujet viewport de super-scheduler/hooks (subscribeScheduler).
  • Un arbre d’équipes avec deux colonnes d’en-tête (rowHeaderColumns, rowHeaderColumnsMergeParents) écrites dans onBeforeRowHeaderRender : avatars, rôles et pastilles de charge qui changent à chaque déplacement.
  • Une ligne de synthèse figée (frozen: 'top') pour la capacité de l’équipe par jour et une carte de chaleur de la charge sur les jours de chacun, toutes deux depuis onBeforeCellRender et recalculées après chaque changement.
  • Des cartes en double réservation empilées avec eventStackingLineHeight (allowEventOverlap), des barres d’avancement avec durationBarMode: 'PercentComplete' et complete, et une zone d’action au survol (visibility: 'Hover', action: 'None') qui passe une tâche à quelqu’un d’autre.
  • Sélection au clic et Ctrl/⌘+clic, l’API multiselect et un déplacement sur plusieurs lignes enregistré comme une seule étape d’annulation (createHistory, événements contrôlés via onEventsChange), avec des liens courbes fin-début qui suivent les tâches.
  • Cartes React (renderEvent) et cartes au survol (eventHover) de super-scheduler/react-render, un séparateur pour l’horloge du studio, des en-têtes de temps sur mesure (onBeforeTimeHeaderRender), la carte de glisser et un menu contextuel.
  • La minicarte de super-scheduler/minimap sous le tableau, alimentée par la charge de l’équipe par jour sur les quatre semaines (une série sur une plage fixe), un ton par jour et des libellés traduits ; son curseur déplace et zoome le tableau, qui s’ouvre sur le sprint (cellWidth mesurée avant le montage).

Le code de cet exemple décide

  • Quel rôle peut prendre quelle discipline, et le message de refus quand ce n’est pas possible.
  • La charge du sprint par personne, la capacité de l’équipe utilisée sur le sprint et chaque jour, qui est surchargé, et la couleur de chaque client.
  • Les dépendances entre tâches, quand l’une est rompue, quels liens sont tracés (les campagnes sélectionnées, ou toutes) et ce que liste la carte au survol.
  • L’horloge du studio (vendredi 23 octobre, 14:00, fixe pour la démo), l’avancement noté sur chaque tâche, les revues fixées avec le client et le collègue le moins chargé pour une passation.
  • La barre du produit, la légende des clients, le résumé de la sélection, la mission et tous les textes de cette page.
  • La charge de l’équipe jour par jour pour la bande, les jours où quelqu’un est réservé deux fois, le jour de pic et le sprint sur lequel s’ouvre le tableau.

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 : échelle en jours et bornes du zoom, colonnes d’en-tête avec avatars et pastilles de charge, la ligne de capacité et la chaleur quotidienne depuis le hook des cellules, les cartes empilées avec avancement et action au survol, les liens, la sélection multiple et les callbacks où les règles acceptent ou refusent un déplacement.

/**
 * Studio North resource plan: the team over a four-week window, one colour per client.
 *
 * Library: a day scale with weekends hidden and a free zoom (zoomGesture, driven by the zoom-ui
 * slider), a team tree with two row-header columns written by onBeforeRowHeaderRender, a frozen
 * summary row and per-day load heat from onBeforeCellRender, overlapping cards cascaded with
 * eventStackingLineHeight, PercentComplete duration bars, a hover action area, multiselection and
 * a multi-row move, curved dependency links, a separator for the studio's clock, undo history,
 * keyboard, React cards and hover cards through `super-scheduler/react-render`, the drag card and
 * a context menu.
 * Application: who can take which task, moving a selection together, sprint and daily load, when a
 * dependency is broken, and every figure on the board. Those rules live in ./rules and run inside
 * the callbacks below.
 */
import { useCallback, useEffect, useMemo, type RefObject } from 'react'
import { SuperScheduler } from 'super-scheduler'
import type {
  SchedulerBeforeTimeHeaderRenderArgs,
  SchedulerEventsChangeArgs,
  SchedulerProps,
} from 'super-scheduler'
import type { SchedulerHistory } from 'super-scheduler/history'
import { SuperSchedulerComponent } from 'super-scheduler/react-render'
import { format } from '~/i18n/format'
import { DAY, parseCivil } from '../../scheduler/civil'
import { headerLabel } from '../../scheduler/header-format'
import { unitOfSpan } from '../../scheduler/live-headers'
import { createEventMenu } from '../kit/context-menu'
import { useEventHover } from '../kit/hover-card'
import { KEYS } from '../kit/keys'
import { useDropRefusal } from '../kit/use-drop-refusal'
import { createDragCard } from '../kit/verdict'
import { skinClass, skinMenuTheme } from '../registry'
import type { DemoCommon } from '../types'
import {
  GEOMETRY,
  LOD,
  SUMMARY_ROW,
  ZOOM,
  civilOf,
  clientOf,
  initialsOf,
  isSpecialistId,
  isTaskId,
  readTaskFields,
  rowHeaderWidth,
  specialistName,
  toResources,
  type TaskEvent,
} from './adapter'
import {
  SPECIALISTS,
  SPRINT,
  STUDIO_NOW,
  TEAM_IDS,
  WINDOW,
  type CampaignId,
  type Discipline,
  type SpecialistId,
  type Task,
  type TaskId,
} from './model'
import {
  TEAM,
  capacityUsed,
  dayAllocation,
  handOverCandidate,
  isoWeek,
  moveProblem,
  planGroupMove,
  teamDayLoad,
  workingDays,
  type DependencyIssue,
  type GroupMovePlan,
  type MoveProblem,
  type PlannedMove,
} from './rules'
import { cardParts, type CardParts, type CardSize } from './card-parts'
import { TaskCard, cardHtml, taskCard } from './task-card'
import type { StudioNorthText } from './text'
import './tokens.css'
import './studio.css'

/** What the board asks the demo to do (context menu, hover action). */
export type TaskAction = 'details' | 'hand-over' | 'select-campaign'

const SLUG = 'agency-campaigns'
const NOW = parseCivil(STUDIO_NOW)
const TODAY = NOW - (NOW % DAY)

export interface StudioNorthSchedulerProps {
  readonly events: TaskEvent[]
  readonly tasks: readonly Task[]
  readonly issues: readonly DependencyIssue[]
  /** Sprint load per specialist (1 = 100 %), computed by the rules. */
  readonly loads: ReadonlyMap<SpecialistId, number>
  readonly text: StudioNorthText
  readonly common: DemoCommon
  /** BCP 47 tag for labels, and the scheduler locale id. */
  readonly tag: string
  readonly schedulerLocale: string
  /** Phones: narrower row-header columns (chosen once by the demo). */
  readonly compact: boolean
  /** The narrowest day width: the whole window fills the board. */
  readonly minZoom: number
  /** The day width on mount: the sprint's ten working days fill the board. */
  readonly initialZoom: number
  /** Every dependency, or only those of the campaigns in `focus` (the selection). */
  readonly showAllLinks: boolean
  readonly focus: ReadonlySet<CampaignId>
  readonly history: SchedulerHistory
  readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
  readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
  readonly onSelectionChange: (ids: TaskId[]) => void
  readonly onMoved: (id: TaskId) => void
  /** A selection dropped together: the application applies and records it as one change. */
  readonly onGroupMove: (moves: readonly PlannedMove[]) => void
  readonly onResized: (id: TaskId) => void
  readonly onRefused: (id: string, message: string) => void
  readonly onAction: (action: TaskAction, id: TaskId) => void
}

/** A selected task gets a ring (red when it starts too early); `sn-selected` is the e2e contract. */
const SELECTED_CLASS = 'sn-selected'

function cardSize(width: number): CardSize {
  return width < 84 ? 'tiny' : width < 140 ? 'compact' : 'full'
}

/** Why one task cannot go to `resource` (a team row, the wrong role, a fixed review), or null. */
function singleProblem(
  data: object,
  resource: SuperScheduler.ResourceId,
): { problem: MoveProblem; discipline: Discipline } | null {
  const fields = readTaskFields(data)
  if (fields === null) return null
  if (!isSpecialistId(resource)) return { problem: 'wrong-role', discipline: fields.discipline }
  const problem = moveProblem(fields, resource)
  return problem === null ? null : { problem, discipline: fields.discipline }
}

/**
 * Time headers: weeks with their ISO number, days with the studio's today in ink. Labels are the
 * preview's (`headerLabel`), so the swap does not jump; cached per cell, the hook runs per cell.
 */
function createHeaderHook(
  tag: string,
  weekLabel: string,
): (args: SchedulerBeforeTimeHeaderRenderArgs) => void {
  const cache = new Map<string, { html: string; css: string; areas: SuperScheduler.AreaData[] }>()
  return (args) => {
    const start = args.header.start.getTime()
    const end = args.header.end.getTime()
    const width = args.control.cellWidth ?? GEOMETRY.day
    const level = args.header.level === 0 ? 'group' : 'cell'
    const unit = unitOfSpan(end - start, level)
    const key = `${level}:${unit}:${start}:${width < 52 ? 'n' : 'w'}`
    let entry = cache.get(key)
    if (entry === undefined) {
      const escape = SuperScheduler.Util.escapeHtml
      const label = escape(headerLabel(start, unit, tag, level, width))
      if (level === 'group') {
        const week =
          unit === 'week'
            ? `<span class="sn-th-week">${escape(format(weekLabel, { week: isoWeek(start) }))}</span>`
            : ''
        entry = { html: `<span class="sn-th-group">${label}${week}</span>`, css: '', areas: [] }
      } else {
        const today = unit === 'day' && start === TODAY
        entry = {
          html: `<span class="sn-th-day">${label}</span>`,
          css: today ? 'sn-th--today' : '',
          // The studio's clock inside its day, as a share of the cell: it follows every zoom.
          areas:
            start <= NOW && NOW < end
              ? [
                  {
                    left: `${((NOW - start) / (end - start)) * 100}%`,
                    bottom: 0,
                    height: 6,
                    width: 2,
                    cssClass: 'sn-th-now',
                  },
                ]
              : [],
        }
      }
      cache.set(key, entry)
    }
    args.header.html = entry.html
    args.header.cssClass = entry.css
    args.header.areas = entry.areas
  }
}

/** Load pill of a person: calm under 80 %, full at 100 %, red above. */
function loadLevel(value: number): 'low' | 'ok' | 'full' | 'over' {
  return value > 1 ? 'over' : value >= 0.95 ? 'full' : value >= 0.5 ? 'ok' : 'low'
}

export function StudioNorthScheduler(props: StudioNorthSchedulerProps) {
  const {
    events,
    tasks,
    issues,
    loads,
    text,
    common,
    tag,
    schedulerLocale,
    compact,
    minZoom,
    initialZoom,
    showAllLinks,
    focus,
    history,
    controlRef,
  } = props
  const {
    onEventsChange,
    onSelectionChange,
    onMoved,
    onGroupMove,
    onResized,
    onRefused,
    onAction,
  } = props

  const resources = useMemo(() => toResources(text), [text])
  // A refused drop (role, fixed review) is said once the pointer is released.
  const refusal = useDropRefusal(onRefused)
  const headerHook = useMemo(() => createHeaderHook(tag, text.week.short), [tag, text])
  const late = useMemo(() => new Set<string>(issues.map((issue) => issue.task)), [issues])

  // Columns are part of the configuration: titles from the page text, widths chosen once.
  const rowHeaderColumns = useMemo<SuperScheduler.RowHeaderColumnData[]>(() => {
    const [person, load] = compact ? GEOMETRY.compactColumns : GEOMETRY.columns
    return [
      { title: text.columns.specialist, width: person, nonresizable: true },
      { title: text.columns.load, width: load, nonresizable: true },
    ]
  }, [text, compact])

  // Finish-to-start links come from the business model, not from the scheduler. By default only
  // the selected campaigns show theirs, so a busy board stays readable.
  const links = useMemo<SuperScheduler.LinkData[]>(() => {
    return tasks.flatMap((task) =>
      !showAllLinks && !focus.has(task.campaign)
        ? []
        : task.after.map((before) => ({
            id: `${before}->${task.id}`,
            from: before,
            to: task.id,
            type: 'FinishToStart' as const,
            ...(issues.some((issue) => issue.task === task.id && issue.waitsFor === before)
              ? { cssClass: 'ss-link--late' }
              : {}),
          })),
    )
  }, [tasks, issues, showAllLinks, focus])

  const config = useMemo<SchedulerProps>(() => {
    const reason = (found: { problem: MoveProblem; discipline: Discipline }) =>
      found.problem === 'fixed' ? text.rules.fixed : text.rules.wrongRole[found.discipline]
    const parts = new Map<string, CardParts>()
    const escape = SuperScheduler.Util.escapeHtml
    const percent = new Intl.NumberFormat(tag, { style: 'percent' })
    const sprintUse = capacityUsed(tasks, SPRINT)

    // The selected tasks move together when the dragged one is part of a multiple selection.
    const groupPlan = (
      dragged: SuperScheduler.EventId,
      start: SuperScheduler.Date,
      resource: SuperScheduler.ResourceId,
    ): GroupMovePlan | null => {
      const ids = new Set(controlRef.current?.multiselect.events().map((event) => event.id()))
      if (ids.size < 2 || !ids.has(dragged) || !isTaskId(dragged)) return null
      const selection = tasks.filter((task) => ids.has(task.id))
      return planGroupMove(selection, dragged, civilOf(start), String(resource))
    }

    return {
      locale: schedulerLocale,
      cssClass: `${skinClass(SLUG)} sn-board`,
      startDate: WINDOW.start,
      days: 28,
      weekStarts: 1,
      scale: 'Day',
      // The sprint fills the board on mount (56 px per day at least); the slider, the week switch
      // and the minimap's brush zoom out to the whole window.
      cellWidth: initialZoom,
      timeHeaders: [{ groupBy: 'Week' }, { groupBy: 'Day' }],
      headerHeight: GEOMETRY.header,
      // Pinch and Ctrl+wheel zoom between the whole window and wide days; cards adapt far out.
      zoomGesture: { min: minZoom, max: ZOOM.max, wheel: 'ctrl' },
      lod: LOD,
      // Weekends stay hidden: the plan counts working days only.
      showNonBusiness: false,
      useEventBoxes: 'Never',
      // Moves keep a task's working days: dropping a Thursday–Friday task on Friday ends it Monday.
      eventMoveSkipNonBusiness: true,
      height: '100%',
      treeEnabled: true,
      treePreventParentUsage: true,
      treeIndent: compact ? 8 : 12,
      rowHeaderColumns,
      rowHeaderColumnsMergeParents: true,
      rowHeaderWidth: rowHeaderWidth(compact),
      rowHeaderWidthAutoFit: false,
      eventHeight: GEOMETRY.event,
      rowMarginTop: GEOMETRY.inset,
      rowMarginBottom: GEOMETRY.inset,
      // A double-booked person's cards pile up instead of stacking in separate lanes.
      eventStackingLineHeight: GEOMETRY.stacking,
      eventBorderRadius: 9,
      // People can be double-booked; the load column and the heat make it visible instead.
      allowEventOverlap: true,
      // Click selects, Ctrl/Cmd+click adds to the selection.
      eventClickHandling: 'Select',
      allowMultiSelect: true,
      timeRangeSelectedHandling: 'Disabled',
      conflictHighlight: true,
      // Progress reported by the owner, as a bar along the card's foot.
      durationBarVisible: true,
      durationBarMode: 'PercentComplete',
      durationBarHeight: 3,
      // The studio's clock: Friday 23 October, 2 PM.
      separators: [{ location: STUDIO_NOW, cssClass: 'sn-now', layer: 'BelowEvents', width: 2 }],
      showToolTip: false,
      keyboardEnabled: true,
      keyboardTarget: 'component',
      keyboardMode: 'Full',
      keyboardOptions: { zoomKeys: true },
      history,
      controlRef,
      onEventsChange,

      onBeforeTimeHeaderRender: headerHook,

      // Row headers: avatar, name and role; the load pill; team rows and the summary's average.
      onBeforeRowHeaderRender: (args) => {
        const id = args.row.id
        const [first, second] = args.row.columns
        if (id === SUMMARY_ROW) {
          args.row.cssClass = 'sn-row--summary'
          if (first !== undefined)
            first.html = `<span class="sn-rh"><span class="sn-rh__text"><span class="sn-rh__name">${escape(text.summary.label)}</span><span class="sn-rh__role">${escape(format(text.summary.meta, { people: TEAM.length }))}</span></span></span>`
          if (second !== undefined) {
            second.html = `<span class="sn-load" data-level="${loadLevel(sprintUse)}">${escape(percent.format(sprintUse))}</span>`
            second.horizontalAlignment = 'right'
          }
          return
        }
        const team = TEAM_IDS.find((candidate) => candidate === id)
        if (team !== undefined) {
          args.row.cssClass = 'sn-row--team'
          const count = SPECIALISTS.filter((person) => person.team === team).length
          if (first !== undefined)
            first.html = `<span class="sn-team">${escape(text.teams[team])}<span class="sn-team__count">${count}</span></span>`
          return
        }
        if (!isSpecialistId(id)) return
        args.row.cssClass = ''
        const person = SPECIALISTS.find((candidate) => candidate.id === id)
        if (person === undefined || first === undefined) return
        const name = specialistName(id, text)
        const avatar =
          person.role === 'client'
            ? '<span class="sn-avatar sn-avatar--client" aria-hidden="true"><svg viewBox="0 0 20 20"><path d="M10 1.8c.5 4.6 3.6 7.7 8.2 8.2-4.6.5-7.7 3.6-8.2 8.2-.5-4.6-3.6-7.7-8.2-8.2 4.6-.5 7.7-3.6 8.2-8.2z" fill="currentColor"/></svg></span>'
            : `<span class="sn-avatar" data-team="${person.team}" aria-hidden="true">${escape(initialsOf(name))}</span>`
        first.html = `<span class="sn-rh">${avatar}<span class="sn-rh__text"><span class="sn-rh__name">${escape(name)}</span><span class="sn-rh__role">${escape(text.roles[person.role])}</span></span></span>`
        const value = loads.get(id)
        if (second === undefined || value === undefined) return
        const label = escape(format(text.loadTitle, { value: Math.round(value * 100) }))
        second.html = `<span class="sn-load" data-level="${loadLevel(value)}" title="${label}">${escape(percent.format(value))}</span>`
        second.horizontalAlignment = 'right'
      },

      // Per-day load: the summary row counts the team's booked capacity, each person's day is
      // tinted by how many tasks it holds (two or more: overbooked).
      onBeforeCellRender: (args) => {
        const { cell } = args
        const day = cell.start.getTime()
        if (cell.resource === SUMMARY_ROW) {
          const value = teamDayLoad(tasks, day)
          const over = value > 1
          cell.properties.cssClass = over ? 'sn-cap sn-cap--over' : 'sn-cap'
          cell.properties.html = `<span class="sn-cap__value">${escape(percent.format(value))}</span><progress class="sn-cap__meter" max="100" value="${Math.min(100, Math.round(value * 100))}"></progress>`
          return
        }
        const owner = cell.resource
        if (cell.isParent || !isSpecialistId(owner) || owner === 'client-desk') return
        const count = dayAllocation(owner, tasks, day)
        const classes = [count >= 2 ? 'sn-heat-over' : count === 1 ? 'sn-heat-1' : '']
        if (day === TODAY) classes.push('sn-today')
        cell.properties.cssClass = classes.join(' ')
      },

      onBeforeEventRender: (args) => {
        const fields = readTaskFields(args.data)
        const id = args.data.id
        if (fields === null || !isTaskId(id)) return
        const start = civilOf(args.data.start)
        const end = civilOf(args.data.end)
        const isLate = late.has(id)
        const key = `${id}|${start}|${end}|${isLate}`
        let content = parts.get(key)
        if (content === undefined) {
          content = cardParts({ id, ...fields, start, end }, isLate, text, tag)
          parts.set(key, content)
        }
        const width = workingDays(start, end) * (args.control.cellWidth ?? GEOMETRY.day)
        // HTML fallback painted until the React card (renderEvent) mounts: the same markup.
        args.data.html = cardHtml(content, cardSize(width))
        const classes = ['sn-ev', `sn-c-${fields.campaign}`]
        if (fields.fixed === true) classes.push('sn-ev--fixed')
        else if (content.done) classes.push('sn-ev--done')
        if (isLate) classes.push('sn-ev--late')
        // Selected tasks get a ring; the control re-runs this hook on selection changes.
        if (args.control.multiselect.events().some((event) => event.id() === id))
          classes.push(SELECTED_CLASS)
        args.data.cssClass = classes.join(' ')
        args.data.ariaLabel = `${clientOf(fields.campaign)}, ${content.title}, ${content.meta}`
        // Progress between start and done fills the bar at the card's foot.
        if (fields.fixed !== true && fields.progress > 0 && fields.progress < 100)
          args.data.complete = fields.progress
        else args.data.barHidden = true
        // A hover button hands the task to the least loaded colleague who can take it.
        const owner = args.data.resource
        const task = tasks.find((candidate) => candidate.id === id)
        const target =
          task === undefined || !isSpecialistId(owner)
            ? null
            : handOverCandidate({ ...task, owner }, tasks, SPRINT)
        args.data.areas =
          target === null || width < 100
            ? []
            : [
                {
                  right: 5,
                  top: (GEOMETRY.event - 26) / 2,
                  width: 26,
                  height: 26,
                  visibility: 'Hover',
                  action: 'None',
                  cssClass: 'sn-act',
                  html: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 20v-1.5A3.5 3.5 0 0 0 11.5 15h-5A3.5 3.5 0 0 0 3 18.5V20"/><circle cx="9" cy="8" r="3.5"/><path d="M17 8h5M19.5 5.5 22 8l-2.5 2.5"/></svg>',
                  toolTip: format(text.actions.handOver, { owner: specialistName(target, text) }),
                  onClick: () => onAction('hand-over', id),
                },
              ]
      },

      // Role compatibility while dragging, for the dragged task and the selection that follows it.
      onEventMoving: (args) => {
        const plan = groupPlan(args.e.id(), args.start, args.resource)
        const found =
          plan === null ? singleProblem(args.e.data, args.resource) : plan.ok ? null : plan
        refusal.track(String(args.e.id()), found === null ? null : reason(found))
        if (found !== null) {
          args.allowed = false
          args.message = reason(found)
        }
      },

      // Final check before the commit (also covers keyboard moves). A selection is moved by the
      // application: the library commit is cancelled and the whole plan becomes one change.
      onEventMove: (args) => {
        const id = String(args.e.id())
        const plan = groupPlan(args.e.id(), args.newStart, args.newResource)
        if (plan !== null) {
          args.preventDefault()
          refusal.clear()
          if (plan.ok) onGroupMove(plan.moves)
          else onRefused(id, reason(plan))
          return
        }
        const found = singleProblem(args.e.data, args.newResource)
        if (found !== null) {
          args.preventDefault()
          refusal.clear()
          onRefused(id, reason(found))
        }
      },

      onEventMoved: (args) => {
        refusal.clear()
        const id = args.e.id()
        if (isTaskId(id)) onMoved(id)
      },

      onEventResized: (args) => {
        refusal.clear()
        const id = args.e.id()
        if (isTaskId(id)) onResized(id)
      },

      // The control owns the selection; React keeps a copy of the ids for the detail panel.
      onEventSelected: () => {
        const selected = controlRef.current?.multiselect.events() ?? []
        onSelectionChange(selected.map((event) => event.id()).filter(isTaskId))
      },
    }
  }, [
    history,
    controlRef,
    late,
    loads,
    tasks,
    compact,
    minZoom,
    initialZoom,
    rowHeaderColumns,
    onEventsChange,
    onMoved,
    onGroupMove,
    onRefused,
    onResized,
    onSelectionChange,
    onAction,
    refusal,
    schedulerLocale,
    headerHook,
    tag,
    text,
  ])

  // React cards: the same parts as the HTML fallback.
  const renderEvent = useMemo<NonNullable<SchedulerProps['renderEvent']>>(
    () =>
      ({ e, data, width }) => {
        const id = e.id()
        const fields = readTaskFields(data)
        if (!isTaskId(id) || fields === null) return e.text()
        const parts = cardParts(
          { id, ...fields, start: civilOf(data.start), end: civilOf(data.end) },
          late.has(id),
          text,
          tag,
        )
        return <TaskCard parts={parts} size={cardSize(width)} />
      },
    [late, text, tag],
  )

  // Hover card: owner, effort, progress, overlaps and dependencies, from the model (./task-card).
  const card = useCallback(
    (event: SuperScheduler.Event) => {
      const task = tasks.find((candidate) => candidate.id === event.id())
      if (task === undefined) return null
      return taskCard({
        task,
        tasks,
        issues,
        load: loads.get(task.owner),
        text,
        common,
        tag,
      })
    },
    [tasks, issues, loads, text, common, tag],
  )
  const { eventHover, suppressHover } = useEventHover(card)

  // Drag verdict on a day board: roles refuse, double-booking and dependencies warn.
  const dragCard = useMemo(
    () =>
      createDragCard({
        tag,
        common,
        days: true,
        overlapAllowed: true,
        rowName: (id) => (isSpecialistId(id) ? specialistName(id, text) : null),
        warn: (info) => {
          const task = tasks.find((candidate) => candidate.id === info.eventId)
          if (task === undefined) return null
          const before = tasks.find(
            (candidate) =>
              task.after.includes(candidate.id) && info.start.getTime() < parseCivil(candidate.end),
          )
          if (before !== undefined) return format(text.card.early, { other: text.tasks[before.id] })
          const next = tasks.find(
            (candidate) =>
              candidate.after.includes(task.id) && parseCivil(candidate.start) < info.end.getTime(),
          )
          return next === undefined
            ? null
            : format(text.card.cascade, { other: text.tasks[next.id] })
        },
      }),
    [tag, common, text, tasks],
  )

  // Context menu: rebuilt when the plan changes, so its labels name the real hand-over.
  const contextMenu = useMemo(
    () =>
      createEventMenu({
        theme: skinMenuTheme(SLUG),
        title: (event) => format(common.kit.menuTitle, { name: event.text() }),
        onOpenChange: (open) => suppressHover(open),
        entries: (event) => {
          const id = event.id()
          const task = tasks.find((candidate) => candidate.id === id)
          if (task === undefined || !isTaskId(id)) return []
          const target = handOverCandidate(task, tasks, SPRINT)
          return [
            {
              label: common.kit.openDetails,
              icon: 'details',
              keys: KEYS.details,
              run: () => onAction('details', id),
            },
            {
              label:
                target === null
                  ? text.actions.noOne
                  : format(text.actions.handOver, { owner: specialistName(target, text) }),
              icon: 'handover',
              primary: true,
              disabled: target === null,
              run: () => onAction('hand-over', id),
            },
            'separator',
            {
              label: format(text.actions.selectCampaign, { campaign: clientOf(task.campaign) }),
              icon: 'layers',
              run: () => onAction('select-campaign', id),
            },
          ]
        },
      }),
    [tasks, common, text, onAction, suppressHover],
  )

  // Imperative and once: a scroll prop would be re-applied on every update.
  useEffect(() => {
    controlRef.current?.scrollTo(WINDOW.start, false, 'left')
  }, [controlRef])

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

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