70 lines
2 KiB
TypeScript
70 lines
2 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { actionClass } from '@/components/ui/formStyles';
|
|
import { downloadJsonText } from '@/utils/downloadJsonText';
|
|
import { backtestApiV2 } from '../services/backtestApiV2';
|
|
|
|
/** Changing the dataset discards pending transport state before another download is possible. */
|
|
export function DatasetDownload({ hash }: { hash: string }) {
|
|
return <Download key={hash} hash={hash} />;
|
|
}
|
|
|
|
function Download({ hash }: { hash: string }) {
|
|
const alive = useRef(false);
|
|
const pending = useRef<AbortController | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState('');
|
|
useEffect(() => {
|
|
alive.current = true;
|
|
return () => {
|
|
alive.current = false;
|
|
pending.current?.abort();
|
|
};
|
|
}, []);
|
|
|
|
const download = async () => {
|
|
if (!alive.current || pending.current) {
|
|
return;
|
|
}
|
|
const controller = new AbortController();
|
|
pending.current = controller;
|
|
setLoading(true);
|
|
setError('');
|
|
const current = () =>
|
|
alive.current && !controller.signal.aborted && pending.current === controller;
|
|
try {
|
|
const text = await backtestApiV2.downloadCanonicalDataset(hash, controller.signal);
|
|
if (!current()) {
|
|
return;
|
|
}
|
|
downloadJsonText(text, `dataset-${hash}.json`);
|
|
} catch (cause) {
|
|
if (current()) {
|
|
setError(cause instanceof Error ? cause.message : 'Could not download retained dataset');
|
|
}
|
|
} finally {
|
|
if (current()) {
|
|
pending.current = null;
|
|
setLoading(false);
|
|
}
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="space-y-2">
|
|
<button
|
|
type="button"
|
|
className={actionClass}
|
|
disabled={loading}
|
|
onClick={() => void download()}
|
|
>
|
|
{error ? 'Retry dataset download' : 'Download retained dataset'}
|
|
</button>
|
|
{loading && <p role="status">Downloading retained dataset...</p>}
|
|
{error && (
|
|
<p role="alert" className="text-error text-sm">
|
|
{error}
|
|
</p>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|