SPB Git

Repository Public

Panels.tsx 11.3 KB 183 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : apps/navigator-web/src/viewer/Panels.tsx9 * Module           : viewer10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * 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: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Side panels of the viewer: session confirmation (scope of pages) and assisted publishing.43import { useCallback, useEffect, useState, type FormEvent } from 'react';44import { get, post } from '../../../shared/api.ts';45import { tCode, useLang, useT } from '../i18n.ts';46import type { AssistJob, NavPolicy, PageRow, ViewerMsg } from '../types.ts';47import { ErrorLine, fmtTime, usePoll } from '../ui.tsx';4849/** Only offered while this user holds control and the session is in MANUAL_CONTROL (the API checks both again). */50export function ConfirmPanel({ sessionId, onConfirmed }: { sessionId: string; onConfirmed: () => void }) {51  const t = useT();52  const [pages, setPages] = useState<PageRow[] | null>(null);53  const [picked, setPicked] = useState<Set<string>>(new Set());54  const [attest, setAttest] = useState(false);55  const [busy, setBusy] = useState(false); const [err, setErr] = useState<unknown>(null); const [done, setDone] = useState(false);56  useEffect(() => { let live = true; get<{ pages: PageRow[] }>('/v1/pages').then((r) => { if (live) setPages(r.pages.filter((p) => p.status === 'confirmed')); }, (e) => { if (live) setErr(e); }); return () => { live = false; }; }, []);57  const toggle = (id: string) => { setDone(false); setPicked((s) => { const n = new Set(s); if (n.has(id)) n.delete(id); else n.add(id); return n; }); };58  const submit = async (e: FormEvent) => {59    e.preventDefault(); setBusy(true); setErr(null); setDone(false);60    try { await post(`/v1/navigator/sessions/${sessionId}/confirm`, { pageIds: [...picked], attest: true }); setDone(true); setAttest(false); onConfirmed(); } catch (x) { setErr(x); } finally { setBusy(false); }61  };62  return (63    <section className="panel" aria-labelledby="cf-t">64      <h2 id="cf-t">{t('confirm.title')}</h2>65      <p>{t('confirm.lead')}</p>66      <form onSubmit={submit}>67        {pages === null && !err && <p role="status">{t('common.loading')}</p>}68        {pages && pages.length === 0 && <p className="empty">{t('confirm.no_pages')}</p>}69        {pages && pages.length > 0 && (70          <fieldset>71            <legend>{t('confirm.pages')}</legend>72            {pages.map((p) => (73              <label key={p.id} className="check"><input type="checkbox" checked={picked.has(p.id)} onChange={() => toggle(p.id)} /> <span><span className="pg-name">{p.display_name}</span> <span className="mono small">{p.url}</span></span></label>74            ))}75          </fieldset>76        )}77        <label className="check attest"><input type="checkbox" checked={attest} onChange={(e) => setAttest(e.target.checked)} /> <span>{t('confirm.attest')}</span></label>78        <p className="hint">{t('confirm.after')}</p>79        <div className="row"><button type="submit" className="btn primary" disabled={busy || !attest || picked.size === 0 || picked.size > 20}>{busy ? t('common.working') : t('confirm.submit', { n: picked.size })}</button></div>80        <div aria-live="polite"><ErrorLine error={err} />{done && <p className="ok" role="status">{t('confirm.done')}</p>}</div>81      </form>82    </section>83  );84}8586type AssistProps = {87  sessionId: string; canControl: boolean; policy: NavPolicy; chooserOpen: boolean; refreshKey: number;88  selected: string | null; onSelect(id: string | null): void; onJobs(ids: string[]): void;89  /** Sends an input message; returns false (and reports why) when control is missing. */90  act(m: ViewerMsg): boolean;91};92export function AssistPanel({ sessionId, canControl, policy, chooserOpen, refreshKey, selected, onSelect, onJobs, act }: AssistProps) {93  const t = useT(); const { lang } = useLang();94  const [jobs, setJobs] = useState<AssistJob[] | null>(null);95  const [err, setErr] = useState<unknown>(null);96  const [ok, setOk] = useState<'assist.published_ok' | 'assist.authorized_ok' | null>(null);97  const load = useCallback(async () => {98    try { const r = await get<{ jobs: AssistJob[] }>(`/v1/navigator/sessions/${sessionId}/assist`); setJobs(r.jobs); onJobs(r.jobs.map((j) => j.id)); setErr(null); }99    catch (e) { setErr(e); }100  }, [sessionId]); // eslint-disable-line react-hooks/exhaustive-deps101  usePoll(load, 15000);102  useEffect(() => { if (refreshKey) void load(); }, [refreshKey, load]);103  return (104    <section className="panel" aria-labelledby="as-t">105      <div className="panel-head"><h2 id="as-t">{t('assist.title')}</h2><button type="button" className="btn quiet" onClick={() => void load()}>{t('common.refresh')}</button></div>106      <p>{t('assist.lead')}</p>107      <p className="rule-note">{t('assist.human_publishes')}</p>108      <div aria-live="polite"><ErrorLine error={err} />{ok && <p className="ok" role="status">{t(ok)}</p>}</div>109      {jobs === null && !err && <p role="status">{t('common.loading')}</p>}110      {jobs && jobs.length === 0 && <p className="empty">{t('assist.empty')}</p>}111      {jobs && jobs.length > 0 && (112        <ul className="jobs">113          {jobs.map((j) => <JobCard key={j.id} j={j} lang={lang} open={selected === j.id} onToggle={() => onSelect(selected === j.id ? null : j.id)} canControl={canControl} policy={policy} chooserOpen={chooserOpen} act={act} reload={load} onOk={setOk} />)}114        </ul>115      )}116    </section>117  );118}119120function JobCard({ j, lang, open, onToggle, canControl, policy, chooserOpen, act, reload, onOk }: { j: AssistJob; onOk(k: 'assist.published_ok' | 'assist.authorized_ok' | null): void; lang: string; open: boolean; onToggle(): void; canControl: boolean; policy: NavPolicy; chooserOpen: boolean; act(m: ViewerMsg): boolean; reload(): Promise<void> }) {121  const t = useT();122  const [url, setUrl] = useState('');123  const [busy, setBusy] = useState<string | null>(null); const [err, setErr] = useState<unknown>(null);124  const [sure, setSure] = useState(false);125  const media = j.media_sha256?.length ?? 0;126  const target = j.composer_url ?? j.page_url;127  const confirmJob = async (action: 'human_published' | 'authorize_submit') => {128    setBusy(action); setErr(null); onOk(null);129    try {130      await post(`/v1/jobs/${j.id}/confirm`, action === 'human_published' ? { action, externalUrl: url.trim() || null } : { action });131      setSure(false);132      onOk(action === 'human_published' ? 'assist.published_ok' : 'assist.authorized_ok');133      await reload();134    } catch (e) { setErr(e); } finally { setBusy(null); }135  };136  return (137    <li className={`job${open ? ' open' : ''}`}>138      <button type="button" className="job-head" aria-expanded={open} onClick={onToggle}>139        <span className="job-title">{j.title}</span>140        <span className="job-meta">{j.page_name} · <time dateTime={j.scheduled_at}>{fmtTime(j.scheduled_at, lang)}</time></span>141      </button>142      {open && (143        <div className="job-body">144          <dl className="facts tight">145            <div><dt>{t('assist.mode')}</dt><dd>{tCode(t, 'jobmode', j.mode)}</dd></div>146            <div><dt>{t('assist.hash')}</dt><dd><code title={j.content_hash}>{j.content_hash.slice(0, 12)}</code></dd></div>147            <div><dt>{t('assist.media')}</dt><dd className="num">{media}</dd></div>148            {j.link_url && <div><dt>{t('assist.link')}</dt><dd className="mono small sel">{j.link_url}</dd></div>}149            {j.alt_text && <div><dt>{t('assist.alt')}</dt><dd className="sel">{j.alt_text}</dd></div>}150          </dl>151          <p className="label">{t('assist.text')}</p>152          <pre className="approved" tabIndex={0} aria-label={t('assist.text')}>{j.body}</pre>153          {!canControl && <p className="hint">{t('assist.need_control')}</p>}154          <div className="col">155            <button type="button" className="btn" disabled={!canControl} onClick={() => act({ t: 'nav', op: 'goto', url: target })}>{t('assist.open_composer')}</button>156            <button type="button" className="btn" disabled={!canControl || !policy.insertApprovedText} onClick={() => act({ t: 'insertApproved', jobId: j.id })} aria-describedby={`ins-${j.id}`}>{t('assist.insert')}</button>157            <p id={`ins-${j.id}`} className="hint">{policy.insertApprovedText ? t('assist.insert_hint') : t('assist.insert_off')}</p>158            {chooserOpen && <>159              <button type="button" className="btn primary" disabled={!canControl || media === 0} onClick={() => act({ t: 'chooseMedia', jobId: j.id })}>{t('assist.attach')}</button>160              {media === 0 && <p className="hint">{t('assist.no_media')}</p>}161              <button type="button" className="btn" disabled={!canControl} onClick={() => act({ t: 'cancelChooser' })}>{t('assist.cancel_chooser')}</button>162            </>}163          </div>164          <form className="publish" onSubmit={(e) => { e.preventDefault(); void confirmJob('human_published'); }}>165            <p className="rule-note">{t('assist.human_publishes')}</p>166            <label htmlFor={`u-${j.id}`}>{t('assist.ext_url')}</label>167            <input id={`u-${j.id}`} type="url" inputMode="url" value={url} onChange={(e) => setUrl(e.target.value)} maxLength={1000} placeholder="https://" autoComplete="off" autoCapitalize="off" spellCheck={false} />168            <label className="check"><input type="checkbox" checked={sure} onChange={(e) => setSure(e.target.checked)} /> <span>{t('assist.published_attest')}</span></label>169            <button type="submit" className="btn primary" disabled={busy !== null || !sure}>{busy === 'human_published' ? t('common.working') : t('assist.published')}</button>170          </form>171          {j.mode === 'auto_submit' && (172            <div className="col">173              <p className="hint">{t('assist.authorize_hint')}</p>174              <button type="button" className="btn" disabled={busy !== null} onClick={() => void confirmJob('authorize_submit')}>{busy === 'authorize_submit' ? t('common.working') : t('assist.authorize')}</button>175            </div>176          )}177          <div aria-live="polite"><ErrorLine error={err} /></div>178        </div>179      )}180    </li>181  );182}183
Files main
Menu

Theme