SPB Git

Repository Public

Generator.tsx 12.2 KB 258 lines tsx

1// Création par IA : brief, briefs de départ, langue, catégorie, identité de marque (mémorisée), puis génération en flux.2import { useEffect, useId, useRef, useState, type FormEvent } from "react"3import { getLang, t } from "../../i18n"4import { S, normalizeBrand, toast, type BrandKit } from "../../state/app"5import { navigate } from "../../state/session"6import { useStore } from "../../state/store"7import { CATEGORIES, T, clearGeneration, loadTemplates, loadUsage, saveBrand, startGeneration, type Category, type GenerateRequest } from "../../state/templates"8import { STARTER_BRIEFS } from "../../templates/briefs"9import { Icon } from "../kit"10import { EmailSkeleton, GenerationPanel } from "./GenerationPanel"11import { AiUsageFooter, StudioHeader, categoryLabel } from "./shared"1213export const BRIEF_MIN = 814export const BRIEF_MAX = 60001516/** Lance la génération d'un nouveau modèle et ouvre l'éditeur quand il est prêt. */17export async function generateAndOpen(req: GenerateRequest) {18  const tpl = await startGeneration(req)19  if (!tpl) return20  const g = T.get().generation21  toast({ kind: "success", text: t("tpl.gen.created", { name: tpl.name, seconds: g?.seconds ?? 0 }) })22  clearGeneration()23  navigate(`/templates/${tpl.id}`, { force: true })24}2526// ---------------------------------------------------------------- identité de marque27export function BrandKitFields({ disabled }: { disabled?: boolean }) {28  const stored = useStore(S, (s) => s.prefs.templateBrand)29  const [brand, setBrand] = useState<BrandKit>(stored)30  const id = useId()31  const timer = useRef<ReturnType<typeof setTimeout> | null>(null)32  const latest = useRef(brand)33  latest.current = brand34  const filled = Object.keys(normalizeBrand(brand)).length35  const [open, setOpen] = useState(filled > 0)3637  // enregistrement différé dans les préférences (PUT /api/prefs, avec toutes les autres préférences)38  const change = (patch: Partial<BrandKit>) => {39    const next = { ...latest.current, ...patch }40    setBrand(next)41    latest.current = next42    if (timer.current) clearTimeout(timer.current)43    timer.current = setTimeout(() => saveBrand(latest.current), 500)44  }45  const flush = () => {46    if (!timer.current) return47    clearTimeout(timer.current)48    timer.current = null49    saveBrand(latest.current)50  }51  useEffect(() => flush, []) // eslint-disable-line react-hooks/exhaustive-deps5253  const accent = brand.accent ?? ""54  const accentValid = accent === "" || /^#[0-9a-fA-F]{6}$/.test(accent)55  const logo = brand.logo_url ?? ""56  const logoValid = logo === "" || /^https:\/\/\S+\.\S+$/.test(logo)57  const site = brand.website ?? ""58  const siteValid = site === "" || /^https?:\/\/\S+\.\S+$/.test(site)59  return (60    <details className="tpl-brand" open={open} onToggle={(e) => setOpen((e.target as HTMLDetailsElement).open)}>61      <summary>62        <Icon name="chevron" small />63        <span>{t("tpl.brand.title")}</span>64        <span className="muted small">{filled ? t("tpl.brand.filled", { n: filled }) : t("tpl.brand.optional")}</span>65      </summary>66      <fieldset className="tpl-brand-grid" disabled={disabled} onBlur={flush}>67        <legend className="sr-only">{t("tpl.brand.title")}</legend>68        <p className="muted small tpl-brand-note">{t("tpl.brand.note")}</p>69        <div className="field">70          <label htmlFor={`${id}-name`}>{t("tpl.brand.name")}</label>71          <input id={`${id}-name`} className="input" value={brand.name ?? ""} maxLength={80} onChange={(e) => change({ name: e.target.value })} autoComplete="organization" />72        </div>73        <div className="field">74          <label htmlFor={`${id}-accent`}>{t("tpl.brand.accent")}</label>75          <div className="row tpl-color">76            <input type="color" aria-label={t("tpl.brand.accentPicker")} value={/^#[0-9a-fA-F]{6}$/.test(accent) ? accent : "#2c5b4d"} onChange={(e) => change({ accent: e.target.value })} />77            <input id={`${id}-accent`} className="input mono" value={accent} placeholder="#2c5b4d" maxLength={7} spellCheck={false} aria-invalid={!accentValid} aria-describedby={accentValid ? undefined : `${id}-accent-err`} onChange={(e) => change({ accent: e.target.value.trim() })} />78          </div>79          {accentValid ? null : (80            <span className="hint tpl-invalid" id={`${id}-accent-err`}>81              {t("tpl.brand.accentInvalid")}82            </span>83          )}84        </div>85        <div className="field">86          <label htmlFor={`${id}-logo`}>{t("tpl.brand.logo")}</label>87          <input id={`${id}-logo`} className="input" type="url" inputMode="url" value={logo} placeholder="https://…/logo.png" maxLength={500} aria-invalid={!logoValid} aria-describedby={`${id}-logo-hint`} onChange={(e) => change({ logo_url: e.target.value.trim() })} />88          <span className={`hint${logoValid ? "" : " tpl-invalid"}`} id={`${id}-logo-hint`}>89            {t("tpl.brand.logoHint")}90          </span>91        </div>92        <div className="field">93          <label htmlFor={`${id}-site`}>{t("tpl.brand.website")}</label>94          <input id={`${id}-site`} className="input" type="url" inputMode="url" value={site} placeholder="https://…" maxLength={300} aria-invalid={!siteValid} onChange={(e) => change({ website: e.target.value.trim() })} />95        </div>96        <div className="field">97          <label htmlFor={`${id}-tone`}>{t("tpl.brand.tone")}</label>98          <input id={`${id}-tone`} className="input" value={brand.tone ?? ""} placeholder={t("tpl.brand.tonePlaceholder")} maxLength={200} onChange={(e) => change({ tone: e.target.value })} />99        </div>100        <div className="field tpl-brand-wide">101          <label htmlFor={`${id}-footer`}>{t("tpl.brand.footer")}</label>102          <input id={`${id}-footer`} className="input" value={brand.footer ?? ""} placeholder={t("tpl.brand.footerPlaceholder")} maxLength={400} onChange={(e) => change({ footer: e.target.value })} />103        </div>104      </fieldset>105    </details>106  )107}108109// ---------------------------------------------------------------- page110export function Generator() {111  const uiLang = getLang()112  const ai = useStore(T, (s) => s.ai)113  const status = useStore(T, (s) => s.status)114  const generation = useStore(T, (s) => (s.generation && s.generation.baseId === null ? s.generation : null))115  const running = generation?.phase === "running"116  const [brief, setBrief] = useState(generation?.request.brief ?? "")117  const [language, setLanguage] = useState<"fr" | "en">(generation?.request.language ?? uiLang)118  const [category, setCategory] = useState<Category | "">(generation?.request.category ?? "")119  const [starter, setStarter] = useState<string | null>(null)120  const id = useId()121  const area = useRef<HTMLTextAreaElement>(null)122123  useEffect(() => {124    if (status === "idle") void loadTemplates()125    void loadUsage()126  }, [status])127128  const length = brief.trim().length129  const valid = length >= BRIEF_MIN && length <= BRIEF_MAX130  const submit = (e?: FormEvent) => {131    e?.preventDefault()132    if (!valid || running) return133    const brand = normalizeBrand(S.get().prefs.templateBrand)134    void generateAndOpen({ brief: brief.trim(), language, ...(category ? { category } : {}), brand })135  }136  const pick = (sid: string) => {137    const s = STARTER_BRIEFS.find((x) => x.id === sid)138    if (!s) return139    setStarter(sid)140    setBrief(s.brief[language])141    setCategory(s.category)142    area.current?.focus()143  }144  const switchLanguage = (l: "fr" | "en") => {145    // un brief de départ non retouché suit la langue choisie146    const s = starter ? STARTER_BRIEFS.find((x) => x.id === starter) : null147    if (s && brief === s.brief[language]) setBrief(s.brief[l])148    setLanguage(l)149  }150151  return (152    <div className="tpl-page">153      <StudioHeader title={t("tpl.new.title")} crumb={{ label: t("tpl.title"), href: "/templates" }} />154      <main className="tpl-scroll" id="main" tabIndex={-1}>155        <div className="tpl-new">156          <form className="tpl-new-form card" onSubmit={submit} aria-busy={running}>157            <div>158              <h2>{t("tpl.new.heading")}</h2>159              <p className="muted">{t("tpl.new.lead")}</p>160            </div>161            {status === "ready" && !ai.configured ? (162              <div className="banner warn" role="status" data-testid="ai-not-configured">163                <Icon name="warn" small />164                <span>{t("tpl.err.ai_not_configured")}</span>165              </div>166            ) : null}167            <div className="field">168              <label htmlFor={`${id}-brief`}>{t("tpl.new.brief")}</label>169              <textarea170                ref={area}171                id={`${id}-brief`}172                className="textarea tpl-brief"173                value={brief}174                maxLength={BRIEF_MAX}175                disabled={running}176                placeholder={t("tpl.new.placeholder")}177                aria-describedby={`${id}-brief-hint`}178                onChange={(e) => {179                  setBrief(e.target.value)180                }}181                onKeyDown={(e) => {182                  if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) submit()183                }}184              />185              <div className="row small muted" id={`${id}-brief-hint`}>186                <span className="spacer">{t("tpl.new.briefHint")}</span>187                <span className={length > BRIEF_MAX - 200 ? "tpl-invalid" : ""}>188                  {length} / {BRIEF_MAX}189                </span>190              </div>191            </div>192            <div className="tpl-starters" role="group" aria-label={t("tpl.new.starters")}>193              <span className="label">{t("tpl.new.starters")}</span>194              <div className="tpl-chips">195                {STARTER_BRIEFS.map((s) => (196                  <button key={s.id} type="button" className="tpl-chip" aria-pressed={starter === s.id && brief === s.brief[language]} disabled={running} onClick={() => pick(s.id)} data-starter={s.id}>197                    {s.label[uiLang]}198                  </button>199                ))}200              </div>201            </div>202            <div className="tpl-new-options">203              <div className="field">204                <span className="label" id={`${id}-lang`}>205                  {t("tpl.new.language")}206                </span>207                <div className="segmented" role="radiogroup" aria-labelledby={`${id}-lang`}>208                  {(["fr", "en"] as const).map((l) => (209                    <button key={l} type="button" role="radio" aria-checked={language === l} disabled={running} onClick={() => switchLanguage(l)}>210                      {l === "fr" ? "Français" : "English"}211                    </button>212                  ))}213                </div>214              </div>215              <div className="field">216                <label htmlFor={`${id}-cat`}>{t("tpl.new.category")}</label>217                <select id={`${id}-cat`} className="select" value={category} disabled={running} onChange={(e) => setCategory(e.target.value as Category | "")}>218                  <option value="">{t("tpl.new.categoryAuto")}</option>219                  {CATEGORIES.map((c) => (220                    <option key={c} value={c}>221                      {categoryLabel(c)}222                    </option>223                  ))}224                </select>225              </div>226            </div>227            <BrandKitFields disabled={running} />228            <div className="row wrap tpl-new-submit">229              <button type="submit" className="btn primary" disabled={!valid || running}>230                <Icon name="sparkle" />231                <span>{t("tpl.new.submit")}</span>232              </button>233              <span className="muted small">{t("tpl.new.duration")}</span>234            </div>235            <p className="muted small">{t("tpl.new.privacy")}</p>236          </form>237          <aside className="tpl-new-side" aria-label={t("tpl.new.sideLabel")}>238            {generation ? (239              <GenerationPanel scope={null} onRetry={(g) => void generateAndOpen(g.request)} />240            ) : (241              <div className="tpl-new-idle">242                <EmailSkeleton active={false} />243                <h3>{t("tpl.new.tipsTitle")}</h3>244                <ul className="tpl-tips">245                  <li>{t("tpl.new.tip1")}</li>246                  <li>{t("tpl.new.tip2")}</li>247                  <li>{t("tpl.new.tip3")}</li>248                </ul>249              </div>250            )}251          </aside>252        </div>253        <AiUsageFooter />254      </main>255    </div>256  )257}258
Files main
Menu

Theme