@milabench/bujang 0.1.17 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/types.d.ts CHANGED
@@ -918,6 +918,8 @@ export type OverviewBlock = {
918
918
  files?: string;
919
919
  /** Vega-Lite, its data the named dataset "rows"; else the builder fields below; neither: guessed */
920
920
  spec?: Record<string, unknown>;
921
+ /** first x values left out, of each event of each file */
922
+ skip?: number;
921
923
  mark?: string;
922
924
  x?: string;
923
925
  y?: string;
@@ -37,10 +37,35 @@ export declare const guessBuilder: (fields: JobDataField[], multipleFiles: boole
37
37
  /** The fields a spec reads (to fetch only those): every `field` of it */
38
38
  export declare const specFields: (spec: unknown, out?: Set<string>) => Set<string>;
39
39
  export declare const isDarkPage: () => boolean;
40
+ type Param = {
41
+ name?: string;
42
+ value?: unknown;
43
+ select?: unknown;
44
+ bind?: {
45
+ input?: string;
46
+ options?: unknown;
47
+ labels?: string[];
48
+ };
49
+ };
50
+ /** The params of a spec with an input. The options of a select can be those of a field of the rows
51
+ * (`options: {field: "epoch"}`), after "all" (null) */
52
+ export declare const boundParams: (spec: Record<string, unknown>, rows: Record<string, unknown>[], values: Map<string, unknown>) => Param[] | undefined;
53
+ /** The rows without the first `skip` x values of each event of each file. An x the spec computes: their `start`, else their `time` */
54
+ export declare const skipFirst: <T extends Record<string, unknown>>(rows: T[], spec: unknown, skip: number) => T[];
55
+ /** The number of first x values a chart leaves out */
56
+ export declare const SkipInput: React.FC<{
57
+ value: number;
58
+ onChange: (skip: number) => void;
59
+ onDone?: () => void;
60
+ }>;
61
+ /** The signals holding the zoom of a spec: those of its interval params bound to the scales (`<param>_<field>`), null: no zoom */
62
+ export declare const zoomSignals: (spec: Record<string, unknown>) => string[];
40
63
  /** A Vega-Lite spec rendered with vega-embed (loaded on first use), `rows` as the dataset "rows" */
41
64
  export declare const VegaChart: React.FC<{
42
65
  spec: Record<string, unknown>;
43
66
  rows: Record<string, unknown>[];
67
+ /** where the inputs of the params go, under the chart when absent */
68
+ controls?: HTMLElement | null;
44
69
  }>;
45
70
  /** The events of a panel (`event`: comma separated, "" for the records without event) */
46
71
  export declare const panelEvents: (event?: string) => string[];
@@ -60,3 +85,4 @@ export declare const panelOfBuilder: (b: Builder, event: string, title?: string)
60
85
  export declare const builderOfPanel: (p: Extract<OverviewBlock, {
61
86
  kind: "chart";
62
87
  }>) => Builder | null;
88
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milabench/bujang",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
package/src/types.ts CHANGED
@@ -965,6 +965,8 @@ export type OverviewBlock =
965
965
  files?: string;
966
966
  /** Vega-Lite, its data the named dataset "rows"; else the builder fields below; neither: guessed */
967
967
  spec?: Record<string, unknown>;
968
+ /** first x values left out, of each event of each file */
969
+ skip?: number;
968
970
  mark?: string;
969
971
  x?: string;
970
972
  y?: string;
@@ -35,7 +35,9 @@ import {
35
35
  MARKS,
36
36
  ROLE_ORDER,
37
37
  ROW_LIMIT,
38
+ SkipInput,
38
39
  fileRanks,
40
+ skipFirst,
39
41
  VegaChart,
40
42
  buildSpec,
41
43
  filesWithEvent,
@@ -256,10 +258,12 @@ export const JobDataOverview: React.FC<{
256
258
  const columnTargets = (layout?.panels || []).flatMap((p, i) => (
257
259
  p.kind === 'columns' ? p.columns.map((_, c) => ({ value: `${i}.${c}`, label: `row ${i + 1}, column ${c + 1}` })) : []
258
260
  ));
261
+ const [skip, setSkip] = useState(0);
262
+ const shownRows = useMemo(() => rows && skipFirst(rows, spec, skip), [rows, spec, skip]);
259
263
  const addToLayout = () => {
260
264
  const base = layout ?? { panels: [] };
261
265
  const chosen = selectedFiles === null ? {} : { files: activeFiles.map((f) => f.path).join(',') };
262
- const panel: OverviewBlock = { ...panelOfBuilder(builder, activeEvent), ...chosen };
266
+ const panel: OverviewBlock = { ...panelOfBuilder(builder, activeEvent), ...chosen, ...(skip ? { skip } : {}) };
263
267
  const [row, col] = columnTargets.some((t) => t.value === target) ? target.split('.').map(Number) : [-1, -1];
264
268
  changeLayout({
265
269
  panels: row < 0
@@ -470,6 +474,7 @@ export const JobDataOverview: React.FC<{
470
474
  <NativeSelect.Indicator />
471
475
  </NativeSelect.Root>
472
476
  )}
477
+ <SkipInput value={skip} onChange={setSkip} />
473
478
  <Button size="2xs" variant="outline" ml={columnTargets.length ? undefined : 'auto'} onClick={addToLayout} disabled={!layout}
474
479
  title="Add this chart to the layout of the job (then save the layout)">
475
480
  <LuPlus /> Add to job layout
@@ -481,7 +486,7 @@ export const JobDataOverview: React.FC<{
481
486
  <Alert.Description>{rowsError.message}</Alert.Description>
482
487
  </Alert.Root>
483
488
  )}
484
- {rows && <VegaChart spec={spec} rows={rows} />}
489
+ {shownRows && <VegaChart spec={spec} rows={shownRows} />}
485
490
  </Card.Body>
486
491
  </Card.Root>
487
492
 
@@ -10,7 +10,6 @@ import {
10
10
  VStack,
11
11
  HStack,
12
12
  Button,
13
- NativeSelect,
14
13
  Card,
15
14
  Spinner,
16
15
  Alert,
@@ -22,7 +21,7 @@ import {
22
21
  SegmentGroup,
23
22
  } from '@chakra-ui/react';
24
23
  import { toaster } from '../toast';
25
- import { LuArrowLeft, LuRefreshCw, LuX, LuInfo, LuClock, LuPencil } from 'react-icons/lu';
24
+ import { LuArrowLeft, LuRefreshCw, LuX, LuInfo, LuClock, LuPencil, LuTimer } from 'react-icons/lu';
26
25
  import { useQuery, useQueryClient } from '@tanstack/react-query';
27
26
  import { getSlurmJobStdoutFull, getSlurmJobStderrFull, getSlurmJobStdoutSize, getSlurmJobStderrSize, getSlurmJobStatusSimple, getSshJobStatus, getSlurmJobAccounting, rerunSlurmJob, cancelSlurmJob, getSlurmJobInfo, getSlurmJobCluster, getSlurmClusterStatus, earlySyncJob, getSlurmJobScript, getSlurmTemplates, getSlurmProfiles, getSlurmClusters } from '../api';
28
27
  import { JobSubmissionForm } from './JobSubmit';
@@ -36,29 +35,8 @@ import type { SlurmJobDetail, ApiError } from '../types';
36
35
  type JobLogsViewProps = Record<string, never>;
37
36
  type JobLogsTab = 'logs' | 'overview';
38
37
 
39
- // Seconds between two automatic early syncs: 'x2' waits twice the time the last one took
40
- type AutoSyncEvery = 'x2' | '10' | '30' | '60';
41
- const AUTO_SYNC_EVERY: { value: AutoSyncEvery; label: string }[] = [
42
- { value: 'x2', label: '2× sync time' },
43
- { value: '10', label: '10 s' },
44
- { value: '30', label: '30 s' },
45
- { value: '60', label: '60 s' },
46
- ];
47
- const AUTO_SYNC_KEY = 'bujang-auto-early-sync';
48
- /** 'x2' does not go below: each sync starts a step in the job */
49
- const AUTO_SYNC_MIN = 5;
50
-
51
- /** Seconds to the next automatic early sync; `took`: seconds of the last one */
52
- const autoSyncDelay = (every: AutoSyncEvery, took = 0) => (every === 'x2' ? Math.max(AUTO_SYNC_MIN, 2 * took) : Number(every));
53
-
54
- const savedAutoSyncEvery = (): AutoSyncEvery => {
55
- try {
56
- const saved = localStorage.getItem(AUTO_SYNC_KEY);
57
- return AUTO_SYNC_EVERY.find((o) => o.value === saved)?.value ?? 'x2';
58
- } catch {
59
- return 'x2';
60
- }
61
- };
38
+ // Seconds before a failed automatic early sync is tried again (a failure can be immediate)
39
+ const AUTO_SYNC_RETRY = 5;
62
40
 
63
41
  const getStatusColor = (status: string) => {
64
42
  switch (status?.toLowerCase()) {
@@ -148,11 +126,6 @@ export const JobLogsView: React.FC<JobLogsViewProps> = () => {
148
126
  // the job synced automatically: off when the page moves to another job
149
127
  const [autoSyncJob, setAutoSyncJob] = useState<string | null>(null);
150
128
  const autoSync = !!jrJobId && autoSyncJob === jrJobId;
151
- const [autoSyncEvery, setAutoSyncEvery] = useState<AutoSyncEvery>(savedAutoSyncEvery);
152
- const changeAutoSyncEvery = (value: AutoSyncEvery) => {
153
- try { localStorage.setItem(AUTO_SYNC_KEY, value); } catch { /* this page only */ }
154
- setAutoSyncEvery(value);
155
- };
156
129
 
157
130
  // Edit & Resubmit state
158
131
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
@@ -534,8 +507,8 @@ export const JobLogsView: React.FC<JobLogsViewProps> = () => {
534
507
  }
535
508
  };
536
509
 
537
- // Automatic early sync, while the job runs. A failed one is tried again at the next turn (the
538
- // error is shown on the button)
510
+ // Automatic early sync, while the job runs: again after twice the time the last one took. A failed
511
+ // one is tried again (the error is shown on the button)
539
512
  const { data: autoSyncResult, error: autoSyncFailure } = useQuery({
540
513
  queryKey: ['bujang-auto-early-sync', jrJobId, slurmJobId],
541
514
  queryFn: async () => {
@@ -549,7 +522,9 @@ export const JobLogsView: React.FC<JobLogsViewProps> = () => {
549
522
  return { ...result, took };
550
523
  },
551
524
  enabled: autoSync && !!slurmJobId && slurmJobId !== '-' && jobStatus?.toUpperCase() === 'RUNNING',
552
- refetchInterval: (query) => 1000 * autoSyncDelay(autoSyncEvery, query.state.data?.took),
525
+ refetchInterval: ({ state }) => 1000 * (
526
+ state.data?.status === 'ok' && !state.error ? 2 * state.data.took : AUTO_SYNC_RETRY
527
+ ),
553
528
  refetchOnWindowFocus: false,
554
529
  retry: false,
555
530
  gcTime: 0,
@@ -739,6 +714,11 @@ export const JobLogsView: React.FC<JobLogsViewProps> = () => {
739
714
  </Button>
740
715
  <Button
741
716
  variant={autoSync && !isJobTerminal ? 'solid' : 'outline'}
717
+ {...(autoSync && !isJobTerminal && !autoSyncError ? {
718
+ bg: 'var(--color-primary)',
719
+ color: 'var(--color-primary-text)',
720
+ _hover: { bg: 'var(--color-primary-hover)' },
721
+ } : {})}
742
722
  colorPalette={autoSync && autoSyncError ? 'red' : undefined}
743
723
  onClick={() => setAutoSyncJob(autoSync ? null : jrJobId ?? null)}
744
724
  disabled={!slurmJobId || slurmJobId === '-' || isJobTerminal}
@@ -748,22 +728,13 @@ export const JobLogsView: React.FC<JobLogsViewProps> = () => {
748
728
  px={2}
749
729
  title={autoSync && autoSyncError
750
730
  ? `Automatic early sync failed, trying again: ${autoSyncError}`
751
- : `Early sync while the job runs (${autoSync ? `on: every ${autoSyncDelay(autoSyncEvery, autoSyncResult?.took).toFixed(0)} s` : 'off'})`}
731
+ : autoSync
732
+ ? `Automatic early sync is on${autoSyncResult ? ` (every ${(2 * autoSyncResult.took).toFixed(1)} s, 2× the last sync)` : ''}: click to stop`
733
+ : 'Early sync again and again while the job runs, every 2× the time a sync takes'}
752
734
  >
735
+ <LuTimer />
753
736
  Auto
754
737
  </Button>
755
- <NativeSelect.Root size="md" w="140px" title="Time between two automatic early syncs">
756
- <NativeSelect.Field
757
- aria-label="Time between two automatic early syncs"
758
- value={autoSyncEvery}
759
- onChange={(e) => changeAutoSyncEvery(e.target.value as AutoSyncEvery)}
760
- borderLeftRadius={0}
761
- borderLeft="none"
762
- >
763
- {AUTO_SYNC_EVERY.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
764
- </NativeSelect.Field>
765
- <NativeSelect.Indicator />
766
- </NativeSelect.Root>
767
738
  </HStack>
768
739
  {canCancelJob(jobStatus) && (
769
740
  <Button
@@ -10,6 +10,7 @@ import { formatSize } from './JobArtifacts';
10
10
  import {
11
11
  FILE_FIELDS,
12
12
  ROW_LIMIT,
13
+ SkipInput,
13
14
  VegaChart,
14
15
  buildSpec,
15
16
  builderOfPanel,
@@ -18,6 +19,7 @@ import {
18
19
  mergeFields,
19
20
  panelEvents,
20
21
  panelFiles,
22
+ skipFirst,
21
23
  specFields,
22
24
  } from './dataCharts';
23
25
 
@@ -828,7 +830,13 @@ const useChart = (jrJobId: string, files: JobData['files'], panel: ChartBlock) =
828
830
  };
829
831
 
830
832
  /** The chart of a block, or why there is none */
831
- const ChartView: React.FC<{ chart: ReturnType<typeof useChart>; files?: string }> = ({ chart, files }) => (
833
+ const ChartView: React.FC<{
834
+ chart: ReturnType<typeof useChart>;
835
+ /** the rows drawn, those of the chart when absent */
836
+ rows?: Record<string, unknown>[];
837
+ files?: string;
838
+ controls?: HTMLElement | null;
839
+ }> = ({ chart, rows = chart.rows, files, controls }) => (
832
840
  <>
833
841
  {!chart.fields.length && (
834
842
  <Text fontSize="sm" color="var(--color-text-muted)">
@@ -838,7 +846,7 @@ const ChartView: React.FC<{ chart: ReturnType<typeof useChart>; files?: string }
838
846
  {chart.error && (
839
847
  <Alert.Root status="error" mb={2}><Alert.Indicator /><Alert.Description>{chart.error.message}</Alert.Description></Alert.Root>
840
848
  )}
841
- {chart.ready && chart.spec && chart.rows && <VegaChart spec={chart.spec} rows={chart.rows} />}
849
+ {chart.ready && chart.spec && rows && <VegaChart spec={chart.spec} rows={rows} controls={controls} />}
842
850
  </>
843
851
  );
844
852
 
@@ -846,7 +854,17 @@ const ChartView: React.FC<{ chart: ReturnType<typeof useChart>; files?: string }
846
854
  export const ChartPanel: React.FC<PanelProps<'chart'>> = ({ jrJobId, files, panel, actions }) => {
847
855
  const chart = useChart(jrJobId, files, panel);
848
856
  const [open, setOpen] = useEditor(actions.onEditor);
857
+ // the inputs of the chart, on the line of its title
858
+ const [controls, setControls] = useState<HTMLElement | null>(null);
849
859
  const { event, rows, isFetching } = chart;
860
+ const [skip, setSkip] = useState(panel.skip ?? 0);
861
+ const shown = useMemo(() => rows && skipFirst(rows, chart.spec, skip), [rows, chart.spec, skip]);
862
+ // kept in the layout when it is edited
863
+ const saveSkip = () => {
864
+ if (!actions.editing || skip === (panel.skip ?? 0)) return;
865
+ const { skip: _skip, ...rest } = panel;
866
+ actions.onChange(skip ? { ...rest, skip } : rest);
867
+ };
850
868
  return (
851
869
  <PanelFrame
852
870
  title={panel.title || event || 'records'}
@@ -856,9 +874,24 @@ export const ChartPanel: React.FC<PanelProps<'chart'>> = ({ jrJobId, files, pane
856
874
  info={<>
857
875
  {isFetching && <Spinner size="xs" />}
858
876
  {rows && <Text>{rows.length}{rows.length >= ROW_LIMIT ? '+' : ''} rows</Text>}
877
+ <SkipInput value={skip} onChange={setSkip} onDone={saveSkip} />
878
+ <Box
879
+ ref={setControls}
880
+ css={{
881
+ '& > div': { display: 'flex', flexWrap: 'wrap', gap: '8px' },
882
+ '& label': { display: 'flex', alignItems: 'center', gap: '4px' },
883
+ '& select, & input': {
884
+ color: 'var(--color-text)',
885
+ background: 'var(--color-bg-card)',
886
+ border: '1px solid var(--color-border)',
887
+ borderRadius: '4px',
888
+ padding: '1px 4px',
889
+ },
890
+ }}
891
+ />
859
892
  </>}
860
893
  >
861
- <ChartView chart={chart} files={panel.files} />
894
+ <ChartView chart={chart} rows={shown} files={panel.files} controls={controls} />
862
895
  {open && (
863
896
  <ChartEditor
864
897
  jrJobId={jrJobId}
@@ -927,6 +960,7 @@ const ChartEditor: React.FC<{
927
960
  onApply({
928
961
  // a spec left as drawn: the builder fields of the panel stay
929
962
  ...(text === initialText && !panel.spec ? fields : { kind: 'chart' as const, spec: parsed }),
963
+ ...(panel.skip ? { skip: panel.skip } : {}),
930
964
  ...(title.trim() ? { title: title.trim() } : {}),
931
965
  event,
932
966
  ...(paths.trim() ? { files: paths.trim() } : {}),
@@ -1,6 +1,6 @@
1
1
  /** Charts of the JSONL data of a job: the chart builder, its Vega-Lite spec, and the chart itself. */
2
2
  import React, { useEffect, useRef, useState } from 'react';
3
- import { Alert, Box } from '@chakra-ui/react';
3
+ import { Alert, Box, HStack, Input, Text } from '@chakra-ui/react';
4
4
  import type { JobData, JobDataField, JobDataRole, OverviewBlock } from '../types';
5
5
  import { useColorMode } from '../hooks/useColorMode';
6
6
 
@@ -140,21 +140,117 @@ export const isDarkPage = () =>
140
140
  typeof document !== 'undefined' &&
141
141
  (document.documentElement.classList.contains('dark') || document.documentElement.dataset.theme === 'dark');
142
142
 
143
+ type Param = { name?: string; value?: unknown; select?: unknown; bind?: { input?: string; options?: unknown; labels?: string[] } };
144
+
145
+ /** The params of a spec with an input. The options of a select can be those of a field of the rows
146
+ * (`options: {field: "epoch"}`), after "all" (null) */
147
+ export const boundParams = (spec: Record<string, unknown>, rows: Record<string, unknown>[], values: Map<string, unknown>): Param[] | undefined => {
148
+ if (!Array.isArray(spec.params)) return undefined;
149
+ return (spec.params as Param[]).map((param) => {
150
+ if (!param.name || !param.bind || typeof param.bind !== 'object' || !param.bind.input) return param;
151
+ let { bind } = param;
152
+ const field = (bind.options as { field?: string } | undefined)?.field;
153
+ let value = values.has(param.name) ? values.get(param.name) : param.value;
154
+ if (typeof field === 'string') {
155
+ const found = [...new Set(rows.map((r) => r[field]).filter((v) => v !== undefined && v !== null))] as (number | string)[];
156
+ found.sort((a, b) => (typeof a === 'number' && typeof b === 'number' ? a - b : String(a).localeCompare(String(b))));
157
+ bind = { ...bind, options: [null, ...found], labels: ['all', ...found.map(String)] };
158
+ if (!found.includes(value as number | string)) value = null;
159
+ }
160
+ return { ...param, bind, value };
161
+ });
162
+ };
163
+
164
+ /** The fields of the x encodings of a spec, those of its layers included */
165
+ const xFields = (spec: unknown, out = new Set<string>()): Set<string> => {
166
+ if (Array.isArray(spec)) spec.forEach((item) => xFields(item, out));
167
+ else if (spec && typeof spec === 'object') {
168
+ const x = (spec as { encoding?: { x?: { field?: unknown } } }).encoding?.x?.field;
169
+ if (typeof x === 'string') out.add(x);
170
+ for (const key of ['layer', 'hconcat', 'vconcat', 'concat', 'spec']) xFields((spec as Record<string, unknown>)[key], out);
171
+ }
172
+ return out;
173
+ };
174
+
175
+ /** The rows without the first `skip` x values of each event of each file. An x the spec computes: their `start`, else their `time` */
176
+ export const skipFirst = <T extends Record<string, unknown>, >(rows: T[], spec: unknown, skip: number): T[] => {
177
+ if (!(skip > 0)) return rows;
178
+ const fields = [...xFields(spec), 'start', 'time'];
179
+ const groups = new Map<string, T[]>();
180
+ rows.forEach((r) => {
181
+ const key = `${r._file ?? ''}|${r.type ?? ''}`;
182
+ const group = groups.get(key);
183
+ if (group) group.push(r); else groups.set(key, [r]);
184
+ });
185
+ const dropped = new Set<T>();
186
+ groups.forEach((group) => {
187
+ const field = fields.find((f) => group.some((r) => typeof r[f] === 'number'));
188
+ if (!field) return;
189
+ const values = [...new Set(group.map((r) => r[field]).filter((v): v is number => typeof v === 'number'))].sort((a, b) => a - b);
190
+ const last = values[Math.min(skip, values.length) - 1];
191
+ group.forEach((r) => { if (typeof r[field] === 'number' && (r[field] as number) <= last) dropped.add(r); });
192
+ });
193
+ return rows.filter((r) => !dropped.has(r));
194
+ };
195
+
196
+ /** The number of first x values a chart leaves out */
197
+ export const SkipInput: React.FC<{ value: number; onChange: (skip: number) => void; onDone?: () => void }> = ({ value, onChange, onDone }) => (
198
+ <HStack gap={1} as="label" title="Leave out the first x values (of each event of each file)">
199
+ <Text fontSize="xs" color="var(--color-text-muted)">skip</Text>
200
+ <Input
201
+ size="2xs"
202
+ w="56px"
203
+ type="number"
204
+ min={0}
205
+ step={1}
206
+ aria-label="First x values left out"
207
+ value={value || ''}
208
+ placeholder="0"
209
+ onChange={(e) => onChange(Math.max(0, Math.floor(Number(e.target.value) || 0)))}
210
+ onBlur={onDone}
211
+ onKeyDown={(e) => { if (e.key === 'Enter') onDone?.(); }}
212
+ />
213
+ </HStack>
214
+ );
215
+
216
+ /** The signals holding the zoom of a spec: those of its interval params bound to the scales (`<param>_<field>`), null: no zoom */
217
+ export const zoomSignals = (spec: Record<string, unknown>): string[] => {
218
+ const encoding = (spec.encoding ?? {}) as Record<string, { field?: string } | undefined>;
219
+ return (Array.isArray(spec.params) ? (spec.params as { name?: string; bind?: unknown; select?: { encodings?: string[] } }[]) : [])
220
+ .filter((p) => p.name && p.bind === 'scales')
221
+ .flatMap((p) => (p.select?.encodings ?? ['x', 'y']).flatMap((channel) => {
222
+ const field = encoding[channel]?.field;
223
+ return field ? [`${p.name}_${field.replace(/\W/g, '_')}`] : [];
224
+ }));
225
+ };
226
+
143
227
  /** A Vega-Lite spec rendered with vega-embed (loaded on first use), `rows` as the dataset "rows" */
144
- export const VegaChart: React.FC<{ spec: Record<string, unknown>; rows: Record<string, unknown>[] }> = ({ spec, rows }) => {
228
+ export const VegaChart: React.FC<{
229
+ spec: Record<string, unknown>;
230
+ rows: Record<string, unknown>[];
231
+ /** where the inputs of the params go, under the chart when absent */
232
+ controls?: HTMLElement | null;
233
+ }> = ({ spec, rows, controls }) => {
145
234
  const ref = useRef<HTMLDivElement>(null);
146
235
  const [error, setError] = useState<string | null>(null);
147
236
  const { colorMode } = useColorMode();
237
+ // what is picked in the inputs of the chart, kept when its rows change
238
+ const picked = useRef(new Map<string, unknown>());
148
239
 
149
240
  useEffect(() => {
150
241
  let cancelled = false;
151
242
  let finalize: (() => void) | undefined;
152
243
  setError(null);
244
+ // one per chart made: an embed that ends too late fills one that is gone
245
+ const inputs = controls ? document.createElement('div') : undefined;
246
+ if (inputs) controls?.replaceChildren(inputs);
153
247
  import('vega-embed')
154
248
  .then(async ({ default: embed }) => {
155
249
  if (cancelled || !ref.current) return;
250
+ const params = boundParams(spec, rows, picked.current);
156
251
  const full = {
157
252
  ...spec,
253
+ ...(params ? { params } : {}),
158
254
  datasets: { ...((spec.datasets as object) || {}), rows },
159
255
  background: 'transparent',
160
256
  };
@@ -163,16 +259,37 @@ export const VegaChart: React.FC<{ spec: Record<string, unknown>; rows: Record<s
163
259
  theme: colorMode === 'dark' || isDarkPage() ? 'dark' : undefined,
164
260
  // canvas: the CSS reset of the page (font: inherit) would restyle the SVG texts Vega measured
165
261
  renderer: 'canvas',
262
+ ...(inputs ? { bind: inputs } : {}),
263
+ });
264
+ if (cancelled) {
265
+ result.finalize();
266
+ return;
267
+ }
268
+ finalize = result.finalize;
269
+ params?.forEach(({ name, bind }) => {
270
+ if (name && bind && typeof bind === 'object' && bind.input) {
271
+ result.view.addSignalListener(name, (_, value) => {
272
+ picked.current.set(name, value);
273
+ // other rows: the zoom on the previous ones would hide them (once the update is over)
274
+ const zoomed = zoomSignals(spec);
275
+ if (!zoomed.length) return;
276
+ window.setTimeout(() => {
277
+ if (cancelled) return;
278
+ zoomed.forEach((signal) => {
279
+ try { result.view.signal(signal, null); } catch { /* not a signal of this chart */ }
280
+ });
281
+ void result.view.runAsync();
282
+ });
283
+ });
284
+ }
166
285
  });
167
- if (cancelled) result.finalize();
168
- else finalize = result.finalize;
169
286
  })
170
287
  .catch((err: unknown) => !cancelled && setError(err instanceof Error ? err.message : String(err)));
171
288
  return () => {
172
289
  cancelled = true;
173
290
  finalize?.();
174
291
  };
175
- }, [spec, rows, colorMode]);
292
+ }, [spec, rows, colorMode, controls]);
176
293
 
177
294
  return (
178
295
  // room for the chart while it loads