Repository Public
1// Bibliothèque : grille de cartes avec miniature vivante (cadre isolé, rendue à l'approche de l'écran), recherche, filtre, tri.2import { memo, useEffect, useMemo, useRef, useState } from "react"3import { getLang, t } from "../../i18n"4import { errorDetail } from "../../jmap/errors"5import { toast } from "../../state/app"6import { linkProps, navigate } from "../../state/session"7import { useStore } from "../../state/store"8import { CATEGORIES, T, createTemplate, deleteTemplateWithUndo, duplicateTemplate, loadTemplates, renderTemplate, type Category, type TemplateSummary } from "../../state/templates"9import { blankTemplateHtml } from "../../templates/briefs"10import { relativeDate } from "../../templates/variables"11import { Icon, MenuButton, Spinner } from "../kit"12import { TemplateFrame } from "./Frame"13import { AiUsageFooter, StudioHeader, categoryLabel } from "./shared"1415// ---------------------------------------------------------------- miniatures : rendu à la demande, trois à la fois16const rendered = new Map<string, string>()17const waiting: (() => void)[] = []18let active = 019function schedule<R>(job: () => Promise<R>): Promise<R> {20 return new Promise<R>((resolve, reject) => {21 const run = () => {22 active++23 job()24 .then(resolve, reject)25 .finally(() => {26 active--27 waiting.shift()?.()28 })29 }30 if (active < 3) run()31 else waiting.push(run)32 })33}34const thumbKey = (tpl: TemplateSummary) => `${tpl.id}:${tpl.version}:${tpl.updated_at}`3536const THUMB_W = 60037function Thumb({ tpl }: { tpl: TemplateSummary }) {38 const box = useRef<HTMLDivElement>(null)39 const key = thumbKey(tpl)40 const [visible, setVisible] = useState(false)41 const [html, setHtml] = useState<string | null>(() => rendered.get(key) ?? null)42 const [failed, setFailed] = useState(false)43 const [size, setSize] = useState<{ w: number; h: number } | null>(null)4445 useEffect(() => {46 const el = box.current47 if (!el) return48 const ro = new ResizeObserver(() => setSize({ w: el.clientWidth, h: el.clientHeight }))49 ro.observe(el)50 setSize({ w: el.clientWidth, h: el.clientHeight })51 const io = new IntersectionObserver(52 (entries) => {53 if (entries.some((e) => e.isIntersecting)) {54 setVisible(true)55 io.disconnect()56 }57 },58 { rootMargin: "300px 0px" },59 )60 io.observe(el)61 return () => {62 ro.disconnect()63 io.disconnect()64 }65 }, [])6667 useEffect(() => {68 const cached = rendered.get(key)69 if (cached !== undefined) return setHtml(cached)70 if (!visible) return71 let alive = true72 setFailed(false)73 schedule(() => renderTemplate(tpl.id)).then(74 (r) => {75 if (rendered.size > 300) rendered.delete(rendered.keys().next().value as string)76 rendered.set(key, r.html)77 if (alive) setHtml(r.html)78 },79 () => alive && setFailed(true),80 )81 return () => {82 alive = false83 }84 }, [key, visible, tpl.id])8586 const scale = size && size.w > 0 ? size.w / THUMB_W : 087 return (88 <div ref={box} className="tpl-thumb" data-state={html !== null ? "ready" : failed ? "error" : "loading"} aria-hidden="true">89 {html !== null && visible && scale > 0 && size ? (90 <TemplateFrame html={html} title="" thumbnail width={THUMB_W} height={Math.ceil(size.h / scale)} scale={scale} />91 ) : failed ? (92 <span className="tpl-thumb-msg muted small">{t("tpl.lib.thumbFailed")}</span>93 ) : (94 <div className="tpl-thumb-skel skeleton" />95 )}96 </div>97 )98}99100const Card = memo(function Card({ tpl }: { tpl: TemplateSummary }) {101 const lang = getLang()102 const [busy, setBusy] = useState(false)103 const href = `/templates/${tpl.id}`104 const duplicate = async () => {105 setBusy(true)106 try {107 const copy = await duplicateTemplate(tpl.id)108 toast({ kind: "success", text: t("tpl.duplicated", { name: copy.name }) })109 } catch (e) {110 toast({ kind: "error", text: t("error.actionFailed"), detail: errorDetail(e) || undefined })111 } finally {112 setBusy(false)113 }114 }115 return (116 <li className="tpl-card" data-testid="template-card" data-template-id={tpl.id} aria-busy={busy || undefined}>117 <a className="tpl-card-open" {...linkProps(href)} aria-label={t("tpl.lib.open", { name: tpl.name })}>118 <Thumb tpl={tpl} />119 </a>120 <div className="tpl-card-body">121 <div className="row">122 <h3 className="truncate spacer" title={tpl.name}>123 {tpl.name}124 </h3>125 <MenuButton126 label={t("tpl.lib.actions", { name: tpl.name })}127 items={[128 { label: t("tpl.open"), icon: "edit", onSelect: () => navigate(href) },129 { label: t("tpl.duplicate"), icon: "copy", onSelect: () => void duplicate() },130 "sep",131 { label: t("common.delete"), icon: "trash", danger: true, onSelect: () => void deleteTemplateWithUndo(tpl) },132 ]}133 />134 </div>135 <p className="tpl-card-subject truncate muted small" title={tpl.subject}>136 {tpl.subject || t("tpl.noSubject")}137 </p>138 <div className="row wrap tpl-card-meta">139 <span className="badge">{categoryLabel(tpl.category)}</span>140 {tpl.source === "ai" ? (141 <span className="badge accent" title={tpl.ai_model ? t("tpl.lib.aiMade", { model: tpl.ai_model }) : undefined}>142 <Icon name="sparkle" small />143 {t("tpl.badge.ai")}144 </span>145 ) : null}146 <span className="muted small">{t("tpl.lib.variables", { n: tpl.variables.length })}</span>147 <span className="spacer" />148 <time className="muted small" dateTime={tpl.updated_at} title={new Date(tpl.updated_at).toLocaleString(lang === "fr" ? "fr-CA" : "en-CA")}>149 {relativeDate(tpl.updated_at, lang)}150 </time>151 </div>152 </div>153 </li>154 )155})156157type Sort = "updated" | "created" | "name"158159export async function createBlank(): Promise<void> {160 const lang = getLang()161 try {162 const tpl = await createTemplate({163 name: t("tpl.blankName"),164 html: blankTemplateHtml(lang),165 subject: lang === "fr" ? "Bonjour {{first_name}}" : "Hello {{first_name}}",166 text: lang === "fr" ? "Bonjour {{first_name}},\n\nÉcrivez ici le contenu de votre courriel.\n" : "Hello {{first_name}},\n\nWrite the content of your email here.\n",167 variables: [{ name: "first_name", description: lang === "fr" ? "Prénom de la personne" : "Recipient's first name", example: lang === "fr" ? "Camille" : "Alex", required: false }],168 })169 navigate(`/templates/${tpl.id}`)170 } catch (e) {171 toast({ kind: "error", text: t("error.actionFailed"), detail: errorDetail(e) || undefined })172 }173}174175function EmptyState() {176 return (177 <div className="tpl-empty" data-testid="templates-empty">178 <div className="tpl-empty-art" aria-hidden="true">179 <div className="tpl-empty-sheet s1" />180 <div className="tpl-empty-sheet s2" />181 <div className="tpl-empty-sheet s3">182 <span />183 <span />184 <span />185 <i />186 </div>187 </div>188 <h2>{t("tpl.empty.title")}</h2>189 <p>{t("tpl.empty.body")}</p>190 <ul className="tpl-empty-points">191 <li>192 <Icon name="sparkle" small />193 <span>{t("tpl.empty.point1")}</span>194 </li>195 <li>196 <Icon name="braces" small />197 <span>{t("tpl.empty.point2")}</span>198 </li>199 <li>200 <Icon name="moon" small />201 <span>{t("tpl.empty.point3")}</span>202 </li>203 </ul>204 <div className="row wrap tpl-empty-actions">205 <a className="btn primary" {...linkProps("/templates/new")}>206 <Icon name="sparkle" />207 <span>{t("tpl.createWithAi")}</span>208 </a>209 <button type="button" className="btn" onClick={() => void createBlank()}>210 <Icon name="plus" />211 <span>{t("tpl.createBlank")}</span>212 </button>213 </div>214 </div>215 )216}217218export function Library() {219 const status = useStore(T, (s) => s.status)220 const all = useStore(T, (s) => s.templates)221 const [q, setQ] = useState("")222 const [category, setCategory] = useState<Category | "all">("all")223 const [sort, setSort] = useState<Sort>("updated")224225 useEffect(() => {226 void loadTemplates()227 }, [])228229 const visible = all230 const shown = useMemo(() => {231 const needle = q.trim().toLowerCase()232 const list = visible.filter((x) => (category === "all" || x.category === category) && (!needle || `${x.name}\n${x.subject}\n${x.preheader}`.toLowerCase().includes(needle)))233 const by: Record<Sort, (a: TemplateSummary, b: TemplateSummary) => number> = {234 updated: (a, b) => b.updated_at.localeCompare(a.updated_at),235 created: (a, b) => b.created_at.localeCompare(a.created_at),236 name: (a, b) => a.name.localeCompare(b.name, getLang(), { sensitivity: "base" }),237 }238 return [...list].sort(by[sort])239 }, [visible, q, category, sort])240 const usedCategories = useMemo(() => CATEGORIES.filter((c) => visible.some((x) => x.category === c)), [visible])241242 return (243 <div className="tpl-page">244 <StudioHeader title={t("tpl.title")}>245 <button type="button" className="btn tpl-hide-narrow" onClick={() => void createBlank()}>246 <Icon name="plus" />247 <span>{t("tpl.createBlank")}</span>248 </button>249 <a className="btn primary" {...linkProps("/templates/new")} title={`${t("tpl.createWithAi")} (n)`}>250 <Icon name="sparkle" />251 <span>{t("tpl.createWithAi")}</span>252 </a>253 </StudioHeader>254 <main className="tpl-scroll" id="main" tabIndex={-1}>255 {status === "loading" || status === "idle" ? (256 <div className="tpl-center">257 <Spinner label={t("common.loading")} />258 </div>259 ) : status === "error" ? (260 <div className="empty" role="alert">261 <Icon name="warn" />262 <h2>{t("tpl.lib.loadFailed")}</h2>263 <button type="button" className="btn" onClick={() => void loadTemplates()}>264 {t("common.retry")}265 </button>266 </div>267 ) : visible.length === 0 ? (268 <EmptyState />269 ) : (270 <>271 <div className="tpl-toolbar" role="search" aria-label={t("tpl.lib.filters")}>272 <label className="tpl-search">273 <Icon name="search" small />274 <span className="sr-only">{t("tpl.lib.search")}</span>275 <input id="tpl-search" type="search" className="input" value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("tpl.lib.searchPlaceholder")} autoComplete="off" />276 </label>277 <label className="tpl-select">278 <span className="sr-only">{t("tpl.lib.category")}</span>279 <select className="select" value={category} onChange={(e) => setCategory(e.target.value as Category | "all")} aria-label={t("tpl.lib.category")}>280 <option value="all">{t("tpl.lib.allCategories")}</option>281 {usedCategories.map((c) => (282 <option key={c} value={c}>283 {categoryLabel(c)}284 </option>285 ))}286 </select>287 </label>288 <label className="tpl-select">289 <span className="sr-only">{t("tpl.lib.sort")}</span>290 <select className="select" value={sort} onChange={(e) => setSort(e.target.value as Sort)} aria-label={t("tpl.lib.sort")}>291 <option value="updated">{t("tpl.lib.sortUpdated")}</option>292 <option value="created">{t("tpl.lib.sortCreated")}</option>293 <option value="name">{t("tpl.lib.sortName")}</option>294 </select>295 </label>296 <span className="muted small tpl-count" role="status">297 {t("tpl.lib.count", { n: shown.length })}298 </span>299 </div>300 {shown.length === 0 ? (301 <div className="empty">302 <Icon name="search" />303 <h2>{t("tpl.lib.noMatch")}</h2>304 <button305 type="button"306 className="btn"307 onClick={() => {308 setQ("")309 setCategory("all")310 }}311 >312 {t("tpl.lib.clearFilters")}313 </button>314 </div>315 ) : (316 <ul className="tpl-grid" aria-label={t("tpl.title")}>317 {shown.map((tpl) => (318 <Card key={tpl.id} tpl={tpl} />319 ))}320 </ul>321 )}322 </>323 )}324 <AiUsageFooter />325 </main>326 </div>327 )328}329