Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SPSearch8 * File : web/search/src/SubmitUrl.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, useRef, useState, type FormEvent } from 'react';44import { api, ApiError, safeHref } from '@spweb/shared-ui';45import { useT } from './i18n/results';46import { Icon } from './icons';4748interface Job {49 job_id: string;50 status: string;51 detail?: string | null;52 updated_at?: number | null;53}5455const TERMINAL = new Set(['indexed', 'denied', 'failed']);56const STEPS = ['queued', 'fetched', 'indexed'] as const;57const POLL_MS = 2500;58const MAX_POLLS = 120;5960type Phase =61 | { k: 'idle' }62 | { k: 'sending' }63 | { k: 'error'; error: ApiError }64 | { k: 'job'; id: string; status: string; detail: string | null; end: null | 'done' | 'lost' | 'timeout'; flaky: boolean };6566/** "Suggest a public URL": POST /v1/submit-url, then polls GET /v1/jobs/{id} until a final state. */67export function SubmitUrl({ onIndexed }: { onIndexed: () => void }) {68 const { t, tx } = useT();69 const [phase, setPhase] = useState<Phase>({ k: 'idle' });70 const [invalid, setInvalid] = useState(false);71 const input = useRef<HTMLInputElement>(null);72 const id = useId();7374 const jobId = phase.k === 'job' && phase.end === null ? phase.id : null;75 useEffect(() => {76 if (!jobId) return;77 const ctl = new AbortController();78 let timer = 0;79 let polls = 0;80 const tick = () => {81 polls++;82 api<Job>(`/v1/jobs/${encodeURIComponent(jobId)}`, { signal: ctl.signal }).then(83 (j) => {84 const status = typeof j.status === 'string' ? j.status : 'queued';85 const end = TERMINAL.has(status) ? 'done' : polls >= MAX_POLLS ? 'timeout' : null;86 setPhase({ k: 'job', id: jobId, status, detail: j.detail ?? null, end, flaky: false });87 if (!end) timer = window.setTimeout(tick, POLL_MS);88 },89 (e: unknown) => {90 if (ctl.signal.aborted) return;91 const lost = e instanceof ApiError && e.status === 404;92 const end = lost ? 'lost' : polls >= MAX_POLLS ? 'timeout' : null;93 setPhase((p) => (p.k === 'job' ? { ...p, end, flaky: !lost } : p));94 if (!end) {95 const wait = e instanceof ApiError && e.retryAfter ? e.retryAfter * 1000 : POLL_MS * 2;96 timer = window.setTimeout(tick, wait);97 }98 },99 );100 };101 timer = window.setTimeout(tick, 800);102 return () => {103 ctl.abort();104 window.clearTimeout(timer);105 };106 }, [jobId]);107108 const submit = (e: FormEvent) => {109 e.preventDefault();110 const url = safeHref(input.current?.value.trim());111 if (!url) {112 setInvalid(true);113 input.current?.focus();114 return;115 }116 setInvalid(false);117 setPhase({ k: 'sending' });118 api<{ job_id: string; status: string }>('/v1/submit-url', { method: 'POST', body: { url } }).then(119 (r) => setPhase({ k: 'job', id: r.job_id, status: r.status ?? 'queued', detail: null, end: null, flaky: false }),120 (err: unknown) => setPhase({ k: 'error', error: err instanceof ApiError ? err : new ApiError('network', String(err)) }),121 );122 };123124 const refusal = phase.k === 'error' && phase.error.code ? tx(`sub.err.${phase.error.code}`, '') : '';125126 return (127 <section className="submit" aria-labelledby={`${id}-h`}>128 <h2 id={`${id}-h`}>{t('sub.title')}</h2>129 <p className="submit-p">{t('sub.body')}</p>130 {phase.k !== 'job' && (131 <form className="submit-form" onSubmit={submit} noValidate>132 <div className="field">133 <label htmlFor={id}><span>{t('sub.label')}</span></label>134 <input135 id={id}136 ref={input}137 className="input"138 type="url"139 name="url"140 required141 inputMode="url"142 autoComplete="off"143 autoCapitalize="off"144 spellCheck={false}145 placeholder="https://"146 maxLength={2048}147 aria-invalid={invalid}148 aria-describedby={invalid ? `${id}-e` : undefined}149 />150 {invalid && <p id={`${id}-e`} className="f-err">{t('sub.client')}</p>}151 </div>152 <button type="submit" className="btn btn-solid" disabled={phase.k === 'sending'}>{t('sub.submit')}<Icon name="arrow" size={16} /></button>153 </form>154 )}155 <div aria-live="polite">156 {phase.k === 'sending' && <p className="submit-note">{t('sub.sending')}</p>}157 {phase.k === 'error' && <p className="submit-note f-err" role="alert">{refusal || t('sub.err')}{!refusal && phase.error.status > 0 ? ` (${phase.error.status})` : ''}</p>}158 {phase.k === 'job' && (159 <div className={`job job-${phase.status === 'indexed' ? 'ok' : phase.status === 'denied' || phase.status === 'failed' ? 'bad' : 'run'}`}>160 <p className="job-t">{t('sub.job', { id: phase.id })}</p>161 <ol className="steps" aria-label={t('sub.steps')}>162 {STEPS.map((st, i) => {163 const at = STEPS.indexOf(phase.status as (typeof STEPS)[number]);164 return (165 <li key={st} className={at > i || phase.status === 'indexed' ? 'step-done' : at === i ? 'step-now' : undefined} aria-current={at === i ? 'step' : undefined}>166 <span className="step-n" aria-hidden="true">{i + 1}</span>{t(`sub.step.${st}`)}167 </li>168 );169 })}170 </ol>171 <p>{tx(`sub.st.${phase.status}`, t('sub.st.unknown', { s: phase.status }))}</p>172 {phase.detail && <p className="submit-p">{phase.detail}</p>}173 {phase.end === null && phase.flaky && <p className="submit-p">{t('sub.pollErr')}</p>}174 {phase.end === 'lost' && <p>{t('sub.lost')}</p>}175 {phase.end === 'timeout' && <p>{t('sub.timeout')}</p>}176 {phase.end !== null && (177 <p className="job-row">178 {phase.status === 'indexed' && <button type="button" className="btn btn-solid" onClick={onIndexed}>{t('sub.search')}</button>}179 <button type="button" className="btn" onClick={() => setPhase({ k: 'idle' })}>{t('sub.again')}</button>180 </p>181 )}182 </div>183 )}184 </div>185 </section>186 );187}188