Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : web/src/ui/next/Dashboard.tsx9 * Module : ui10 * Repository : https://git.spboucher.ai/sp-mail11 * Project Website : https://mail.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *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: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// SP Mail Next — centre de commande : grille de widgets (12 colonnes), personnalisation (afficher, masquer, réordonner au pointeur et au clavier, largeur), relecture.44import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from "react"45import { fmtListDate, t } from "../../i18n"46import { WIDGET_IDS, defaultLayout, dropWidgetOn, hiddenWidgets, isDefaultLayout, moveWidget, sameLayout, setWidgetHidden, setWidgetWide, visibleWidgets, widgetRank, type DashboardLayout, type WidgetId } from "../../next/dashboard"47import { DASH, cancelScheduledSend, loadDashboard, widgetAvailable, type OutboundItem } from "../../next/dashboard-data"48import { S, toast } from "../../state/app"49import { linkProps, updatePrefs } from "../../state/session"50import { useStore } from "../../state/store"51import { Icon, IconButton, confirmAsync } from "../kit"52import { WIDGETS, widgetBody, widgetTitle, type WidgetProps } from "./DashboardWidgets"53import "./dashboard.css"5455const isWidgetId = (v: string | null | undefined): v is WidgetId => !!v && (WIDGET_IDS as readonly string[]).includes(v)5657function Skeleton() {58 return (59 <div className="nx-dash-skel" aria-hidden="true">60 <div className="skeleton" />61 <div className="skeleton" />62 <div className="skeleton" />63 </div>64 )65}6667export default function Dashboard() {68 const saved = useStore(S, (s) => s.prefs.dashboard)69 const online = useStore(S, (s) => s.online)70 const data = useStore(DASH, (d) => d.data)71 const loading = useStore(DASH, (d) => d.loading)72 const error = useStore(DASH, (d) => d.error)73 const overdue = useStore(DASH, (d) => d.overdue)74 const [editing, setEditing] = useState(false)75 const [announce, setAnnounce] = useState("")76 /** disposition provisoire pendant un glissement (enregistrée au relâchement) */77 const [draft, setDraft] = useState<DashboardLayout | null>(null)78 const [dragging, setDragging] = useState<WidgetId | null>(null)79 const layout = draft ?? saved80 const drag = useRef<{ id: WidgetId; lastOver: WidgetId | null } | null>(null)81 const refocus = useRef<string | null>(null)82 const grid = useRef<HTMLDivElement>(null)8384 useEffect(() => {85 void loadDashboard()86 // retour sur l'onglet : les compteurs ont pu bouger ailleurs87 const onFocus = () => {88 if (document.visibilityState === "visible") void loadDashboard()89 }90 document.addEventListener("visibilitychange", onFocus)91 window.addEventListener("focus", onFocus)92 window.addEventListener("online", onFocus)93 return () => {94 document.removeEventListener("visibilitychange", onFocus)95 window.removeEventListener("focus", onFocus)96 window.removeEventListener("online", onFocus)97 }98 }, [])99100 // un déplacement change la place du nœud dans le document : le bouton qui avait le focus le retrouve101 useLayoutEffect(() => {102 if (!refocus.current) return103 grid.current?.querySelector<HTMLElement>(refocus.current)?.focus()104 refocus.current = null105 })106107 const shown = visibleWidgets(layout, widgetAvailable)108 const hidden = hiddenWidgets(layout, widgetAvailable)109110 const commit = (next: DashboardLayout, message: string, focus?: string) => {111 if (next === saved || sameLayout(next, saved)) return112 if (focus) refocus.current = focus113 updatePrefs({ dashboard: next })114 setAnnounce(message)115 }116 const move = (id: WidgetId, delta: -1 | 1, control: string) => {117 const next = moveWidget(saved, id, delta, widgetAvailable)118 if (next === saved) return setAnnounce(t(delta < 0 ? "nx.dashboard.edit.atStart" : "nx.dashboard.edit.atEnd", { name: widgetTitle(id) }))119 const { rank, of } = widgetRank(next, id, widgetAvailable)120 commit(next, t("nx.dashboard.edit.moved", { name: widgetTitle(id), rank, of }), `[data-widget="${id}"] [data-ctl="${control}"]`)121 }122 const onHandleKey = (e: ReactKeyboardEvent, id: WidgetId) => {123 if (e.altKey || e.metaKey || e.ctrlKey) return124 const delta = e.key === "ArrowUp" || e.key === "ArrowLeft" ? -1 : e.key === "ArrowDown" || e.key === "ArrowRight" ? 1 : 0125 if (!delta) return126 e.preventDefault()127 move(id, delta, "handle")128 }129130 // ---- glisser au pointeur (souris, doigt, stylet) : la poignée capture le pointeur, le widget survolé cède sa place131 const onPointerDown = (e: ReactPointerEvent<HTMLButtonElement>, id: WidgetId) => {132 if (e.button !== 0) return133 e.currentTarget.setPointerCapture(e.pointerId)134 drag.current = { id, lastOver: null }135 setDragging(id)136 setDraft(saved)137 }138 const onPointerMove = (e: ReactPointerEvent<HTMLButtonElement>) => {139 const d = drag.current140 if (!d) return141 const over = document.elementFromPoint(e.clientX, e.clientY)?.closest("[data-widget]")?.getAttribute("data-widget")142 if (!isWidgetId(over) || over === d.id) {143 d.lastOver = null144 return145 }146 // après un échange, le voisin peut rester sous le pointeur (tailles différentes) : on attend d'en être sorti147 if (over === d.lastOver) return148 d.lastOver = over149 setDraft((cur) => dropWidgetOn(cur ?? saved, d.id, over))150 }151 const endDrag = (cancelled: boolean) => {152 const d = drag.current153 if (!d) return154 drag.current = null155 setDragging(null)156 const next = draft157 setDraft(null)158 if (cancelled || !next) return159 const { rank, of } = widgetRank(next, d.id, widgetAvailable)160 commit(next, t("nx.dashboard.edit.moved", { name: widgetTitle(d.id), rank, of }))161 }162163 const cancelScheduled = async (o: OutboundItem) => {164 const to = o.recipients[0]?.address ?? ""165 if (!(await confirmAsync({ title: t("nx.dashboard.scheduled.confirmTitle"), body: t("nx.dashboard.scheduled.confirmBody", { to }), confirmLabel: t("nx.dashboard.scheduled.confirm"), danger: true }))) return166 const r = await cancelScheduledSend(o.id)167 if (r === "cancelled") toast({ kind: "success", text: t("nx.dashboard.scheduled.cancelled") })168 else toast({ kind: "error", text: r === "tooLate" ? t("nx.dashboard.scheduled.tooLate") : r === "offline" ? t("nx.offline") : t("nx.error.generic") })169 }170 const props: WidgetProps | null = data ? { data, overdue, online, onCancelScheduled: (o) => void cancelScheduled(o) } : null171172 return (173 <div className={`nx-page nx-dash${editing ? " editing" : ""}`} data-testid="dashboard">174 <header className="nx-head">175 <h1>{t("nx.dashboard.title")}</h1>176 {data ? (177 <span className="nx-sub" data-testid="dash-generated">178 {t("nx.dashboard.generated")}{" "}179 <time dateTime={data.generated_at}>{fmtListDate(data.generated_at)}</time>180 </span>181 ) : null}182 <span className="spacer" />183 <div className="nx-toolbar">184 {editing ? (185 <button type="button" className="btn" disabled={isDefaultLayout(saved)} onClick={() => commit(defaultLayout(), t("nx.dashboard.edit.resetDone"))}>186 {t("nx.dashboard.edit.reset")}187 </button>188 ) : (189 <IconButton icon="refresh" label={online ? t("nx.dashboard.refresh") : t("nx.offline")} disabled={!online || loading} className={loading ? "nx-dash-spin" : undefined} onClick={() => void loadDashboard(true)} />190 )}191 <button type="button" className={`btn${editing ? " primary" : ""}`} aria-pressed={editing} onClick={() => setEditing((v) => !v)} data-testid="dash-customize">192 <Icon name={editing ? "check" : "grid"} small />193 <span>{editing ? t("nx.dashboard.edit.done") : t("nx.dashboard.edit.start")}</span>194 </button>195 </div>196 </header>197198 <div className="sr-only" role="status" aria-live="polite" data-testid="dash-live">199 {announce}200 </div>201202 {error && data ? (203 <div className="banner warn" role="status">204 <Icon name="warn" />205 <div className="nx-dash-banner-text">{error === "offline" ? t("nx.dashboard.staleOffline") : t("nx.dashboard.stale")}</div>206 <button type="button" className="btn small" disabled={!online} onClick={() => void loadDashboard(true)}>207 {t("nx.retry")}208 </button>209 </div>210 ) : null}211212 {editing ? (213 <div className="nx-dash-editbar" data-testid="dash-editbar">214 <p className="nx-note">{t("nx.dashboard.edit.help")}</p>215 {hidden.length ? (216 <div className="nx-dash-hidden" role="group" aria-label={t("nx.dashboard.edit.hidden")}>217 <span className="nx-note">{t("nx.dashboard.edit.hidden")}</span>218 {hidden.map((w) => (219 <button key={w.id} type="button" className="nx-chip" data-testid={`show-${w.id}`} onClick={() => commit(setWidgetHidden(saved, w.id, false), t("nx.dashboard.edit.shown", { name: widgetTitle(w.id) }))}>220 <Icon name="plus" />221 <span>{t("nx.dashboard.edit.show", { name: widgetTitle(w.id) })}</span>222 </button>223 ))}224 </div>225 ) : null}226 </div>227 ) : null}228229 {error && !data ? (230 <div className="nx-card nx-dash-error" role="alert">231 <div className="nx-empty">232 <Icon name={error === "offline" ? "offline" : "warn"} />233 <p>{error === "offline" ? t("nx.offline") : error === "rate_limited" ? t("nx.error.rateLimited") : t("nx.dashboard.loadFailed")}</p>234 <button type="button" className="btn" onClick={() => void loadDashboard(true)}>235 {t("nx.retry")}236 </button>237 </div>238 </div>239 ) : shown.length === 0 ? (240 <div className="nx-card">241 <div className="nx-empty">242 <Icon name="grid" />243 <p>{t("nx.dashboard.allHidden")}</p>244 {editing ? null : (245 <button type="button" className="btn" onClick={() => setEditing(true)}>246 {t("nx.dashboard.edit.start")}247 </button>248 )}249 </div>250 </div>251 ) : (252 <div className="nx-dash-grid" ref={grid} aria-busy={!data}>253 {shown.map((w, i) => {254 const def = WIDGETS[w.id]255 const title = widgetTitle(w.id)256 const more = editing ? null : (def.more?.() ?? null)257 return (258 <section key={w.id} className={`nx-card nx-widget${dragging === w.id ? " dragging" : ""}`} data-widget={w.id} data-wide={w.wide} aria-labelledby={`nxw-${w.id}`}>259 <div className="nx-card-head">260 <Icon name={def.icon} small className="nx-widget-icon" />261 <h2 id={`nxw-${w.id}`}>{title}</h2>262 {more ? (263 <a className="nx-widget-more" {...linkProps(more.href)}>264 {more.label}265 </a>266 ) : null}267 </div>268 {editing ? (269 <div className="nx-widget-tools" role="group" aria-label={t("nx.dashboard.edit.tools", { name: title })}>270 <button271 type="button"272 className="icon-btn nx-widget-handle"273 data-ctl="handle"274 aria-label={t("nx.dashboard.edit.handle", { name: title })}275 title={t("nx.dashboard.edit.handle", { name: title })}276 onKeyDown={(e) => onHandleKey(e, w.id)}277 onPointerDown={(e) => onPointerDown(e, w.id)}278 onPointerMove={onPointerMove}279 onPointerUp={() => endDrag(false)}280 onPointerCancel={() => endDrag(true)}281 >282 <Icon name="grip" />283 </button>284 <button type="button" className="icon-btn nx-widget-up" data-ctl="up" aria-label={t("nx.dashboard.edit.up", { name: title })} title={t("nx.dashboard.edit.up", { name: title })} disabled={i === 0} onClick={() => move(w.id, -1, i === 1 ? "down" : "up")}>285 <Icon name="chevron" />286 </button>287 <button type="button" className="icon-btn" data-ctl="down" aria-label={t("nx.dashboard.edit.down", { name: title })} title={t("nx.dashboard.edit.down", { name: title })} disabled={i === shown.length - 1} onClick={() => move(w.id, 1, i === shown.length - 2 ? "up" : "down")}>288 <Icon name="chevron" />289 </button>290 <span className="spacer" />291 <button type="button" className="btn small nx-widget-wide" data-ctl="wide" aria-pressed={w.wide} aria-label={t("nx.dashboard.edit.wide", { name: title })} onClick={() => commit(setWidgetWide(saved, w.id, !w.wide), t(w.wide ? "nx.dashboard.edit.narrowed" : "nx.dashboard.edit.widened", { name: title }), `[data-widget="${w.id}"] [data-ctl="wide"]`)}>292 2×293 </button>294 <button type="button" className="icon-btn" data-ctl="hide" aria-label={t("nx.dashboard.edit.hide", { name: title })} title={t("nx.dashboard.edit.hide", { name: title })} onClick={() => commit(setWidgetHidden(saved, w.id, true), t("nx.dashboard.edit.hiddenDone", { name: title }))}>295 <Icon name="close" />296 </button>297 </div>298 ) : null}299 <div className="nx-card-body nx-widget-body" inert={editing}>300 {props ? widgetBody(w.id, props) : <Skeleton />}301 </div>302 </section>303 )304 })}305 </div>306 )}307 </div>308 )309}310