SPB Git

Repository Public

ContactDialogs.tsx 19.2 KB 415 lines tsx

1// SP Mail Next — dialogues des contacts : création / modification d'une fiche, doublons et fusion, gestion des groupes, résumé d'un import vCard.2import { useEffect, useId, useState, type CSSProperties } from "react"3import { t } from "../../i18n"4import { isAbort } from "../../next/api"5import {6  CU, PALETTE, closeContactDialog, colorToken, contactTitle, createContact, createGroup, deleteGroup, fetchDuplicates, formOf, formProblem, formToInput, groups, mergeContacts, mergePreview, pickKeep,7  pruneDuplicates, updateContact, updateGroup, type Contact, type ContactForm, type ContactGroup, type DuplicateGroup, type ImportResult,8} from "../../next/contacts"9import { nextHref } from "../../next/nav"10import { navigate } from "../../state/session"11import { useStore } from "../../state/store"12import { Dialog, Icon, IconButton, Spinner, confirmAsync } from "../kit"13import { ContactAvatar, attempt, contactError, useOnline } from "./ContactBits"1415// ---------------------------------------------------------------- fiche : création et modification16function EditDialog({ contact, init }: { contact: Contact | null; init?: Partial<ContactForm> }) {17  const [f, setF] = useState<ContactForm>(() => formOf(contact, init))18  const [busy, setBusy] = useState(false)19  const [error, setError] = useState<string | null>(null)20  const [touched, setTouched] = useState(false)21  const groupList = groups.use()22  const online = useOnline()23  const uid = useId()24  const problem = formProblem(f)25  const patch = (p: Partial<ContactForm>) => {26    setF((cur) => ({ ...cur, ...p }))27    setError(null)28  }29  const setEmail = (i: number, p: Partial<ContactForm["emails"][number]>) => patch({ emails: f.emails.map((e, j) => (j === i ? { ...e, ...p } : e)) })30  const setPhone = (i: number, p: Partial<ContactForm["phones"][number]>) => patch({ phones: f.phones.map((e, j) => (j === i ? { ...e, ...p } : e)) })31  const submit = async () => {32    setTouched(true)33    if (problem || busy) return34    if (!online) return setError(t("nx.offline"))35    setBusy(true)36    try {37      const input = formToInput(f)38      const saved = contact ? await updateContact(contact.id, input) : await createContact(input)39      closeContactDialog()40      if (!contact) navigate(nextHref("contacts", saved.id))41    } catch (e) {42      setError(contactError(e))43    } finally {44      setBusy(false)45    }46  }47  return (48    <Dialog49      title={contact ? t("nx.contacts.edit.title") : t("nx.contacts.new")}50      onClose={closeContactDialog}51      wide52      footer={53        <>54          <button type="button" className="btn" onClick={closeContactDialog}>55            {t("common.cancel")}56          </button>57          <button type="submit" form={`${uid}-form`} className="btn primary" disabled={busy}>58            {t("nx.contacts.save")}59          </button>60        </>61      }62    >63      <form64        id={`${uid}-form`}65        className="nx-ct-form"66        noValidate67        onSubmit={(e) => {68          e.preventDefault()69          void submit()70        }}71      >72        <div className="field">73          <label htmlFor={`${uid}-name`}>{t("nx.contacts.field.name")}</label>74          <input id={`${uid}-name`} className="input" value={f.name} maxLength={120} autoComplete="off" data-autofocus onChange={(e) => patch({ name: e.target.value })} />75        </div>76        <div className="nx-ct-form-2">77          <div className="field">78            <label htmlFor={`${uid}-org`}>{t("nx.contacts.field.organization")}</label>79            <input id={`${uid}-org`} className="input" value={f.organization} maxLength={160} autoComplete="off" onChange={(e) => patch({ organization: e.target.value })} />80          </div>81          <div className="field">82            <label htmlFor={`${uid}-title`}>{t("nx.contacts.field.title")}</label>83            <input id={`${uid}-title`} className="input" value={f.title} maxLength={160} autoComplete="off" onChange={(e) => patch({ title: e.target.value })} />84          </div>85        </div>8687        <fieldset className="nx-ct-set">88          <legend>{t("nx.contacts.field.emails")}</legend>89          {f.emails.map((e, i) => {90            const bad = touched && e.email.trim() !== "" && formProblem({ ...f, emails: [e], name: "x" }) === "email"91            return (92              <div key={i} className="nx-ct-line">93                <input className="input" type="email" inputMode="email" value={e.email} maxLength={254} autoComplete="off" spellCheck={false} aria-label={t("nx.contacts.field.emailN", { n: i + 1 })} aria-invalid={bad || undefined} placeholder={t("nx.contacts.ph.email")} onChange={(ev) => setEmail(i, { email: ev.target.value })} />94                <input className="input nx-ct-label" value={e.label} maxLength={24} autoComplete="off" aria-label={t("nx.contacts.field.emailLabelN", { n: i + 1 })} placeholder={t("nx.contacts.ph.label")} onChange={(ev) => setEmail(i, { label: ev.target.value })} />95                <IconButton icon="close" label={t("nx.contacts.removeEmailN", { n: i + 1 })} onClick={() => patch({ emails: f.emails.filter((_, j) => j !== i) })} />96              </div>97            )98          })}99          <button type="button" className="btn small ghost nx-ct-addline" disabled={f.emails.length >= 20} onClick={() => patch({ emails: [...f.emails, { email: "", label: "" }] })}>100            <Icon name="plus" small />101            <span>{t("nx.contacts.addEmail")}</span>102          </button>103        </fieldset>104105        <fieldset className="nx-ct-set">106          <legend>{t("nx.contacts.field.phones")}</legend>107          {f.phones.map((p, i) => (108            <div key={i} className="nx-ct-line">109              <input className="input" type="tel" inputMode="tel" value={p.number} maxLength={40} autoComplete="off" aria-label={t("nx.contacts.field.phoneN", { n: i + 1 })} placeholder={t("nx.contacts.ph.phone")} onChange={(ev) => setPhone(i, { number: ev.target.value })} />110              <input className="input nx-ct-label" value={p.label} maxLength={24} autoComplete="off" aria-label={t("nx.contacts.field.phoneLabelN", { n: i + 1 })} placeholder={t("nx.contacts.ph.label")} onChange={(ev) => setPhone(i, { label: ev.target.value })} />111              <IconButton icon="close" label={t("nx.contacts.removePhoneN", { n: i + 1 })} onClick={() => patch({ phones: f.phones.filter((_, j) => j !== i) })} />112            </div>113          ))}114          <button type="button" className="btn small ghost nx-ct-addline" disabled={f.phones.length >= 20} onClick={() => patch({ phones: [...f.phones, { number: "", label: "" }] })}>115            <Icon name="plus" small />116            <span>{t("nx.contacts.addPhone")}</span>117          </button>118        </fieldset>119120        <div className="field">121          <label htmlFor={`${uid}-notes`}>{t("nx.contacts.field.notes")}</label>122          <textarea id={`${uid}-notes`} className="textarea" rows={3} value={f.notes} maxLength={4000} onChange={(e) => patch({ notes: e.target.value })} />123        </div>124125        {groupList.length ? (126          <fieldset className="nx-ct-set">127            <legend>{t("nx.contacts.groups")}</legend>128            <div className="nx-ct-groups">129              {groupList.map((g) => (130                <button key={g.id} type="button" className="nx-chip" aria-pressed={f.groups.includes(g.id)} onClick={() => patch({ groups: f.groups.includes(g.id) ? f.groups.filter((x) => x !== g.id) : [...f.groups, g.id] })}>131                  <span className="nx-dot" style={{ background: colorToken(g.color) }} aria-hidden="true" />132                  <span className="truncate">{g.name}</span>133                </button>134              ))}135            </div>136          </fieldset>137        ) : null}138139        <div className="nx-ct-flags">140          <label className="check">141            <input type="checkbox" checked={f.favorite} onChange={(e) => patch({ favorite: e.target.checked })} />142            <span>{t("nx.contacts.favorite")}</span>143          </label>144          <label className="check">145            <input type="checkbox" checked={f.vip} onChange={(e) => patch({ vip: e.target.checked })} />146            <span>{t("nx.contacts.vipLong")}</span>147          </label>148        </div>149150        {error || (touched && problem) ? (151          <p className="banner danger" role="alert">152            <Icon name="warn" small />153            <span>{error ?? (problem === "email" ? t("nx.contacts.err.email") : t("nx.contacts.err.empty"))}</span>154          </p>155        ) : null}156      </form>157    </Dialog>158  )159}160161// ---------------------------------------------------------------- doublons et fusion162function Summary({ c }: { c: Pick<Contact, "name" | "emails" | "phones" | "organization" | "title"> }) {163  return (164    <span className="nx-item-main">165      <span className="truncate nx-ct-strong">{contactTitle(c) || t("nx.contacts.unnamed")}</span>166      {c.emails.map((e) => (167        <span key={e.email} className="small truncate">168          {e.email}169        </span>170      ))}171      {c.phones.map((p, i) => (172        <span key={`${p.number}-${i}`} className="small truncate">173          {p.number}174        </span>175      ))}176      {c.organization || c.title ? <span className="small truncate">{[c.title, c.organization].filter(Boolean).join(" · ")}</span> : null}177    </span>178  )179}180function DuplicateCard({ group, onMerged }: { group: DuplicateGroup; onMerged: (gone: string[], kept: Contact) => void }) {181  const [keepId, setKeepId] = useState(() => pickKeep(group.contacts) ?? group.contacts[0].id)182  const [busy, setBusy] = useState(false)183  const online = useOnline()184  const name = useId()185  const keep = group.contacts.find((c) => c.id === keepId) ?? group.contacts[0]186  const others = group.contacts.filter((c) => c.id !== keep.id)187  const result = mergePreview(keep, others)188  const merge = async () => {189    setBusy(true)190    let kept: Contact | null = null191    const ok = await attempt(async () => {192      kept = await mergeContacts(keep.id, others.map((c) => c.id))193    }, t("nx.contacts.merge.done", { n: others.length }))194    setBusy(false)195    if (ok && kept) onMerged(others.map((c) => c.id), kept)196  }197  return (198    <li className="nx-card nx-ct-dup">199      <p className="nx-ct-dup-why">200        <Icon name="merge" small />201        <span>202          {group.reason === "email" ? t("nx.contacts.merge.sameEmail") : t("nx.contacts.merge.sameName")} <strong>{group.key}</strong>203        </span>204      </p>205      <div className="nx-ct-dup-cols">206        <fieldset className="nx-ct-set">207          <legend>{t("nx.contacts.merge.keep")}</legend>208          {group.contacts.map((c) => (209            <label key={c.id} className={`nx-ct-dup-opt${c.id === keep.id ? " on" : ""}`}>210              <input type="radio" name={name} checked={c.id === keep.id} onChange={() => setKeepId(c.id)} />211              <ContactAvatar contact={c} size="s" />212              <Summary c={c} />213              {c.kind === "suggested" ? <span className="badge">{t("nx.contacts.suggested")}</span> : null}214            </label>215          ))}216        </fieldset>217        <div className="nx-ct-dup-result" role="group" aria-label={t("nx.contacts.merge.result")}>218          <p className="label">{t("nx.contacts.merge.result")}</p>219          <div className="nx-ct-dup-kept">220            <ContactAvatar contact={{ ...keep, ...result }} size="s" />221            <Summary c={result} />222          </div>223          <p className="nx-note">{t("nx.contacts.merge.removed", { n: others.length })}</p>224        </div>225      </div>226      <div className="nx-ct-dup-foot">227        <button type="button" className="btn primary" disabled={busy || !online} title={online ? undefined : t("nx.offline")} onClick={() => void merge()}>228          <Icon name="merge" />229          <span>{t("nx.contacts.merge.action", { n: group.contacts.length })}</span>230        </button>231      </div>232    </li>233  )234}235function DuplicatesDialog() {236  const [state, setState] = useState<{ status: "loading" | "ready" | "error"; groups: DuplicateGroup[]; error?: string }>({ status: "loading", groups: [] })237  const [round, setRound] = useState(0)238  useEffect(() => {239    const ctrl = new AbortController()240    setState({ status: "loading", groups: [] })241    fetchDuplicates(ctrl.signal).then(242      (list) => !ctrl.signal.aborted && setState({ status: "ready", groups: list }),243      (e: unknown) => !ctrl.signal.aborted && !isAbort(e) && setState({ status: "error", groups: [], error: contactError(e) }),244    )245    return () => ctrl.abort()246  }, [round])247  return (248    <Dialog title={t("nx.contacts.duplicates")} onClose={closeContactDialog} wide footer={<button type="button" className="btn" onClick={closeContactDialog}>{t("common.close")}</button>}>249      {state.status === "loading" ? (250        <Spinner label={t("nx.loading")} />251      ) : state.status === "error" ? (252        <div className="nx-empty" role="alert">253          <Icon name="warn" />254          <p>{state.error}</p>255          <button type="button" className="btn" onClick={() => setRound((n) => n + 1)}>256            {t("nx.retry")}257          </button>258        </div>259      ) : state.groups.length === 0 ? (260        <div className="nx-empty">261          <Icon name="check" />262          <p>{t("nx.contacts.merge.none")}</p>263        </div>264      ) : (265        <>266          <p className="nx-note nx-ct-dup-intro">{t("nx.contacts.merge.intro")}</p>267          <ul className="nx-list nx-ct-dups">268            {state.groups.map((g) => (269              <DuplicateCard key={`${g.reason}:${g.key}:${g.contacts.map((c) => c.id).join(",")}`} group={g} onMerged={(gone, kept) => setState((s) => ({ ...s, groups: pruneDuplicates(s.groups, gone, kept) }))} />270            ))}271          </ul>272        </>273      )}274    </Dialog>275  )276}277278// ---------------------------------------------------------------- groupes279function Swatches({ value, onChange, label }: { value: string; onChange: (hex: string) => void; label: string }) {280  return (281    <div className="nx-ct-swatches" role="radiogroup" aria-label={label}>282      {PALETTE.map((hex, i) => (283        <button key={hex} type="button" role="radio" aria-checked={value === hex} aria-label={t("nx.contacts.groups.colorN", { n: i + 1 })} className="nx-ct-swatch" style={{ "--c": `var(--label-${i + 1})` } as CSSProperties} onClick={() => onChange(hex)} />284      ))}285    </div>286  )287}288function GroupRow({ g }: { g: ContactGroup }) {289  const [editing, setEditing] = useState(false)290  const [name, setName] = useState(g.name)291  const [color, setColor] = useState(g.color)292  const online = useOnline()293  const save = async () => {294    const n = name.trim()295    if (!n) return296    if (await attempt(() => updateGroup(g.id, { ...(n !== g.name ? { name: n } : {}), ...(color !== g.color ? { color } : {}) }))) setEditing(false)297  }298  const remove = async () => {299    if (await confirmAsync({ title: t("nx.contacts.groups.delete.title"), body: t("nx.contacts.groups.delete.body", { name: g.name }), confirmLabel: t("nx.contacts.delete"), danger: true })) await attempt(() => deleteGroup(g.id))300  }301  if (!editing) {302    return (303      <li className="nx-item nx-ct-group">304        <span className="nx-dot" style={{ background: colorToken(g.color) }} aria-hidden="true" />305        <span className="nx-item-main">306          <span className="truncate">{g.name}</span>307        </span>308        <span className="nx-meta">{t("nx.contacts.groups.members", { n: g.members })}</span>309        <IconButton icon="edit" label={t("nx.contacts.groups.editNamed", { name: g.name })} onClick={() => (setName(g.name), setColor(g.color), setEditing(true))} />310        <IconButton icon="trash" label={t("nx.contacts.groups.deleteNamed", { name: g.name })} disabled={!online} onClick={() => void remove()} />311      </li>312    )313  }314  return (315    <li className="nx-ct-group editing">316      <form317        className="nx-ct-groupform"318        onSubmit={(e) => {319          e.preventDefault()320          void save()321        }}322      >323        <input className="input" value={name} maxLength={60} autoFocus aria-label={t("nx.contacts.groups.name")} onChange={(e) => setName(e.target.value)} />324        <Swatches value={color} onChange={setColor} label={t("nx.contacts.groups.color")} />325        <div className="row">326          <button type="button" className="btn small" onClick={() => setEditing(false)}>327            {t("common.cancel")}328          </button>329          <button type="submit" className="btn small primary" disabled={!name.trim() || !online}>330            {t("nx.contacts.save")}331          </button>332        </div>333      </form>334    </li>335  )336}337function GroupsDialog() {338  const list = groups.use()339  const online = useOnline()340  const [name, setName] = useState("")341  const [color, setColor] = useState<string>(PALETTE[5])342  const id = useId()343  const add = async () => {344    const n = name.trim()345    if (!n) return346    if (await attempt(() => createGroup(n, color))) setName("")347  }348  return (349    <Dialog title={t("nx.contacts.groups.manage")} onClose={closeContactDialog} footer={<button type="button" className="btn" onClick={closeContactDialog}>{t("common.close")}</button>}>350      <div className="stack">351        {list.length ? (352          <ul className="nx-list" aria-label={t("nx.contacts.groups")}>353            {list.map((g) => (354              <GroupRow key={g.id} g={g} />355            ))}356          </ul>357        ) : (358          <p className="nx-note">{t("nx.contacts.groups.none")}</p>359        )}360        <form361          className="nx-ct-groupform new"362          onSubmit={(e) => {363            e.preventDefault()364            void add()365          }}366        >367          <div className="field">368            <label htmlFor={id}>{t("nx.contacts.groups.new")}</label>369            <input id={id} className="input" value={name} maxLength={60} autoComplete="off" data-autofocus onChange={(e) => setName(e.target.value)} />370          </div>371          <Swatches value={color} onChange={setColor} label={t("nx.contacts.groups.color")} />372          <div className="row">373            <button type="submit" className="btn primary" disabled={!name.trim() || !online} title={online ? undefined : t("nx.offline")}>374              <Icon name="plus" />375              <span>{t("nx.contacts.groups.create")}</span>376            </button>377          </div>378        </form>379      </div>380    </Dialog>381  )382}383384// ---------------------------------------------------------------- résumé d'un import385function ImportedDialog({ result }: { result: ImportResult }) {386  return (387    <Dialog title={t("nx.contacts.imported.title")} onClose={closeContactDialog} footer={<button type="button" className="btn primary" data-autofocus onClick={closeContactDialog}>{t("common.close")}</button>}>388      <dl className="nx-ct-stats" data-testid="import-result">389        <div>390          <dt>{t("nx.contacts.imported.created")}</dt>391          <dd>{result.imported}</dd>392        </div>393        <div>394          <dt>{t("nx.contacts.imported.updated")}</dt>395          <dd>{result.updated}</dd>396        </div>397        <div>398          <dt>{t("nx.contacts.imported.skipped")}</dt>399          <dd>{result.skipped}</dd>400        </div>401      </dl>402      <p className="nx-note">{t("nx.contacts.imported.note", { n: result.total })}</p>403    </Dialog>404  )405}406407export function ContactDialogs() {408  const dialog = useStore(CU, (s) => s.dialog)409  if (!dialog) return null410  if (dialog.type === "edit") return <EditDialog key={dialog.contact?.id ?? "new"} contact={dialog.contact} init={dialog.init} />411  if (dialog.type === "duplicates") return <DuplicatesDialog />412  if (dialog.type === "groups") return <GroupsDialog />413  return <ImportedDialog result={dialog.result} />414}415
Files main
Menu

Theme