SPB Git

Repository Public

Notifications.tsx 20.6 KB 404 lines tsx

1// SP Mail Next — Réglages › Notifications : notifications de ce navigateur (onglet ouvert) et préférences des appareils natifs (/api/next/push) : aperçu, heures calmes, prioritaires, boîtes, appareils, état de l'envoi.2import { useEffect, useId, useRef, useState } from "react"3import { fmtDateTime, fmtNumber, t } from "../../i18n"4import { toNextError, useFeature } from "../../next/api"5import { WEB_NOTIFY, setWebNotify, syncWebNotify } from "../../next/notify"6import {7  PUSH, addPrioritySender, isValidTimeZone, listDevices, loadPushPrefs, mailboxEnabled, pushStatus, quietHoursIssue, removeDevice, savePushPrefs, sendTestPush, setDeviceEnabled, setMailboxEnabled, spansMidnight,8  type Preview, type PushDevice, type PushPrefs, type PushStatus, type QuietHours,9} from "../../next/push"10import { S, toast } from "../../state/app"11import { useStore } from "../../state/store"12import { ConfirmDialog, Field, Icon, IconButton, Spinner } from "../kit"13import { Section } from "../Page"14import { LoadError, useLoad } from "./shared"15import "./next-settings.css"1617const errorMessage = (e: unknown): string => {18  const err = toNextError(e)19  return err.kind === "offline" ? t("nx.offline") : err.kind === "rate_limited" ? t("nx.error.rateLimited") : err.kind === "not_found" ? t("nx.error.notFound") : t("nx.error.generic")20}21const localZone = (): string => {22  try {23    return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"24  } catch {25    return "UTC"26  }27}28function zones(current: string): string[] {29  let list: string[] = []30  try {31    list = (Intl as unknown as { supportedValuesOf?: (k: string) => string[] }).supportedValuesOf?.("timeZone") ?? []32  } catch {33    list = []34  }35  return [...new Set([current, localZone(), "UTC", ...list])].filter(Boolean)36}37const previewLabel = (p: Preview) => (p === "none" ? t("nx.settings.push.previewNone") : p === "sender" ? t("nx.settings.push.previewSender") : t("nx.settings.push.previewFull"))38const previewHelp = (p: Preview) => (p === "none" ? t("nx.settings.push.previewNoneHelp") : p === "sender" ? t("nx.settings.push.previewSenderHelp") : t("nx.settings.push.previewFullHelp"))3940// ---------------------------------------------------------------- ce navigateur41function WebSection({ preview }: { preview: Preview }) {42  const enabled = useStore(WEB_NOTIFY, (w) => w.enabled)43  const permission = useStore(WEB_NOTIFY, (w) => w.permission)44  const [busy, setBusy] = useState(false)45  useEffect(() => {46    syncWebNotify()47    const onFocus = () => syncWebNotify()48    window.addEventListener("focus", onFocus)49    return () => window.removeEventListener("focus", onFocus)50  }, [])51  const on = enabled && permission === "granted"52  const toggle = async (next: boolean) => {53    setBusy(true)54    const p = await setWebNotify(next)55    setBusy(false)56    if (next && p === "denied") toast({ kind: "error", text: t("nx.settings.web.deniedToast") })57  }58  return (59    <Section title={t("nx.settings.web.title")} description={t("nx.settings.web.desc")}>60      <div className="stack" data-testid="web-notify">61        <label className="check">62          <input type="checkbox" role="switch" checked={on} disabled={busy || permission === "unsupported" || permission === "denied"} onChange={(e) => void toggle(e.target.checked)} data-testid="web-notify-switch" />63          <span>{t("nx.settings.web.enable")}</span>64        </label>65        {permission === "unsupported" ? (66          <p className="nx-note" data-testid="web-notify-state">{t("nx.settings.web.unsupported")}</p>67        ) : permission === "denied" ? (68          <div className="banner warn" role="status" data-testid="web-notify-state">69            <Icon name="bellOff" />70            <div>{t("nx.settings.web.denied")}</div>71          </div>72        ) : on ? (73          <p className="nx-note" data-testid="web-notify-state">{t("nx.settings.web.on", { preview: previewLabel(preview).toLowerCase() })}</p>74        ) : (75          <p className="nx-note" data-testid="web-notify-state">{t("nx.settings.web.off")}</p>76        )}77        <p className="nx-note">{t("nx.settings.web.limits")}</p>78      </div>79    </Section>80  )81}8283// ---------------------------------------------------------------- état de l'envoi84function StatusSection({ status, hasDevices, onTest, testing }: { status: PushStatus; hasDevices: boolean; onTest: () => void; testing: boolean }) {85  const online = useStore(S, (s) => s.online)86  return (87    <Section88      title={t("nx.settings.push.statusTitle")}89      actions={90        <button type="button" className="btn small" disabled={!online || testing || !status.configured || !hasDevices} title={!online ? t("nx.offline") : !status.configured ? t("nx.settings.push.testNeedsApns") : !hasDevices ? t("nx.settings.push.testNeedsDevice") : undefined} onClick={onTest} data-testid="push-test">91          {t("nx.settings.push.test")}92        </button>93      }94    >95      {status.configured ? (96        <dl className="set-kv nx-set-status" data-testid="push-status" data-configured="true">97          <dt>{t("nx.settings.push.pipeline")}</dt>98          <dd>99            <span className="badge ok">{t("nx.settings.push.configured")}</span>100          </dd>101          <dt>{t("nx.settings.push.queue")}</dt>102          <dd className="nx-set-nums">{t("nx.settings.push.queueLine", { pending: fmtNumber(status.queue.pending), sent: fmtNumber(status.queue.sent_24h), failed: fmtNumber(status.queue.failed_24h) })}</dd>103          {status.last_error ? (104            <>105              <dt>{t("nx.settings.push.lastError")}</dt>106              <dd className="mono set-wrap">{status.last_error}</dd>107            </>108          ) : null}109        </dl>110      ) : (111        <div className="banner warn" role="status" data-testid="push-status" data-configured="false">112          <Icon name="bellOff" />113          <div>114            <div>{t("nx.settings.push.notConfigured")}</div>115            {status.last_error ? <div className="muted mono set-wrap">{status.last_error}</div> : null}116          </div>117        </div>118      )}119    </Section>120  )121}122123// ---------------------------------------------------------------- préférences124function PrefsSection({ prefs }: { prefs: PushPrefs }) {125  const online = useStore(S, (s) => s.online)126  const mailboxes = useStore(S, (s) => s.me?.mailboxes ?? [])127  const [saving, setSaving] = useState(0)128  const [savedAt, setSavedAt] = useState(0)129  const [quiet, setQuiet] = useState<QuietHours>(prefs.quiet_hours ?? { start: "22:00", end: "07:00", tz: localZone() })130  const [quietOn, setQuietOn] = useState(!!prefs.quiet_hours)131  const [sender, setSender] = useState("")132  const [senderError, setSenderError] = useState<string | null>(null)133  const id = useId()134  const senderInput = useRef<HTMLInputElement>(null)135136  const save = async (patch: Partial<PushPrefs>) => {137    setSaving((n) => n + 1)138    try {139      await savePushPrefs(patch)140      setSavedAt(Date.now())141    } catch (e) {142      toast({ kind: "error", text: errorMessage(e) })143      void loadPushPrefs().catch(() => {})144    } finally {145      setSaving((n) => n - 1)146    }147  }148  const quietIssue = quietOn ? quietHoursIssue(quiet) : null149  const changeQuiet = (on: boolean, next: QuietHours) => {150    setQuietOn(on)151    setQuiet(next)152    if (!on) return void save({ quiet_hours: null })153    if (!quietHoursIssue(next)) void save({ quiet_hours: next })154  }155  const addSender = () => {156    const r = addPrioritySender(prefs.priority_senders, sender)157    if (!r.ok) return setSenderError(r.issue === "invalid" ? t("nx.settings.push.senderInvalid") : r.issue === "duplicate" ? t("nx.settings.push.senderDuplicate") : t("nx.settings.push.senderFull"))158    setSender("")159    setSenderError(null)160    void save({ priority_senders: r.list })161    senderInput.current?.focus()162  }163  const off = !prefs.enabled164  const dis = !online165166  return (167    <Section title={t("nx.settings.push.prefsTitle")} description={t("nx.settings.push.prefsDesc")}>168      <div className="stack nx-set-prefs" data-testid="push-prefs">169        <label className="check">170          <input type="checkbox" role="switch" checked={prefs.enabled} disabled={dis} onChange={(e) => void save({ enabled: e.target.checked })} data-testid="push-enabled" />171          <span>{t("nx.settings.push.enabled")}</span>172        </label>173174        <fieldset className="set-fieldset" disabled={dis || off}>175          <legend>{t("nx.settings.push.preview")}</legend>176          <div className="segmented set-segmented" role="radiogroup" aria-label={t("nx.settings.push.preview")}>177            {(["none", "sender", "full"] as const).map((p) => (178              <button key={p} type="button" role="radio" aria-checked={prefs.preview === p} onClick={() => prefs.preview !== p && void save({ preview: p })} data-testid={`push-preview-${p}`}>179                {previewLabel(p)}180              </button>181            ))}182          </div>183          <p className="nx-note nx-set-help">{previewHelp(prefs.preview)}</p>184        </fieldset>185186        <fieldset className="set-fieldset" disabled={dis || off}>187          <legend>{t("nx.settings.push.quiet")}</legend>188          <div className="stack">189            <label className="check">190              <input type="checkbox" checked={quietOn} onChange={(e) => changeQuiet(e.target.checked, quiet)} data-testid="push-quiet" />191              <span>{t("nx.settings.push.quietEnable")}</span>192            </label>193            {quietOn ? (194              <div className="stack set-indent">195                <div className="nx-set-quiet">196                  <Field id={`${id}-qs`} label={t("nx.settings.push.quietStart")}>197                    <input id={`${id}-qs`} type="time" className="input" value={quiet.start} onChange={(e) => changeQuiet(true, { ...quiet, start: e.target.value })} aria-invalid={quietIssue === "start" || quietIssue === "same" || undefined} data-testid="push-quiet-start" />198                  </Field>199                  <Field id={`${id}-qe`} label={t("nx.settings.push.quietEnd")}>200                    <input id={`${id}-qe`} type="time" className="input" value={quiet.end} onChange={(e) => changeQuiet(true, { ...quiet, end: e.target.value })} aria-invalid={quietIssue === "end" || quietIssue === "same" || undefined} data-testid="push-quiet-end" />201                  </Field>202                  <Field id={`${id}-qz`} label={t("nx.settings.push.quietZone")}>203                    <select id={`${id}-qz`} className="select" value={quiet.tz} onChange={(e) => changeQuiet(true, { ...quiet, tz: e.target.value })} data-testid="push-quiet-tz">204                      {zones(quiet.tz).filter(isValidTimeZone).map((z) => (205                        <option key={z} value={z}>206                          {z}207                        </option>208                      ))}209                    </select>210                  </Field>211                </div>212                {quietIssue ? (213                  <p className="set-error" role="alert">214                    {quietIssue === "same" ? t("nx.settings.push.quietSame") : quietIssue === "tz" ? t("nx.settings.push.quietTz") : t("nx.settings.push.quietTime")}215                  </p>216                ) : (217                  <p className="nx-note">{spansMidnight(quiet) ? t("nx.settings.push.quietOvernight", { start: quiet.start, end: quiet.end }) : t("nx.settings.push.quietSameDay", { start: quiet.start, end: quiet.end })}</p>218                )}219              </div>220            ) : null}221          </div>222        </fieldset>223224        <fieldset className="set-fieldset" disabled={dis || off}>225          <legend>{t("nx.settings.push.priority")}</legend>226          <div className="stack">227            <p className="nx-note">{t("nx.settings.push.priorityDesc")}</p>228            <form229              className="set-inline nx-set-sender"230              onSubmit={(e) => {231                e.preventDefault()232                addSender()233              }}234            >235              <input ref={senderInput} className="input" aria-label={t("nx.settings.push.senderLabel")} placeholder={t("nx.settings.push.senderHint")} value={sender} onChange={(e) => (setSender(e.target.value), setSenderError(null))} maxLength={254} spellCheck={false} autoCapitalize="off" autoComplete="off" aria-invalid={!!senderError || undefined} data-testid="push-sender-input" />236              <button type="submit" className="btn" disabled={!sender.trim()}>237                {t("nx.settings.push.senderAdd")}238              </button>239            </form>240            {senderError ? (241              <p className="set-error" role="alert">242                {senderError}243              </p>244            ) : null}245            {prefs.priority_senders.length ? (246              <ul className="nx-set-chips" aria-label={t("nx.settings.push.priority")} data-testid="push-senders">247                {prefs.priority_senders.map((s) => (248                  <li key={s} className="nx-chip">249                    <span className="truncate">{s}</span>250                    <IconButton icon="close" label={t("nx.settings.push.senderRemove", { sender: s })} onClick={() => void save({ priority_senders: prefs.priority_senders.filter((x) => x !== s) })} />251                  </li>252                ))}253              </ul>254            ) : null}255            <label className="check">256              <input type="checkbox" checked={prefs.priority_only} onChange={(e) => void save({ priority_only: e.target.checked })} data-testid="push-priority-only" />257              <span>{t("nx.settings.push.priorityOnly")}</span>258            </label>259          </div>260        </fieldset>261262        {mailboxes.length ? (263          <fieldset className="set-fieldset" disabled={dis || off}>264            <legend>{t("nx.settings.push.mailboxes")}</legend>265            <div className="stack">266              {mailboxes.map((m) => (267                <label key={m.id} className="check">268                  <input type="checkbox" role="switch" checked={mailboxEnabled(prefs, m.id)} onChange={(e) => void save({ mailboxes: setMailboxEnabled(prefs.mailboxes, m.id, e.target.checked) })} data-testid="push-mailbox" data-address={m.address} />269                  <span className="set-wrap">{m.address}</span>270                </label>271              ))}272              <p className="nx-note">{t("nx.settings.push.mailboxesHelp")}</p>273            </div>274          </fieldset>275        ) : null}276277        <fieldset className="set-fieldset" disabled={dis || off}>278          <legend>{t("nx.settings.push.badge")}</legend>279          <label className="check">280            <input type="checkbox" checked={prefs.badge === "inbox"} onChange={(e) => void save({ badge: e.target.checked ? "inbox" : "none" })} data-testid="push-badge" />281            <span>{t("nx.settings.push.badgeInbox")}</span>282          </label>283        </fieldset>284285        <div className="row nx-set-saved" role="status" aria-live="polite" data-testid="push-saved">286          {saving > 0 ? <Spinner label={t("nx.settings.push.saving")} /> : savedAt ? <span className="muted small">{t("nx.settings.push.saved")}</span> : null}287          {dis ? <span className="muted small">{t("nx.offline")}</span> : null}288        </div>289      </div>290    </Section>291  )292}293294// ---------------------------------------------------------------- appareils295function DevicesSection({ devices, onChange, onTest, canTest }: { devices: PushDevice[]; onChange: (devices: PushDevice[]) => void; onTest: (id: string) => void; canTest: boolean }) {296  const online = useStore(S, (s) => s.online)297  const [removing, setRemoving] = useState<PushDevice | null>(null)298  const name = (d: PushDevice) => d.device_name?.trim() || t("nx.settings.push.deviceUnnamed")299  const toggle = async (d: PushDevice, enabled: boolean) => {300    onChange(devices.map((x) => (x.id === d.id ? { ...x, enabled } : x)))301    try {302      await setDeviceEnabled(d.id, enabled)303    } catch (e) {304      toast({ kind: "error", text: errorMessage(e) })305      onChange(devices)306    }307  }308  const remove = async (d: PushDevice) => {309    try {310      await removeDevice(d.id)311      onChange(devices.filter((x) => x.id !== d.id))312      toast({ kind: "success", text: t("nx.settings.push.deviceRemoved") })313    } catch (e) {314      toast({ kind: "error", text: errorMessage(e) })315    }316  }317  return (318    <Section title={t("nx.settings.push.devicesTitle")} description={t("nx.settings.push.devicesDesc")}>319      {devices.length === 0 ? (320        <div className="nx-empty" data-testid="push-devices-empty">321          <Icon name="phone" />322          <p>{t("nx.settings.push.devicesEmpty")}</p>323        </div>324      ) : (325        <ul className="set-list" aria-label={t("nx.settings.push.devicesTitle")} data-testid="push-devices">326          {devices.map((d) => (327            <li key={d.id} className="set-item">328              <div className="set-item-row">329                <label className="check set-item-main">330                  <input type="checkbox" role="switch" checked={d.enabled} disabled={!online} aria-label={t("nx.settings.push.deviceEnable", { name: name(d) })} onChange={(e) => void toggle(d, e.target.checked)} />331                  <span className="set-rule-text">332                    <strong className="set-wrap">{name(d)}</strong>333                    {d.current ? <span className="badge accent nx-set-badge">{t("nx.settings.push.deviceCurrent")}</span> : null}334                    {d.environment === "sandbox" ? <span className="badge nx-set-badge">{t("nx.settings.push.deviceSandbox")}</span> : null}335                    <span className="muted small set-wrap set-block">{[d.bundle_id, d.app_version ? t("nx.settings.push.deviceVersion", { version: d.app_version }) : ""].filter(Boolean).join(" · ")}</span>336                    <span className="muted small set-wrap set-block">337                      {t("nx.settings.push.deviceRegistered", { when: fmtDateTime(d.last_registered_at) })} · {d.last_push_at ? t("nx.settings.push.deviceLastPush", { when: fmtDateTime(d.last_push_at) }) : t("nx.settings.push.deviceNoPush")}338                    </span>339                    {d.last_error ? <span className="set-error set-wrap set-block">{t("nx.settings.push.deviceError", { error: d.last_error })}</span> : null}340                  </span>341                </label>342                <div className="row set-rule-actions">343                  <button type="button" className="btn small" disabled={!online || !canTest || !d.enabled} onClick={() => onTest(d.id)}>344                    {t("nx.settings.push.deviceTest")}345                  </button>346                  <IconButton icon="trash" label={t("nx.settings.push.deviceRemove", { name: name(d) })} disabled={!online} onClick={() => setRemoving(d)} />347                </div>348              </div>349            </li>350          ))}351        </ul>352      )}353      {removing ? <ConfirmDialog title={t("nx.settings.push.deviceRemoveTitle")} body={t("nx.settings.push.deviceRemoveBody", { name: name(removing) })} confirmLabel={t("nx.settings.push.deviceRemoveConfirm")} danger onConfirm={() => remove(removing)} onClose={() => setRemoving(null)} /> : null}354    </Section>355  )356}357358// ---------------------------------------------------------------- partie « appareils natifs » (fonction `push` du serveur)359function NativePart() {360  const prefs = useStore(PUSH, (p) => p.prefs)361  const { state, reload, setData } = useLoad(async (signal) => {362    const [, devices, status] = await Promise.all([loadPushPrefs(signal), listDevices(signal), pushStatus(signal)])363    return { devices, status }364  }, "push")365  const [testing, setTesting] = useState(false)366  if (state.status === "loading" || (state.status === "ready" && !prefs)) return <Spinner label={t("nx.loading")} />367  if (state.status === "error") return <LoadError error={state.error} onRetry={reload} />368  const { devices, status } = state.data369  const test = async (deviceId?: string) => {370    setTesting(true)371    try {372      const r = await sendTestPush(deviceId)373      toast(r.queued > 0 ? { kind: "success", text: t("nx.settings.push.testQueued", { n: r.queued }) } : { kind: "info", text: t("nx.settings.push.testNone") })374      setData({ devices, status: await pushStatus().catch(() => status) })375    } catch (e) {376      toast({ kind: "error", text: errorMessage(e) })377    } finally {378      setTesting(false)379    }380  }381  return (382    <>383      <div className="banner nx-set-explain" data-testid="push-native-note">384        <Icon name="phone" />385        <div>{t("nx.settings.push.nativeNote")}</div>386      </div>387      <StatusSection status={status} hasDevices={devices.some((d) => d.enabled)} testing={testing} onTest={() => void test()} />388      {prefs ? <PrefsSection prefs={prefs} /> : null}389      <DevicesSection devices={devices} onChange={(next) => setData({ devices: next, status })} onTest={(id) => void test(id)} canTest={status.configured && !testing} />390    </>391  )392}393394export default function Notifications() {395  const push = useFeature("push")396  const preview = useStore(PUSH, (p) => p.prefs?.preview ?? "sender")397  return (398    <>399      <WebSection preview={preview} />400      {push ? <NativePart /> : null}401    </>402  )403}404
Files main
Menu

Theme