SPB Git

Repository Public

Pickers.tsx 9.0 KB 223 lines tsx

1// Sélecteurs de la rédaction : extraits (recherche, insertion) et modèles de la bibliothèque (variables, rendu par l'API, insertion ou envoi tel quel).2import { useEffect, useId, useMemo, useState } from "react"3import { createPortal } from "react-dom"4import { t } from "../../i18n"5import { errorDetail } from "../../jmap/errors"6import { htmlToText } from "../../mail/compose"7import { linkProps } from "../../state/session"8import { useStore } from "../../state/store"9import { T, loadTemplates, renderTemplate, type Rendered, type TemplateSummary } from "../../state/templates"10import { missingRequired } from "../../templates/variables"11import { Dialog, Field, Icon, Spinner } from "../kit"12import { D, type Snippet } from "./data"1314// ---------------------------------------------------------------- extraits15export function SnippetPicker({ onPick, onClose }: { onPick: (s: Snippet) => void; onClose: () => void }) {16  const snippets = useStore(D, (d) => d.snippets)17  const [q, setQ] = useState("")18  const [active, setActive] = useState(0)19  const id = useId()20  const needle = q.trim().toLowerCase().replace(/^;/, "")21  const list = useMemo(() => snippets.filter((s) => !needle || s.name.toLowerCase().includes(needle) || (s.shortcut ?? "").includes(needle) || s.text.toLowerCase().includes(needle)), [snippets, needle])22  const index = Math.min(active, Math.max(0, list.length - 1))23  const choose = (s: Snippet | undefined) => {24    if (!s) return25    onPick(s)26    onClose()27  }28  return createPortal(29    <Dialog title={t("cmp.snippet.pick")} onClose={onClose}>30      <div className="stack cmp-picker">31        <input32          className="input"33          data-autofocus34          role="combobox"35          aria-expanded="true"36          aria-controls={`${id}-list`}37          aria-activedescendant={list.length ? `${id}-${index}` : undefined}38          aria-label={t("cmp.snippet.search")}39          placeholder={t("cmp.snippet.search")}40          value={q}41          onChange={(e) => {42            setQ(e.target.value)43            setActive(0)44          }}45          onKeyDown={(e) => {46            if (e.key === "ArrowDown") {47              e.preventDefault()48              setActive(Math.min(list.length - 1, index + 1))49            } else if (e.key === "ArrowUp") {50              e.preventDefault()51              setActive(Math.max(0, index - 1))52            } else if (e.key === "Enter") {53              e.preventDefault()54              choose(list[index])55            }56          }}57        />58        {list.length ? (59          <ul id={`${id}-list`} role="listbox" aria-label={t("cmp.snippet.pick")} className="cmp-picker-list">60            {list.map((s, i) => (61              <li key={s.id} id={`${id}-${i}`} role="option" aria-selected={i === index} className={i === index ? "active" : ""} onMouseEnter={() => setActive(i)} onClick={() => choose(s)}>62                <span className="cmp-picker-title">63                  <span className="truncate">{s.name}</span>64                  {s.shortcut ? <kbd className="cmp-kbd">;{s.shortcut}</kbd> : null}65                </span>66                <span className="muted small truncate">{s.text.replace(/\s+/g, " ").slice(0, 140)}</span>67              </li>68            ))}69          </ul>70        ) : (71          <p className="muted">{snippets.length ? t("cmp.snippet.none") : t("cmp.snippet.empty")}</p>72        )}73        <p className="small muted">74          {t("cmp.snippet.tip")}{" "}75          <a {...linkProps("/settings/snippets")} className="cmp-link">76            {t("cmp.snippet.manage")}77          </a>78        </p>79      </div>80    </Dialog>,81    document.body,82  )83}8485// ---------------------------------------------------------------- modèles86export interface TemplateChoice {87  template: TemplateSummary88  values: Record<string, string>89}90export function TemplateDialog({ canSend, onInsert, onSend, onClose }: { canSend: boolean; onInsert: (rendered: Rendered) => void; onSend: (choice: TemplateChoice) => void; onClose: () => void }) {91  const status = useStore(T, (s) => s.status)92  const templates = useStore(T, (s) => s.templates)93  const [q, setQ] = useState("")94  const [chosen, setChosen] = useState<TemplateSummary | null>(null)95  const [values, setValues] = useState<Record<string, string>>({})96  const [busy, setBusy] = useState(false)97  const [error, setError] = useState<string | null>(null)98  const id = useId()99  useEffect(() => {100    void loadTemplates()101  }, [])102  const needle = q.trim().toLowerCase()103  const list = templates.filter((x) => !needle || x.name.toLowerCase().includes(needle) || x.subject.toLowerCase().includes(needle))104  const missing = chosen ? missingRequired(chosen.variables, values) : []105106  const insert = async () => {107    if (!chosen) return108    setBusy(true)109    setError(null)110    try {111      onInsert(await renderTemplate(chosen.id, values))112      onClose()113    } catch (e) {114      setError(errorDetail(e) || t("cmp.tpl.renderFailed"))115      setBusy(false)116    }117  }118  return createPortal(119    <Dialog120      title={chosen ? t("cmp.tpl.fill", { name: chosen.name }) : t("cmp.tpl.pick")}121      wide={!!chosen && chosen.variables.length > 3}122      onClose={onClose}123      footer={124        chosen ? (125          <>126            <button type="button" className="btn ghost" onClick={() => setChosen(null)}>127              <Icon name="back" />128              <span>{t("cmp.tpl.back")}</span>129            </button>130            <span className="spacer" />131            {canSend ? (132              <button type="button" className="btn" disabled={busy || missing.length > 0} title={t("cmp.tpl.sendAsHint")} onClick={() => {133                onSend({ template: chosen, values })134                onClose()135              }}>136                {t("cmp.tpl.sendAs")}137              </button>138            ) : null}139            <button type="button" className="btn primary" disabled={busy} onClick={() => void insert()}>140              {busy ? <span className="spinner" aria-hidden="true" /> : null}141              <span>{t("cmp.tpl.insert")}</span>142            </button>143          </>144        ) : undefined145      }146    >147      {!chosen ? (148        <div className="stack cmp-picker">149          <input className="input" data-autofocus aria-label={t("cmp.tpl.search")} placeholder={t("cmp.tpl.search")} value={q} onChange={(e) => setQ(e.target.value)} />150          {status === "loading" && !templates.length ? (151            <Spinner label={t("common.loading")} />152          ) : list.length ? (153            <ul className="cmp-picker-list" aria-label={t("cmp.tpl.pick")}>154              {list.map((x) => (155                <li key={x.id}>156                  <button157                    type="button"158                    className="cmp-picker-btn"159                    onClick={() => {160                      setChosen(x)161                      setValues({})162                      setError(null)163                    }}164                  >165                    <span className="cmp-picker-title">166                      <span className="truncate">{x.name}</span>167                      {x.variables.length ? <span className="badge">{t("cmp.tpl.vars", { n: x.variables.length })}</span> : null}168                    </span>169                    <span className="muted small truncate">{x.subject || htmlToText(x.preheader)}</span>170                  </button>171                </li>172              ))}173            </ul>174          ) : (175            <p className="muted">{templates.length ? t("cmp.tpl.none") : t("cmp.tpl.empty")}</p>176          )}177          <p className="small muted">178            <a {...linkProps("/templates")} className="cmp-link">179              {t("cmp.tpl.manage")}180            </a>181          </p>182        </div>183      ) : (184        <form185          className="stack cmp-picker"186          onSubmit={(e) => {187            e.preventDefault()188            void insert()189          }}190        >191          {chosen.variables.length ? (192            chosen.variables.map((v, i) => (193              <Field key={v.name} id={`${id}-${v.name}`} label={`{{${v.name}}}${v.required ? " *" : ""}`} hint={v.description || undefined}>194                <input195                  id={`${id}-${v.name}`}196                  className="input"197                  {...(i === 0 ? { "data-autofocus": true } : {})}198                  value={values[v.name] ?? ""}199                  placeholder={v.example || undefined}200                  aria-required={v.required}201                  maxLength={20_000}202                  onChange={(e) => setValues((cur) => ({ ...cur, [v.name]: e.target.value }))}203                />204              </Field>205            ))206          ) : (207            <p className="muted">{t("cmp.tpl.noVars")}</p>208          )}209          <p className="small muted">{t("cmp.tpl.insertHint")}</p>210          {missing.length && canSend ? <p className="small muted">{t("cmp.tpl.missing", { names: missing.map((n) => `{{${n}}}`).join(", ") })}</p> : null}211          {error ? (212            <div className="banner danger" role="alert">213              <Icon name="warn" small />214              <span>{error}</span>215            </div>216          ) : null}217        </form>218      )}219    </Dialog>,220    document.body,221  )222}223
Files main
Menu

Theme