SPB Git

Repository Public

Omnibox.tsx 16.7 KB 436 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SPSearch8 * File             : web/search/src/Omnibox.tsx9 * Module           : web10 * Repository       : https://git.spboucher.ai/spweb11 * Project Website  : https://search.spboucher.ai12 * Created          : 2026-11-2713 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { useEffect, useId, useMemo, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from 'react';44import { api, safeHref, useDebounced, useLang } from '@spweb/shared-ui';45import { useT } from './i18n/core';46import { Icon } from './icons';47import { Favicon } from './Favicon';48import { clearHistory, forget, parseRecent, setPref, usePref } from './prefs';49import { speechSupported, useDictation } from './voice';5051/** One row of the panel. `history` comes from this browser; the three others from /v2/autocomplete. */52type Item =53  | { k: 'history'; text: string }54  | { k: 'completion'; text: string }55  | { k: 'correction'; text: string }56  | { k: 'site'; text: string; url: string; title: string };5758const IS_MAC = /Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent);5960/** Reads /v2/autocomplete defensively: unknown types and malformed rows are dropped. */61function readSuggestions(body: unknown): Item[] {62  const list = (body as { suggestions?: unknown } | null)?.suggestions;63  if (!Array.isArray(list)) return [];64  const out: Item[] = [];65  for (const s of list as { text?: unknown; type?: unknown; url?: unknown; title?: unknown }[]) {66    if (!s || typeof s.text !== 'string' || s.text.trim() === '') continue;67    if (s.type === 'site') {68      const url = safeHref(s.url);69      if (url) out.push({ k: 'site', text: s.text, url, title: typeof s.title === 'string' ? s.title : '' });70    } else if (s.type === 'correction') out.push({ k: 'correction', text: s.text });71    else if (s.type === 'completion' || s.type === undefined) out.push({ k: 'completion', text: s.text });72  }73  return out.slice(0, 8);74}7576/** The part already typed stays plain; what the suggestion adds carries the weight. */77function completed(s: string, typed: string): ReactNode {78  const q = typed.trim().toLowerCase();79  if (q !== '' && s.toLowerCase().startsWith(q) && s.length > q.length) {80    return <>{s.slice(0, q.length)}<b>{s.slice(q.length)}</b></>;81  }82  return s;83}8485/**86 * The search bar: an ARIA 1.2 combobox. Its panel unfolds inside the same surface and lists, in87 * this order, matching entries of the local history, then what /v2/autocomplete returns88 * (completions, sites, corrections — each drawn differently). "/" and ⌘K / Ctrl K focus it from89 * anywhere; Escape closes the panel, then empties the field.90 */91export function Omnibox({ initial, onSearch, autoFocus, hero }: {92  initial: string;93  onSearch: (q: string) => void;94  autoFocus?: boolean;95  hero?: boolean;96}) {97  const { t } = useT();98  const lang = useLang();99  const [value, setValue] = useState(initial);100  const [remote, setRemote] = useState<Item[]>([]);101  const [open, setOpen] = useState(false);102  const [active, setActive] = useState(-1);103  const [ask, setAsk] = useState(false);104  const input = useRef<HTMLInputElement>(null);105  const typed = useRef(false);106  const id = useId();107  const listId = `${id}-l`;108  const debounced = useDebounced(value.trim(), 140);109  const historyPref = usePref('history');110  const recentRaw = usePref('recent');111  const recent = useMemo(() => parseRecent(recentRaw), [recentRaw]);112  const voicePref = usePref('voice');113  const newTab = usePref('newtab') === '1';114115  useEffect(() => {116    setValue(initial);117    typed.current = false;118    setRemote([]);119    setOpen(false);120  }, [initial]);121122  useEffect(() => {123    if (autoFocus && window.matchMedia('(pointer: fine)').matches) input.current?.focus({ preventScroll: true });124  }, [autoFocus]);125126  // Suggestions: debounced; a request in flight is aborted when the text changes.127  useEffect(() => {128    if (!typed.current || Array.from(debounced).length < 2) {129      setRemote([]);130      return;131    }132    const ctl = new AbortController();133    api<unknown>(`/v2/autocomplete?q=${encodeURIComponent(debounced)}&hl=${lang}`, { signal: ctl.signal }).then(134      (r) => {135        setRemote(readSuggestions(r));136        setActive(-1);137      },138      () => {139        // An enhancement only: when the endpoint fails the list stays empty.140        if (!ctl.signal.aborted) setRemote([]);141      },142    );143    return () => ctl.abort();144  }, [debounced, lang]);145146  useEffect(() => {147    const onKey = (e: globalThis.KeyboardEvent) => {148      const cmdK = (e.metaKey || e.ctrlKey) && !e.altKey && e.key.toLowerCase() === 'k';149      const slash = e.key === '/' && !e.metaKey && !e.ctrlKey && !e.altKey;150      if (!cmdK && !slash) return;151      const el = e.target instanceof HTMLElement ? e.target : null;152      if (slash && el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName))) return;153      if (document.querySelector('dialog[open]')) return;154      e.preventDefault();155      input.current?.focus();156      input.current?.select();157      setOpen(true);158    };159    window.addEventListener('keydown', onKey);160    return () => window.removeEventListener('keydown', onKey);161  }, []);162163  const go = (q: string) => {164    const s = q.trim();165    if (!s) return;166    typed.current = false;167    setOpen(false);168    setRemote([]);169    setActive(-1);170    setValue(s);171    input.current?.blur();172    onSearch(s);173  };174175  const dictation = useDictation(lang, (text, final) => {176    typed.current = true;177    setValue(text);178    if (final) go(text);179  });180  const canSpeak = speechSupported && voicePref !== '0';181182  const items = useMemo<Item[]>(() => {183    const q = value.trim().toLowerCase();184    const mine = historyPref === '0' ? [] : recent.filter((h) => (q === '' ? true : h.toLowerCase().includes(q) && h.toLowerCase() !== q));185    const hist: Item[] = mine.slice(0, q === '' ? 6 : 2).map((text) => ({ k: 'history', text }));186    if (q === '') return hist;187    const seen = new Set(hist.map((h) => h.text.toLowerCase()));188    return [...hist, ...remote.filter((r) => r.k === 'site' || !seen.has(r.text.toLowerCase()))].slice(0, 8);189  }, [value, remote, recent, historyPref]);190191  const showPanel = open && (items.length > 0 || ask || dictation.error !== null);192193  const choose = (it: Item) => {194    if (it.k !== 'site') {195      go(it.text);196      return;197    }198    setOpen(false);199    if (newTab) window.open(it.url, '_blank', 'noopener,noreferrer');200    else window.location.assign(it.url);201  };202203  const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {204    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {205      if (!open) {206        e.preventDefault();207        setOpen(true);208        return;209      }210      if (items.length === 0) return;211      e.preventDefault();212      // -1 is the text field itself: the selection cycles through it.213      const n = items.length + 1;214      setActive((a) => ((a + 1 + (e.key === 'ArrowDown' ? 1 : n - 1)) % n) - 1);215    } else if (e.key === 'Enter' && open && active >= 0 && items[active]) {216      e.preventDefault();217      choose(items[active]);218    } else if (e.key === 'Delete' && e.shiftKey && open && items[active]?.k === 'history') {219      e.preventDefault();220      forget(items[active].text);221      setActive(-1);222    } else if (e.key === 'Escape') {223      if (open && (showPanel || active >= 0)) {224        e.preventDefault();225        setOpen(false);226        setActive(-1);227        setAsk(false);228      } else if (value !== '') {229        e.preventDefault();230        setValue('');231      }232    }233  };234235  const onSubmit = (e: FormEvent) => {236    e.preventDefault();237    go(value);238  };239240  const onMic = () => {241    if (dictation.listening) {242      dictation.stop();243      return;244    }245    if (voicePref !== '1') {246      // First use: say plainly who does the transcription before the microphone is requested.247      setAsk(true);248      setOpen(true);249      return;250    }251    dictation.start();252  };253254  const historyShown = items.some((i) => i.k === 'history');255  const cls = ['omni', hero ? 'omni-hero' : '', showPanel ? 'omni-open' : ''].filter(Boolean).join(' ');256  return (257    <form role="search" className={cls} onSubmit={onSubmit} action="/search" method="get">258      <label className="sr-only" htmlFor={id}>{t('box.label')}</label>259      <div260        className="omni-shell"261        onBlur={(e) => {262          if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {263            setOpen(false);264            setActive(-1);265            setAsk(false);266          }267        }}268      >269        <div className="omni-row">270          <span className="omni-lens"><Icon name="search" size={hero ? 22 : 20} /></span>271          <input272            id={id}273            ref={input}274            name="q"275            type="text"276            inputMode="search"277            enterKeyHint="search"278            role="combobox"279            aria-expanded={showPanel && items.length > 0}280            aria-controls={listId}281            aria-autocomplete="list"282            aria-activedescendant={showPanel && active >= 0 ? `${id}-o${active}` : undefined}283            aria-keyshortcuts="/ Meta+K Control+K"284            autoComplete="off"285            autoCapitalize="off"286            autoCorrect="off"287            spellCheck={false}288            maxLength={256}289            placeholder={dictation.listening ? t('voice.listening') : t('box.placeholder')}290            value={value}291            onChange={(e) => {292              typed.current = true;293              setValue(e.target.value);294              setOpen(true);295              setActive(-1);296            }}297            onPointerDown={() => setOpen(true)}298            onKeyDown={onKeyDown}299          />300          {value !== '' && (301            <button302              type="button"303              className="omni-btn"304              aria-label={t('box.clear')}305              title={t('box.clear')}306              onClick={() => {307                typed.current = false;308                setValue('');309                setRemote([]);310                input.current?.focus();311                setOpen(true);312              }}313            >314              <Icon name="x" size={18} />315            </button>316          )}317          {value === '' && !hero && (318            <kbd className="omni-key" aria-hidden="true" title={IS_MAC ? '/  ·  ⌘K' : '/  ·  Ctrl K'}>/</kbd>319          )}320          {canSpeak && (321            <button322              type="button"323              className={dictation.listening ? 'omni-btn omni-mic omni-mic-on' : 'omni-btn omni-mic'}324              aria-label={dictation.listening ? t('voice.stop') : t('voice.start')}325              title={dictation.listening ? t('voice.stop') : t('voice.start')}326              aria-pressed={dictation.listening}327              onClick={onMic}328            >329              <Icon name="mic" size={19} />330            </button>331          )}332          <button type="submit" className="omni-go" aria-label={t('box.submit')} title={t('box.submit')}>333            <Icon name="arrow" size={hero ? 20 : 18} />334          </button>335        </div>336        <div className="omni-panel" inert={!showPanel}>337          <div className="omni-panel-in">338            {ask && (339              <div className="omni-ask" role="group" aria-labelledby={`${id}-vt`}>340                <p className="omni-ask-t" id={`${id}-vt`}>{t('voice.ask.t')}</p>341                <p>{t('voice.ask.p')}</p>342                <p className="omni-ask-row">343                  <button344                    type="button"345                    className="btn btn-solid"346                    onClick={() => {347                      setPref('voice', '1');348                      setAsk(false);349                      input.current?.focus();350                      dictation.start();351                    }}352                  >353                    {t('voice.ask.yes')}354                  </button>355                  <button type="button" className="btn" onClick={() => { setAsk(false); input.current?.focus(); }}>{t('voice.ask.no')}</button>356                </p>357              </div>358            )}359            {!ask && dictation.error !== null && <p className="omni-note" role="status">{t(`voice.err.${dictation.error}`)}</p>}360            {!ask && historyShown && value.trim() === '' && <p className="omni-head">{t('box.recent')}</p>}361            <ul id={listId} role="listbox" aria-label={t('box.list')} className="omni-list" hidden={ask || items.length === 0}>362              {items.map((it, i) => (363                <li364                  key={`${it.k}:${it.text}`}365                  id={`${id}-o${i}`}366                  role="option"367                  aria-selected={i === active}368                  className={`omni-opt omni-${it.k}`}369                  onMouseDown={(e) => e.preventDefault()}370                  onMouseMove={() => { if (active !== i) setActive(i); }}371                  onClick={() => choose(it)}372                >373                  {it.k === 'site' ? (374                    <>375                      <Favicon src={`/v2/favicon?domain=${encodeURIComponent(it.text)}`} domain={it.text} size={18} />376                      <span className="omni-text">377                        <span className="omni-site-t">{it.title || it.text}</span>378                        {it.title !== '' && <span className="omni-site-d">{it.text}</span>}379                      </span>380                      <span className="omni-hint">{t('box.site')}<Icon name="out" size={14} /></span>381                    </>382                  ) : it.k === 'correction' ? (383                    <>384                      <Icon name="spell" size={18} />385                      <span className="omni-text"><span className="omni-lead">{t('box.correction')}</span> <i>{it.text}</i></span>386                    </>387                  ) : it.k === 'history' ? (388                    <>389                      <Icon name="clock" size={18} />390                      <span className="omni-text">{it.text}</span>391                      <button392                        type="button"393                        tabIndex={-1}394                        className="omni-forget"395                        aria-label={t('box.recent.remove', { q: it.text })}396                        title={t('box.recent.remove', { q: it.text })}397                        onClick={(e) => {398                          e.stopPropagation();399                          forget(it.text);400                          setActive(-1);401                        }}402                      >403                        <Icon name="x" size={14} />404                      </button>405                    </>406                  ) : (407                    <>408                      <Icon name="search" size={18} />409                      <span className="omni-text">{completed(it.text, value)}</span>410                    </>411                  )}412                </li>413              ))}414            </ul>415            {!ask && items.length > 0 && (416              <p className="omni-foot">417                <span className="omni-keys" aria-hidden="true">418                  <span><kbd>↑</kbd><kbd>↓</kbd> {t('box.keys.move')}</span>419                  <span><kbd>↵</kbd> {t('box.keys.go')}</span>420                  <span><kbd>esc</kbd> {t('box.keys.close')}</span>421                </span>422                {historyShown && (423                  <button type="button" className="linklike" onMouseDown={(e) => e.preventDefault()} onClick={() => { clearHistory(); setActive(-1); }}>424                    {t('box.recent.clear')}425                  </button>426                )}427              </p>428            )}429          </div>430        </div>431      </div>432      <p className="sr-only" role="status">{showPanel && items.length > 0 ? t('box.count', { n: items.length }) : ''}</p>433    </form>434  );435}436
Files main
Menu

Theme