SPB Git

Repository Public

Editor.tsx 7.7 KB 167 lines tsx

1// Webhooks : formulaire de création et de modification (nom, URL, événements, filtre d'adresses, contenu, activation).2import { useId, useMemo, useState, type FormEvent } from "react"3import { EVENT_TYPES, checkWebhookUrl, eventKey, isEventType, type EventType, type Webhook } from "../../../admin/webhooks"4import { t } from "../../../i18n"5import { v1, type ApiAddress } from "../../../mail/v1"6import { Icon } from "../../kit"7import { AddressPicker } from "../kit"8import { errorText } from "../shared"9import { hookCodes, useFocusOnMount } from "./common"1011export function Editor({ hook, addresses, allow, onCancel, onSaved }: { hook: Webhook | null; addresses: readonly ApiAddress[]; allow: readonly string[]; onCancel: () => void; onSaved: (w: Webhook, created: boolean) => void }) {12  const id = useId()13  const title = useFocusOnMount<HTMLHeadingElement>()14  const [name, setName] = useState(hook?.name ?? "")15  const [url, setUrl] = useState(hook?.url ?? "")16  const [events, setEvents] = useState<EventType[]>(() => (hook?.events ?? []).filter(isEventType))17  const [addressIds, setAddressIds] = useState<string[]>(hook?.address_ids ?? [])18  const [content, setContent] = useState(hook?.include_content ?? false)19  const [active, setActive] = useState(hook?.active ?? true)20  const [busy, setBusy] = useState(false)21  const [error, setError] = useState<string | null>(null)2223  const check = useMemo(() => checkWebhookUrl(url, allow), [url, allow])24  const urlTouched = url.trim() !== ""25  const urlNote = !urlTouched26    ? null27    : check.problem28      ? { bad: true, text: t(`adm.webhooks.url.${check.problem}`, { hostPort: check.hostPort ?? "" }) }29      : check.allowlisted30        ? { bad: false, text: t("adm.webhooks.url.allowlisted", { hostPort: check.hostPort ?? "" }) }31        : null3233  const toggle = (e: EventType, on: boolean) => setEvents((list) => EVENT_TYPES.filter((x) => (x === e ? on : list.includes(x))))3435  const submit = async (ev: FormEvent) => {36    ev.preventDefault()37    if (busy) return38    if (!name.trim()) return setError(t("adm.webhooks.error.name"))39    if (check.blocking) return setError(t(`adm.webhooks.url.${check.problem ?? "invalid"}`, { hostPort: "" }))40    if (events.length === 0) return setError(t("adm.webhooks.error.events"))41    setBusy(true)42    setError(null)43    try {44      const body = { name: name.trim(), events, address_ids: addressIds, include_content: content, active }45      const cleanUrl = url.trim()46      // en modification, l'URL n'est renvoyée que si elle a changé : le serveur la revérifie (DNS compris) quand il la reçoit47      const w = hook48        ? await v1<Webhook>(`/webhooks/${hook.id}`, { method: "PATCH", json: cleanUrl === hook.url ? body : { ...body, url: cleanUrl } })49        : await v1<Webhook>("/webhooks", { method: "POST", json: { ...body, url: cleanUrl } })50      onSaved(w, !hook)51    } catch (e) {52      setError(errorText(e, hookCodes()))53    } finally {54      setBusy(false)55    }56  }5758  return (59    <section className="card section" data-testid="webhook-editor">60      <h3 ref={title} tabIndex={-1}>61        {hook ? t("adm.webhooks.edit.title", { name: hook.name }) : t("adm.webhooks.new.title")}62      </h3>63      <form className="stack" onSubmit={(e) => void submit(e)} noValidate>64        <div className="adm-form">65          <div className="field">66            <label htmlFor={`${id}-name`}>{t("adm.webhooks.field.name")}</label>67            <input id={`${id}-name`} className="input" value={name} onChange={(e) => setName(e.target.value)} maxLength={80} required autoComplete="off" />68          </div>69          <div className="field">70            <label htmlFor={`${id}-url`}>{t("adm.webhooks.field.url")}</label>71            <input72              id={`${id}-url`}73              className="input mono"74              value={url}75              onChange={(e) => setUrl(e.target.value)}76              maxLength={2000}77              required78              inputMode="url"79              autoComplete="off"80              autoCapitalize="none"81              spellCheck={false}82              placeholder="https://exemple.org/hook"83              aria-describedby={`${id}-url-hint ${id}-url-note`}84              aria-invalid={urlNote?.bad && check.blocking ? true : undefined}85            />86            <span className="hint" id={`${id}-url-hint`}>87              {t("adm.webhooks.url.hint")}88            </span>89            <span id={`${id}-url-note`} aria-live="polite" data-testid="webhook-url-note">90              {urlNote ? (91                <span className={`adm-wh-note${urlNote.bad ? " bad" : ""}`}>92                  <Icon name={urlNote.bad ? "warn" : "check"} small />93                  <span>{urlNote.text}</span>94                </span>95              ) : null}96            </span>97          </div>98        </div>99100        <fieldset className="adm-picker" data-testid="webhook-events">101          <legend className="label">{t("adm.webhooks.field.events")}</legend>102          <div className="row wrap">103            <p className="small muted adm-grow" aria-live="polite">104              {t("adm.webhooks.events.count", { n: events.length })}105            </p>106            <button type="button" className="btn small" onClick={() => setEvents([...EVENT_TYPES])}>107              {t("adm.webhooks.events.all")}108            </button>109            <button type="button" className="btn small" onClick={() => setEvents([])}>110              {t("adm.webhooks.events.none")}111            </button>112          </div>113          <div className="adm-wh-eventgrid">114            {EVENT_TYPES.map((e) => (115              <label key={e} className="adm-choice">116                <input type="checkbox" checked={events.includes(e)} onChange={(x) => toggle(e, x.target.checked)} />117                <span>118                  <span className="mono">{e}</span>119                  <span className="small muted">{t(eventKey(e))}</span>120                </span>121              </label>122            ))}123          </div>124        </fieldset>125126        <AddressPicker addresses={addresses} value={addressIds} onChange={setAddressIds} legend={t("adm.webhooks.field.addresses")} hint={t("adm.webhooks.addresses.hint")} />127128        <div className="stack">129          <label className="check" htmlFor={`${id}-content`}>130            <input id={`${id}-content`} type="checkbox" checked={content} onChange={(e) => setContent(e.target.checked)} aria-describedby={`${id}-content-hint`} />131            <span>{t("adm.webhooks.content.label")}</span>132          </label>133          <p className="small muted" id={`${id}-content-hint`}>134            {t("adm.webhooks.content.hint")}135          </p>136          {content ? (137            <div className="banner warn" role="status" data-testid="webhook-content-warning">138              <Icon name="warn" />139              <span>{t("adm.webhooks.content.warning")}</span>140            </div>141          ) : null}142          <label className="check" htmlFor={`${id}-active`}>143            <input id={`${id}-active`} type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} />144            <span>{t("adm.webhooks.active.label")}</span>145          </label>146        </div>147148        {error ? (149          <p className="adm-error" role="alert" data-testid="webhook-error">150            {error}151          </p>152        ) : null}153        <div className="row wrap">154          <span className="spacer" />155          <button type="button" className="btn" onClick={onCancel}>156            {t("common.cancel")}157          </button>158          <button type="submit" className="btn primary" disabled={busy} data-testid="webhook-save">159            {busy ? <span className="spinner" aria-hidden="true" /> : null}160            <span>{hook ? t("common.save") : t("adm.webhooks.create")}</span>161          </button>162        </div>163      </form>164    </section>165  )166}167
Files main
Menu

Theme