SPB Git

Repository Public

CommandPalette.tsx 10.2 KB 201 lines tsx

1// Palette de commandes (⌘K / Ctrl-K) : recherche approximative dans les commandes, dossiers, boîtes et recherches récentes.2// Préfixes : « > » commandes, « / » recherche dans le courrier, « @ » contacts et « # » libellés (sources inscrites par les3// modules à venir). Modèle ARIA combobox + listbox ; le focus revient à l'élément d'origine à la fermeture.4import { useEffect, useId, useMemo, useRef, useState } from "react"5import { t } from "../i18n"6import { fuzzyRank } from "../mail/fuzzy"7import { S, routeHref } from "../state/app"8import { folderLabel, sortedFolders, viewOfFolder } from "../state/mail"9import { R, type PaletteItem, type PalettePrefix } from "../state/registry"10import { navigate, rememberSearch } from "../state/session"11import { useStore } from "../state/store"12import { builtinCommands, type CommandSection } from "./commands"13import { Icon, useModal } from "./kit"1415interface Group {16  id: string17  label: string18  items: PaletteItem[]19}20const SECTION_LABEL: Record<CommandSection, "palette.section.actions" | "palette.section.go" | "palette.section.view" | "palette.section.settings"> = { actions: "palette.section.actions", go: "palette.section.go", view: "palette.section.view", settings: "palette.section.settings" }21const SECTIONS: CommandSection[] = ["actions", "go", "view", "settings"]2223function runSearch(q: string) {24  const query = q.trim()25  if (!query) return26  const s = S.get()27  rememberSearch(query)28  navigate(routeHref({ name: "mail", mbIndex: s.route.name === "mail" ? s.route.mbIndex : 0, view: "search", threadId: null, q: query }))29}3031/** Dossiers de la boîte courante, autres boîtes : destinations proposées sans préfixe. */32function placeItems(): { folders: PaletteItem[]; mailboxes: PaletteItem[] } {33  const s = S.get()34  const me = s.me35  if (!me) return { folders: [], mailboxes: [] }36  const index = Math.max(0, me.mailboxes.findIndex((m) => m.id === s.mb))37  const account = s.mb ? s.accounts[s.mb] : undefined38  const { system, custom } = sortedFolders(account)39  const folders = [...system, ...custom].map((f) => ({40    id: `folder.${f.id}`, title: folderLabel(f), subtitle: me.mailboxes[index]?.address, icon: "folder" as const,41    run: () => navigate(routeHref({ name: "mail", mbIndex: index, view: viewOfFolder(f), threadId: null, q: "" })),42  }))43  const mailboxes = me.mailboxes.map((m, i) => ({44    id: `mailbox.${m.id}`, title: m.address, subtitle: m.display_name || undefined, icon: "mail" as const, keywords: [m.display_name],45    run: () => navigate(routeHref({ name: "mail", mbIndex: i, view: "inbox", threadId: null, q: "" })),46  }))47  return { folders, mailboxes }48}4950function useGroups(input: string): { groups: Group[]; hint: string | null } {51  const recent = useStore(S, (s) => s.device.recentSearches)52  const providers = useStore(R, (r) => r.palette)53  const prefix = (["@", "#", ">", "/"] as const).find((p) => input.startsWith(p)) ?? ""54  const query = (prefix ? input.slice(1) : input).trim()55  // les commandes sont figées à l'ouverture : la palette ne se réordonne pas sous le curseur56  const commands = useMemo(builtinCommands, [])57  const places = useMemo(placeItems, [])58  const [provided, setProvided] = useState<PaletteItem[]>([])59  const provider = prefix === "@" || prefix === "#" ? providers[prefix as PalettePrefix] : undefined60  useEffect(() => {61    if (!provider) return setProvided([])62    const ctrl = new AbortController()63    void Promise.resolve(provider(query, ctrl.signal)).then(64      (items) => {65        if (!ctrl.signal.aborted) setProvided(items)66      },67      () => {68        if (!ctrl.signal.aborted) setProvided([])69      },70    )71    return () => ctrl.abort()72  }, [provider, query])7374  return useMemo(() => {75    const rank = (items: PaletteItem[], limit = 40) => fuzzyRank(query, items, (i) => [i.title, ...(i.subtitle ? [i.subtitle] : []), ...(i.keywords ?? [])], limit)76    const recentItems: PaletteItem[] = recent.map((q) => ({ id: `recent.${q}`, title: q, icon: "clock" as const, run: () => runSearch(q) }))77    const searchItem: PaletteItem[] = query ? [{ id: "search.run", title: t("palette.searchFor", { query }), icon: "search" as const, run: () => runSearch(query) }] : []78    if (prefix === "/") {79      const groups = [{ id: "search", label: t("palette.section.search"), items: searchItem }, { id: "recent", label: t("palette.section.recent"), items: rank(recentItems, 8) }]80      return { groups: groups.filter((g) => g.items.length), hint: query || recent.length ? null : t("palette.hint.search") }81    }82    if (prefix === "@" || prefix === "#") {83      const label = prefix === "@" ? t("palette.section.contacts") : t("palette.section.labels")84      if (!provider) return { groups: [], hint: prefix === "@" ? t("palette.hint.contacts") : t("palette.hint.labels") }85      return { groups: provided.length ? [{ id: "provided", label, items: provided.slice(0, 40) }] : [], hint: provided.length ? null : t("palette.empty") }86    }87    const groups: Group[] = SECTIONS.map((sec) => ({ id: sec, label: t(SECTION_LABEL[sec]), items: rank(commands.filter((c) => c.section === sec), query ? 12 : 40) }))88    if (prefix !== ">") {89      // sans requête : les commandes d'abord ; avec : les destinations qui correspondent passent devant les réglages90      groups.splice(2, 0, { id: "folders", label: t("palette.section.folders"), items: rank(places.folders, query ? 8 : 0) }, { id: "mailboxes", label: t("palette.section.mailboxes"), items: rank(places.mailboxes, query ? 8 : 0) })91      groups.push({ id: "recent", label: t("palette.section.recent"), items: rank(recentItems, query ? 4 : 5) }, { id: "search", label: t("palette.section.search"), items: searchItem })92    }93    const shown = groups.filter((g) => g.items.length)94    return { groups: shown, hint: shown.length ? null : t("palette.empty") }95  }, [prefix, query, commands, places, recent, provider, provided])96}9798export default function CommandPalette() {99  const close = () => S.set({ paletteOpen: false })100  const ref = useModal(close)101  const [input, setInput] = useState("")102  const [active, setActive] = useState(0)103  const { groups, hint } = useGroups(input)104  const flat = useMemo(() => groups.flatMap((g) => g.items), [groups])105  const ids = { list: useId(), label: useId(), hint: useId() }106  const listRef = useRef<HTMLDivElement>(null)107  const index = Math.min(active, Math.max(0, flat.length - 1))108  const optionId = (i: number) => `${ids.list}-o${i}`109110  useEffect(() => setActive(0), [input])111  useEffect(() => {112    listRef.current?.querySelector(`[id="${optionId(index)}"]`)?.scrollIntoView({ block: "nearest" })113  })114115  const run = (item: PaletteItem | undefined) => {116    if (!item) return117    close()118    // après le démontage : le focus est d'abord rendu à l'élément d'origine, puis la commande agit (elle peut le déplacer)119    setTimeout(item.run, 0)120  }121122  let n = 0123  return (124    <div className="overlay palette-overlay" onMouseDown={(e) => e.target === e.currentTarget && close()}>125      <div ref={ref} className="palette" role="dialog" aria-modal="true" aria-labelledby={ids.label} tabIndex={-1}>126        <h2 id={ids.label} className="sr-only">127          {t("palette.title")}128        </h2>129        <div className="palette-input">130          <Icon name="search" />131          <input132            data-autofocus133            type="text"134            role="combobox"135            aria-expanded="true"136            aria-controls={ids.list}137            aria-autocomplete="list"138            aria-activedescendant={flat.length ? optionId(index) : undefined}139            aria-labelledby={ids.label}140            aria-describedby={ids.hint}141            placeholder={t("palette.placeholder")}142            autoComplete="off"143            autoCapitalize="off"144            spellCheck={false}145            value={input}146            onChange={(e) => setInput(e.target.value)}147            onKeyDown={(e) => {148              if (e.key === "ArrowDown" || e.key === "ArrowUp") {149                e.preventDefault()150                if (flat.length) setActive((index + (e.key === "ArrowDown" ? 1 : -1) + flat.length) % flat.length)151              } else if (e.key === "Home" && flat.length && !input) {152                e.preventDefault()153                setActive(0)154              } else if (e.key === "End" && flat.length && !input) {155                e.preventDefault()156                setActive(flat.length - 1)157              } else if (e.key === "PageDown" || e.key === "PageUp") {158                e.preventDefault()159                if (flat.length) setActive(Math.max(0, Math.min(flat.length - 1, index + (e.key === "PageDown" ? 8 : -8))))160              } else if (e.key === "Enter") {161                e.preventDefault()162                run(flat[index])163              }164            }}165          />166          <kbd className="palette-esc">Esc</kbd>167        </div>168        <div ref={listRef} id={ids.list} className="palette-list" role="listbox" aria-labelledby={ids.label}>169          {groups.map((g) => (170            <div key={g.id} role="group" aria-labelledby={`${ids.list}-g${g.id}`} className="palette-group">171              <div id={`${ids.list}-g${g.id}`} className="palette-section" role="presentation">172                {g.label}173              </div>174              {g.items.map((item) => {175                const i = n++176                return (177                  <div key={item.id} id={optionId(i)} role="option" aria-selected={i === index} className={`palette-item${i === index ? " active" : ""}`} data-command={item.id} onMouseMove={() => i !== index && setActive(i)} onClick={() => run(item)}>178                    {item.icon ? <Icon name={item.icon} /> : <span className="icon" />}179                    <span className="palette-title truncate">{item.title}</span>180                    {item.subtitle ? <span className="palette-sub truncate">{item.subtitle}</span> : null}181                    {item.keys ? (182                      <span className="palette-keys">183                        {item.keys.split(" ").map((k, j) => (184                          <kbd key={j}>{k}</kbd>185                        ))}186                      </span>187                    ) : null}188                  </div>189                )190              })}191            </div>192          ))}193        </div>194        <p id={ids.hint} className={`palette-hint${hint ? " empty" : ""}`} role={hint ? "status" : undefined}>195          {hint ?? t("palette.footer")}196        </p>197      </div>198    </div>199  )200}201
Files main
Menu

Theme