@akohn/dashql-react 0.0.20-dev.673.g3732f233a → 0.0.20-dev.872.ge142320b5

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.
Files changed (43) hide show
  1. package/NOTICE +53 -1
  2. package/README.md +88 -1
  3. package/dist/components/data_table/data_table.d.ts +0 -1
  4. package/dist/components/data_table/data_table.js +4 -9
  5. package/dist/components/data_table/data_table_cell_header_plots.d.ts +1 -3
  6. package/dist/components/data_table/data_table_cell_header_plots.js +4 -6
  7. package/dist/components/data_table/histogram_brush.d.ts +0 -1
  8. package/dist/components/data_table/histogram_brush.js +3 -5
  9. package/dist/components/data_table/histogram_cell.d.ts +0 -2
  10. package/dist/components/data_table/histogram_cell.js +1 -2
  11. package/dist/components/name_input.d.ts +1 -0
  12. package/dist/components/name_input.js +13 -1
  13. package/dist/components/query_history_viewer.d.ts +1 -3
  14. package/dist/components/query_history_viewer.js +7 -4
  15. package/dist/components/query_profile/profile_execution_controller.d.ts +0 -2
  16. package/dist/components/query_profile/profile_execution_controller.js +0 -12
  17. package/dist/components/query_profile/query_profile_view.d.ts +1 -9
  18. package/dist/components/query_profile/query_profile_view.js +19 -27
  19. package/dist/components/vegalite_chart.d.ts +0 -2
  20. package/dist/components/vegalite_chart.js +1 -3
  21. package/dist/components/vegalite_view.d.ts +0 -1
  22. package/dist/components/vegalite_view.js +9 -18
  23. package/dist/components/visualization/vegalite_preview.d.ts +1 -1
  24. package/dist/components/visualization/visualization_dispatch.d.ts +0 -1
  25. package/dist/components/visualization/visualization_dispatch.js +0 -1
  26. package/dist/components/visualization/visualization_panel.d.ts +1 -1
  27. package/dist/components/visualization/visualization_panel.js +0 -1
  28. package/dist/hooks.d.ts +2 -1
  29. package/dist/hooks.js +4 -1
  30. package/dist/logger.d.ts +2 -2
  31. package/dist/logger.js +8 -1
  32. package/dist/models/script_model.js +4 -14
  33. package/dist/platform/content_length.d.ts +1 -0
  34. package/dist/platform/content_length.js +7 -0
  35. package/dist/platform/core_provider.d.ts +18 -0
  36. package/dist/platform/core_provider.js +106 -0
  37. package/dist/platform/embedded_database_provider.d.ts +19 -0
  38. package/dist/platform/embedded_database_provider.js +53 -0
  39. package/dist/platform/page_runtime.d.ts +3 -0
  40. package/dist/platform/page_runtime.js +29 -0
  41. package/dist/vegalite/vegalite_image.d.ts +0 -2
  42. package/dist/vegalite/vegalite_image.js +1 -1
  43. package/package.json +372 -16
@@ -63,7 +63,6 @@ function VegaLiteChart(props) {
63
63
  };
64
64
  const onView = React.useRef(props.onView);
65
65
  onView.current = props.onView;
66
- const loader = props.loader ?? loadVega;
67
66
  const colorScheme = useColorScheme();
68
67
  const flavorId = useBrand().id;
69
68
  const datasetSizes = Object.fromEntries(Object.entries(props.datasets).map(([name, items]) => [`data-dataset-${name}`, items.length]));
@@ -74,7 +73,7 @@ function VegaLiteChart(props) {
74
73
  let disposed = false;
75
74
  let view = null;
76
75
  setReady(false);
77
- loader().then(async ({ embed, vega, expressionInterpreter }) => {
76
+ loadVega().then(async ({ embed, vega, expressionInterpreter }) => {
78
77
  if (disposed) return;
79
78
  const colors = resolveChartColors();
80
79
  const runtimeSpec = {
@@ -118,7 +117,6 @@ function VegaLiteChart(props) {
118
117
  };
119
118
  }, [
120
119
  spec,
121
- loader,
122
120
  colorScheme,
123
121
  flavorId
124
122
  ]);
@@ -17,7 +17,6 @@ export interface VegaLiteViewProps {
17
17
  vegaLiteSpec: TopLevelSpec | null;
18
18
  width?: number;
19
19
  height?: number;
20
- scale?: number;
21
20
  hideLegend?: boolean;
22
21
  config?: (colors: ChartColors) => Config;
23
22
  className?: string;
@@ -125,17 +125,15 @@ function VegaLiteView(props) {
125
125
  React.useEffect(() => {
126
126
  crossFilterUpdaterRef.current?.update(crossFilterMask);
127
127
  }, [crossFilterMask]);
128
- const scale = props.scale != null && props.scale > 0 ? props.scale : 1;
129
- const width = props.width != null ? Math.round(props.width / scale) : null;
130
- const height = props.height != null ? Math.round(props.height / scale) : null;
128
+ const width = props.width ?? null;
129
+ const height = props.height ?? null;
131
130
  React.useEffect(() => {
132
131
  const el = containerRef.current;
133
- if (!el || !spec || !rows) return;
132
+ if (!el || !rows || crossFilterBinding == null) return;
134
133
  let disposed = false;
135
134
  let finalizeView = null;
136
135
  let stableScaleDomains = [];
137
- const baseSpec = crossFilterBinding?.spec ?? (props.hideLegend ? stripLegends(spec) : spec);
138
- const runtimeSpec = { ...withViewEncodings(baseSpec) };
136
+ const runtimeSpec = { ...withViewEncodings(crossFilterBinding.spec) };
139
137
  runtimeSpec.width = width != null ? width : "container";
140
138
  runtimeSpec.height = height != null ? height : "container";
141
139
  runtimeSpec.autosize = {
@@ -173,11 +171,9 @@ function VegaLiteView(props) {
173
171
  return;
174
172
  }
175
173
  finalizeView = () => result.view.finalize();
176
- if (crossFilterBinding != null) {
177
- const updater = new VegaCrossFilterUpdater(result.view, crossFilterBinding.sourceDatasetName, rows, crossFilterBinding.maskDatasetName, crossFilterBinding.maskActiveSignalName, (e) => setError(e instanceof Error ? e.message : String(e)), stableScaleDomains);
178
- crossFilterUpdaterRef.current = updater;
179
- updater.update(crossFilterMaskRef.current);
180
- }
174
+ const updater = new VegaCrossFilterUpdater(result.view, crossFilterBinding.sourceDatasetName, rows, crossFilterBinding.maskDatasetName, crossFilterBinding.maskActiveSignalName, (e) => setError(e instanceof Error ? e.message : String(e)), stableScaleDomains);
175
+ crossFilterUpdaterRef.current = updater;
176
+ updater.update(crossFilterMaskRef.current);
181
177
  setError(null);
182
178
  }).catch((e) => {
183
179
  setError(e instanceof Error ? e.message : String(e));
@@ -190,13 +186,10 @@ function VegaLiteView(props) {
190
186
  if (el) el.replaceChildren();
191
187
  };
192
188
  }, [
193
- spec,
194
189
  rows,
195
190
  crossFilterBinding,
196
191
  width,
197
192
  height,
198
- scale,
199
- props.hideLegend,
200
193
  props.config,
201
194
  dependencies,
202
195
  colorScheme,
@@ -218,11 +211,9 @@ function VegaLiteView(props) {
218
211
  query: props.model?.query ?? null,
219
212
  rows: chartRows
220
213
  });
221
- const chartStyle = width != null || height != null || scale !== 1 ? {
214
+ const chartStyle = width != null || height != null ? {
222
215
  width: width ?? void 0,
223
- height: height ?? void 0,
224
- transform: scale !== 1 ? `scale(${scale})` : void 0,
225
- transformOrigin: scale !== 1 ? "top left" : void 0
216
+ height: height ?? void 0
226
217
  } : void 0;
227
218
  return /* @__PURE__ */ jsxs("div", {
228
219
  className: props.className ?? "dashql_root_vG43rg",
@@ -1,7 +1,7 @@
1
1
  import * as React from 'react';
2
2
  import { type VegaLiteViewProps } from '../vegalite_view.js';
3
3
  export declare const VEGALITE_PREVIEW_INSET = 8;
4
- export type VegaLitePreviewProps = Omit<VegaLiteViewProps, 'width' | 'height' | 'scale' | 'hideLegend' | 'config' | 'className'> & {
4
+ export type VegaLitePreviewProps = Omit<VegaLiteViewProps, 'width' | 'height' | 'hideLegend' | 'config' | 'className'> & {
5
5
  width: number;
6
6
  height: number;
7
7
  };
@@ -6,7 +6,6 @@ export interface VisualizationDispatchProps {
6
6
  visualizeQuery: ResolvedVisualizeQuery | null;
7
7
  width?: number;
8
8
  height?: number;
9
- scale?: number;
10
9
  hideLegend?: boolean;
11
10
  preview?: boolean;
12
11
  table: () => React.ReactNode;
@@ -24,7 +24,6 @@ function VisualizationDispatch(props) {
24
24
  vegaLiteSpec: vq.vegaLiteSpec,
25
25
  width: props.width,
26
26
  height: props.height,
27
- scale: props.scale,
28
27
  hideLegend: props.hideLegend
29
28
  });
30
29
  case "markdown": return /* @__PURE__ */ jsx(MarkdownView, {
@@ -1,7 +1,7 @@
1
1
  import * as React from 'react';
2
2
  import type { ResolvedVisualizeQuery } from '@akohn/dashql/platform/workbook/script_types';
3
3
  import { type VisualizationDispatchProps } from './visualization_dispatch.js';
4
- export interface VisualizationPanelProps extends Omit<VisualizationDispatchProps, 'visualizeQuery' | 'scale'> {
4
+ export interface VisualizationPanelProps extends Omit<VisualizationDispatchProps, 'visualizeQuery' | 'hideLegend'> {
5
5
  visualizeQuery: ResolvedVisualizeQuery;
6
6
  width?: number;
7
7
  height?: number;
@@ -27,7 +27,6 @@ function VisualizationPanel(props) {
27
27
  visualizeQuery: vq,
28
28
  width: props.width,
29
29
  height: props.height == null ? void 0 : Math.max(0, props.height - (showHeader ? HEADER_HEIGHT : 0)),
30
- hideLegend: props.hideLegend,
31
30
  preview: props.preview,
32
31
  table: props.table
33
32
  })
package/dist/hooks.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as React from 'react';
2
2
  import type * as arrow from 'apache-arrow';
3
3
  import type * as core from '@akohn/dashql';
4
- import type { Runtime, Settled } from '@akohn/dashql/runtime/runtime';
4
+ import type { Runtime, Settled } from '@akohn/dashql/runtime';
5
5
  import type { StoreView } from '@akohn/dashql/runtime/store/runtime_store';
6
6
  import type { ConnectionState } from '@akohn/dashql/platform/connections/connection_state';
7
7
  import type { EmbeddedClientContext, EmbeddedComputeDatabase } from '@akohn/dashql/platform/embedded_database';
@@ -54,6 +54,7 @@ export type TableComputationState = {
54
54
  export declare function useTableComputation(load: (() => Promise<arrow.Table>) | null, clientContext?: EmbeddedClientContext | null): TableComputationState;
55
55
  export interface WorkbookExecutionOptions {
56
56
  inputs?: readonly string[];
57
+ targets?: readonly number[];
57
58
  }
58
59
  export declare function useComputeReady(): boolean;
59
60
  export declare function useComputeDatabase(): EmbeddedComputeDatabase | null;
package/dist/hooks.js CHANGED
@@ -270,7 +270,10 @@ function useWorkbookExecution(workbookId) {
270
270
  workbookId,
271
271
  error: stringifyError(error)
272
272
  }, "workbook_execution");
273
- runtime.runWorkbook(workbookId, { inputs: options?.inputs == null ? void 0 : [...options.inputs] }).then((result) => {
273
+ runtime.runWorkbook(workbookId, {
274
+ inputs: options?.inputs == null ? void 0 : [...options.inputs],
275
+ targets: options?.targets == null ? void 0 : [...options.targets]
276
+ }).then((result) => {
274
277
  const failure = result.outcome.failure;
275
278
  if (failure != null && failure.kind === "error" && failure.queryId == null) failed(result.error);
276
279
  }, failed);
package/dist/logger.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import * as React from 'react';
2
- import type { Logger } from '@akohn/dashql/platform/logger/logger';
3
- export declare const LoggerContext: React.Context<Logger | null>;
2
+ import { Logger } from '@akohn/dashql/platform/logger/logger';
3
+ export declare const LoggerContext: React.Context<Logger>;
4
4
  export declare function useLogger(): Logger;
package/dist/logger.js CHANGED
@@ -1,5 +1,12 @@
1
1
  import * as React from "react";
2
- var LoggerContext = React.createContext(null);
2
+ import { Logger } from "@akohn/dashql/platform/logger/logger";
3
+ var DroppingLogger = class extends Logger {
4
+ destroy() {}
5
+ flushPendingRecords() {
6
+ this.pendingRecords = [];
7
+ }
8
+ };
9
+ var LoggerContext = React.createContext(new DroppingLogger());
3
10
  function useLogger() {
4
11
  return React.useContext(LoggerContext);
5
12
  }
@@ -1,27 +1,16 @@
1
- import { useDispatch, useOptionalRuntime, useScript, useViewSelector } from "../hooks.js";
1
+ import { useDispatch, useOptionalRuntime, useScript, useScriptRun, useViewSelector } from "../hooks.js";
2
2
  import { useQueryModel } from "./query_model.js";
3
3
  import * as React from "react";
4
- import { stringifyError } from "@akohn/dashql/platform/logger/logger";
5
4
  function useScriptModel(workbookId, scriptKey) {
6
5
  const runtime = useOptionalRuntime();
6
+ const runScript = useScriptRun();
7
7
  const script = useScript(scriptKey);
8
8
  const query = useQueryModel(script?.latestQueryId ?? null);
9
9
  const runActive = useViewSelector("run", workbookId, (run) => run?.state?.busy === true || run?.held != null);
10
10
  const dispatch = useDispatch({ workbook: workbookId });
11
11
  const key = script?.scriptKey ?? null;
12
12
  const operations = React.useMemo(() => key == null ? null : {
13
- run: async (options) => {
14
- if (runtime == null) return;
15
- try {
16
- await runtime.runScript(workbookId, key, { refresh: options?.refresh });
17
- } catch (error) {
18
- runtime.logger.warn("Workbook script run failed", {
19
- workbookId,
20
- scriptKey: key.toString(),
21
- error: stringifyError(error)
22
- }, "workbook_execution");
23
- }
24
- },
13
+ run: async (options) => await runScript?.(workbookId, key, options),
25
14
  cancel: async () => await runtime?.cancelScript(workbookId, key),
26
15
  setText: (text) => dispatch({
27
16
  kind: "setScriptText",
@@ -48,6 +37,7 @@ function useScriptModel(workbookId, scriptKey) {
48
37
  }).settled
49
38
  }, [
50
39
  runtime,
40
+ runScript,
51
41
  workbookId,
52
42
  key,
53
43
  dispatch
@@ -0,0 +1 @@
1
+ export declare function decodedContentLength(response: Response): number;
@@ -0,0 +1,7 @@
1
+ function decodedContentLength(response) {
2
+ const encoding = response.headers.get("content-encoding");
3
+ if (encoding != null && encoding.trim().toLowerCase() !== "identity") return 0;
4
+ const length = parseInt(response.headers.get("content-length") ?? "", 10);
5
+ return Number.isFinite(length) && length > 0 ? length : 0;
6
+ }
7
+ export { decodedContentLength };
@@ -0,0 +1,18 @@
1
+ import * as dashql from '@akohn/dashql';
2
+ import * as React from 'react';
3
+ import { type CoreSetup } from '../host.js';
4
+ export interface InstantiationProgress {
5
+ startedAt: Date;
6
+ updatedAt: Date;
7
+ bytesTotal: bigint;
8
+ bytesLoaded: bigint;
9
+ }
10
+ interface Props {
11
+ wasmUrl: string | URL;
12
+ children?: React.ReactNode;
13
+ }
14
+ export declare function DashQLCoreProvider(props: Props): React.FunctionComponentElement<React.ProviderProps<import("../host.js").Host>>;
15
+ export declare const useDashQLCoreSetupProgress: () => InstantiationProgress | null;
16
+ export declare function useDashQLCoreSetup(): CoreSetup;
17
+ export declare function useDashQLCore(): dashql.DashQL | null;
18
+ export {};
@@ -0,0 +1,106 @@
1
+ import { HostProvider, useHost } from "../host.js";
2
+ import { useLogger } from "../logger.js";
3
+ import { decodedContentLength } from "./content_length.js";
4
+ import * as React from "react";
5
+ import { stringifyError } from "@akohn/dashql/platform/logger/logger";
6
+ import * as dashql from "@akohn/dashql";
7
+ import { createTrace } from "@akohn/dashql/platform/logger/trace_context";
8
+ var PROGRESS_CONTEXT = React.createContext(null);
9
+ var CORE_CONTEXT = React.createContext(null);
10
+ function DashQLCoreProvider(props) {
11
+ const logger = useLogger();
12
+ const outer = useHost();
13
+ const wasmUrl = props.wasmUrl.toString();
14
+ const instantiation = React.useRef(null);
15
+ const lifecycle = React.useRef({ disposed: false });
16
+ const [progress, setProgress] = React.useState(null);
17
+ const [core, setCore] = React.useState(null);
18
+ const instantiator = React.useCallback(async (context) => {
19
+ const owner = lifecycle.current;
20
+ if (owner.disposed) throw new DOMException("Core provider was disposed", "AbortError");
21
+ if (instantiation.current != null) return await instantiation.current;
22
+ const now = /* @__PURE__ */ new Date();
23
+ const internal = {
24
+ startedAt: now,
25
+ updatedAt: now,
26
+ bytesTotal: BigInt(0),
27
+ bytesLoaded: BigInt(0)
28
+ };
29
+ const fetchWithProgress = async (url, traced) => {
30
+ traced.info("Fetching core wasm", { "context": context }, "core");
31
+ const response = await fetch(new Request(url));
32
+ if (!response.ok) throw new Error(`Failed to fetch core wasm: ${response.status} ${response.statusText}`);
33
+ const contentLength = decodedContentLength(response);
34
+ const now = /* @__PURE__ */ new Date();
35
+ internal.startedAt = now;
36
+ internal.updatedAt = now;
37
+ internal.bytesTotal = BigInt(contentLength) || BigInt(0);
38
+ internal.bytesLoaded = BigInt(0);
39
+ return new Response(response.body?.pipeThrough(new TransformStream({ transform(chunk, ctrl) {
40
+ const prevUpdate = internal.updatedAt;
41
+ internal.updatedAt = /* @__PURE__ */ new Date();
42
+ internal.bytesLoaded += BigInt(chunk.byteLength);
43
+ if (internal.updatedAt.getTime() - prevUpdate.getTime() > 20) setProgress((_) => ({ ...internal }));
44
+ ctrl.enqueue(chunk);
45
+ } })), response);
46
+ };
47
+ const instantiate = async () => {
48
+ const traced = logger.withTrace(createTrace());
49
+ const initStart = performance.now();
50
+ try {
51
+ traced.info("Loading core Wasm", { "context": context }, "core");
52
+ const response = await fetchWithProgress(wasmUrl, traced);
53
+ const wasmBinary = new Uint8Array(await response.arrayBuffer());
54
+ const instance = await dashql.DashQL.create({ wasmBinary });
55
+ if (owner.disposed) throw new DOMException("Core provider was disposed", "AbortError");
56
+ traced.info("Instantiated core", {
57
+ "context": context,
58
+ "duration": Math.floor(performance.now() - initStart).toString()
59
+ }, "core");
60
+ setProgress((_) => ({
61
+ ...internal,
62
+ updatedAt: /* @__PURE__ */ new Date()
63
+ }));
64
+ return instance;
65
+ } catch (e) {
66
+ traced.error("Failed to instantiate core", {
67
+ "error": stringifyError(e),
68
+ "duration": Math.floor(performance.now() - initStart).toString()
69
+ }, "core");
70
+ throw e;
71
+ }
72
+ };
73
+ instantiation.current = instantiate();
74
+ instantiation.current.then((instance) => {
75
+ if (!owner.disposed) setCore(instance);
76
+ }, () => {});
77
+ return await instantiation.current;
78
+ }, [logger, wasmUrl]);
79
+ React.useEffect(() => {
80
+ if (lifecycle.current.disposed) lifecycle.current = { disposed: false };
81
+ const owner = lifecycle.current;
82
+ return () => {
83
+ owner.disposed = true;
84
+ instantiation.current = null;
85
+ };
86
+ }, []);
87
+ const host = React.useMemo(() => ({
88
+ ...outer,
89
+ setupCore: instantiator
90
+ }), [outer, instantiator]);
91
+ return React.createElement(HostProvider, { value: host }, React.createElement(PROGRESS_CONTEXT.Provider, { value: progress }, React.createElement(CORE_CONTEXT.Provider, { value: core }, props.children)));
92
+ }
93
+ var useDashQLCoreSetupProgress = () => React.useContext(PROGRESS_CONTEXT);
94
+ function useDashQLCoreSetup() {
95
+ return useHost().setupCore;
96
+ }
97
+ function useDashQLCore() {
98
+ const setup = useHost().setupCore;
99
+ const core = React.useContext(CORE_CONTEXT);
100
+ const [instantiated] = React.useState(() => setup == null ? dashql.DashQL.instantiated() : null);
101
+ React.useEffect(() => {
102
+ if (setup != null && core == null) setup("runtime").catch(() => {});
103
+ }, [setup, core]);
104
+ return setup == null ? instantiated : core;
105
+ }
106
+ export { DashQLCoreProvider, useDashQLCore, useDashQLCoreSetup, useDashQLCoreSetupProgress };
@@ -0,0 +1,19 @@
1
+ import * as React from 'react';
2
+ import type { EmbeddedComputeDatabase } from '@akohn/dashql/platform/embedded_database';
3
+ import type { EmbeddedDatabaseOptions, SetupProgress } from '@akohn/dashql/platform/hyperdb/hyperdb_web';
4
+ import type { Logger } from '@akohn/dashql/platform/logger/logger';
5
+ export type { EmbeddedDatabaseOptions, SetupProgress };
6
+ export type EmbeddedDatabaseFactory = (context: string, logger: Logger, onSetupProgress?: (progress: SetupProgress) => void, options?: EmbeddedDatabaseOptions) => Promise<EmbeddedComputeDatabase>;
7
+ export type EmbeddedDatabaseSetupFn = (context: string, onSetupProgress?: (progress: SetupProgress) => void) => Promise<EmbeddedComputeDatabase>;
8
+ interface EmbeddedDatabase {
9
+ setup: EmbeddedDatabaseSetupFn;
10
+ terminate: () => Promise<void>;
11
+ }
12
+ interface Props {
13
+ setupDatabase: EmbeddedDatabaseFactory;
14
+ options?: EmbeddedDatabaseOptions | null;
15
+ children?: React.ReactNode;
16
+ }
17
+ export declare function EmbeddedDatabaseProvider(props: Props): React.FunctionComponentElement<React.ProviderProps<EmbeddedDatabase | null>>;
18
+ export declare function useEmbeddedDatabaseSetup(): EmbeddedDatabaseSetupFn | null;
19
+ export declare function useEmbeddedDatabaseTermination(): () => Promise<void>;
@@ -0,0 +1,53 @@
1
+ import { useLogger } from "../logger.js";
2
+ import * as React from "react";
3
+ var DATABASE_CTX = React.createContext(null);
4
+ var DEFAULT_OPTIONS = {};
5
+ function EmbeddedDatabaseProvider(props) {
6
+ const logger = useLogger();
7
+ const instantiation = React.useRef(null);
8
+ const [options, resolveOptions] = React.useMemo(() => {
9
+ let resolve;
10
+ return [new Promise((r) => {
11
+ resolve = r;
12
+ }), resolve];
13
+ }, []);
14
+ const knownOptions = props.options === void 0 ? DEFAULT_OPTIONS : props.options;
15
+ React.useEffect(() => {
16
+ if (knownOptions != null) resolveOptions(knownOptions);
17
+ }, [knownOptions, resolveOptions]);
18
+ const { setupDatabase } = props;
19
+ const setup = React.useCallback(async (context, onSetupProgress) => {
20
+ if (instantiation.current != null) return await instantiation.current;
21
+ const instantiate = async () => setupDatabase(context, logger, onSetupProgress, await options);
22
+ instantiation.current = instantiate().catch((error) => {
23
+ instantiation.current = null;
24
+ throw error;
25
+ });
26
+ return await instantiation.current;
27
+ }, [
28
+ logger,
29
+ setupDatabase,
30
+ options
31
+ ]);
32
+ const terminate = React.useCallback(async () => {
33
+ const pending = instantiation.current;
34
+ instantiation.current = null;
35
+ if (pending) await (await pending.catch(() => null))?.terminate();
36
+ }, []);
37
+ React.useEffect(() => () => {
38
+ terminate().catch(() => {});
39
+ }, [terminate]);
40
+ const database = React.useMemo(() => ({
41
+ setup,
42
+ terminate
43
+ }), [setup, terminate]);
44
+ return React.createElement(DATABASE_CTX.Provider, { value: database }, props.children);
45
+ }
46
+ function useEmbeddedDatabaseSetup() {
47
+ return React.useContext(DATABASE_CTX)?.setup ?? null;
48
+ }
49
+ function useEmbeddedDatabaseTermination() {
50
+ return React.useContext(DATABASE_CTX)?.terminate ?? NO_TERMINATION;
51
+ }
52
+ var NO_TERMINATION = async () => {};
53
+ export { EmbeddedDatabaseProvider, useEmbeddedDatabaseSetup, useEmbeddedDatabaseTermination };
@@ -0,0 +1,3 @@
1
+ import type { Runtime } from '@akohn/dashql/runtime';
2
+ export declare function usePageRuntime(create: () => Runtime): Runtime;
3
+ export declare function flushRuntimeStorage(runtime: Runtime, closing: boolean): Promise<void>;
@@ -0,0 +1,29 @@
1
+ import { useOwnedRuntime } from "../hooks.js";
2
+ import * as React from "react";
3
+ import { stringifyError } from "@akohn/dashql/platform/logger/logger";
4
+ function usePageRuntime(create) {
5
+ const runtime = useOwnedRuntime(create);
6
+ React.useEffect(() => runtime.computeDatabase.prepare(), [runtime]);
7
+ React.useEffect(() => {
8
+ const flush = (closing) => void flushRuntimeStorage(runtime, closing);
9
+ const flushIfHidden = () => {
10
+ if (document.visibilityState === "hidden") flush(false);
11
+ };
12
+ const flushOnPageHide = (event) => flush(!event.persisted);
13
+ window.addEventListener("pagehide", flushOnPageHide);
14
+ document.addEventListener("visibilitychange", flushIfHidden);
15
+ return () => {
16
+ window.removeEventListener("pagehide", flushOnPageHide);
17
+ document.removeEventListener("visibilitychange", flushIfHidden);
18
+ };
19
+ }, [runtime]);
20
+ return runtime;
21
+ }
22
+ async function flushRuntimeStorage(runtime, closing) {
23
+ try {
24
+ await runtime.storage.flush({ closing });
25
+ } catch (error) {
26
+ runtime.logger.error("Failed to flush the storage writer", { error: stringifyError(error) }, "runtime");
27
+ }
28
+ }
29
+ export { flushRuntimeStorage, usePageRuntime };
@@ -1,12 +1,10 @@
1
1
  import type { TopLevelSpec } from 'vega-lite';
2
2
  import { CHART_IMAGE_HEIGHT, CHART_IMAGE_SCALE, CHART_IMAGE_WIDTH } from '@akohn/dashql/platform/workbook/chart_config';
3
- import { type VegaModules } from './vegalite_loader.js';
4
3
  export { CHART_IMAGE_HEIGHT, CHART_IMAGE_SCALE, CHART_IMAGE_WIDTH };
5
4
  export interface ChartImageOptions {
6
5
  width?: number;
7
6
  height?: number;
8
7
  scale?: number;
9
- loader?: () => Promise<VegaModules>;
10
8
  }
11
9
  export interface ChartImage {
12
10
  png: Uint8Array;
@@ -3,7 +3,7 @@ import { createVegaLiteConfig, resolveChartColors } from "./vegalite_theme.js";
3
3
  import { CHART_IMAGE_HEIGHT, CHART_IMAGE_SCALE, CHART_IMAGE_WIDTH, chartImageConfig, chartImageSpec } from "@akohn/dashql/platform/workbook/chart_config";
4
4
  var VEGA_LOG_LEVEL_ERROR = 1;
5
5
  async function renderVegaLitePng(spec, rows, options = {}) {
6
- const { vega, vegaLite, expressionInterpreter } = await (options.loader ?? loadVega)();
6
+ const { vega, vegaLite, expressionInterpreter } = await loadVega();
7
7
  const sizedSpec = chartImageSpec(spec, rows, options.width ?? CHART_IMAGE_WIDTH, options.height ?? CHART_IMAGE_HEIGHT);
8
8
  const compiled = vegaLite.compile(sizedSpec, { config: chartImageConfig(createVegaLiteConfig(resolveChartColors("light"))) }).spec;
9
9
  const view = new vega.View(vega.parse(compiled, void 0, { ast: true }), {