storebound/apps/desktop/src/ui/ConsoleFill.tsx

131 lines
8.1 KiB
TypeScript

// "Fill in console": the store forms without an API (App Store app record, age rating, App Privacy; Play Create app,
// content rating, target audience). Click -> dry run of `console.fill` (the answers from the config, nothing opens) -> this
// panel lists them, the uncertain ones marked for the owner, with the disclaimer -> "Open the browser" goes through
// write_with_confirm (the host shows the answers again in a native dialog and mints the token only on its button) ->
// a visible browser the owner signs in to; storebound fills the fields, moves through the pages and never submits or publishes. The run
// lasts until the owner closes that browser; Cancel here stops the command, which closes it.
import { failureText } from '../lib/results';
import { type KeyboardEvent, useEffect, useRef, useState } from 'react';
import { api, type ConsoleFillResult, type ConsoleForm, errorText, newJob, onProgress, type Project, type ToolResult } from '../api';
import { type Key, t } from '../i18n';
import { useData } from '../store';
import { Icon, StoreGlyph } from './icons';
import { Chip, Notice } from './kit';
export const CONSOLE_FORM_NAME: Record<ConsoleForm, Key> = {
'apple-app-record': 'cf.appleAppRecord', 'apple-age-rating': 'cf.appleAgeRating', 'apple-app-privacy': 'cf.appleAppPrivacy',
'play-app-record': 'cf.playAppRecord', 'play-content-rating': 'cf.playContentRating', 'play-target-audience': 'cf.playTargetAudience',
};
type Stage =
| { s: 'idle' }
| { s: 'dry' }
| { s: 'review'; data: ConsoleFillResult; note?: string }
| { s: 'running'; data: ConsoleFillResult; job: string; lines: string[] }
| { s: 'done'; data: ConsoleFillResult; result: ConsoleFillResult | null; ok: boolean; detail?: string };
const tail = (out: string): string => out.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
export function ConsoleFillButton({ project, form, small = true, primary }: { project: Project; form: ConsoleForm; small?: boolean; primary?: boolean }) {
const d = useData();
const [st, setSt] = useState<Stage>({ s: 'idle' });
const name = t(CONSOLE_FORM_NAME[form]);
const start = async () => {
setSt({ s: 'dry' });
try {
const r = await api.call<ToolResult & { data?: ConsoleFillResult }>('console.fill', project.id, { args: { form } }, newJob('console.fill-dry'));
if (!r.ok || !r.data) { setSt({ s: 'idle' }); d.toast({ kind: 'bad', title: t('cf.dryFailed', { form: name }), detail: failureText(r) }); return; }
setSt({ s: 'review', data: r.data });
} catch (e) {
setSt({ s: 'idle' });
d.toast({ kind: 'bad', title: t('cf.dryFailed', { form: name }), detail: errorText(e) });
}
};
const open = async (data: ConsoleFillResult) => {
const job = newJob('console.fill');
setSt({ s: 'running', data, job, lines: [] });
const un = onProgress(p => {
if (p.job !== job || !p.line?.trim()) return;
setSt(x => (x.s === 'running' && x.job === job ? { ...x, lines: [...x.lines, p.line!].slice(-12) } : x));
});
try {
const o = await api.writeWithConfirm('console.fill', project.id, { form }, job);
if (o.stage === 'dialog') setSt({ s: 'review', data, note: t('cf.notOpened') });
else if (o.stage === 'dry-run') setSt({ s: 'done', data, result: null, ok: false, detail: tail(o.dryRun.output) });
else {
const res = (o.result?.data ?? null) as ConsoleFillResult | null;
setSt({ s: 'done', data, result: res, ok: !!o.result?.ok, detail: o.result?.ok ? undefined : o.result ? failureText(o.result) : undefined });
}
} catch (e) {
const msg = errorText(e);
setSt({ s: 'done', data, result: null, ok: /cancel/i.test(msg), detail: /cancel/i.test(msg) ? t('cf.cancelled') : msg });
} finally { un.then(f => f()); }
};
const busy = st.s === 'dry';
return (
<>
<button className={`btn${small ? ' btn-sm' : ''}${primary ? ' btn-primary' : ''}`} disabled={busy || st.s === 'running'} aria-busy={busy || undefined}
title={t('cf.hint', { form: name })} onClick={() => { start(); }}>
<Icon name={busy ? 'refresh' : 'wand'} className={busy ? 'spin' : undefined} />{t('cf.button')}
</button>
{(st.s === 'review' || st.s === 'running' || st.s === 'done') && (
<FillPanel st={st} name={name} onOpen={() => { open(st.data); }} onCancel={() => { if (st.s === 'running') api.cancel(st.job).catch(() => {}); }} onClose={() => setSt({ s: 'idle' })} />
)}
</>
);
}
function FillPanel({ st, name, onOpen, onCancel, onClose }: {
st: Extract<Stage, { s: 'review' | 'running' | 'done' }>; name: string; onOpen: () => void; onCancel: () => void; onClose: () => void;
}) {
const root = useRef<HTMLDivElement>(null);
useEffect(() => { root.current?.focus(); }, []);
const running = st.s === 'running';
const data = st.data;
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape' && !running) { e.preventDefault(); onClose(); } };
return (
<div className="scrim lightbox" onMouseDown={e => { if (e.target === e.currentTarget && !running) onClose(); }}>
<div className="lb cf-panel" role="dialog" aria-modal="true" aria-labelledby="cf-title" tabIndex={-1} ref={root} onKeyDown={onKey}>
<div className="cf-body stack">
<div className="stack" style={{ gap: 4 }}>
<h2 id="cf-title" className="row" style={{ gap: 8 }}><Icon name="wand" />{t('cf.panelTitle', { form: data.title || name })}</h2>
<span className="small muted row" style={{ gap: 6 }}><StoreGlyph store={data.store === 'apple' ? 'ios' : 'android'} className="ic13" />{data.store === 'apple' ? 'App Store Connect' : 'Google Play Console'}</span>
</div>
<Notice tone="warn" icon="alert">{t('cf.disclaimer')}</Notice>
{st.s === 'review' && st.note && <Notice tone="info">{st.note}</Notice>}
{running && <Notice tone="info" icon="globe">{t('cf.runningText')}</Notice>}
{st.s === 'done' && (st.ok
? <Notice tone="ok">{st.result ? t('cf.doneText', { filled: st.result.filled ?? 0, highlighted: st.result.highlighted ?? 0 }) : st.detail ?? t('cf.closed')}</Notice>
: <Notice tone="bad">{t('cf.failed')}{st.detail ? `: ${st.detail}` : ''}</Notice>)}
{st.s === 'done' && st.result?.fallback ? <Notice tone="warn">{t('cf.fallback')}</Notice> : null}
<div className="stack" style={{ gap: 6 }}>
<div className="row between small"><b>{t('cf.answers', { count: data.answers.length })}</b>{data.uncertain > 0 && <Chip tone="warn" icon="question">{t('cf.uncertain', { count: data.uncertain })}</Chip>}</div>
{!data.answers.length ? <span className="small muted">{t('cf.noAnswers')}</span> : (
<table className="table cf-table">
<tbody>
{data.answers.map(a => (
<tr key={a.id}>
<td><div className="strong">{a.label}</div>{(a.note || a.source) && <div className="small muted">{a.note ?? a.source}</div>}</td>
<td>{a.certain ? <span>{a.value}</span> : <Chip tone="warn" icon="question">{t('cf.youAnswer')}</Chip>}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
{data.guidance.length > 0 && <ul className="note-list cf-guidance">{data.guidance.map((g, i) => <li key={i}>{g}</li>)}</ul>}
{running && st.lines.length > 0 && <pre className="log" aria-live="polite">{st.lines.join('\n')}</pre>}
</div>
<div className="lb-foot">
<div className="grow small muted">{st.s === 'review' ? t('cf.foot') : null}</div>
{running ? <button className="btn btn-sm btn-danger" onClick={onCancel}><Icon name="x" />{t('cf.cancelRun')}</button> : <button className="btn btn-sm btn-ghost" onClick={onClose}>{st.s === 'done' ? t('common.close') : t('common.cancel')}</button>}
{st.s === 'review' && <button className="btn btn-sm btn-primary" onClick={onOpen}><Icon name="external" />{t('cf.open')}</button>}
{running && <span className="small muted row" style={{ gap: 6 }}><Icon name="refresh" className="spin ic13" />{t('cf.waiting')}</span>}
</div>
</div>
</div>
);
}