Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : web/src/ctx.tsx9 * Module : web10 * 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 { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';43import type { CameraDto } from './api';4445export type AppCtx = {46 cameras: CameraDto[];47 refreshCameras: () => Promise<void>;48 path: string;49 query: URLSearchParams;50 navigate: (to: string, replace?: boolean) => void;51 toast: (msg: string) => void;52 logout: () => void;53 sessionId: string;54 clockOffset: number;55 version: string;56};57export const Ctx = createContext<AppCtx>(null as unknown as AppCtx);58export const useApp = () => useContext(Ctx);5960export function useRoute(): { path: string; query: URLSearchParams; navigate: (to: string, replace?: boolean) => void } {61 const [loc, setLoc] = useState(() => location.pathname + location.search);62 useEffect(() => {63 const on = () => setLoc(location.pathname + location.search);64 window.addEventListener('popstate', on);65 return () => window.removeEventListener('popstate', on);66 }, []);67 const navigate = useCallback((to: string, replace = false) => {68 if (replace) history.replaceState(null, '', to);69 else history.pushState(null, '', to);70 setLoc(to);71 if (!replace) window.scrollTo(0, 0);72 }, []);73 const u = new URL(loc, location.origin);74 return { path: u.pathname, query: u.searchParams, navigate };75}7677export function Link({ to, children, className, current }: { to: string; children: ReactNode; className?: string; current?: boolean }) {78 const { navigate } = useApp();79 return (80 <a81 href={to}82 className={className}83 aria-current={current ? 'page' : undefined}84 onClick={(e) => {85 if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;86 e.preventDefault();87 navigate(to);88 }}89 >90 {children}91 </a>92 );93}9495/** Interroge périodiquement une ressource tant que l'onglet est visible. */96export function usePoll<T>(fn: () => Promise<T>, intervalMs: number, deps: unknown[] = []): { data: T | null; error: string | null; reload: () => void } {97 const [data, setData] = useState<T | null>(null);98 const [error, setError] = useState<string | null>(null);99 const fnRef = useRef(fn);100 fnRef.current = fn;101 const [tick, setTick] = useState(0);102 useEffect(() => {103 let alive = true;104 const run = () => {105 if (document.hidden) return;106 fnRef.current().then(107 (d) => {108 if (alive) {109 setData(d);110 setError(null);111 }112 },113 (e) => {114 if (alive) setError(e?.message || 'Erreur');115 },116 );117 };118 run();119 const t = window.setInterval(run, intervalMs);120 const vis = () => !document.hidden && run();121 document.addEventListener('visibilitychange', vis);122 return () => {123 alive = false;124 clearInterval(t);125 document.removeEventListener('visibilitychange', vis);126 };127 // eslint-disable-next-line react-hooks/exhaustive-deps128 }, [intervalMs, tick, ...deps]);129 return { data, error, reload: () => setTick((x) => x + 1) };130}131132export function useNow(intervalMs = 1000): number {133 const [now, setNow] = useState(Date.now());134 useEffect(() => {135 const t = window.setInterval(() => setNow(Date.now()), intervalMs);136 return () => clearInterval(t);137 }, [intervalMs]);138 return now;139}140