SPB Git

Repository Public

Signature.tsx 11.1 KB 257 lines tsx

1// Champs riches de la fiche d'une adresse : signature HTML (zone éditable assainie, quelques boutons de mise en forme)2// et avatar (image réduite dans un canevas jusqu'à tenir sous la borne de l'API, 90 ko en URL data:).3import { useEffect, useId, useRef, useState, type CSSProperties } from "react"4import { AVATAR_RE, dataUrlBytes, fitWithin, pickAvatar } from "../../../admin/addresses"5import { t } from "../../../i18n"6import { sanitizeEmailHtml } from "../../../mail/sanitize"7import { sanitizeComposerHtml } from "../../../state/composer"8import { clearFormatting, run, setLink as setLinkCommand, toggleList, toggleMark, type Command } from "../../compose/editor"9import { Icon } from "../../kit"10import { fmtBytes } from "../shared"1112// ---------------------------------------------------------------- signature HTML13/** HTML stocké → HTML éditable : assaini comme un message cité, puis réduit aux balises permises à la rédaction. */14const toEditable = (html: string): string => (html.trim() ? sanitizeComposerHtml(sanitizeEmailHtml(html, { mode: "quote" }).body) : "")15/** Contenu de la zone → valeur du champ ; une zone sans texte ni image vaut « pas de signature ». */16function fromEditable(node: HTMLElement): string {17  const html = sanitizeComposerHtml(node.innerHTML)18  return (node.textContent ?? "").trim() === "" && !/<img\b/i.test(html) ? "" : html19}20const LINK_RE = /^(https?:\/\/|mailto:)\S+$/i2122/**23 * Petit éditeur de signature. La valeur rendue par `onChange` est toujours passée par `sanitizeComposerHtml` ;24 * le contenu initial (venu de l'API) est assaini avant d'entrer dans la zone éditable.25 */26export function RichField({ label, hint, value, onChange }: { label: string; hint?: string; value: string; onChange: (html: string) => void }) {27  const ref = useRef<HTMLDivElement>(null)28  const range = useRef<Range | null>(null)29  const [link, setLink] = useState<string | null>(null)30  const [linkError, setLinkError] = useState(false)31  const id = useId()3233  // Contenu initial seulement : ensuite la zone éditable est la source, on ne la réécrit pas (le curseur sauterait).34  useEffect(() => {35    if (ref.current) ref.current.innerHTML = toEditable(value)36    // eslint-disable-next-line react-hooks/exhaustive-deps37  }, [])3839  const sync = () => {40    if (ref.current) onChange(fromEditable(ref.current))41  }42  /** Sélection courante dans la zone (à défaut le point gardé à l'ouverture du champ de lien, sinon la fin du texte). */43  const selection = (): Range => {44    const node = ref.current!45    const sel = window.getSelection()46    if (sel && sel.rangeCount && node.contains(sel.anchorNode) && node.contains(sel.focusNode)) return sel.getRangeAt(0)47    const kept = range.current48    if (kept && node.contains(kept.startContainer) && node.contains(kept.endContainer)) return kept49    const end = document.createRange()50    end.selectNodeContents(node)51    end.collapse(false)52    return end53  }54  /** Commandes de l'éditeur de rédaction (Selection/Range sur le DOM) : plus aucun `document.execCommand`. */55  const exec = (command: Command) => {56    const node = ref.current57    if (!node) return58    node.focus()59    const next = run(node, selection(), command)60    const sel = window.getSelection()61    sel?.removeAllRanges()62    sel?.addRange(next)63    range.current = next.cloneRange()64    sync()65  }66  const keepRange = () => {67    const sel = window.getSelection()68    range.current = sel && sel.rangeCount && ref.current?.contains(sel.anchorNode) ? sel.getRangeAt(0).cloneRange() : null69  }70  const insertLink = () => {71    const href = (link ?? "").trim()72    if (!LINK_RE.test(href)) return setLinkError(true)73    if (!ref.current) return74    // rien de sélectionné : le lien s'insère avec son adresse pour texte (nœud de texte, aucun HTML interprété)75    const at = selection()76    exec(setLinkCommand(href, at.collapsed ? href : undefined))77    setLink(null)78    setLinkError(false)79  }8081  // la lettre du bouton suit la langue (G/I/S, B/I/U)82  const buttons: { cmd: "bold" | "italic" | "underline"; label: string; style: CSSProperties }[] = [83    { cmd: "bold", label: t("adm.addr.sig.bold"), style: { fontWeight: 700 } },84    { cmd: "italic", label: t("adm.addr.sig.italic"), style: { fontStyle: "italic" } },85    { cmd: "underline", label: t("adm.addr.sig.underline"), style: { textDecoration: "underline" } },86  ]87  return (88    <div className="field">89      <span className="label" id={`${id}-l`}>90        {label}91      </span>92      <div className="adm-addr-rich-wrap">93        <div className="adm-addr-rich-bar" role="toolbar" aria-label={t("adm.addr.sig.toolbar")}>94          {buttons.map((b) => (95            <button key={b.cmd} type="button" className="btn small ghost" aria-label={b.label} title={b.label} onMouseDown={(e) => e.preventDefault()} onClick={() => exec(toggleMark(b.cmd))}>96              <span aria-hidden="true" style={b.style}>97                {b.label.charAt(0)}98              </span>99            </button>100          ))}101          <button type="button" className="btn small ghost" aria-label={t("adm.addr.sig.list")} title={t("adm.addr.sig.list")} onMouseDown={(e) => e.preventDefault()} onClick={() => exec(toggleList("ul"))}>102            <Icon name="list" small />103          </button>104          <button105            type="button"106            className="btn small ghost"107            aria-expanded={link !== null}108            onMouseDown={(e) => {109              e.preventDefault()110              keepRange()111            }}112            onClick={() => {113              setLinkError(false)114              setLink(link === null ? "https://" : null)115            }}116          >117            {t("adm.addr.sig.link")}118          </button>119          <button type="button" className="btn small ghost" onMouseDown={(e) => e.preventDefault()} onClick={() => exec(clearFormatting)}>120            {t("adm.addr.sig.clear")}121          </button>122        </div>123        {link !== null ? (124          <div className="adm-addr-link">125            <div className="field">126              <label htmlFor={`${id}-url`}>{t("adm.addr.sig.linkUrl")}</label>127              <input128                id={`${id}-url`}129                className="input"130                type="url"131                inputMode="url"132                value={link}133                autoFocus134                spellCheck={false}135                aria-invalid={linkError || undefined}136                aria-describedby={linkError ? `${id}-urlerr` : undefined}137                onChange={(e) => setLink(e.target.value)}138                onKeyDown={(e) => {139                  if (e.key === "Enter") {140                    e.preventDefault()141                    insertLink()142                  }143                }}144              />145            </div>146            <button type="button" className="btn small" onClick={insertLink}>147              {t("adm.addr.sig.linkInsert")}148            </button>149            <button type="button" className="btn small ghost" onClick={() => setLink(null)}>150              {t("common.cancel")}151            </button>152            {linkError ? (153              <p className="adm-error small" id={`${id}-urlerr`} role="alert">154                {t("adm.addr.sig.linkInvalid")}155              </p>156            ) : null}157          </div>158        ) : null}159        <div ref={ref} className="adm-addr-rich" contentEditable suppressContentEditableWarning role="textbox" aria-multiline="true" aria-labelledby={`${id}-l`} aria-describedby={hint ? `${id}-h` : undefined} tabIndex={0} onInput={sync} onBlur={sync} data-testid="signature-html" />160      </div>161      {hint ? (162        <span className="hint" id={`${id}-h`}>163          {hint}164        </span>165      ) : null}166    </div>167  )168}169170// ---------------------------------------------------------------- avatar171/** Réduit l'image choisie jusqu'à tenir sous la borne de l'API ; null si elle est illisible ou irréductible. */172async function fileToAvatar(file: File): Promise<string | null> {173  let bitmap: ImageBitmap174  try {175    bitmap = await createImageBitmap(file)176  } catch {177    return null178  }179  try {180    return pickAvatar(({ size, quality }) => {181      const { width, height } = fitWithin(bitmap.width, bitmap.height, size)182      if (!width || !height) return null183      const canvas = document.createElement("canvas")184      canvas.width = width185      canvas.height = height186      const ctx = canvas.getContext("2d")187      if (!ctx) return null188      ctx.drawImage(bitmap, 0, 0, width, height)189      const webp = canvas.toDataURL("image/webp", quality)190      if (webp.startsWith("data:image/webp")) return webp191      // navigateur sans encodeur WebP : JPEG sur fond blanc (le JPEG n'a pas de transparence)192      ctx.globalCompositeOperation = "destination-over"193      ctx.fillStyle = "#ffffff"194      ctx.fillRect(0, 0, width, height)195      return canvas.toDataURL("image/jpeg", quality)196    })197  } finally {198    bitmap.close()199  }200}201202export function AvatarField({ address, value, onChange }: { address: string; value: string | null; onChange: (avatar: string | null) => void }) {203  const input = useRef<HTMLInputElement>(null)204  const [busy, setBusy] = useState(false)205  const [error, setError] = useState(false)206  const id = useId()207  // seule une URL data: d'image matricielle est affichée (jamais une URL distante ni du SVG)208  const shown = value && AVATAR_RE.test(value) ? value : null209  const pick = async (file: File | undefined) => {210    if (!file) return211    setBusy(true)212    setError(false)213    const url = await fileToAvatar(file)214    setBusy(false)215    if (input.current) input.current.value = ""216    if (!url) return setError(true)217    onChange(url)218  }219  return (220    <div className="field">221      <span className="label" id={`${id}-l`}>222        {t("adm.addr.avatar")}223      </span>224      <div className="adm-addr-avatar-row">225        {shown ? (226          <img className="adm-addr-avatar-big" src={shown} alt={t("adm.addr.avatar.alt", { address })} data-testid="avatar-preview" />227        ) : (228          <span className="adm-addr-avatar-empty" role="img" aria-label={t("adm.addr.avatar.none")}>229            <Icon name="user" />230          </span>231        )}232        <div className="row wrap">233          <input ref={input} id={`${id}-f`} className="sr-only" type="file" accept="image/png,image/jpeg,image/webp" aria-labelledby={`${id}-l`} tabIndex={-1} onChange={(e) => void pick(e.target.files?.[0])} data-testid="avatar-file" />234          <button type="button" className="btn small" disabled={busy} onClick={() => input.current?.click()}>235            {busy ? <span className="spinner" aria-hidden="true" /> : <Icon name="image" small />}236            <span>{shown ? t("adm.addr.avatar.replace") : t("adm.addr.avatar.choose")}</span>237          </button>238          {shown ? (239            <button type="button" className="btn small ghost" onClick={() => onChange(null)}>240              {t("adm.addr.avatar.remove")}241            </button>242          ) : null}243        </div>244      </div>245      <span className="hint" aria-live="polite">246        {shown ? `${t("adm.addr.avatar.size", { size: fmtBytes(dataUrlBytes(shown)) })} — ` : ""}247        {t("adm.addr.avatar.hint")}248      </span>249      {error ? (250        <p className="adm-error small" role="alert">251          {t("adm.addr.avatar.failed")}252        </p>253      ) : null}254    </div>255  )256}257
Files main
Menu

Theme