Repository Public
1// SP Mail Next — dialogues des libellés : sélecteur (appliquer / retirer, filtrer, créer à la volée), édition (nom et2// couleur parmi les dix teintes), gestion (ordre au clavier, modifier, supprimer).3import { useEffect, useId, useRef, useState } from "react"4import { t } from "../../i18n"5import type { MsgKey } from "../../i18n"6import { LABEL_NAME_MAX, LABEL_PALETTE, cleanName, createLabel, filterLabels, fold, labelColor, labelState, labelsCollection, paletteIndex, updateLabel, type Label, type LabelWriteError } from "../../next/labels"7import { LabelUi, applyLabel, closeLabelUi, confirmDeleteLabel, moveLabelBy, openLabelCreate, openLabelEdit, openLabelManage, type LabelUiState } from "../../next/labelsUi"8import { targetCount } from "../../next/rowmenu"9import { S, toast } from "../../state/app"10import { useStore } from "../../state/store"11import { Icon } from "../kit"12import { Sheet } from "./RowMenuSheet"13import "./labels.css"1415const ERR: Record<LabelWriteError, MsgKey> = { name_taken: "nx.labels.err.taken", limit_reached: "nx.labels.err.limit", offline: "nx.offline", error: "nx.labels.err.failed" }16const colorName = (n: number) => t(`nx.labels.color.${n}` as MsgKey)1718// ---------------------------------------------------------------- sélecteur19function Check({ label, state, disabled, onToggle }: { label: Label; state: "all" | "some" | "none"; disabled: boolean; onToggle: (on: boolean) => void }) {20 const ref = useRef<HTMLInputElement>(null)21 useEffect(() => {22 if (ref.current) ref.current.indeterminate = state === "some"23 }, [state])24 return (25 <li>26 <label className="check nx-label-opt" data-label={label.name}>27 <input ref={ref} type="checkbox" checked={state === "all"} disabled={disabled} onChange={() => onToggle(state !== "all")} />28 <span className="label-dot" style={{ background: labelColor(label.color) }} aria-hidden="true" />29 <span className="truncate">{label.name}</span>30 </label>31 </li>32 )33}3435function Picker({ picker }: { picker: NonNullable<LabelUiState["picker"]> }) {36 const labels = labelsCollection.use()37 const online = useStore(S, (s) => s.online && !s.offlineShell)38 const [q, setQ] = useState("")39 const [over, setOver] = useState<Record<string, boolean>>({})40 const [error, setError] = useState<string | null>(null)41 const [busy, setBusy] = useState(false)42 const list = useRef<HTMLUListElement>(null)43 const inputId = useId()44 const shown = filterLabels(labels, q)45 const name = cleanName(q)46 const canCreate = !!name && !labels.some((l) => fold(l.name) === fold(name))47 const stateOf = (l: Label) => (l.keyword in over ? (over[l.keyword] ? "all" : "none") : labelState(l.keyword, picker.keywords))48 const toggle = (l: Label, on: boolean) => {49 setOver((o) => ({ ...o, [l.keyword]: on }))50 void applyLabel(l, on, picker.targets).then((ok) => {51 if (!ok) setOver((o) => ({ ...o, [l.keyword]: !on }))52 })53 }54 const create = async () => {55 if (!name || busy) return56 setBusy(true)57 const r = await createLabel(name)58 setBusy(false)59 if (!r.ok) return setError(t(ERR[r.error]))60 setError(null)61 setQ("")62 toggle(r.label, true)63 }64 const close = () => closeLabelUi("picker")65 const n = targetCount(picker.targets)66 return (67 <Sheet68 title={t("nx.labels.pickerTitle")}69 sub={t("nx.labels.pickerCount", { n })}70 onClose={close}71 testid="label-picker"72 footer={73 <>74 <button type="button" className="btn ghost" onClick={openLabelManage}>75 {t("nx.labels.manage")}76 </button>77 <span className="spacer" />78 <button type="button" className="btn primary" onClick={close}>79 {t("nx.labels.done")}80 </button>81 </>82 }83 >84 <div className="stack nx-label-picker">85 <label className="sr-only" htmlFor={inputId}>86 {t("nx.labels.filter")}87 </label>88 <input89 id={inputId}90 className="input"91 data-autofocus92 value={q}93 maxLength={LABEL_NAME_MAX}94 placeholder={t("nx.labels.filterPlaceholder")}95 autoComplete="off"96 spellCheck={false}97 onChange={(e) => {98 setQ(e.target.value)99 setError(null)100 }}101 onKeyDown={(e) => {102 if (e.key === "ArrowDown") {103 e.preventDefault()104 list.current?.querySelector<HTMLElement>("input:not([disabled])")?.focus()105 } else if (e.key === "Enter") {106 e.preventDefault()107 // Entrée : bascule le seul libellé affiché (ou celui du nom exact) ; sinon crée le libellé tapé108 const exact = shown.find((l) => fold(l.name) === fold(q)) ?? (shown.length === 1 ? shown[0] : null)109 if (exact) toggle(exact, stateOf(exact) !== "all")110 else if (canCreate && online) void create()111 }112 }}113 />114 {!online ? (115 <p className="nx-note" role="status" data-nx-offline-note="">116 {t("nx.labels.offlineQueued")}117 </p>118 ) : null}119 {shown.length ? (120 <ul121 ref={list}122 className="nx-label-list"123 aria-label={t("nx.labels.pickerTitle")}124 onKeyDown={(e) => {125 if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return126 e.preventDefault()127 const boxes = Array.from(list.current?.querySelectorAll<HTMLElement>("input:not([disabled])") ?? [])128 const i = boxes.indexOf(document.activeElement as HTMLElement)129 if (e.key === "ArrowUp" && i <= 0) document.getElementById(inputId)?.focus()130 else boxes[Math.min(boxes.length - 1, i + (e.key === "ArrowDown" ? 1 : -1))]?.focus()131 }}132 >133 {shown.map((l) => (134 <Check key={l.id} label={l} state={stateOf(l)} disabled={false} onToggle={(on) => toggle(l, on)} />135 ))}136 </ul>137 ) : (138 <p className="nx-note nx-label-none">{labels.length ? t("nx.labels.noMatch") : t("nx.labels.none")}</p>139 )}140 {canCreate ? (141 <button type="button" className="btn nx-label-create" disabled={busy || !online} onClick={() => void create()}>142 <Icon name="plus" small />143 <span className="truncate">{t("nx.labels.createNamed", { name: name ?? "" })}</span>144 </button>145 ) : null}146 {error ? (147 <p className="nx-label-error" role="alert">148 {error}149 </p>150 ) : null}151 </div>152 </Sheet>153 )154}155156// ---------------------------------------------------------------- création / modification157function Edit({ edit }: { edit: NonNullable<LabelUiState["edit"]> }) {158 const count = useStore(labelsCollection.store, (s) => s.items.length)159 const online = useStore(S, (s) => s.online)160 const [name, setName] = useState(edit.name)161 const [hue, setHue] = useState(() => (edit.label ? paletteIndex(edit.label.color) : (count % LABEL_PALETTE.length) + 1))162 const [error, setError] = useState<string | null>(null)163 const [busy, setBusy] = useState(false)164 const nameId = useId()165 const errId = useId()166 const close = () => closeLabelUi("edit")167 const submit = async () => {168 const clean = cleanName(name)169 if (!clean) return setError(t("nx.labels.err.name"))170 setBusy(true)171 const color = LABEL_PALETTE[hue - 1]172 const r = edit.label ? await updateLabel(edit.label.id, { ...(clean !== edit.label.name ? { name: clean } : {}), ...(paletteIndex(edit.label.color) !== hue || !LABEL_PALETTE.includes(edit.label.color as (typeof LABEL_PALETTE)[number]) ? { color } : {}) }) : await createLabel(clean, color)173 setBusy(false)174 if (!r.ok) return setError(t(ERR[r.error]))175 toast({ kind: "success", text: edit.label ? t("nx.labels.saved") : t("nx.labels.created", { name: r.label.name }) })176 close()177 if (edit.applyTo) void applyLabel(r.label, true, edit.applyTo)178 }179 return (180 <Sheet title={edit.label ? t("nx.labels.editTitle") : t("nx.labels.new")} onClose={close} testid="label-edit">181 <form182 className="stack nx-label-form"183 onSubmit={(e) => {184 e.preventDefault()185 void submit()186 }}187 >188 <div className="field">189 <label htmlFor={nameId}>{t("nx.labels.name")}</label>190 <input191 id={nameId}192 className="input"193 data-autofocus194 value={name}195 maxLength={LABEL_NAME_MAX}196 autoComplete="off"197 aria-invalid={error ? true : undefined}198 aria-describedby={error ? errId : undefined}199 onChange={(e) => {200 setName(e.target.value)201 setError(null)202 }}203 />204 {error ? (205 <p id={errId} className="nx-label-error" role="alert">206 {error}207 </p>208 ) : null}209 </div>210 <fieldset className="nx-swatches">211 <legend>{t("nx.labels.color")}</legend>212 <div className="nx-swatch-row">213 {LABEL_PALETTE.map((_, i) => (214 <label key={i} className="nx-swatch" title={colorName(i + 1)} style={{ "--lc": `var(--label-${i + 1})` } as React.CSSProperties}>215 <input type="radio" name="label-color" className="sr-only" value={i + 1} checked={hue === i + 1} onChange={() => setHue(i + 1)} aria-label={colorName(i + 1)} />216 <span className="nx-swatch-dot" aria-hidden="true">217 {hue === i + 1 ? <Icon name="check" small /> : null}218 </span>219 </label>220 ))}221 </div>222 </fieldset>223 {!online ? (224 <p className="nx-note" role="status">225 {t("nx.offline")}226 </p>227 ) : null}228 <div className="row nx-label-form-foot">229 <span className="spacer" />230 <button type="button" className="btn" onClick={close}>231 {t("nx.labels.cancel")}232 </button>233 <button type="submit" className="btn primary" disabled={busy || !online}>234 {edit.label ? t("nx.labels.save") : t("nx.labels.create")}235 </button>236 </div>237 </form>238 </Sheet>239 )240}241242// ---------------------------------------------------------------- gestion243function Manage() {244 const labels = labelsCollection.use()245 const online = useStore(S, (s) => s.online)246 const [said, setSaid] = useState("")247 const close = () => closeLabelUi("manage")248 const move = async (l: Label, delta: number) => {249 const msg = await moveLabelBy(l, delta)250 if (msg) setSaid(msg)251 }252 // un bouton en butée reste focalisable (aria-disabled) : le focus ne se perd pas quand le libellé arrive en tête ou en queue253 const step = (l: Label, delta: number, i: number) => {254 const blocked = !online || (delta < 0 ? i === 0 : i === labels.length - 1)255 return (256 <button type="button" className="icon-btn" aria-label={t(delta < 0 ? "nx.labels.moveUpNamed" : "nx.labels.moveDownNamed", { name: l.name })} title={t(delta < 0 ? "nx.labels.moveUp" : "nx.labels.moveDown")} aria-disabled={blocked || undefined} onClick={() => !blocked && void move(l, delta)}>257 <Icon name={delta < 0 ? "arrowUp" : "arrowDown"} />258 </button>259 )260 }261 return (262 <Sheet263 title={t("nx.labels.manage")}264 onClose={close}265 testid="label-manage"266 footer={267 <>268 <button type="button" className="btn" disabled={!online} onClick={() => openLabelCreate()}>269 <Icon name="plus" small />270 <span>{t("nx.labels.new")}</span>271 </button>272 <span className="spacer" />273 <button type="button" className="btn primary" onClick={close}>274 {t("nx.labels.done")}275 </button>276 </>277 }278 >279 <p className="nx-note">{online ? t("nx.labels.manageHint") : t("nx.offline")}</p>280 {labels.length ? (281 <ul className="nx-label-manage">282 {labels.map((l, i) => (283 <li key={l.id} data-label={l.name}>284 <span className="label-dot" style={{ background: labelColor(l.color) }} aria-hidden="true" />285 <span className="truncate nx-label-manage-name">{l.name}</span>286 {step(l, -1, i)}287 {step(l, 1, i)}288 <button type="button" className="icon-btn" aria-label={t("nx.labels.editNamed", { name: l.name })} title={t("nx.labels.rename")} disabled={!online} onClick={() => openLabelEdit(l)}>289 <Icon name="edit" />290 </button>291 <button type="button" className="icon-btn" aria-label={t("nx.labels.deleteNamed", { name: l.name })} title={t("nx.labels.delete")} disabled={!online} onClick={() => void confirmDeleteLabel(l)}>292 <Icon name="trash" />293 </button>294 </li>295 ))}296 </ul>297 ) : (298 <p className="nx-note nx-label-none">{t("nx.labels.none")}</p>299 )}300 <span className="sr-only" role="status" aria-live="polite">301 {said}302 </span>303 </Sheet>304 )305}306307export default function LabelDialogs() {308 const ui = useStore(LabelUi, (s) => s)309 // un seul dialogue à la fois : l'édition passe devant la gestion ou le sélecteur, qui se rouvrent à sa fermeture310 if (ui.edit) return <Edit key={ui.edit.label?.id ?? "new"} edit={ui.edit} />311 if (ui.manage) return <Manage />312 if (ui.picker) return <Picker picker={ui.picker} />313 return null314}315