Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 | 76x 76x 76x 76x 280x 54x 54x 54x 129x 129x 129x 64x 65x 4x 9x 1x 1x 1x 1x 1x 14x 9x 5x 90x 104x 90x 90x 18x 90x 103x 103x 103x 104x 216x 97x 97x 97x 1x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 32x 32x 32x 711x 97x 42x 97x 97x 42x 97x 42x 97x 97x 97x 97x 97x 97x 20x 20x 20x 12x 12x 12x 12x 9x 1x 6x 6x 6x 2x 2x 2x 1x 1x 1x 6x 6x 23x 23x 23x 23x 6x 1x 6x 6x 388x 2x 1x 97x 467x 97x 711x 97x 97x 97x 97x 5x 6x 8x 4x 1x 6x 97x 97x 97x 97x 97x 52x 45x 20x 105x 105x 81x 45x 1x 270x 225x | import { CircleAlert, CircleHelp, Plus, Trash2, Wand2 } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import {
AccessControlledButton as Button,
AccessControlledCheckbox as Checkbox,
AccessControlledInput as Input,
} from "@/ahuora-design-system/ui/accessControlled";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { Label } from "@/ahuora-design-system/ui/label";
import { SearchSelectInput } from "@/ahuora-design-system/ui/search-select-input";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/ahuora-design-system/ui/select";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import {
api,
DataColumnRead,
EligibleParameterSweepTarget,
MssInputModeEnum,
ParameterSweepPreviewResponse,
ParameterSweepRequest,
ParameterSweepRequestMethodEnum,
ScenarioRead,
useCoreScenarioEligibleParameterSweepTargetsListQuery,
useCoreScenarioGenerateParameterSweepCreateMutation,
useCoreScenarioParameterSweepPreviewCreateMutation,
} from "@/api/apiStore.gen";
import { useAppDispatch } from "@/store/hooks";
import { PreviewData } from "./PreviewData";
type SweepParameterForm = {
propertyValue?: number;
lowerBound: string;
upperBound: string;
step: string;
};
type PreviewLoadState =
| { status: "idle" | "loading" }
| { status: "success"; preview: ParameterSweepPreviewResponse }
| { status: "error"; error: unknown };
type SweepFormValues = {
method: ParameterSweepRequestMethodEnum;
sampleCount: string;
seed: string;
parameters: SweepParameterForm[];
};
const PARAMETER_SWEEP_HELP =
"Generate multiple steady-state input rows by varying one or more free numeric parameters. Grid mode creates every combination; sampling modes create a fixed number of rows inside the chosen bounds.";
const METHOD_OPTIONS = [
{
value: ParameterSweepRequestMethodEnum.Grid,
label: "Grid",
tooltip:
"Uses lower, upper, and step values to create every combination across the selected parameters.",
},
{
value: ParameterSweepRequestMethodEnum.MonteCarlo,
label: "Monte Carlo",
tooltip:
"Randomly samples values inside each selected parameter range. Use a seed when you need repeatable samples.",
},
{
value: ParameterSweepRequestMethodEnum.Hammersley,
label: "Hammersley",
tooltip:
"Uses a low-discrepancy sequence to spread a fixed number of samples evenly across the parameter ranges.",
},
{
value: ParameterSweepRequestMethodEnum.HaltonZaremba,
label: "Halton",
tooltip:
"Uses a deterministic Halton low-discrepancy sequence with no scrambling for broad, repeatable coverage of the parameter ranges.",
},
];
const createEmptyParameter = (): SweepParameterForm => ({
lowerBound: "",
upperBound: "",
step: "",
});
const isSamplingSweepMethod = (method: ParameterSweepRequestMethodEnum) =>
method !== ParameterSweepRequestMethodEnum.Grid;
const buildSweepRequest = ({
method,
sampleCount,
seed,
parameters,
}: SweepFormValues): ParameterSweepRequest => {
const isSamplingMethod = isSamplingSweepMethod(method);
return {
method,
parameters: parameters.map((parameter) => ({
property_value: parameter.propertyValue ?? 0,
lower_bound: parameter.lowerBound,
upper_bound: parameter.upperBound,
step: isSamplingMethod ? null : parameter.step,
})),
sample_count: isSamplingMethod ? Number(sampleCount) : null,
monte_carlo_seed:
method === ParameterSweepRequestMethodEnum.MonteCarlo && seed !== ""
? Number(seed)
: null,
};
};
const isSweepFormComplete = ({
method,
sampleCount,
parameters,
}: SweepFormValues) => {
const isSamplingMethod = isSamplingSweepMethod(method);
return (
parameters.length > 0 &&
parameters.every((parameter) => {
const hasBounds =
parameter.propertyValue !== undefined &&
parameter.lowerBound !== "" &&
parameter.upperBound !== "";
if (!hasBounds) {
return false;
}
return isSamplingMethod || parameter.step !== "";
}) &&
(!isSamplingMethod || Number(sampleCount) > 0)
);
};
const toRequestMethod = (method?: string): ParameterSweepRequestMethodEnum => {
if (
method &&
Object.values(ParameterSweepRequestMethodEnum).includes(
method as ParameterSweepRequestMethodEnum,
)
) {
return method as ParameterSweepRequestMethodEnum;
}
return ParameterSweepRequestMethodEnum.Grid;
};
const getErrorMessage = (error: unknown, fallback: string) => {
if (!error || typeof error !== "object") {
return fallback;
}
const data = "data" in error ? error.data : undefined;
if (typeof data === "string") {
return data;
}
if (data && typeof data === "object") {
if ("detail" in data && typeof data.detail === "string") {
return data.detail;
}
if ("error" in data && typeof data.error === "string") {
return data.error;
}
return Object.values(data)
.flat()
.filter((value) => typeof value === "string")
.join(" ");
}
return fallback;
};
const getUserFacingPreviewError = (message: string) => {
const cleanedMessage = message.replace(/^Value error,?\s*/i, "").trim();
return cleanedMessage || "Parameter sweep preview failed.";
};
function getSavedSweepParameters(scenario: ScenarioRead): SweepParameterForm[] {
const savedParameters = scenario.parameterSweepDefinition?.parameters ?? [];
if (savedParameters.length === 0) {
return [createEmptyParameter()];
}
return savedParameters.map((parameter) => ({
propertyValue: parameter.property_value,
lowerBound: parameter.lower_bound,
upperBound: parameter.upper_bound,
step: parameter.step ?? "",
}));
}
type ParameterSweepPanelProps = {
scenario: ScenarioRead;
dataColumns?: DataColumnRead[];
canMutate?: boolean;
};
type ParameterSweepPanelFormProps = ParameterSweepPanelProps & {
initialMethod: ParameterSweepRequestMethodEnum;
initialSampleCount: string;
initialSeed: string;
initialParameters: SweepParameterForm[];
};
export function ParameterSweepPanel({
scenario,
dataColumns = [],
canMutate = true,
}: ParameterSweepPanelProps) {
const savedDefinition = scenario.parameterSweepDefinition;
return (
<ParameterSweepPanelForm
key={scenario.id}
scenario={scenario}
dataColumns={dataColumns}
canMutate={canMutate}
initialMethod={toRequestMethod(savedDefinition?.method)}
initialSampleCount={savedDefinition?.sample_count?.toString() ?? "20"}
initialSeed={savedDefinition?.monte_carlo_seed?.toString() ?? ""}
initialParameters={getSavedSweepParameters(scenario)}
/>
);
}
function ParameterSweepPanelForm({
scenario,
dataColumns = [],
canMutate = true,
initialMethod,
initialSampleCount,
initialSeed,
initialParameters,
}: ParameterSweepPanelFormProps) {
const dispatch = useAppDispatch();
const isParameterSweepMode =
scenario.mss_input_mode === MssInputModeEnum.ParameterSweep;
const hasGeneratedRows =
isParameterSweepMode &&
(Boolean(scenario.parameterSweepDefinition) ||
dataColumns.some((column) => column.property_value != null));
const [method, setMethod] =
useState<ParameterSweepRequestMethodEnum>(initialMethod);
const [sampleCount, setSampleCount] = useState(initialSampleCount);
const [seed, setSeed] = useState(initialSeed);
const [parameters, setParameters] =
useState<SweepParameterForm[]>(initialParameters);
const { data: targets = [], isFetching: isLoadingTargets } =
useCoreScenarioEligibleParameterSweepTargetsListQuery({ id: scenario.id });
const [generateSweep, { isLoading: isGenerating }] =
useCoreScenarioGenerateParameterSweepCreateMutation();
const [requestPreview] = useCoreScenarioParameterSweepPreviewCreateMutation();
const [previewState, setPreviewState] = useState<PreviewLoadState>({
status: "idle",
});
const [confirmedPreviewKey, setConfirmedPreviewKey] = useState<string | null>(
null,
);
const latestPreviewRequestId = useRef(0);
const selectedTargetIds = useMemo(
() =>
new Set(
parameters
.map((parameter) => parameter.propertyValue)
.filter((value): value is number => value !== undefined),
),
[parameters],
);
const targetOptions = targets.map((target: EligibleParameterSweepTarget) => ({
value: String(target.property_value),
label: target.label,
}));
const currentFormValues = useMemo(
() => ({
method,
sampleCount,
seed,
parameters,
}),
[method, parameters, sampleCount, seed],
);
const isSamplingMethod = isSamplingSweepMethod(method);
const sweepRequest = useMemo(
() => buildSweepRequest(currentFormValues),
[currentFormValues],
);
const sweepRequestKey = useMemo(
() => JSON.stringify({ scenario: scenario.id, sweepRequest }),
[scenario.id, sweepRequest],
);
const isFormComplete = isSweepFormComplete(currentFormValues);
const preview =
previewState.status === "success" ? previewState.preview : undefined;
const isPreviewFetching = previewState.status === "loading";
const confirmLargeGeneration = confirmedPreviewKey === sweepRequestKey;
const showGenerateControls = canMutate && isFormComplete;
const canGenerate =
showGenerateControls &&
preview !== undefined &&
(!preview.warns_above_threshold || confirmLargeGeneration);
const requestPreviewForForm = async (formValues: SweepFormValues) => {
if (!canMutate || !isSweepFormComplete(formValues)) {
latestPreviewRequestId.current += 1;
setPreviewState({ status: "idle" });
return;
}
const requestId = latestPreviewRequestId.current + 1;
latestPreviewRequestId.current = requestId;
setPreviewState({ status: "loading" });
try {
const preview = await requestPreview({
id: scenario.id,
parameterSweepRequest: {
...buildSweepRequest(formValues),
confirm_replace: true,
confirm_large_generation: false,
},
}).unwrap();
if (latestPreviewRequestId.current === requestId) {
setPreviewState({ status: "success", preview });
}
} catch (error) {
if (latestPreviewRequestId.current === requestId) {
setPreviewState({ status: "error", error });
}
}
};
const handleMethodChange = (nextMethod: ParameterSweepRequestMethodEnum) => {
const nextFormValues = {
...currentFormValues,
method: nextMethod,
};
setMethod(nextMethod);
void requestPreviewForForm(nextFormValues);
};
const handleSampleCountChange = (nextSampleCount: string) => {
const nextFormValues = {
...currentFormValues,
sampleCount: nextSampleCount,
};
setSampleCount(nextSampleCount);
void requestPreviewForForm(nextFormValues);
};
const handleSeedChange = (nextSeed: string) => {
const nextFormValues = {
...currentFormValues,
seed: nextSeed,
};
setSeed(nextSeed);
void requestPreviewForForm(nextFormValues);
};
const buildPayload = (
preview: ParameterSweepPreviewResponse,
confirmLargeGeneration: boolean,
) => {
const previewSeed =
method === ParameterSweepRequestMethodEnum.MonteCarlo && seed === ""
? preview.monte_carlo_seed
: undefined;
return {
...sweepRequest,
monte_carlo_seed: previewSeed ?? sweepRequest.monte_carlo_seed,
confirm_replace: true,
confirm_large_generation: confirmLargeGeneration,
};
};
const updateParameter = (
index: number,
patch: Partial<SweepParameterForm>,
) => {
const nextParameters = parameters.map((parameter, currentIndex) =>
currentIndex === index ? { ...parameter, ...patch } : parameter,
);
setParameters(nextParameters);
void requestPreviewForForm({
...currentFormValues,
parameters: nextParameters,
});
};
const handleGenerate = async (
preview: ParameterSweepPreviewResponse,
confirmLargeGeneration: boolean,
) => {
if (preview.warns_above_threshold && !confirmLargeGeneration) {
toast.error("Wait for the row count and confirm required options.");
return;
}
try {
const result = await generateSweep({
id: scenario.id,
parameterSweepRequest: buildPayload(preview, confirmLargeGeneration),
}).unwrap();
if (
method === ParameterSweepRequestMethodEnum.MonteCarlo &&
seed === "" &&
result.monte_carlo_seed !== null &&
result.monte_carlo_seed !== undefined
) {
setSeed(String(result.monte_carlo_seed));
}
dispatch(
api.util.invalidateTags([
"mss" as never,
"DataColumns" as never,
"Scenario" as never,
"Optimizations" as never,
"ScenarioResultTable" as never,
]),
);
toast.success(`Generated ${result.row_count} parameter sweep rows.`);
} catch (error) {
toast.error(getErrorMessage(error, "Parameter sweep generation failed."));
}
};
return (
<div
data-testid="parameter-sweep-panel"
className="mt-3 border border-input rounded-md bg-background/70 p-3 flex flex-col gap-3"
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<Wand2 size={16} className="text-muted-foreground" />
<h3 className="text-sm font-medium">Parameter sweep</h3>
<Badge
variant="pending"
borderRadius="round"
aria-label="parameter-sweep-preview-feature"
>
Preview
</Badge>
<ToolTipCover
content={PARAMETER_SWEEP_HELP}
contentClassName="max-w-72"
asChild
side="right"
delay={150}
>
<Button
type="button"
variant="ghost"
size="xs"
writeAccessOnly={false}
className="text-muted-foreground"
aria-label="parameter-sweep-info"
>
<CircleHelp size={14} />
</Button>
</ToolTipCover>
</div>
{hasGeneratedRows && (
<Badge
variant="muted"
borderRadius="round"
className="text-muted-foreground font-light"
>
Active
</Badge>
)}
</div>
<div className="grid grid-cols-1 gap-2">
<div>
<Label className="text-xs" htmlFor="parameter-sweep-method">
Sampling
</Label>
<Select
value={method}
onValueChange={handleMethodChange}
disabled={!canMutate}
>
<SelectTrigger id="parameter-sweep-method" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>Sampling</SelectLabel>
{METHOD_OPTIONS.map((option) => (
<SelectItem
key={option.value}
value={option.value}
ariaLabel={`${option.label}. ${option.tooltip}`}
className="gap-4"
trailing={
<ToolTipCover
content={option.tooltip}
contentClassName="max-w-64"
asChild
side="right"
delay={150}
>
<span
className="inline-flex text-muted-foreground"
data-testid={`sampling-method-info-${option.value}`}
aria-hidden="true"
>
<CircleHelp size={13} />
</span>
</ToolTipCover>
}
>
<span className="truncate font-light">{option.label}</span>
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
</div>
{isSamplingMethod && (
<div
className={
method === ParameterSweepRequestMethodEnum.MonteCarlo
? "grid grid-cols-2 gap-2"
: "grid grid-cols-1 gap-2"
}
>
<div>
<Label className="text-xs" htmlFor="parameter-sweep-samples">
Samples
</Label>
<Input
id="parameter-sweep-samples"
type="number"
min={1}
value={sampleCount}
disabled={!canMutate}
onInput={(event) =>
handleSampleCountChange(event.currentTarget.value)
}
/>
</div>
{method === ParameterSweepRequestMethodEnum.MonteCarlo && (
<div>
<Label className="text-xs" htmlFor="parameter-sweep-seed">
Seed
</Label>
<Input
id="parameter-sweep-seed"
type="number"
min={0}
value={seed}
disabled={!canMutate}
onInput={(event) =>
handleSeedChange(event.currentTarget.value)
}
/>
</div>
)}
</div>
)}
</div>
<div className="flex flex-col gap-2">
{parameters.map((parameter, index) => {
const currentTarget = targets.find(
(target) => target.property_value === parameter.propertyValue,
);
const options = targetOptions.filter(
(option) =>
option.value === String(parameter.propertyValue) ||
!selectedTargetIds.has(Number(option.value)),
);
const lowerInputId = `sweep-lower-${index}`;
const upperInputId = `sweep-upper-${index}`;
const stepInputId = `sweep-step-${index}`;
return (
<div
key={index}
className="border border-input rounded-md p-2 flex flex-col gap-2"
>
<div className="flex items-center gap-2">
<div className="min-w-0 flex-1">
<SearchSelectInput
options={options}
value={
parameter.propertyValue
? String(parameter.propertyValue)
: ""
}
onValueChange={(value) =>
updateParameter(index, {
propertyValue: value ? Number(value) : undefined,
})
}
placeholder={
isLoadingTargets ? "Loading..." : "Select parameter"
}
searchPlaceholder="Search parameters"
ariaLabel={`parameter-sweep-target-${index}`}
disabled={!canMutate}
/>
</div>
<Button
type="button"
variant="ghost"
size="icon"
disabled={!canMutate}
aria-label={
parameters.length === 1
? `clear-sweep-parameter-${index}`
: `remove-sweep-parameter-${index}`
}
onClick={() => {
const nextParameters =
parameters.length === 1
? [createEmptyParameter()]
: parameters.filter(
(_, currentIndex) => currentIndex !== index,
);
setParameters(nextParameters);
void requestPreviewForForm({
...currentFormValues,
parameters: nextParameters,
});
}}
>
<Trash2 size={16} />
</Button>
</div>
{currentTarget && (
<p className="text-xs text-muted-foreground truncate">
{currentTarget.simulation_object_name} /{" "}
{currentTarget.property_name}
{currentTarget.unit ? ` (${currentTarget.unit})` : ""}
</p>
)}
<div
className={
isSamplingMethod
? "grid grid-cols-2 gap-2"
: "grid grid-cols-3 gap-2"
}
>
<div>
<Label className="text-xs" htmlFor={lowerInputId}>
Start
</Label>
<Input
id={lowerInputId}
type="number"
value={parameter.lowerBound}
disabled={!canMutate}
onInput={(event) =>
updateParameter(index, {
lowerBound: event.currentTarget.value,
})
}
/>
</div>
<div>
<Label className="text-xs" htmlFor={upperInputId}>
End
</Label>
<Input
id={upperInputId}
type="number"
value={parameter.upperBound}
disabled={!canMutate}
onInput={(event) =>
updateParameter(index, {
upperBound: event.currentTarget.value,
})
}
/>
</div>
{!isSamplingMethod && (
<div>
<Label className="text-xs" htmlFor={stepInputId}>
Step
</Label>
<Input
id={stepInputId}
type="number"
value={parameter.step}
disabled={!canMutate}
onInput={(event) =>
updateParameter(index, {
step: event.currentTarget.value,
})
}
/>
</div>
)}
</div>
</div>
);
})}
</div>
<Button
type="button"
variant="outline"
size="sm"
disabled={!canMutate || parameters.length >= targets.length}
onClick={() => {
const nextParameters = [...parameters, createEmptyParameter()];
setParameters(nextParameters);
void requestPreviewForForm({
...currentFormValues,
parameters: nextParameters,
});
}}
>
<Plus size={14} />
Add parameter
</Button>
<ParameterSweepPreview
previewState={previewState}
canMutate={canMutate}
isFormComplete={isFormComplete}
confirmLargeGeneration={confirmLargeGeneration}
onConfirmLargeGenerationChange={(confirmed) =>
setConfirmedPreviewKey(confirmed ? sweepRequestKey : null)
}
/>
{(hasGeneratedRows || showGenerateControls) && (
<div className="flex items-center justify-end gap-2">
{showGenerateControls && (
<Button
type="button"
size="sm"
disabled={isGenerating || isPreviewFetching || !canGenerate}
onClick={() => {
if (preview) {
void handleGenerate(preview, confirmLargeGeneration);
}
}}
>
Generate
</Button>
)}
{hasGeneratedRows ? (
<PreviewData
hasFile
onRemove={() => undefined}
fileName="Show data"
optimization={scenario}
canMutate={false}
previewAriaLabel="Show generated parameter sweep data"
triggerVariant="button"
triggerClassName="shrink-0"
/>
) : (
<Button
type="button"
variant="outline"
size="sm"
disabled
className="shrink-0"
>
Show data
</Button>
)}
</div>
)}
</div>
);
}
function ParameterSweepPreview({
previewState,
canMutate,
isFormComplete,
confirmLargeGeneration,
onConfirmLargeGenerationChange,
}: {
previewState: PreviewLoadState;
canMutate: boolean;
isFormComplete: boolean;
confirmLargeGeneration: boolean;
onConfirmLargeGenerationChange: (confirmed: boolean) => void;
}) {
const preview =
previewState.status === "success" ? previewState.preview : undefined;
const error =
previewState.status === "error" ? previewState.error : undefined;
const isFetching = previewState.status === "loading";
const showGenerateControls = canMutate && isFormComplete;
if (!showGenerateControls) {
return null;
}
return (
<>
{showGenerateControls && isFetching && !preview && (
<div className="rounded-md border border-input bg-muted/70 p-2 text-xs text-muted-foreground">
Calculating rows...
</div>
)}
{showGenerateControls && error && !preview && (
<div
role="alert"
className="flex items-start gap-2 rounded-md border border-orange-500/60 bg-orange-950 p-2 text-xs text-orange-100"
>
<CircleAlert
size={15}
className="mt-0.5 shrink-0 text-orange-300"
aria-hidden="true"
/>
<p className="leading-snug">
{getUserFacingPreviewError(
getErrorMessage(error, "Parameter sweep preview failed."),
)}
</p>
</div>
)}
{showGenerateControls && preview && (
<div className="rounded-md border border-input bg-muted/70 p-2 text-xs flex flex-col gap-1">
<div className="flex items-center justify-between gap-2">
<span>{preview.row_count} rows</span>
{preview.warns_above_threshold && (
<Badge variant="pending" borderRadius="round">
Large
</Badge>
)}
</div>
{preview.monte_carlo_seed !== null &&
preview.monte_carlo_seed !== undefined && (
<span className="text-muted-foreground">
Seed {preview.monte_carlo_seed}
</span>
)}
{preview.parameters.map((parameter) => (
<span
key={parameter.property_value}
className="text-muted-foreground"
>
{parameter.label}: {parameter.value_count}
</span>
))}
</div>
)}
{showGenerateControls && (
<div className="flex flex-col gap-2">
{preview?.warns_above_threshold && (
<label className="flex items-center gap-2 text-xs">
<Checkbox
checked={confirmLargeGeneration}
disabled={!canMutate}
onCheckedChange={(checked) =>
onConfirmLargeGenerationChange(checked === true)
}
/>
Generate more than {preview.warning_threshold} rows
</label>
)}
</div>
)}
</>
);
}
|