SPB Git

Repository Public

ContactsScreen.tsx 11.4 KB 267 lines tsx

1// SP Mail Next — écran « Contacts » : liste (recherche, filtres, suggestions) et fiche côte à côte ; une colonne avec retour sur téléphone ; dépôt d'un fichier .vcf.2import { useEffect, useRef, useState } from "react"3import { t } from "../../i18n"4import { CT, CU, contactTitle, exportVcf, groups, importVcf, loadContacts, loadMoreContacts, openCard, saveSuggestion, setFilter, vcfProblem, colorToken, type Contact, type KindFilter } from "../../next/contacts"5import { saveBlob } from "../../next/attachments"6import { nextHref } from "../../next/nav"7import { S, toast } from "../../state/app"8import { linkProps } from "../../state/session"9import { shallowEqual, useStore } from "../../state/store"10import { Icon, MenuButton, Spinner } from "../kit"11import { ContactAvatar, attempt, contactError, useOnline } from "./ContactBits"12import { ContactCard } from "./ContactCard"13import { ContactDialogs } from "./ContactDialogs"1415const KINDS: KindFilter[] = ["all", "saved", "suggested"]1617/** Lit et envoie un fichier .vcf choisi ou déposé ; le résumé s'affiche dans un dialogue. */18async function importFile(file: File) {19  const problem = vcfProblem(file)20  if (problem) return void toast({ kind: "error", text: t(problem === "type" ? "nx.contacts.err.vcfType" : problem === "empty" ? "nx.contacts.err.vcard" : "nx.contacts.err.vcfTooLarge") })21  if (!S.get().online) return void toast({ kind: "error", text: t("nx.offline") })22  try {23    const result = await importVcf(file)24    CU.set({ dialog: { type: "imported", result } })25  } catch (e) {26    toast({ kind: "error", text: contactError(e) })27  }28}29async function exportAll() {30  await attempt(async () => saveBlob(await exportVcf(), "contacts.vcf"), t("nx.contacts.exported"))31}3233function Row({ c, current }: { c: Contact; current: boolean }) {34  const online = useOnline()35  const title = contactTitle(c) || t("nx.contacts.unnamed")36  const second = c.name.trim() ? [c.emails[0]?.email, c.organization].filter(Boolean).join(" · ") : (c.organization ?? "")37  return (38    <li className="nx-ct-row" data-kind={c.kind}>39      <a {...linkProps(nextHref("contacts", c.id))} className="nx-ct-row-link" aria-current={current ? "page" : undefined}>40        <ContactAvatar contact={c} />41        <span className="nx-item-main">42          <span className="nx-ct-row-name">43            <span className="truncate">{title}</span>44            {c.favorite ? <Icon name="star" small className="nx-ct-fav" /> : null}45            {c.vip ? <span className="badge accent">{t("nx.contacts.vip")}</span> : null}46          </span>47          {second ? <span className="small truncate">{second}</span> : null}48        </span>49      </a>50      {c.kind === "suggested" ? (51        <button type="button" className="btn small nx-ct-add" disabled={!online} title={online ? undefined : t("nx.offline")} aria-label={t("nx.contacts.addNamed", { name: title })} onClick={() => void attempt(() => saveSuggestion(c.id), t("nx.contacts.added"))}>52          <Icon name="userPlus" small />53          <span>{t("nx.contacts.add")}</span>54        </button>55      ) : null}56    </li>57  )58}5960function Skeleton() {61  return (62    <ul className="nx-list" aria-hidden="true">63      {[0, 1, 2, 3, 4, 5].map((i) => (64        <li key={i} className="nx-ct-row">65          <span className="nx-ct-row-link">66            <span className="skeleton nx-ct-avatar" />67            <span className="nx-item-main">68              <span className="skeleton nx-ct-skel" style={{ width: `${46 + ((i * 17) % 30)}%` }} />69              <span className="skeleton nx-ct-skel thin" style={{ width: `${30 + ((i * 23) % 30)}%` }} />70            </span>71          </span>72        </li>73      ))}74    </ul>75  )76}7778export default function ContactsScreen() {79  const id = useStore(S, (s) => (s.route.name === "next" && s.route.page === "contacts" ? s.route.id : null))80  const st = useStore(CT, (s) => ({ items: s.items, next: s.next, status: s.status, error: s.error, loadingMore: s.loadingMore, filter: s.filter }), shallowEqual)81  const groupList = groups.use()82  const online = useOnline()83  const [q, setQ] = useState(st.filter.q)84  const [dropping, setDropping] = useState(false)85  const fileRef = useRef<HTMLInputElement>(null)86  const sentinel = useRef<HTMLDivElement>(null)87  const dragDepth = useRef(0)8889  useEffect(() => {90    void groups.refresh()91    void loadContacts()92  }, [])93  useEffect(() => {94    void openCard(id)95  }, [id])96  // la saisie filtre après une courte pause97  useEffect(() => {98    if (q.trim() === CT.get().filter.q.trim()) return99    const timer = setTimeout(() => setFilter({ q }), 250)100    return () => clearTimeout(timer)101  }, [q])102  // page suivante quand la fin de la liste devient visible103  useEffect(() => {104    const node = sentinel.current105    if (!node || !st.next || typeof IntersectionObserver === "undefined") return106    const io = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && void loadMoreContacts(), { rootMargin: "200px" })107    io.observe(node)108    return () => io.disconnect()109  }, [st.next, st.items.length])110111  const hasFiles = (e: React.DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes("Files")112  const filtered = !!(st.filter.q.trim() || st.filter.kind !== "all" || st.filter.favorite || st.filter.group)113  return (114    <div115      className="nx-ct"116      data-pane={id ? "card" : "list"}117      onDragEnter={(e) => {118        if (!hasFiles(e)) return119        dragDepth.current++120        setDropping(true)121      }}122      onDragLeave={(e) => {123        if (!hasFiles(e)) return124        if (--dragDepth.current <= 0) setDropping(false)125      }}126      onDragOver={(e) => hasFiles(e) && e.preventDefault()}127      onDrop={(e) => {128        if (!hasFiles(e)) return129        e.preventDefault()130        dragDepth.current = 0131        setDropping(false)132        const file = e.dataTransfer.files[0]133        if (file) void importFile(file)134      }}135    >136      <section className="nx-ct-list" aria-label={t("nx.contacts.list")}>137        <div className="nx-head">138          <h1>{t("nx.contacts.title")}</h1>139          <span className="spacer" />140          <button type="button" className="btn primary" onClick={() => CU.set({ dialog: { type: "edit", contact: null } })}>141            <Icon name="userPlus" />142            <span>{t("nx.contacts.new")}</span>143          </button>144          <MenuButton145            label={t("nx.contacts.more")}146            items={[147              { label: t("nx.contacts.import"), icon: "upload", disabled: !online, onSelect: () => fileRef.current?.click() },148              { label: t("nx.contacts.export"), icon: "download", disabled: !online, onSelect: () => void exportAll() },149              "sep",150              { label: t("nx.contacts.duplicates"), icon: "merge", disabled: !online, onSelect: () => CU.set({ dialog: { type: "duplicates" } }) },151              { label: t("nx.contacts.groups.manage"), icon: "users", onSelect: () => CU.set({ dialog: { type: "groups" } }) },152            ]}153          />154          <input155            ref={fileRef}156            type="file"157            className="sr-only"158            accept=".vcf,.vcard,text/vcard"159            aria-label={t("nx.contacts.importFile")}160            tabIndex={-1}161            onChange={(e) => {162              const file = e.target.files?.[0]163              e.target.value = ""164              if (file) void importFile(file)165            }}166          />167        </div>168        <div className="nx-ct-search">169          <Icon name="search" small />170          <input className="input" type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("nx.contacts.search")} aria-label={t("nx.contacts.search")} maxLength={200} autoComplete="off" spellCheck={false} />171        </div>172        <div className="nx-ct-filters">173          <div className="segmented" role="group" aria-label={t("nx.contacts.filter.kind")}>174            {KINDS.map((k) => (175              <button key={k} type="button" aria-pressed={st.filter.kind === k} onClick={() => setFilter({ kind: k })}>176                {t(`nx.contacts.kind.${k}`)}177              </button>178            ))}179          </div>180          <button type="button" className="nx-chip" aria-pressed={st.filter.favorite} onClick={() => setFilter({ favorite: !st.filter.favorite })}>181            <Icon name="star" />182            {t("nx.contacts.favorites")}183          </button>184        </div>185        {groupList.length ? (186          <div className="nx-ct-groups" role="group" aria-label={t("nx.contacts.groups")}>187            {groupList.map((g) => (188              <button key={g.id} type="button" className="nx-chip" aria-pressed={st.filter.group === g.id} onClick={() => setFilter({ group: st.filter.group === g.id ? null : g.id })}>189                <span className="nx-dot" style={{ background: colorToken(g.color) }} aria-hidden="true" />190                <span className="truncate">{g.name}</span>191                <span className="nx-meta">{g.members}</span>192              </button>193            ))}194          </div>195        ) : null}196        <div className="nx-ct-scroll">197          {st.status === "loading" || st.status === "idle" ? (198            <Skeleton />199          ) : st.status === "error" ? (200            <div className="nx-empty" role="alert">201              <Icon name="warn" />202              <p>{st.error === "offline" ? t("nx.offline") : st.error === "rate_limited" ? t("nx.error.rateLimited") : t("nx.contacts.loadFailed")}</p>203              <button type="button" className="btn" onClick={() => void loadContacts()}>204                {t("nx.retry")}205              </button>206            </div>207          ) : st.items.length === 0 ? (208            <div className="nx-empty">209              <Icon name="users" />210              <p>{filtered ? t("nx.contacts.noMatch") : t("nx.contacts.empty")}</p>211              {filtered ? null : (212                <button type="button" className="btn" onClick={() => CU.set({ dialog: { type: "edit", contact: null } })}>213                  {t("nx.contacts.new")}214                </button>215              )}216            </div>217          ) : (218            <>219              <ul className="nx-list" aria-label={t("nx.contacts.list")}>220                {st.items.map((c) => (221                  <Row key={c.id} c={c} current={c.id === id} />222                ))}223              </ul>224              {st.next ? (225                <div ref={sentinel} className="nx-ct-more">226                  {st.loadingMore ? (227                    <Spinner label={t("nx.loading")} />228                  ) : (229                    <button type="button" className="btn small" onClick={() => void loadMoreContacts()}>230                      {t("nx.contacts.loadMore")}231                    </button>232                  )}233                </div>234              ) : null}235            </>236          )}237        </div>238      </section>239      <section className="nx-ct-card" aria-label={t("nx.contacts.card")}>240        {id ? (241          <>242            <div className="nx-ct-back">243              <a {...linkProps(nextHref("contacts"))} className="btn ghost">244                <Icon name="back" />245                <span>{t("nx.contacts.title")}</span>246              </a>247            </div>248            <ContactCard />249          </>250        ) : (251          <div className="nx-empty nx-ct-none">252            <Icon name="user" />253            <p>{t("nx.contacts.pick")}</p>254          </div>255        )}256      </section>257      {dropping ? (258        <div className="nx-ct-drop" aria-hidden="true">259          <Icon name="upload" />260          <span>{t("nx.contacts.dropHere")}</span>261        </div>262      ) : null}263      <ContactDialogs />264    </div>265  )266}267
Files main
Menu

Theme