-
-
Notifications
You must be signed in to change notification settings - Fork 660
Expand file tree
/
Copy pathModelBuilderDialog.tsx
More file actions
982 lines (917 loc) · 33.3 KB
/
Copy pathModelBuilderDialog.tsx
File metadata and controls
982 lines (917 loc) · 33.3 KB
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
import { useTranslation } from "react-i18next";
import {
useAppStore,
type GeoLibreLayer,
type ProcessingModel,
type ProcessingModelStep,
} from "@geolibre/core";
import { detectGeometryProfile, type MapController } from "@geolibre/map";
import {
VECTOR_TOOLS,
getVectorTool,
runAlgorithmCapture,
runModel,
type AlgorithmParameter,
type GeometryFamily,
type ProcessingAlgorithm,
type RunnerHost,
} from "@geolibre/processing";
import { createDuckDbCapability } from "../../lib/duckdb-processing";
import { modelToPipeline, pipelineToModel } from "../../lib/processing-pipeline";
import {
Button,
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
Input,
Label,
ScrollArea,
Select,
Separator,
cn,
} from "@geolibre/ui";
import { ParameterField } from "./ParameterField";
import {
ArrowDown,
ArrowUp,
Download,
Layers,
Loader2,
Play,
Plus,
Save,
Trash2,
Upload,
Workflow,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
interface ModelBuilderDialogProps {
mapControllerRef: React.RefObject<MapController | null>;
}
/** The conventional id of a tool's primary input layer parameter. */
const PRIMARY_INPUT_PARAM = "layer";
/** Sample size when scanning a layer's attribute field names. */
const FIELD_SCAN_SAMPLE = 1000;
/** A best-effort unique id (webview always has crypto.randomUUID). */
function createId(): string {
return typeof crypto !== "undefined" && crypto.randomUUID
? crypto.randomUUID()
: `id-${Math.floor(performance.now())}-${VECTOR_TOOLS.length}`;
}
/** Vector tools grouped by their `group` label, preserving registry order. */
function groupedTools(): { group: string; tools: ProcessingAlgorithm[] }[] {
const groups: { group: string; tools: ProcessingAlgorithm[] }[] = [];
for (const tool of VECTOR_TOOLS) {
const label = tool.group ?? "Tools";
let entry = groups.find((g) => g.group === label);
if (!entry) {
entry = { group: label, tools: [] };
groups.push(entry);
}
entry.tools.push(tool);
}
return groups;
}
/** Render a `<select>`'s tool options grouped by registry group. */
function ToolOptions(): ReactElement {
return (
<>
{groupedTools().map((group) => (
<optgroup key={group.group} label={group.group}>
{group.tools.map((tool) => (
<option key={tool.id} value={tool.id}>
{tool.name}
</option>
))}
</optgroup>
))}
</>
);
}
/** GeoJSON layers usable as inputs, optionally filtered by geometry family. */
function geojsonLayers(layers: GeoLibreLayer[], filter?: GeometryFamily[]): GeoLibreLayer[] {
return layers.filter((layer) => {
if (layer.type !== "geojson" || !layer.geojson) return false;
if (!filter?.length) return true;
const profile = detectGeometryProfile(layer.geojson);
return filter.some(
(family) =>
(family === "point" && profile.hasPoint) ||
(family === "line" && profile.hasLine) ||
(family === "polygon" && profile.hasPolygon),
);
});
}
/** Default parameter values for a tool, keyed by parameter id. */
function defaultParams(tool: ProcessingAlgorithm): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const param of tool.parameters) {
if (param.default !== undefined) out[param.id] = param.default;
}
return out;
}
/** Whether a parameter is visible given the current parameter values. */
function isParamVisible(param: AlgorithmParameter, params: Record<string, unknown>): boolean {
const vw = param.visibleWhen;
if (!vw) return true;
const current = params[vw.param] as string | undefined;
if ("in" in vw) return current != null && vw.in.includes(current);
return current == null || !vw.notIn.includes(current);
}
/** Attribute field names per GeoJSON layer, sampled for schemaless data. */
function useFieldsByLayer(layers: GeoLibreLayer[], enabled: boolean): Map<string, string[]> {
return useMemo(() => {
const map = new Map<string, string[]>();
if (!enabled) return map;
for (const layer of layers) {
if (layer.type !== "geojson" || !layer.geojson) continue;
const keys = new Set<string>();
for (const feature of layer.geojson.features.slice(0, FIELD_SCAN_SAMPLE)) {
for (const key of Object.keys(feature.properties ?? {})) keys.add(key);
}
map.set(layer.id, [...keys]);
}
return map;
}, [layers, enabled]);
}
/** Read the current map viewport as [west, south, east, north]. */
function viewportBoundsReader(
mapControllerRef: React.RefObject<MapController | null>,
): () => [number, number, number, number] | null {
return () => {
const map = mapControllerRef.current?.getMap();
if (!map) return null;
const b = map.getBounds();
return [b.getWest(), b.getSouth(), b.getEast(), b.getNorth()];
};
}
/**
* Batch and pipeline runner UI (issue #344). Two modes share the vector-tools
* registry and run on the client engine:
*
* - **Batch**: apply one tool across many input layers with shared parameters.
* - **Models**: chain tools so each step's output feeds the next; saved with the
* project and re-runnable.
*/
export function ModelBuilderDialog({ mapControllerRef }: ModelBuilderDialogProps): ReactElement {
const { t } = useTranslation();
const open = useAppStore((s) => s.ui.modelBuilderOpen);
const setOpen = useAppStore((s) => s.setModelBuilderOpen);
const [mode, setMode] = useState<"batch" | "models">("batch");
return (
<Dialog
open={open}
onOpenChange={(next: boolean) => {
if (!next) setOpen(false);
}}
>
<DialogContent className="max-w-5xl">
<DialogHeader>
<DialogTitle>{t("processing.modelBuilder.title")}</DialogTitle>
<DialogDescription>{t("processing.modelBuilder.description")}</DialogDescription>
</DialogHeader>
<div className="inline-flex w-fit rounded-md border p-0.5 text-sm">
<button
type="button"
onClick={() => setMode("batch")}
className={cn(
"flex items-center gap-1.5 rounded px-3 py-1 transition-colors",
mode === "batch"
? "bg-accent font-medium text-accent-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
<Layers className="h-3.5 w-3.5" /> {t("processing.modelBuilder.tabBatch")}
</button>
<button
type="button"
onClick={() => setMode("models")}
className={cn(
"flex items-center gap-1.5 rounded px-3 py-1 transition-colors",
mode === "models"
? "bg-accent font-medium text-accent-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
<Workflow className="h-3.5 w-3.5" /> {t("processing.modelBuilder.tabModels")}
</button>
</div>
{mode === "batch" ? (
<BatchPanel mapControllerRef={mapControllerRef} />
) : (
<ModelPanel mapControllerRef={mapControllerRef} />
)}
</DialogContent>
</Dialog>
);
}
/** Output log shared by both panels. */
function LogView({ log }: { log: string[] }): ReactElement {
const { t } = useTranslation();
const endRef = useRef<HTMLDivElement>(null);
useEffect(() => {
endRef.current?.scrollIntoView({ block: "end" });
}, [log]);
return (
<ScrollArea className="h-24 rounded-md border bg-muted/30 p-2 font-mono text-xs">
{log.length === 0 ? (
<span className="text-muted-foreground">
{t("processing.modelBuilder.outputPlaceholder")}
</span>
) : (
log.map((line, index) => (
<div key={index} className="whitespace-pre-wrap">
{line}
</div>
))
)}
<div ref={endRef} />
</ScrollArea>
);
}
/** Batch mode: one tool over many input layers with shared parameters. */
function BatchPanel({ mapControllerRef }: ModelBuilderDialogProps): ReactElement {
const { t } = useTranslation();
const layers = useAppStore((s) => s.layers);
const addGeoJsonLayer = useAppStore((s) => s.addGeoJsonLayer);
const duckdb = useMemo(() => createDuckDbCapability(), []);
const [toolId, setToolId] = useState<string>(VECTOR_TOOLS[0].id);
const tool = useMemo(() => getVectorTool(toolId) ?? VECTOR_TOOLS[0], [toolId]);
const [params, setParams] = useState<Record<string, unknown>>(() => defaultParams(tool));
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [log, setLog] = useState<string[]>([]);
const [running, setRunning] = useState(false);
const appendLog = useCallback((message: string) => setLog((prev) => [...prev, message]), []);
// Reset parameters and selection when the tool changes.
useEffect(() => {
setParams(defaultParams(tool));
setSelectedIds([]);
setLog([]);
}, [tool]);
const fieldsByLayer = useFieldsByLayer(layers, true);
const primaryParam = tool.parameters.find(
(p) => p.id === PRIMARY_INPUT_PARAM && p.type === "layer",
);
const inputLayers = useMemo(
() => geojsonLayers(layers, primaryParam?.geometryFilter),
[layers, primaryParam],
);
// Every parameter except the primary input, which the batch iterates over.
const sharedParams = useMemo(
() => tool.parameters.filter((p) => p.id !== PRIMARY_INPUT_PARAM),
[tool],
);
const layerOptions = useCallback(
(filter?: GeometryFamily[]) => geojsonLayers(layers, filter),
[layers],
);
// Field options come from the param's source layer; a `field` whose source is
// the (iterated) primary input samples the first selected layer, assuming the
// batched layers share a schema.
const fieldOptions = useCallback(
(param: AlgorithmParameter): string[] => {
const sourceId = param.fieldSource ?? PRIMARY_INPUT_PARAM;
const layerId =
sourceId === PRIMARY_INPUT_PARAM
? selectedIds[0]
: (params[sourceId] as string | undefined);
return (layerId && fieldsByLayer.get(layerId)) || [];
},
[fieldsByLayer, params, selectedIds],
);
const handleParamChange = useCallback(
(id: string, value: unknown) => {
setParams((prev) => {
const next = { ...prev, [id]: value };
// Clear any field parameter that drew its options from this layer.
for (const param of tool.parameters) {
if (param.type === "field" && (param.fieldSource ?? PRIMARY_INPUT_PARAM) === id) {
next[param.id] = undefined;
}
}
return next;
});
},
[tool],
);
const toggleLayer = useCallback((id: string) => {
setSelectedIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
}, []);
const allSelected = inputLayers.length > 0 && selectedIds.length === inputLayers.length;
const toggleAll = useCallback(() => {
setSelectedIds(allSelected ? [] : inputLayers.map((l) => l.id));
}, [allSelected, inputLayers]);
const handleRun = useCallback(async () => {
setLog([]);
if (selectedIds.length === 0) {
appendLog("Error: select at least one input layer");
return;
}
for (const param of sharedParams) {
if (!param.required || !isParamVisible(param, params)) continue;
const value = params[param.id];
if (
value === undefined ||
value === "" ||
value === null ||
(param.type === "number" && Number.isNaN(value))
) {
appendLog(`Error: "${param.label}" is required`);
return;
}
}
setRunning(true);
const host: RunnerHost = {
layers,
log: appendLog,
duckdb,
viewportBounds: viewportBoundsReader(mapControllerRef),
};
try {
let produced = 0;
for (const id of selectedIds) {
const layer = layers.find((l) => l.id === id);
if (!layer) continue;
appendLog(`Running "${tool.name}" on ${layer.name}...`);
const output = await runAlgorithmCapture(
tool,
{ ...params, [PRIMARY_INPUT_PARAM]: id },
host,
);
if (output && output.features.length) {
addGeoJsonLayer(`${tool.name}: ${layer.name}`, output);
produced++;
} else {
appendLog(`No features produced for ${layer.name}`);
}
}
appendLog(`Batch complete: ${produced}/${selectedIds.length} layer(s) produced output`);
} catch (error) {
appendLog(`Error: ${(error as Error).message}`);
} finally {
setRunning(false);
}
}, [
selectedIds,
sharedParams,
params,
layers,
appendLog,
duckdb,
mapControllerRef,
tool,
addGeoJsonLayer,
]);
return (
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
<Label className="text-xs">{t("processing.modelBuilder.tool")}</Label>
<Select value={toolId} onChange={(e) => setToolId(e.target.value)}>
<ToolOptions />
</Select>
<p className="text-xs text-muted-foreground">{tool.description}</p>
</div>
<div className="grid grid-cols-2 gap-4">
{/* Shared parameters */}
<div className="flex flex-col gap-3">
<Label className="text-xs font-medium">
{t("processing.modelBuilder.sharedParameters")}
</Label>
{sharedParams.filter((p) => isParamVisible(p, params)).length === 0 ? (
<p className="text-xs text-muted-foreground">
{t("processing.modelBuilder.noExtraParameters")}
</p>
) : (
sharedParams
.filter((p) => isParamVisible(p, params))
.map((param) => (
<ParameterField
key={param.id}
param={param}
value={params[param.id]}
layerOptions={layerOptions(param.geometryFilter)}
fieldOptions={param.type === "field" ? fieldOptions(param) : undefined}
onChange={(value) => handleParamChange(param.id, value)}
/>
))
)}
</div>
{/* Input layers to iterate over */}
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between">
<Label className="text-xs font-medium">
{t("processing.modelBuilder.inputLayers")}
</Label>
{inputLayers.length > 0 ? (
<button
type="button"
className="text-xs text-muted-foreground hover:text-foreground"
onClick={toggleAll}
>
{allSelected
? t("processing.modelBuilder.clearSelection")
: t("processing.modelBuilder.selectAll")}
</button>
) : null}
</div>
<ScrollArea className="h-44 rounded-md border p-1">
{inputLayers.length === 0 ? (
<p className="p-2 text-xs text-muted-foreground">
{t("processing.modelBuilder.noCompatibleLayers")}
</p>
) : (
inputLayers.map((layer) => (
<label
key={layer.id}
className="flex items-center gap-2 rounded px-2 py-1 text-sm hover:bg-accent"
>
<input
type="checkbox"
className="h-4 w-4 rounded border-input"
checked={selectedIds.includes(layer.id)}
onChange={() => toggleLayer(layer.id)}
/>
<span className="truncate">{layer.name}</span>
</label>
))
)}
</ScrollArea>
</div>
</div>
<div>
<Button onClick={handleRun} disabled={running} className="gap-2">
{running ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
Run batch
</Button>
</div>
<LogView log={log} />
</div>
);
}
/** Models mode: chain tools into a saved, re-runnable pipeline. */
function ModelPanel({ mapControllerRef }: ModelBuilderDialogProps): ReactElement {
const { t } = useTranslation();
const layers = useAppStore((s) => s.layers);
const addGeoJsonLayer = useAppStore((s) => s.addGeoJsonLayer);
const models = useAppStore((s) => s.models);
const saveModel = useAppStore((s) => s.saveModel);
const deleteModel = useAppStore((s) => s.deleteModel);
const duckdb = useMemo(() => createDuckDbCapability(), []);
const [draft, setDraft] = useState<ProcessingModel>(() => ({
id: createId(),
name: "Untitled model",
steps: [],
}));
const [addToolId, setAddToolId] = useState<string>(VECTOR_TOOLS[0].id);
const [log, setLog] = useState<string[]>([]);
const [running, setRunning] = useState(false);
const [selectedStepId, setSelectedStepId] = useState<string | null>(null);
const importRef = useRef<HTMLInputElement>(null);
const appendLog = useCallback((message: string) => setLog((prev) => [...prev, message]), []);
const fieldsByLayer = useFieldsByLayer(layers, true);
const isSaved = models.some((m) => m.id === draft.id);
const newDraft = useCallback(() => {
setDraft({ id: createId(), name: "Untitled model", steps: [] });
setSelectedStepId(null);
setLog([]);
}, []);
const loadModel = useCallback((model: ProcessingModel) => {
// Deep clone so editing the draft never mutates the stored model.
setDraft({
id: model.id,
name: model.name,
steps: model.steps.map((s) => ({ ...s, parameters: { ...s.parameters } })),
});
setSelectedStepId(model.steps[0]?.id ?? null);
setLog([]);
}, []);
const addStep = useCallback(() => {
const tool = getVectorTool(addToolId);
if (!tool) return;
const id = createId();
setDraft((prev) => ({
...prev,
steps: [...prev.steps, { id, toolId: tool.id, parameters: defaultParams(tool) }],
}));
setSelectedStepId(id);
}, [addToolId]);
const removeStep = useCallback((stepId: string) => {
setDraft((prev) => ({
...prev,
steps: prev.steps.filter((s) => s.id !== stepId),
}));
setSelectedStepId((current) => (current === stepId ? null : current));
}, []);
const handleExport = useCallback(() => {
const json = JSON.stringify(modelToPipeline(draft), null, 2);
const url = URL.createObjectURL(new Blob([json], { type: "application/json" }));
const anchor = document.createElement("a");
const slug = draft.name
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "");
anchor.href = url;
anchor.download = `${slug || "pipeline"}.pipeline.json`;
anchor.click();
URL.revokeObjectURL(url);
appendLog(`Exported ${anchor.download}`);
}, [draft, appendLog]);
const handleImport = useCallback(
async (file: File) => {
try {
const model = pipelineToModel(JSON.parse(await file.text()), createId);
for (const step of model.steps) {
if (!getVectorTool(step.toolId)) throw new Error(`Unknown vector tool "${step.toolId}"`);
}
setDraft(model);
setSelectedStepId(model.steps[0]?.id ?? null);
setLog([`Imported ${file.name}`]);
} catch (error) {
appendLog(`Error: ${(error as Error).message}`);
}
},
[appendLog],
);
const moveStep = useCallback((stepId: string, dir: -1 | 1) => {
setDraft((prev) => {
const index = prev.steps.findIndex((s) => s.id === stepId);
const target = index + dir;
if (index < 0 || target < 0 || target >= prev.steps.length) return prev;
const steps = [...prev.steps];
[steps[index], steps[target]] = [steps[target], steps[index]];
return { ...prev, steps };
});
}, []);
const updateStepParam = useCallback((stepId: string, paramId: string, value: unknown) => {
setDraft((prev) => ({
...prev,
steps: prev.steps.map((step) => {
if (step.id !== stepId) return step;
const tool = getVectorTool(step.toolId);
const parameters = { ...step.parameters, [paramId]: value };
// Clear a field parameter when its source layer changes.
if (tool) {
for (const param of tool.parameters) {
if (param.type === "field" && (param.fieldSource ?? PRIMARY_INPUT_PARAM) === paramId) {
parameters[param.id] = undefined;
}
}
}
return { ...step, parameters };
}),
}));
}, []);
const handleSave = useCallback(() => {
const name = draft.name.trim();
if (!name) {
appendLog("Error: give the model a name before saving");
return;
}
if (draft.steps.length === 0) {
appendLog("Error: add at least one step before saving");
return;
}
saveModel({ ...draft, name });
appendLog(`Saved model "${name}"`);
}, [draft, saveModel, appendLog]);
const handleDelete = useCallback(() => {
deleteModel(draft.id);
appendLog(`Deleted model "${draft.name}"`);
newDraft();
}, [deleteModel, draft.id, draft.name, appendLog, newDraft]);
const handleRun = useCallback(async () => {
setLog([]);
if (draft.steps.length === 0) {
appendLog("Error: the model has no steps");
return;
}
const firstStep = draft.steps[0];
const inputParam = firstStep.inputParam ?? PRIMARY_INPUT_PARAM;
const inputId = firstStep.parameters[inputParam];
if (!inputId || !layers.some((l) => l.id === inputId)) {
appendLog("Error: pick an input layer for the first step");
return;
}
setRunning(true);
const host: RunnerHost = {
layers,
log: appendLog,
duckdb,
viewportBounds: viewportBoundsReader(mapControllerRef),
};
try {
const results = await runModel(draft, host);
const final = results[results.length - 1];
if (results.every((r) => !r.error) && final?.output?.features.length) {
addGeoJsonLayer(draft.name.trim() || final.toolName, final.output);
appendLog(`Model complete: added "${draft.name.trim()}"`);
} else if (results.some((r) => r.error)) {
appendLog("Model stopped before completing (see errors above)");
} else {
appendLog("Model produced no features");
}
} catch (error) {
appendLog(`Error: ${(error as Error).message}`);
} finally {
setRunning(false);
}
}, [draft, layers, appendLog, duckdb, mapControllerRef, addGeoJsonLayer]);
return (
<div className="flex gap-4">
{/* Saved models */}
<div className="flex w-44 shrink-0 flex-col gap-2">
<Button variant="outline" size="sm" className="gap-1.5" onClick={newDraft}>
<Plus className="h-3.5 w-3.5" /> {t("processing.modelBuilder.newModel")}
</Button>
<ScrollArea className="h-72 rounded-md border p-1">
{models.length === 0 ? (
<p className="p-2 text-xs text-muted-foreground">
{t("processing.modelBuilder.noSavedModels")}
</p>
) : (
models.map((model) => (
<button
key={model.id}
type="button"
onClick={() => loadModel(model)}
className={cn(
"w-full truncate rounded-md px-2 py-1.5 text-start text-sm transition-colors hover:bg-accent",
model.id === draft.id && "bg-accent font-medium text-accent-foreground",
)}
>
{model.name || t("processing.modelBuilder.untitledModel")}
</button>
))
)}
</ScrollArea>
</div>
{/* Editor */}
<div className="flex min-w-0 flex-1 flex-col gap-3">
<div className="flex flex-col gap-1">
<Label htmlFor="model-name" className="text-xs">
{t("processing.modelBuilder.modelName")}
</Label>
<Input
id="model-name"
value={draft.name}
onChange={(e) => setDraft((prev) => ({ ...prev, name: e.target.value }))}
/>
</div>
<WorkflowCanvas
steps={draft.steps}
selectedStepId={selectedStepId}
onSelect={setSelectedStepId}
/>
<ScrollArea className="h-56 rounded-md border p-2">
{draft.steps.length === 0 ? (
<p className="p-2 text-xs text-muted-foreground">
{t("processing.modelBuilder.emptyPipelineHint")}
</p>
) : (
<div className="flex flex-col gap-3">
{draft.steps.map((step, index) => (
<StepCard
key={step.id}
step={step}
index={index}
total={draft.steps.length}
layers={layers}
fieldsByLayer={fieldsByLayer}
onParamChange={(paramId, value) => updateStepParam(step.id, paramId, value)}
onRemove={() => removeStep(step.id)}
onMove={(dir) => moveStep(step.id, dir)}
selected={step.id === selectedStepId}
onSelect={() => setSelectedStepId(step.id)}
/>
))}
</div>
)}
</ScrollArea>
<div className="flex items-end gap-2">
<div className="flex flex-1 flex-col gap-1">
<Label className="text-xs">{t("processing.modelBuilder.addStep")}</Label>
<Select value={addToolId} onChange={(e) => setAddToolId(e.target.value)}>
<ToolOptions />
</Select>
</div>
<Button variant="outline" className="gap-1.5" onClick={addStep}>
<Plus className="h-4 w-4" /> {t("common.add")}
</Button>
</div>
<Separator />
<div className="flex flex-wrap items-center gap-2">
<Button onClick={handleRun} disabled={running} className="gap-2">
{running ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
{t("processing.modelBuilder.runModel")}
</Button>
<Button variant="outline" className="gap-2" onClick={handleSave}>
<Save className="h-4 w-4" /> {t("common.save")}
</Button>
<Button variant="outline" className="gap-2" onClick={() => importRef.current?.click()}>
<Upload className="h-4 w-4" /> {t("processing.modelBuilder.importPipeline")}
</Button>
<Button variant="outline" className="gap-2" onClick={handleExport}>
<Download className="h-4 w-4" /> {t("processing.modelBuilder.exportPipeline")}
</Button>
<input
ref={importRef}
type="file"
accept="application/json,.json"
className="hidden"
onChange={(event) => {
const file = event.target.files?.[0];
if (file) void handleImport(file);
event.target.value = "";
}}
/>
<Button variant="outline" className="gap-2" onClick={handleDelete} disabled={!isSaved}>
<Trash2 className="h-4 w-4" /> {t("processing.modelBuilder.deleteModel")}
</Button>
</div>
<LogView log={log} />
</div>
</div>
);
}
/** Compact node-and-edge canvas for the ordered graph executed by the model runner. */
function WorkflowCanvas({
steps,
selectedStepId,
onSelect,
}: {
steps: ProcessingModelStep[];
selectedStepId: string | null;
onSelect: (id: string) => void;
}): ReactElement {
const { t } = useTranslation();
return (
<div
className="min-h-28 overflow-x-auto rounded-md border bg-muted/20 p-4"
aria-label={t("processing.modelBuilder.canvas")}
>
{steps.length === 0 ? (
<p className="py-6 text-center text-xs text-muted-foreground">
{t("processing.modelBuilder.emptyPipelineHint")}
</p>
) : (
<div className="flex min-w-max items-center py-2">
{steps.map((step, index) => {
const tool = getVectorTool(step.toolId);
return (
<div key={step.id} className="flex items-center">
{index > 0 ? (
<div className="flex w-12 items-center" aria-hidden="true">
<div className="h-px flex-1 bg-primary/60" />
<div className="h-0 w-0 border-y-4 border-s-8 border-y-transparent border-s-primary/60" />
</div>
) : null}
<button
type="button"
onClick={() => onSelect(step.id)}
className={cn(
"w-40 rounded-lg border bg-card px-3 py-2 text-start shadow-sm transition-colors hover:bg-accent",
selectedStepId === step.id && "border-primary ring-2 ring-primary/30",
)}
aria-pressed={selectedStepId === step.id}
>
<span className="block text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
{index + 1}. {t("processing.modelBuilder.stepKindTransform")}
</span>
<span className="block truncate text-sm font-medium">
{tool?.name ?? step.toolId}
</span>
</button>
</div>
);
})}
</div>
)}
</div>
);
}
interface StepCardProps {
step: ProcessingModelStep;
index: number;
total: number;
layers: GeoLibreLayer[];
fieldsByLayer: Map<string, string[]>;
onParamChange: (paramId: string, value: unknown) => void;
onRemove: () => void;
onMove: (dir: -1 | 1) => void;
selected: boolean;
onSelect: () => void;
}
/** One step in the model editor: its tool, parameters, and reorder controls. */
function StepCard({
step,
index,
total,
layers,
fieldsByLayer,
onParamChange,
onRemove,
onMove,
selected,
onSelect,
}: StepCardProps): ReactElement {
const { t } = useTranslation();
const tool = getVectorTool(step.toolId);
const inputParam = step.inputParam ?? PRIMARY_INPUT_PARAM;
const isFirst = index === 0;
const layerOptions = useCallback(
(filter?: GeometryFamily[]) => geojsonLayers(layers, filter),
[layers],
);
// The chained input parameter is hidden on every step after the first (the
// runner supplies it from the previous step's output). Hidden `visibleWhen`
// parameters are skipped too.
const visibleParams = (tool?.parameters ?? []).filter((param) => {
if (!isFirst && param.id === inputParam) return false;
return isParamVisible(param, step.parameters);
});
const fieldOptions = (param: AlgorithmParameter): string[] => {
const sourceId = param.fieldSource ?? PRIMARY_INPUT_PARAM;
// A field drawn from the chained input has no resolvable layer on later
// steps (the upstream output is in-memory only), so offer no options there.
if (!isFirst && sourceId === inputParam) return [];
const layerId = step.parameters[sourceId] as string | undefined;
return (layerId && fieldsByLayer.get(layerId)) || [];
};
return (
<div
className={cn("rounded-md border p-2", selected && "border-primary ring-1 ring-primary")}
onClick={onSelect}
>
<div className="mb-2 flex items-center justify-between gap-2">
<span className="truncate text-sm font-medium">
{index + 1}. {tool?.name ?? step.toolId}
</span>
<div className="flex items-center gap-0.5">
<button
type="button"
className="rounded p-1 text-muted-foreground hover:bg-accent disabled:opacity-30"
onClick={(event) => {
event.stopPropagation();
onMove(-1);
}}
disabled={index === 0}
aria-label={t("processing.modelBuilder.moveStepUp")}
>
<ArrowUp className="h-3.5 w-3.5" />
</button>
<button
type="button"
className="rounded p-1 text-muted-foreground hover:bg-accent disabled:opacity-30"
onClick={(event) => {
event.stopPropagation();
onMove(1);
}}
disabled={index === total - 1}
aria-label={t("processing.modelBuilder.moveStepDown")}
>
<ArrowDown className="h-3.5 w-3.5" />
</button>
<button
type="button"
className="rounded p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
onClick={(event) => {
event.stopPropagation();
onRemove();
}}
aria-label={t("processing.modelBuilder.removeStep")}
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
{!isFirst ? (
<p className="mb-2 text-xs text-muted-foreground">
{t("processing.modelBuilder.inputPreviousStep")}
</p>
) : null}
{!tool ? (
<p className="text-xs text-destructive">
{t("processing.modelBuilder.unknownTool", { id: step.toolId })}
</p>
) : visibleParams.length === 0 ? (
<p className="text-xs text-muted-foreground">{t("processing.modelBuilder.noParameters")}</p>
) : (
<div className="flex flex-col gap-2">
{visibleParams.map((param) => (
<ParameterField
key={param.id}
param={param}
value={step.parameters[param.id]}
layerOptions={layerOptions(param.geometryFilter)}
fieldOptions={param.type === "field" ? fieldOptions(param) : undefined}
onChange={(value) => onParamChange(param.id, value)}
/>
))}
</div>
)}
</div>
);
}