Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : web/src/pages/History.tsx9 * Module : pages10 * Repository : https://git.spboucher.ai/maclustr-vision11 * Project Website : https://camera.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { useCallback, useEffect, useMemo, useRef, useState } from 'react';43import { isTyping } from '../App';44import { api, type ExportDto, type MotionDto, type RangeDto, type SegmentDto } from '../api';45import { Timeline } from '../components/Timeline';46import { useApp, useNow, usePoll } from '../ctx';47import { dayBounds, dayKey, fmtBitrate, fmtBytes, fmtDateLong, fmtDateTime, fmtDuration, fmtTime, shiftDay, zonedToMs } from '../fmt';48import { IconDownload, IconGapNext, IconGapPrev, IconNext, IconPause, IconPlay, IconPrev, IconSkipBack, IconSkipFwd } from '../icons';49import { useZoom } from '../zoom';50import { hevcSupported } from '../live';5152// sans décodeur HEVC, le serveur fournit une copie de lecture H.264 720p (l'archive 4K reste intacte)53const COMPAT = hevcSupported() ? '' : '?compat=1';5455type TimelineData = { ranges: RangeDto[]; gaps: RangeDto[]; segments: number; bytes: number; motion?: MotionDto[]; protections: { id: number; fromMs: number; toMs: number; label: string | null }[] };56const ZOOMS = [57 { h: 24, label: '24 h' },58 { h: 6, label: '6 h' },59 { h: 1, label: '1 h' },60 { h: 1 / 6, label: '10 min' },61];62const RATES = [0.25, 0.5, 1, 2, 4, 8];6364export function HistoryPage() {65 const { cameras, query, navigate, toast } = useApp();66 const now = useNow(15000);67 const qCam = query.get('camera');68 const qT = Number(query.get('t')) || 0;69 const [cameraId, setCameraId] = useState<string>(qCam || '');70 const [day, setDay] = useState<string>(() => dayKey(qT || Date.now()));71 const [segments, setSegments] = useState<SegmentDto[]>([]);72 const [tl, setTl] = useState<TimelineData | null>(null);73 const [loading, setLoading] = useState(true);74 const [cursor, setCursor] = useState<number>(qT);75 const [playing, setPlaying] = useState(false);76 const [rate, setRate] = useState(1);77 const [zoom, setZoom] = useState(24);78 const [sel, setSel] = useState<{ inMs: number | null; outMs: number | null }>({ inMs: null, outMs: null });79 const [veil, setVeil] = useState<string | null>('Choisissez un moment sur la frise.');80 const [month, setMonth] = useState<string>(() => dayKey(qT || Date.now()).slice(0, 7));81 const [monthDays, setMonthDays] = useState<Map<string, number>>(new Map());82 const video = useRef<HTMLVideoElement>(null);83 const segRef = useRef<SegmentDto | null>(null);84 const segsRef = useRef<SegmentDto[]>([]);85 segsRef.current = segments;86 const playingRef = useRef(playing);87 playingRef.current = playing;88 const rateRef = useRef(rate);89 rateRef.current = rate;90 const z = useZoom();91 const cursorRef = useRef(cursor);92 cursorRef.current = cursor;9394 useEffect(() => {95 if (!cameraId && cameras.length) setCameraId(cameras[0].id);96 }, [cameras, cameraId]);9798 const bounds = useMemo(() => dayBounds(day), [day]);99100 const load = useCallback(async () => {101 if (!cameraId) return;102 const q = `cameraId=${encodeURIComponent(cameraId)}&from=${bounds.startMs}&to=${bounds.endMs}`;103 const [t, s] = await Promise.all([api<TimelineData>(`/api/recordings/timeline?${q}`), api<{ segments: SegmentDto[] }>(`/api/recordings?${q}&limit=2000`)]);104 setTl(t);105 setSegments(s.segments);106 setLoading(false);107 return s.segments;108 }, [cameraId, bounds.startMs, bounds.endMs]);109110 // chargement de la journée ; rafraîchie chaque minute si c'est aujourd'hui111 useEffect(() => {112 let alive = true;113 setLoading(true);114 setSegments([]);115 setTl(null);116 segRef.current = null;117 void load()118 .then((segs) => {119 if (!alive || !segs) return;120 if (!segs.length) {121 setVeil('Aucun enregistrement ce jour-là.');122 return;123 }124 setCursor((c) => (c >= bounds.startMs && c < bounds.endMs ? c : segs[Math.max(0, segs.length - 3)].startMs));125 setVeil(null);126 })127 .catch((e) => alive && setVeil(e.message));128 const t = window.setInterval(() => !document.hidden && dayKey(Date.now()) === day && void load().catch(() => {}), 60000);129 return () => {130 alive = false;131 clearInterval(t);132 };133 }, [load, day, bounds.startMs, bounds.endMs]);134135 // calendrier du mois136 useEffect(() => {137 if (!cameraId) return;138 const [y, m] = month.split('-').map(Number);139 const a = dayBounds(`${month}-01`).startMs;140 const last = new Date(Date.UTC(y, m, 0)).getUTCDate();141 const b = dayBounds(`${month}-${String(last).padStart(2, '0')}`).endMs;142 let alive = true;143 api<{ days: { day: string; seconds: number }[] }>(`/api/recordings/days?cameraId=${encodeURIComponent(cameraId)}&from=${a}&to=${b}`)144 .then((r) => alive && setMonthDays(new Map(r.days.map((d) => [d.day, d.seconds]))))145 .catch(() => {});146 return () => {147 alive = false;148 };149 }, [cameraId, month, segments.length]);150151 const findSeg = (ms: number): { seg: SegmentDto | null; next: SegmentDto | null } => {152 const list = segsRef.current;153 let lo = 0;154 let hi = list.length - 1;155 let next: SegmentDto | null = null;156 while (lo <= hi) {157 const mid = (lo + hi) >> 1;158 const s = list[mid];159 if (ms < s.startMs) {160 next = s;161 hi = mid - 1;162 } else if (ms >= s.endMs) lo = mid + 1;163 else return { seg: s, next: list[mid + 1] || null };164 }165 return { seg: null, next };166 };167168 /** Place la lecture à un instant : charge le bon segment réellement enregistré, ou signale l'absence de vidéo. */169 const seek = useCallback(170 (ms: number, autoplay?: boolean) => {171 const v = video.current;172 if (!v) return;173 const { seg, next } = findSeg(ms);174 setCursor(ms);175 if (autoplay !== undefined) setPlaying(autoplay);176 if (!seg) {177 segRef.current = null;178 v.pause();179 v.removeAttribute('src');180 v.load();181 setVeil(next ? `Aucun enregistrement à ${fmtTime(ms)}. Prochaine vidéo à ${fmtTime(next.startMs)}.` : `Aucun enregistrement à ${fmtTime(ms)}.`);182 return;183 }184 setVeil(null);185 const offset = Math.max(0, (ms - seg.startMs) / 1000);186 if (segRef.current?.id === seg.id && v.readyState >= 1) {187 v.currentTime = offset;188 } else {189 segRef.current = seg;190 v.src = `/api/recordings/${seg.id}/playback${COMPAT}`;191 v.onloadedmetadata = () => {192 v.currentTime = Math.min(offset, Math.max(0, v.duration - 0.2));193 v.playbackRate = rateRef.current;194 if (playingRef.current) v.play().catch(() => setPlaying(false));195 };196 v.load();197 // prépare le segment suivant côté serveur pour un enchaînement fluide198 const n = segsRef.current[segsRef.current.indexOf(seg) + 1];199 if (n) void fetch(`/api/recordings/${n.id}/playback${COMPAT}`, { headers: { Range: 'bytes=0-1' }, credentials: 'same-origin' }).catch(() => {});200 }201 if ((autoplay ?? playingRef.current) && v.readyState >= 1) v.play().catch(() => setPlaying(false));202 },203 [],204 );205206 // première position une fois la journée chargée207 const inited = useRef('');208 useEffect(() => {209 const k = `${cameraId}|${day}`;210 if (segments.length && inited.current !== k && cursor >= bounds.startMs && cursor < bounds.endMs) {211 inited.current = k;212 seek(cursor, false);213 }214 }, [segments, cursor, cameraId, day, bounds.startMs, bounds.endMs, seek]);215216 function onTimeUpdate() {217 const v = video.current;218 const s = segRef.current;219 if (v && s && !v.seeking) setCursor(Math.round(s.startMs + v.currentTime * 1000));220 }221 function onEnded() {222 const s = segRef.current;223 if (!s) return;224 const list = segsRef.current;225 const n = list[list.indexOf(s) + 1];226 if (!n) {227 setPlaying(false);228 setVeil('Fin des enregistrements disponibles pour cette journée.');229 return;230 }231 if (n.startMs - s.endMs > 5000) toast(`Trou de ${fmtDuration((n.startMs - s.endMs) / 1000)} : reprise à ${fmtTime(n.startMs)}`);232 seek(n.startMs, true);233 }234 function togglePlay() {235 const v = video.current;236 if (!v) return;237 if (playing) {238 v.pause();239 setPlaying(false);240 } else if (segRef.current) {241 setPlaying(true);242 v.play().catch(() => setPlaying(false));243 } else {244 const { next } = findSeg(cursor);245 if (next) seek(next.startMs, true);246 }247 }248 useEffect(() => {249 if (video.current) video.current.playbackRate = rate;250 }, [rate]);251252 const jumpGap = (dir: 1 | -1) => {253 const gaps = tl?.gaps || [];254 const c = cursorRef.current;255 const g = dir > 0 ? gaps.find((x) => x.startMs > c + 500) : [...gaps].reverse().find((x) => x.endMs < c - 1500);256 if (!g) return toast(dir > 0 ? 'Aucun trou après cette position.' : 'Aucun trou avant cette position.');257 // se placer quelques secondes avant le trou pour voir ce qui le précède258 seek(Math.max(bounds.startMs, g.startMs - 5000), false);259 };260 const jumpMotion = (dir: 1 | -1) => {261 const list = tl?.motion || [];262 const c = cursorRef.current;263 const m = dir > 0 ? list.find((x) => x.fromMs > c + 1500) : [...list].reverse().find((x) => x.fromMs < c - 4000);264 if (!m) return toast(dir > 0 ? 'Aucun mouvement détecté après cette position.' : 'Aucun mouvement détecté avant cette position.');265 seek(Math.max(bounds.startMs, m.fromMs - 2000), true);266 };267 const stepFrame = (dir: 1 | -1) => {268 const v = video.current;269 if (!v || !segRef.current) return;270 v.pause();271 setPlaying(false);272 v.currentTime = Math.max(0, Math.min(v.duration || 0, v.currentTime + dir / 20));273 };274 useEffect(() => {275 const on = (e: KeyboardEvent) => {276 if (isTyping(e) || e.metaKey || e.ctrlKey || e.altKey) return;277 const k = e.key;278 const c = cursorRef.current;279 if (k === ' ' || k === 'k' || k === 'K') (e.preventDefault(), togglePlay());280 else if (k === 'ArrowLeft') (e.preventDefault(), seek(c - (e.shiftKey ? 60000 : 10000)));281 else if (k === 'ArrowRight') (e.preventDefault(), seek(c + (e.shiftKey ? 60000 : 10000)));282 else if (k === 'j' || k === 'J') setRate((r) => RATES[Math.max(0, RATES.indexOf(r) - 1)]);283 else if (k === 'l' || k === 'L') setRate((r) => RATES[Math.min(RATES.length - 1, RATES.indexOf(r) + 1)]);284 else if (k === ',') stepFrame(-1);285 else if (k === '.') stepFrame(1);286 else if (k === '[') setSel((x) => ({ ...x, inMs: c }));287 else if (k === ']') setSel((x) => ({ ...x, outMs: c }));288 else if (k === 'N') jumpMotion(1);289 else if (k === 'P') jumpMotion(-1);290 else if (k === 'n') jumpGap(1);291 else if (k === 'p') jumpGap(-1);292 };293 window.addEventListener('keydown', on);294 return () => window.removeEventListener('keydown', on);295 });296297 // fenêtre visible de la frise298 const span = zoom * 3600000;299 const dayLen = bounds.endMs - bounds.startMs;300 let viewStart = bounds.startMs;301 if (zoom < 24) viewStart = Math.max(bounds.startMs, Math.min(bounds.endMs - span, bounds.startMs + Math.floor(((cursor || bounds.startMs) - bounds.startMs) / span) * span));302 const viewEnd = zoom < 24 ? viewStart + span : bounds.startMs + dayLen;303304 const exportsPoll = usePoll(() => api<{ exports: ExportDto[] }>('/api/exports'), 2500, []);305 const myExports = (exportsPoll.data?.exports || []).filter((e) => e.cameraId === cameraId).slice(0, 6);306 const maxExportMs = 120 * 60000;307 const selOk = sel.inMs !== null && sel.outMs !== null && sel.outMs > sel.inMs;308 async function doExport() {309 if (!selOk) return;310 if (sel.outMs! - sel.inMs! > maxExportMs) return toast('Un export est limité à 120 minutes.');311 try {312 await api('/api/exports', { method: 'POST', body: { cameraId, fromMs: sel.inMs, toMs: sel.outMs } });313 toast('Export lancé');314 exportsPoll.reload();315 } catch (e: any) {316 toast(e.message);317 }318 }319 async function doProtect(on: boolean) {320 if (!selOk) return;321 try {322 const r = await api('/api/recordings/protect', { method: 'POST', body: { cameraId, fromMs: sel.inMs, toMs: sel.outMs, protected: on } });323 toast(on ? `${r.segments} segment(s) protégé(s) contre la purge` : `Protection retirée de ${r.segments} segment(s)`);324 void load();325 } catch (e: any) {326 toast(e.message);327 }328 }329330 const today = dayKey(now);331 const recorded = tl ? tl.ranges.reduce((a, r) => a + (r.endMs - r.startMs), 0) / 1000 : 0;332 const avgRate = tl && recorded > 0 ? (tl.bytes * 8) / recorded : 0;333 const setDayNav = (k: string) => {334 if (k > today) return;335 setDay(k);336 setMonth(k.slice(0, 7));337 setSel({ inMs: null, outMs: null });338 setPlaying(false);339 setCursor(0);340 navigate(`/history?camera=${encodeURIComponent(cameraId)}`, true);341 };342343 return (344 <>345 <div className="page-head">346 <h1>347 Historique348 <span className="sub">{fmtDateLong(bounds.startMs + 12 * 3600000)}</span>349 </h1>350 <div className="seg" role="group" aria-label="Jour">351 <button onClick={() => setDayNav(shiftDay(day, -1))} aria-label="Jour précédent">352 ‹353 </button>354 <button onClick={() => setDayNav(today)} aria-pressed={day === today}>355 AUJ.356 </button>357 <button onClick={() => setDayNav(shiftDay(day, 1))} disabled={day >= today} aria-label="Jour suivant">358 ›359 </button>360 </div>361 <select className="input" style={{ width: 'auto', maxWidth: '100%' }} value={cameraId} onChange={(e) => (setCameraId(e.target.value), setPlaying(false), setSel({ inMs: null, outMs: null }))} aria-label="Caméra">362 {cameras.map((c) => (363 <option key={c.id} value={c.id}>364 {c.name}365 </option>366 ))}367 </select>368 </div>369 <div className="cam-layout">370 <div className="stack">371 <div className="player">372 <div className="stage" ref={z.stage} {...z.handlers}>373 <video ref={video} style={z.style} playsInline onTimeUpdate={onTimeUpdate} onEnded={onEnded} onPlay={() => setPlaying(true)} onError={() => segRef.current && setVeil('Ce segment n’a pas pu être lu.')} aria-label="Lecture de l’enregistrement" />374 </div>375 <div className="marks" aria-hidden="true" />376 {veil && <div className="veil">{loading ? <div className="spinner" /> : veil}</div>}377 {z.zoom > 1.01 && <span className="badge zoomtag">{z.zoom.toFixed(1).replace('.', ',')}×</span>}378 {!veil && cursor > 0 && <span className="badge stamp">Enregistré</span>}379 </div>380 <Timeline cameraId={cameraId} viewStart={viewStart} viewEnd={viewEnd} ranges={tl?.ranges || []} gaps={tl?.gaps || []} segments={segments} motion={tl?.motion || []} protections={tl?.protections || []} cursorMs={cursor} selection={sel} nowMs={now} onSeek={(ms) => seek(ms)} />381 <div className="legend">382 <span>383 <i className="sw" style={{ background: 'var(--accent)' }} /> Activité (débit vidéo{avgRate ? ` · moy. ${fmtBitrate(avgRate)}` : ''})384 </span>385 <span>386 <i className="sw" style={{ background: '#d9dde1' }} /> Enregistré <b className="mono">{fmtDuration(recorded)}</b>387 </span>388 <span>389 <i className="sw" style={{ background: '#7a3437' }} /> Trous <b className="mono">{tl?.gaps.length ?? 0}</b>390 </span>391 <span>392 <i className="sw" style={{ background: 'var(--warn)' }} /> Mouvements <b className="mono">{tl?.motion?.length ?? 0}</b>393 </span>394 <span>395 <i className="sw" style={{ background: '#e9ebed', height: 3 }} /> Protégé396 </span>397 <span className="mono">{tl ? `${tl.segments} segments · ${fmtBytes(tl.bytes)}` : ''}</span>398 </div>399 <p className="faint" style={{ fontSize: 12.5 }}>400 La piste d’activité montre le débit réellement enregistré. Les marques « Mouvements » viennent de la détection par différence d’images faite sur le serveur ; elle ne reconnaît ni les personnes ni les objets.401 </p>402 <div className="row wrap" style={{ justifyContent: 'space-between' }}>403 <div className="timecode" aria-live="off">404 {cursor > 0 ? fmtTime(cursor) : '––:––:––'}405 <small>{rate !== 1 ? `${String(rate).replace('.', ',')}×` : 'AMERICA/TORONTO'}</small>406 </div>407 <label className="row" style={{ gap: 8 }}>408 <span className="cap">Aller à</span>409 <input410 className="input mono"411 style={{ width: 132, minHeight: 40 }}412 type="time"413 step={1}414 aria-label="Aller à l’heure"415 onChange={(e) => {416 const m = /^(\d\d):(\d\d)(?::(\d\d))?$/.exec(e.target.value);417 if (!m) return;418 const [y, mo, d] = day.split('-').map(Number);419 seek(zonedToMs(y, mo, d, +m[1], +m[2], +(m[3] || 0)));420 }}421 />422 </label>423 </div>424 <div className="controls">425 <button className="btn icon" onClick={() => jumpGap(-1)} aria-label="Trou précédent" title="Trou précédent (P)">426 <IconGapPrev />427 </button>428 <button className="btn icon" onClick={() => seek(cursor - 10000)} aria-label="Reculer de 10 secondes" title="−10 s (←)" disabled={!cursor}>429 <IconSkipBack />430 </button>431 <button className="btn icon primary" onClick={togglePlay} aria-label={playing ? 'Pause' : 'Lecture'} title="Lecture / pause (Espace)" disabled={!segments.length}>432 {playing ? <IconPause /> : <IconPlay />}433 </button>434 <button className="btn icon" onClick={() => seek(cursor + 10000)} aria-label="Avancer de 10 secondes" title="+10 s (→)" disabled={!cursor}>435 <IconSkipFwd />436 </button>437 <button className="btn icon" onClick={() => jumpGap(1)} aria-label="Trou suivant" title="Trou suivant (N)">438 <IconGapNext />439 </button>440 <div className="seg" role="group" aria-label="Mouvements détectés">441 <button onClick={() => jumpMotion(-1)} title="Mouvement précédent (Maj P)" aria-label="Mouvement précédent">442 ‹ MVT443 </button>444 <button onClick={() => jumpMotion(1)} title="Mouvement suivant (Maj N)" aria-label="Mouvement suivant">445 MVT ›446 </button>447 </div>448 <div className="seg" role="group" aria-label="Vitesse">449 {RATES.map((r) => (450 <button key={r} aria-pressed={rate === r} onClick={() => setRate(r)}>451 {String(r).replace('.', ',')}×452 </button>453 ))}454 </div>455 <div className="grow" />456 <div className="seg" role="group" aria-label="Zoom de la frise">457 {ZOOMS.map((zz) => (458 <button key={zz.label} aria-pressed={zoom === zz.h} onClick={() => setZoom(zz.h)}>459 {zz.label.toUpperCase()}460 </button>461 ))}462 </div>463 </div>464 <div className="card pad stack">465 <h2>Extrait</h2>466 <div className="row wrap">467 <button className="btn small" onClick={() => setSel((s) => ({ ...s, inMs: cursor }))} disabled={!cursor}>468 Début ici <kbd>[</kbd>469 </button>470 <button className="btn small" onClick={() => setSel((s) => ({ ...s, outMs: cursor }))} disabled={!cursor}>471 Fin ici <kbd>]</kbd>472 </button>473 <span className="mono muted">474 {sel.inMs ? fmtTime(sel.inMs) : '––:––:––'} → {sel.outMs ? fmtTime(sel.outMs) : '––:––:––'}475 {selOk ? ` · ${fmtDuration((sel.outMs! - sel.inMs!) / 1000)}` : ''}476 </span>477 </div>478 <div className="row wrap">479 <button className="btn" onClick={doExport} disabled={!selOk}>480 <IconDownload />481 Exporter en MP4482 </button>483 <button className="btn" onClick={() => doProtect(true)} disabled={!selOk}>484 Protéger de la purge485 </button>486 <button className="btn" onClick={() => doProtect(false)} disabled={!selOk}>487 Retirer la protection488 </button>489 </div>490 {myExports.length > 0 && (491 <div className="list">492 {myExports.map((e) => (493 <div key={e.id} className="list-item" style={{ paddingLeft: 0, paddingRight: 0 }}>494 <div className="grow">495 <div className="mono" style={{ fontSize: 13 }}>496 {fmtDateTime(e.fromMs)} → {fmtTime(e.toMs)}497 </div>498 <div className="muted" style={{ fontSize: 13 }}>499 {e.state === 'done' ? `${fmtBytes(e.sizeBytes)} · disponible jusqu’au ${e.expiresMs ? fmtDateTime(e.expiresMs) : '—'}` : e.state === 'failed' ? `Échec : ${e.error}` : `En cours… ${Math.round(e.progress * 100)} %`}500 </div>501 </div>502 {e.state === 'done' && (503 <a className="btn small" href={`/api/exports/${e.id}/download`} download>504 Télécharger505 </a>506 )}507 {e.state !== 'running' && (508 <button className="btn small" onClick={() => void api(`/api/exports/${e.id}`, { method: 'DELETE' }).then(exportsPoll.reload, () => {})} aria-label="Supprimer l’export">509 ×510 </button>511 )}512 </div>513 ))}514 </div>515 )}516 </div>517 {COMPAT && <div className="notice">Ce navigateur ne décode pas le HEVC : lecture en copie H.264 720p préparée à la demande (quelques secondes par minute de vidéo). Les exports restent en qualité d’origine.</div>}518 </div>519 <Calendar month={month} setMonth={setMonth} day={day} today={today} days={monthDays} onPick={setDayNav} />520 </div>521 </>522 );523}524525function Calendar({ month, setMonth, day, today, days, onPick }: { month: string; setMonth: (m: string) => void; day: string; today: string; days: Map<string, number>; onPick: (k: string) => void }) {526 const [y, m] = month.split('-').map(Number);527 const first = new Date(Date.UTC(y, m - 1, 1));528 const count = new Date(Date.UTC(y, m, 0)).getUTCDate();529 const lead = (first.getUTCDay() + 6) % 7; // semaine commençant le lundi530 const title = new Intl.DateTimeFormat('fr-CA', { month: 'long', year: 'numeric', timeZone: 'UTC' }).format(first);531 const shift = (d: number) => {532 const x = new Date(Date.UTC(y, m - 1 + d, 1));533 setMonth(`${x.getUTCFullYear()}-${String(x.getUTCMonth() + 1).padStart(2, '0')}`);534 };535 return (536 <div className="card pad stack">537 <div className="row">538 <button className="btn icon small" onClick={() => shift(-1)} aria-label="Mois précédent">539 <IconPrev />540 </button>541 <div className="grow" style={{ textAlign: 'center', fontWeight: 600, textTransform: 'capitalize' }}>542 {title}543 </div>544 <button className="btn icon small" onClick={() => shift(1)} disabled={month >= today.slice(0, 7)} aria-label="Mois suivant">545 <IconNext />546 </button>547 </div>548 <div className="cal">549 {['L', 'M', 'M', 'J', 'V', 'S', 'D'].map((d, i) => (550 <div key={i} className="dow">551 {d}552 </div>553 ))}554 {Array.from({ length: lead }, (_, i) => (555 <span key={`b${i}`} />556 ))}557 {Array.from({ length: count }, (_, i) => {558 const k = `${month}-${String(i + 1).padStart(2, '0')}`;559 const secs = days.get(k) || 0;560 return (561 <button key={k} className={`${secs ? 'has' : ''} ${k === day ? 'sel' : ''} ${k === today ? 'today' : ''}`} style={secs ? ({ ['--fill' as any]: String(Math.max(0.35, Math.min(1, secs / 86400))) } as any) : undefined} disabled={k > today} onClick={() => onPick(k)} aria-label={`${i + 1} — ${secs ? fmtDuration(secs) + ' enregistrées' : 'aucun enregistrement'}`} aria-pressed={k === day}>562 {i + 1}563 </button>564 );565 })}566 </div>567 <p className="muted" style={{ fontSize: 13 }}>568 Les jours marqués contiennent des enregistrements. Heures affichées : America/Toronto.569 </p>570 </div>571 );572}573