refactor: diff panel now compares input wsids → sorted output

Drops the prev-sort snapshot ref. Diff is always available — no "sort once
first" empty state — and surfaces drops (banned/missing/collection IDs that
expanded), additions (collection expansion, branch picks), and reorderings
in one pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-06 19:10:52 +00:00
parent 8deaf82eac
commit f8b48fbacb

View File

@@ -145,67 +145,47 @@ function WsidLink({ wsid, children, className }) {
); );
} }
// Snapshot the fields needed to diff against the next sort/resort. Called // Compare the wsids the user pasted (input order, deduped) against the wsids
// before each fetch fires so the snapshot captures "what the user saw // in WORKSHOP_ITEMS_LINE (sort order). Always available — no "previous sort"
// before this action". Polling-mid-flight ticks intentionally don't snapshot // required. Surfaces drops (banned / missing mod.info / unknown / collection
// (would erase the prior visible state on every 2.5s update). // IDs that expanded), additions (collection expansion, branch picks), and
function snapshotForDiff(src) { // position changes.
if (!src) return null; function computeDiff(inputWsids, outputWsids) {
return { if (!inputWsids || !outputWsids) return null;
SORTED_ORDER: [...(src.SORTED_ORDER || [])], const inSet = new Set(inputWsids);
MOD_DB: (src.MOD_DB || []).map(m => ({ modId: m.modId, wsid: m.wsid, name: m.name })), const outSet = new Set(outputWsids);
MODS_LINE: src.MODS_LINE || '', const added = outputWsids.filter(w => !inSet.has(w));
WORKSHOP_ITEMS_LINE: src.WORKSHOP_ITEMS_LINE || '', const removed = inputWsids.filter(w => !outSet.has(w));
}; const inPos = new Map(inputWsids.map((w, i) => [w, i]));
}
function computeDiff(prev, curr) {
if (!prev || !curr) return null;
const prevSorted = prev.SORTED_ORDER || [];
const currSorted = curr.SORTED_ORDER || [];
const prevSet = new Set(prevSorted);
const currSet = new Set(currSorted);
const added = currSorted.filter(id => !prevSet.has(id));
const removed = prevSorted.filter(id => !currSet.has(id));
const prevPos = new Map(prevSorted.map((id, i) => [id, i]));
const movers = []; const movers = [];
currSorted.forEach((id, ci) => { outputWsids.forEach((w, oi) => {
if (!prevSet.has(id)) return; if (!inSet.has(w)) return;
const pi = prevPos.get(id); const ii = inPos.get(w);
if (pi !== ci) movers.push({ id, from: pi, to: ci, delta: ci - pi }); if (ii !== oi) movers.push({ wsid: w, from: ii, to: oi, delta: oi - ii });
}); });
movers.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta)); movers.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta));
const prevWsl = (prev.WORKSHOP_ITEMS_LINE || '').replace(/;+$/, '').split(';').filter(Boolean); return { added, removed, movers };
const currWsl = (curr.WORKSHOP_ITEMS_LINE || '').replace(/;+$/, '').split(';').filter(Boolean);
const prevWsidPos = new Map(prevWsl.map((w, i) => [w, i]));
const wsidMovers = [];
currWsl.forEach((w, ci) => {
const pi = prevWsidPos.get(w);
if (pi !== undefined && pi !== ci) wsidMovers.push({ wsid: w, from: pi, to: ci });
});
wsidMovers.sort((a, b) => Math.abs(b.to - b.from) - Math.abs(a.to - a.from));
return { added, removed, movers, wsidMovers };
} }
function DiffPanel({ prev, curr, onClose }) { function DiffPanel({ inputWsids, outputWsids, onClose }) {
const diff = computeDiff(prev, curr); const diff = computeDiff(inputWsids, outputWsids);
if (!diff) { if (!diff) {
return ( return (
<div className="diff-panel"> <div className="diff-panel">
<div className="diff-head"> <div className="diff-head">
<span className="diff-title">diff vs previous sort</span> <span className="diff-title">diff: input sorted</span>
<button type="button" className="diff-close" onClick={onClose}>close</button> <button type="button" className="diff-close" onClick={onClose}>close</button>
</div> </div>
<div className="diff-empty">no previous sort to compare against - sort once first.</div> <div className="diff-empty">no input or output yet.</div>
</div> </div>
); );
} }
const { added, removed, movers, wsidMovers } = diff; const { added, removed, movers } = diff;
const empty = !added.length && !removed.length && !movers.length && !wsidMovers.length; const empty = !added.length && !removed.length && !movers.length;
return ( return (
<div className="diff-panel"> <div className="diff-panel">
<div className="diff-head"> <div className="diff-head">
<span className="diff-title">diff vs previous sort</span> <span className="diff-title">diff: input sorted</span>
<span className="diff-summary"> <span className="diff-summary">
<span className="diff-stat add">+{added.length}</span> <span className="diff-stat add">+{added.length}</span>
<span className="diff-stat rm">{removed.length}</span> <span className="diff-stat rm">{removed.length}</span>
@@ -213,41 +193,29 @@ function DiffPanel({ prev, curr, onClose }) {
</span> </span>
<button type="button" className="diff-close" onClick={onClose}>close</button> <button type="button" className="diff-close" onClick={onClose}>close</button>
</div> </div>
{empty && <div className="diff-empty">nothing changed.</div>} {empty && <div className="diff-empty">order matches your input. nothing dropped or added.</div>}
{added.length > 0 && ( {added.length > 0 && (
<div className="diff-section"> <div className="diff-section">
<div className="diff-label">added ({added.length})</div> <div className="diff-label">added ({added.length}) collection expansion or branch-picker</div>
{added.slice(0, 30).map(id => <div key={id} className="diff-row diff-add">+ {id}</div>)} {added.slice(0, 30).map(w => <div key={w} className="diff-row diff-add">+ {w}</div>)}
{added.length > 30 && <div className="diff-more">and {added.length - 30} more</div>} {added.length > 30 && <div className="diff-more">and {added.length - 30} more</div>}
</div> </div>
)} )}
{removed.length > 0 && ( {removed.length > 0 && (
<div className="diff-section"> <div className="diff-section">
<div className="diff-label">removed ({removed.length})</div> <div className="diff-label">removed ({removed.length}) dropped, banned, missing mod.info, or a collection ID that expanded</div>
{removed.slice(0, 30).map(id => <div key={id} className="diff-row diff-rm"> {id}</div>)} {removed.slice(0, 30).map(w => <div key={w} className="diff-row diff-rm"> {w}</div>)}
{removed.length > 30 && <div className="diff-more">and {removed.length - 30} more</div>} {removed.length > 30 && <div className="diff-more">and {removed.length - 30} more</div>}
</div> </div>
)} )}
{movers.length > 0 && ( {movers.length > 0 && (
<div className="diff-section"> <div className="diff-section">
<div className="diff-label">moved by load order ({movers.length}, top {Math.min(10, movers.length)} shown)</div> <div className="diff-label">reordered by load order ({movers.length}, top {Math.min(10, movers.length)} shown)</div>
{movers.slice(0, 10).map(({ id, from, to, delta }) => ( {movers.slice(0, 10).map(({ wsid, from, to, delta }) => (
<div key={id} className="diff-row diff-mv">
<span className="diff-arrow">{delta < 0 ? '↑' : '↓'}</span>
{id}
<span className="diff-pos">pos {from + 1} {to + 1} ({delta > 0 ? '+' : ''}{delta})</span>
</div>
))}
</div>
)}
{wsidMovers.length > 0 && (
<div className="diff-section">
<div className="diff-label">WorkshopItems= reorder ({wsidMovers.length})</div>
{wsidMovers.slice(0, 10).map(({ wsid, from, to }) => (
<div key={wsid} className="diff-row diff-mv"> <div key={wsid} className="diff-row diff-mv">
<span className="diff-arrow">{to < from ? '↑' : '↓'}</span> <span className="diff-arrow">{delta < 0 ? '↑' : '↓'}</span>
{wsid} {wsid}
<span className="diff-pos">pos {from + 1} {to + 1}</span> <span className="diff-pos">pos {from + 1} {to + 1} ({delta > 0 ? '+' : ''}{delta})</span>
</div> </div>
))} ))}
</div> </div>
@@ -1039,7 +1007,7 @@ function BuildToggle({ value, onChange }) {
); );
} }
function RightColumn({ state, counts, progress, emptyVariant, successVariant, modTableDefault, pzBuild, setPzBuild, branchSelections, onToggleBranch, expandedWsids, onToggleExpansion, inputWsids, onAddWsid, onPickBranch, onSwapWsid, onRemoveWsid, onAutoFixAddDeps, onAutoFixSwaps, onAutoFixRemoves, onRetry, previousResult, diffOpen, setDiffOpen }) { function RightColumn({ state, counts, progress, emptyVariant, successVariant, modTableDefault, pzBuild, setPzBuild, branchSelections, onToggleBranch, expandedWsids, onToggleExpansion, inputWsids, onAddWsid, onPickBranch, onSwapWsid, onRemoveWsid, onAutoFixAddDeps, onAutoFixSwaps, onAutoFixRemoves, onRetry, inputWsidList, diffOpen, setDiffOpen }) {
// Phase-state mapping: legacy `success` ≈ B+F `done`; legacy `partial` ≈ B+F `queued`/`draining`. // Phase-state mapping: legacy `success` ≈ B+F `done`; legacy `partial` ≈ B+F `queued`/`draining`.
const isTerminalDone = state === 'success' || state === 'done'; const isTerminalDone = state === 'success' || state === 'done';
const isInflightPartial = state === 'partial' || state === 'queued' || state === 'draining'; const isInflightPartial = state === 'partial' || state === 'queued' || state === 'draining';
@@ -1131,21 +1099,15 @@ function RightColumn({ state, counts, progress, emptyVariant, successVariant, mo
type="button" type="button"
className={'diff-toggle' + (diffOpen ? ' open' : '')} className={'diff-toggle' + (diffOpen ? ' open' : '')}
onClick={() => setDiffOpen(o => !o)} onClick={() => setDiffOpen(o => !o)}
disabled={!previousResult} title="diff your input against the sorted output"
title={previousResult ? 'compare to previous sort' : 'sort once first'}
> >
{diffOpen ? ' diff' : ' diff'} {diffOpen ? ' diff' : ' diff'}
</button> </button>
</div> </div>
{diffOpen && ( {diffOpen && (
<DiffPanel <DiffPanel
prev={previousResult} inputWsids={inputWsidList}
curr={{ outputWsids={(D.WORKSHOP_ITEMS_LINE || '').replace(/;+$/, '').split(';').filter(Boolean)}
SORTED_ORDER: D.SORTED_ORDER || [],
MOD_DB: D.MOD_DB || [],
MODS_LINE: D.MODS_LINE || '',
WORKSHOP_ITEMS_LINE: D.WORKSHOP_ITEMS_LINE || '',
}}
onClose={() => setDiffOpen(false)} onClose={() => setDiffOpen(false)}
/> />
)} )}
@@ -1434,15 +1396,16 @@ function App() {
const pollAbortRef = useRef(null); const pollAbortRef = useRef(null);
const [activeJobId, setActiveJobId] = useState(null); const [activeJobId, setActiveJobId] = useState(null);
const [expandedWsids, setExpandedWsids] = useState(() => new Set()); const [expandedWsids, setExpandedWsids] = useState(() => new Set());
// Diff: snapshot of the result that's about to be replaced; toggle for the // Diff toggle. The diff is input-vs-output (textarea wsids vs sorted
// panel. Snapshot is taken at the START of any sort/resort - polling-mid-flight // WORKSHOP_ITEMS_LINE), recomputed live every render — no snapshot ref
// ticks don't snapshot so the user's prior visible state stays available. // needed. Always available, even on the first sort.
const previousResultRef = useRef(null);
const [diffOpen, setDiffOpen] = useState(false); const [diffOpen, setDiffOpen] = useState(false);
// Set of wsids currently in the input textarea, used by warning rows to // Ordered list of wsids currently in the input textarea (deduped, first-seen
// derive their staged state. Memoized off `input` so re-renders triggered // order). The Set wrapper below is for warning rows that need O(1) `.has()`
// by unrelated state changes don't churn the Set. // lookup when deriving their staged state. Both are memoized off `input` so
const inputWsids = useMemo(() => new Set(parseWorkshopInput(input)), [input]); // re-renders triggered by unrelated state changes don't churn them.
const inputWsidList = useMemo(() => parseWorkshopInput(input), [input]);
const inputWsids = useMemo(() => new Set(inputWsidList), [inputWsidList]);
// True when the user has staged edits since the last successful sort. Stays // True when the user has staged edits since the last successful sort. Stays
// false until the first sort completes (lastSortedInputRef starts null). // false until the first sort completes (lastSortedInputRef starts null).
const sortPending = lastSortedInputRef.current !== null && input !== lastSortedInputRef.current; const sortPending = lastSortedInputRef.current !== null && input !== lastSortedInputRef.current;
@@ -1589,8 +1552,6 @@ function App() {
const onRetry = () => onSort(); const onRetry = () => onSort();
async function runResort(nextSelections) { async function runResort(nextSelections) {
// Snapshot for the diff panel: capture state before this resort.
previousResultRef.current = snapshotForDiff(_liveSortData);
// Compose the flat list of selected mod_ids from MOD_DB + nextSelections. // Compose the flat list of selected mod_ids from MOD_DB + nextSelections.
// For wsids not in nextSelections, use the §4 default (all-ticked or // For wsids not in nextSelections, use the §4 default (all-ticked or
// first-only depending on radio mode). For wsids with N=1, include the // first-only depending on radio mode). For wsids with N=1, include the
@@ -1794,9 +1755,6 @@ function App() {
// event as arg 0 - reject anything that isn't a string and fall back // event as arg 0 - reject anything that isn't a string and fall back
// to the state input. // to the state input.
const submitInput = typeof inputOverride === 'string' ? inputOverride : input; const submitInput = typeof inputOverride === 'string' ? inputOverride : input;
// Snapshot the about-to-be-replaced result so the [diff] button can
// surface what changed. Skip if there's nothing meaningful yet.
previousResultRef.current = snapshotForDiff(_liveSortData);
clearTimers(); clearTimers();
setState('loading'); setState('loading');
setProgress(15); setProgress(15);
@@ -2065,7 +2023,7 @@ function App() {
onAutoFixSwaps={onAutoFixSwaps} onAutoFixSwaps={onAutoFixSwaps}
onAutoFixRemoves={onAutoFixRemoves} onAutoFixRemoves={onAutoFixRemoves}
onRetry={onRetry} onRetry={onRetry}
previousResult={previousResultRef.current} inputWsidList={inputWsidList}
diffOpen={diffOpen} diffOpen={diffOpen}
setDiffOpen={setDiffOpen} setDiffOpen={setDiffOpen}
/> />