Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | ACADEMIC RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project : UQO Éval10 * File : src/components/metre/ui.tsx11 * Module : components12 * Repository : https://git.spboucher.ai/uqo-eval13 * Project Website : https://www.uqo-eval.app14 * Created : 2026-10-2815 * Last Modified : 2026-10-2816 *17 * =============================================================================18 * SOFTWARE MAINTAINER & AFFILIATION19 * =============================================================================20 *21 * Maintainer : Simon-Pierre Boucher22 * Position : Professor of Finance23 * Institution : Université du Québec en Outaouais (UQO)24 * Department : Département des sciences administratives25 * Website : https://spboucher.ai26 * Git : https://git.spboucher.ai27 *28 * Research Contact : research@spboucher.ai29 * Direct Contact : simon@spboucher.ai30 * Security/Admin : admin@spboucher.ai31 *32 * The affiliation is descriptive. It is not an institutional endorsement,33 * a license grant or a determination of ownership.34 *35 * =============================================================================36 * COPYRIGHT, AUTHORSHIP & DATA37 * =============================================================================38 *39 * Copyright (c) the author(s) of this work.40 * Ownership is not asserted by this notice; see the repository records.41 *42 * This header identifies the maintainer of the software. Scientific43 * authorship of any associated paper is stated in the paper itself and44 * is not changed by this notice. Datasets and third-party materials45 * remain the property of their respective owners and licensors.46 *47 * This file is governed by the applicable project license, copyright48 * notices, institutional agreements and relevant law.49 *50 * =============================================================================51 * LICENSE & MAINTENANCE52 * =============================================================================53 *54 * License : None specified (no license file in this repository)55 * Classification : Public56 *57 * =============================================================================58 * END OF SP BOUCHER SOURCE HEADER59 * =============================================================================60 */6162// UQO Éval — Métré : primitives d'interface du module (appel API, connexion, badges, champs). Client.63"use client";64import { useEffect, useState } from "react";65import Link from "next/link";66import { useLang } from "@/components/LangContext";67import type { MetreUser } from "@/lib/metre/types";6869export class ApiError extends Error { constructor(public status: number, message: string) { super(message); } }7071export async function api<T = unknown>(path: string, init?: RequestInit & { json?: unknown }): Promise<T> {72 const headers: Record<string, string> = { ...(init?.headers as Record<string, string> | undefined) };73 let body = init?.body;74 if (init?.json !== undefined) { headers["Content-Type"] = "application/json"; body = JSON.stringify(init.json); }75 const r = await fetch(`/api/metre${path}`, { ...init, headers, body, credentials: "same-origin" });76 if (r.status === 204) return undefined as T;77 const ct = r.headers.get("content-type") ?? "";78 const data = ct.includes("application/json") ? await r.json() : await r.text();79 if (!r.ok) throw new ApiError(r.status, (data as { error?: string })?.error ?? (typeof data === "string" ? data : r.statusText));80 return data as T;81}8283export const money = (v: number | null | undefined, lang = "fr", frac = 0) => (v == null || !Number.isFinite(v) ? "—" : new Intl.NumberFormat(lang === "fr" ? "fr-CA" : "en-CA", { style: "currency", currency: "CAD", maximumFractionDigits: frac, minimumFractionDigits: frac }).format(v));84export const num = (v: number | null | undefined, lang = "fr", frac = 2) => (v == null || !Number.isFinite(v) ? "—" : v.toLocaleString(lang === "fr" ? "fr-CA" : "en-CA", { maximumFractionDigits: frac }));85export const dt = (iso: string | null | undefined, lang = "fr") => (iso ? new Date(iso.length <= 10 ? `${iso}T12:00:00` : iso).toLocaleString(lang === "fr" ? "fr-CA" : "en-CA", { dateStyle: "medium", timeStyle: iso.length <= 10 ? undefined : "short" }) : "—");8687/** Session courante ; plateforme OUVERTE : une session anonyme est créée automatiquement si nécessaire. */88export function useMe(): { user: MetreUser | null; enabled: boolean; loading: boolean; refresh: () => void } {89 const [state, set] = useState<{ user: MetreUser | null; enabled: boolean; loading: boolean }>({ user: null, enabled: true, loading: true });90 const [tick, setTick] = useState(0);91 useEffect(() => {92 let c = false;93 (async () => {94 try {95 const r = await api<{ enabled: boolean; user: MetreUser | null }>("/auth/me");96 if (c) return;97 if (!r.enabled) { set({ user: null, enabled: false, loading: false }); return; }98 if (r.user) { set({ user: r.user, enabled: true, loading: false }); return; }99 const a = await api<{ user: MetreUser }>("/auth/anonymous", { method: "POST", json: {} });100 if (!c) set({ user: a.user, enabled: true, loading: false });101 } catch { if (!c) set({ user: null, enabled: true, loading: false }); }102 })();103 return () => { c = true; };104 }, [tick]);105 return { ...state, refresh: () => setTick((t) => t + 1) };106}107108export function Kicker({ children }: { children: React.ReactNode }) { return <span className="kicker">{children}</span>; }109110export function Block({ num: n, title, children, aside, id }: { num: string; title: string; children: React.ReactNode; aside?: React.ReactNode; id?: string }) {111 return (112 <section id={id} className="sec scroll-mt-24">113 <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1"><p className="vp-mono text-[10px] font-bold uppercase tracking-[0.12em] text-accent">{n} — {title}</p>{aside}</div>114 <div className="mt-4 space-y-4">{children}</div>115 </section>116 );117}118119export function Field({ label, children, hint }: { label: string; children: React.ReactNode; hint?: string }) {120 return <label className="block" title={hint}><span className="klabel">{label}</span><div className="mt-1">{children}</div></label>;121}122123export function Input(props: React.InputHTMLAttributes<HTMLInputElement>) { return <input {...props} className={`vp-input text-[14px] ${props.className ?? ""}`} />; }124export function Select(props: React.SelectHTMLAttributes<HTMLSelectElement>) { return <select {...props} className={`vp-input text-[14px] ${props.className ?? ""}`} />; }125export function Textarea(props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) { return <textarea {...props} className={`vp-input text-[14px] ${props.className ?? ""}`} />; }126127export function Btn({ tone = "ghost", small, ...p }: React.ButtonHTMLAttributes<HTMLButtonElement> & { tone?: "primary" | "ghost" | "accent"; small?: boolean }) {128 return <button type="button" {...p} className={`btn btn-${tone} ${small ? "!min-h-0 !px-3 !py-1.5 text-[12px]" : ""} ${p.className ?? ""}`} />;129}130131export function Err({ msg }: { msg: string | null }) { return msg ? <p className="border-l-2 border-[var(--danger)] pl-3 text-[13px] text-[var(--danger)]">{msg}</p> : null; }132133export function Pill({ tone, children }: { tone: "A" | "B" | "C" | "D"; children: React.ReactNode }) { return <span className={`pill pill-conf-${tone}`}>{children}</span>; }134135/** Badge de provenance : ● observé/officiel · ○ indexé · ◐ calculé · ◇ référence/hypothèse · ≈ modèle */136export function Prov({ kind, share, fr }: { kind: string; share?: number; fr: boolean }) {137 const g = kind === "observed" || kind === "official" ? "●" : kind === "indexed" ? "○" : kind === "derived" ? "◐" : kind === "modeled" ? "≈" : "◇";138 const tone = kind === "observed" || kind === "official" ? "text-ink" : kind === "indexed" || kind === "derived" ? "text-accent" : "text-[var(--amber)]";139 const label: Record<string, [string, string]> = { observed: ["observé", "observed"], official: ["officiel", "official"], indexed: ["indexé", "indexed"], derived: ["calculé", "computed"], reference: ["référence (hypothèse)", "reference (assumption)"], assumption: ["hypothèse", "assumption"], modeled: ["modèle", "model"] };140 const l = label[kind] ?? [kind, kind];141 return <span className={`vp-mono inline-flex items-center gap-1 text-[11px] ${tone}`} title={fr ? l[0] : l[1]}>{g}{share != null && <span className="text-ink-3">{Math.round(share * 100)} %</span>}</span>;142}143144export function LoginCard({ onDone }: { onDone: () => void }) {145 const { lang } = useLang(); const fr = lang === "fr";146 const [code, setCode] = useState(""); const [name, setName] = useState(""); const [err, setErr] = useState<string | null>(null); const [busy, setBusy] = useState(false);147 const go = async () => { setBusy(true); setErr(null); try { await api("/auth/login", { method: "POST", json: { code, displayName: name } }); onDone(); } catch (e) { setErr((e as Error).message); } finally { setBusy(false); } };148 return (149 <div className="mx-auto max-w-md py-16">150 <Kicker>{fr ? "Espace du personnel" : "Staff area"}</Kicker>151 <h1 className="vp-display mt-2 text-[28px] font-bold uppercase leading-none tracking-[-0.03em]">{fr ? "Code enseignant / administrateur" : "Instructor / administrator code"}</h1>152 <p className="mt-2 text-[13.5px] text-ink-2">{fr ? "Le module Quantity Survey est ouvert à tous sans mot de passe. Cette page (sources, devoirs, corrigés, codes) est réservée au personnel : entrez votre code ; votre session actuelle et vos projets sont conservés." : "The Métré module is open to everyone without a password. This page (sources, assignments, answer keys, codes) is for staff: enter your code; your current session and projects are kept."}</p>153 <form className="mt-6 space-y-4" onSubmit={(e) => { e.preventDefault(); void go(); }}>154 <Field label={fr ? "Code d'accès" : "Access code"}><Input value={code} onChange={(e) => setCode(e.target.value)} autoComplete="off" spellCheck={false} className="vp-mono uppercase" required /></Field>155 <Field label={fr ? "Nom d'affichage (si nouvelle session)" : "Display name (if new session)"}><Input value={name} onChange={(e) => setName(e.target.value)} maxLength={80} /></Field>156 <Err msg={err} />157 <Btn tone="primary" disabled={busy} onClick={() => void go()}>{busy ? "…" : fr ? "Entrer" : "Enter"}</Btn>158 </form>159 <p className="vp-mono mt-8 text-[10px] uppercase tracking-[0.06em] text-ink-3">{fr ? "Module « Quantity Survey » d'UQO Éval — laboratoire pédagogique (IMM1033)." : "UQO Éval “Quantity Survey” module — teaching laboratory (IMM1033)."} <Link href="/cout" className="text-accent">{fr ? "Méthode du coût" : "Cost approach"}</Link></p>160 </div>161 );162}163164export function Crumbs({ items }: { items: { href?: string; label: string }[] }) {165 return (166 <nav className="vp-mono flex flex-wrap items-center gap-2 text-[10.5px] uppercase tracking-[0.08em] text-ink-3">167 {items.map((it, i) => (<span key={i} className="flex items-center gap-2">{i > 0 && <span aria-hidden="true">/</span>}{it.href ? <Link href={it.href} className="text-ink-2 hover:text-accent-deep">{it.label}</Link> : <span>{it.label}</span>}</span>))}168 </nav>169 );170}171