108 lines
11 KiB
TypeScript
108 lines
11 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
||
import { Check, Files, LoaderCircle, RotateCcw, ScanLine, ShieldCheck } from 'lucide-react';
|
||
import type { ChangeSet, Session } from './types';
|
||
import { api } from './api';
|
||
import { DiffView, Modal, Status } from './components';
|
||
import './ChangeSetPanel.css';
|
||
|
||
const openStates = ['prepared', 'applying', 'rolling_back', 'unknown', 'partial'];
|
||
const labels: Record<string, string> = { before: '原文件', after: '建议内容', external: '外部改动', unavailable: '无法读取', writing: '正在写入', restoring: '正在回退' };
|
||
|
||
export function ChangeSetPanel({ session, busy, onSession, onError, onFilesChanged }: {
|
||
session: Session; busy: boolean; onSession: (session: Session) => void; onError: (error: unknown) => void; onFilesChanged: () => Promise<void>;
|
||
}) {
|
||
const sets = session.execution?.changeSets ?? [], taskId = session.execution?.task?.id;
|
||
const pending = session.changes.filter(change => change.taskId === taskId && change.status === 'pending'
|
||
&& !sets.some(set => set.id === change.changeSetId && openStates.includes(set.status)));
|
||
const current = sets.slice().reverse().find(set => openStates.includes(set.status)) ?? sets.at(-1);
|
||
const [stage, setStage] = useState<'select' | 'review' | null>(null);
|
||
const [setId, setSetId] = useState(''), [fileId, setFileId] = useState('');
|
||
const [choices, setChoices] = useState<string[]>([]), [working, setWorking] = useState(false);
|
||
const [confirmation, setConfirmation] = useState<'rollback' | 'acknowledge' | null>(null);
|
||
const scope = session.id + ':' + (taskId ?? ''), scopeRef = useRef(scope); scopeRef.current = scope;
|
||
const filesSignature = sets.filter(set => ['completed', 'rolled_back', 'partial', 'unknown', 'resolved_external'].includes(set.status))
|
||
.map(set => set.id + ':' + set.status + ':' + set.finishedAt).join('|');
|
||
const lastFiles = useRef({ scope, signature: filesSignature });
|
||
useEffect(() => {
|
||
scopeRef.current = scope;
|
||
setStage(null); setSetId(''); setFileId(''); setChoices([]); setConfirmation(null); setWorking(false);
|
||
return () => { if (scopeRef.current === scope) scopeRef.current = ''; };
|
||
}, [scope]);
|
||
useEffect(() => {
|
||
const previous = lastFiles.current; lastFiles.current = { scope, signature: filesSignature };
|
||
if (previous.scope === scope && previous.signature !== filesSignature) void onFilesChanged().catch(error => { if (scopeRef.current === scope) onError(error); });
|
||
}, [scope, filesSignature, onFilesChanged, onError]);
|
||
const selected = sets.find(set => set.id === setId) ?? current;
|
||
const file = selected?.files.find(value => value.changeId === fileId) ?? selected?.files[0];
|
||
const proposal = session.changes.find(change => change.id === file?.changeId);
|
||
const active = !!selected && ['applying', 'rolling_back'].includes(selected.status);
|
||
const disabled = busy || working || active;
|
||
const close = () => { setStage(null); setConfirmation(null); };
|
||
async function prepare() {
|
||
if (!choices.length || choices.length > 32 || disabled) return;
|
||
const target = scope; setWorking(true);
|
||
try {
|
||
const result = await api<Session>('/sessions/' + session.id + '/change-sets', { changeIds: choices });
|
||
if (scopeRef.current !== target) return;
|
||
onSession(result);
|
||
const next = result.execution?.changeSets?.slice().reverse().find(set => set.status === 'prepared');
|
||
if (next) { setSetId(next.id); setFileId(next.files[0]?.changeId ?? ''); setStage('review'); }
|
||
} catch (error) { if (scopeRef.current === target) onError(error); }
|
||
finally { if (scopeRef.current === target) setWorking(false); }
|
||
}
|
||
async function act(set: ChangeSet, action: 'apply' | 'reconcile' | 'rollback' | 'discard' | 'acknowledge') {
|
||
if (disabled) return;
|
||
const target = scope; setWorking(true);
|
||
try {
|
||
const result = await api<Session>('/sessions/' + session.id + '/change-sets/' + set.id + '/' + action,
|
||
{ fingerprint: set.fingerprint, ...(action === 'acknowledge' ? { observationFingerprint: set.observationFingerprint } : {}) });
|
||
if (scopeRef.current === target) { onSession(result); setConfirmation(null); }
|
||
} catch (error) { if (scopeRef.current === target) onError(error); }
|
||
finally { if (scopeRef.current === target) setWorking(false); }
|
||
}
|
||
const canAcknowledge = selected?.status === 'partial' && !!selected.observationFingerprint
|
||
&& !!selected.observations?.length && selected.observations.every(value => ['before', 'external'].includes(value.state));
|
||
return <>
|
||
<div className={'change-set-bar' + (current?.requiresVerification ? ' batch-attention' : '')}>
|
||
<Files size={17} /><div><strong>{current ? `多文件变更集 · ${current.files.length} 个文件` : '组合审查文件改动'}</strong>
|
||
<small>{current ? current.requiresVerification ? '实际文件需要核对,恢复入口保留在这个任务。' : current.summary : pending.length ? `${pending.length} 份提案可组合为一个审查批次。` : '本任务有提案后,可一起审查与应用。'}</small></div>
|
||
{current && <button type="button" className="button secondary" disabled={working} onClick={() => { setSetId(current.id); setFileId(current.files[0]?.changeId ?? ''); setStage('review'); }}>审查变更集</button>}
|
||
{!current || !openStates.includes(current.status) ? <button type="button" className="button secondary" disabled={!taskId || !pending.length || busy || working}
|
||
onClick={() => { setChoices(pending.slice(0, 32).map(change => change.id)); setStage('select'); }}>组合审查</button> : null}
|
||
</div>
|
||
{stage === 'select' && <Modal title="选择要一起审查的提案" description="选择1到32份同任务提案,封存后查看整批差异。" wide onClose={close}>
|
||
<div className="batch-select-list">{pending.map(change => <label key={change.id}><input type="checkbox" aria-label={'选择提案 ' + change.path} checked={choices.includes(change.id)}
|
||
onChange={event => setChoices(previous => event.target.checked ? [...previous, change.id] : previous.filter(id => id !== change.id))} />
|
||
<span><strong>{change.path}</strong><small>{change.reason}</small></span><span className="change-stats"><b>+{change.additions}</b><i>−{change.deletions}</i></span></label>)}</div>
|
||
<div className="batch-actions"><span>已选择 {choices.length} / 32 项</span><button type="button" className="button primary" disabled={disabled || !choices.length || choices.length > 32} onClick={prepare}>
|
||
{working ? <LoaderCircle size={14} className="spin" /> : <ShieldCheck size={14} />}封存审查范围</button></div>
|
||
</Modal>}
|
||
{stage === 'review' && selected && <Modal title="多文件变更集审查" description={`本任务 ${selected.taskId.slice(0, 8)} · ${selected.files.length} 个文件`} wide onClose={close}>
|
||
<div className="batch-heading"><Status value={selected.status} /><span>{selected.summary}</span>
|
||
{sets.length > 1 && <select aria-label="选择变更批次" value={selected.id} onChange={event => { setSetId(event.target.value); setFileId(''); setConfirmation(null); }}>
|
||
{sets.slice().reverse().map(set => <option key={set.id} value={set.id}>{set.id.slice(0, 8)} · {set.files.length} 个文件 · {set.status}</option>)}</select>}
|
||
</div>
|
||
<div className="batch-review-grid"><div className="batch-file-list" aria-label="批次文件范围">{selected.files.map(item => {
|
||
const observation = selected.observations?.find(value => value.path === item.path);
|
||
return <button type="button" key={item.changeId} aria-label={'查看批次差异 ' + item.path} className={file?.changeId === item.changeId ? 'selected' : ''}
|
||
onClick={() => setFileId(item.changeId)}><strong>{item.path}</strong><small>{labels[observation?.state ?? item.state] ?? item.state}</small>
|
||
<code title={observation?.actualSha256 ?? item.baseSha256 ?? '新文件'}>{(observation?.actualSha256 ?? item.baseSha256)?.slice(0, 12) ?? '新文件'}</code>
|
||
{observation?.problem && <small className="batch-problem">{observation.problem}</small>}{item.restoreError && <small className="batch-problem">{item.restoreError}</small>}</button>;
|
||
})}</div><div className="batch-diff"><div className="batch-diff-heading"><strong>{file?.path}</strong><span>提案差异</span></div>{proposal && <DiffView change={proposal} />}</div></div>
|
||
<div className="batch-fingerprint"><span>审查指纹</span><code>{selected.fingerprint}</code><span>Git基线</span><code>{selected.baseline.available ? `${selected.baseline.branch ?? '未命名'} · ${selected.baseline.head?.slice(0, 12) ?? '尚无提交'}` : '项目尚未启用Git'}</code></div>
|
||
{confirmation && <div className="batch-confirmation" role="alert"><strong>{confirmation === 'rollback' ? '回退本批次已写入的文件' : '保留外部改动并结束恢复'}</strong>
|
||
<p>{confirmation === 'rollback' ? '只有当前字节仍等于本批次建议时才恢复原文,外部修改会保留。已新建的文件会按同样规则移除。' : '将保留目前已核对的外部内容,并结束这个未成功应用的批次。当前文件再次变化时会拒绝确认。'}</p>
|
||
<button type="button" className="button secondary" disabled={disabled} onClick={() => setConfirmation(null)}>返回审查</button>
|
||
<button type="button" className="button primary" disabled={disabled} onClick={() => act(selected, confirmation)}>{confirmation === 'rollback' ? '确认回退本批次' : '确认保留外部改动'}</button></div>}
|
||
<div className="batch-actions"><span>{active ? '文件批次正在执行,结果会持续更新。' : selected.requiresVerification ? '先核对实际文件,恢复不会自动续写。' : '应用前会核对所有文件及原审查指纹。'}</span>
|
||
{working && <LoaderCircle size={14} className="spin" />}
|
||
{['prepared', 'stale'].includes(selected.status) && <button type="button" className="button secondary" disabled={disabled} onClick={() => act(selected, 'discard')}>撤销未执行批次</button>}
|
||
{selected.status === 'prepared' && <button type="button" className="button primary" disabled={disabled} onClick={() => act(selected, 'apply')}><Check size={14} />确认应用全部 {selected.files.length} 项</button>}
|
||
{selected.requiresVerification && <button type="button" className="button secondary" disabled={disabled} onClick={() => act(selected, 'reconcile')}><ScanLine size={14} />核对实际文件</button>}
|
||
{['completed', 'partial', 'unknown'].includes(selected.status) && <button type="button" className="button secondary" disabled={disabled || !!confirmation} onClick={() => setConfirmation('rollback')}><RotateCcw size={14} />回退本批已写入文件</button>}
|
||
{canAcknowledge && <button type="button" className="button secondary" disabled={disabled || !!confirmation} onClick={() => setConfirmation('acknowledge')}>保留外部改动,结束恢复</button>}
|
||
</div>
|
||
</Modal>}
|
||
</>;
|
||
}
|