@timefoldai/viz-platform 0.0.0-stage → 0.1.0

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 (59) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +70 -2
  3. package/dist/analytics/use-analytics-bridge.d.mts +6 -0
  4. package/dist/analytics/use-analytics-bridge.mjs +21 -0
  5. package/dist/assignability/assignability.d.mts +97 -0
  6. package/dist/assignability/assignability.mjs +51 -0
  7. package/dist/assignability/use-assignability.d.mts +32 -0
  8. package/dist/assignability/use-assignability.mjs +151 -0
  9. package/dist/config/credential-channel.d.mts +13 -0
  10. package/dist/config/credential-channel.mjs +33 -0
  11. package/dist/config/embedding-params.d.mts +30 -0
  12. package/dist/config/embedding-params.mjs +54 -0
  13. package/dist/config/security.d.mts +36 -0
  14. package/dist/config/security.mjs +64 -0
  15. package/dist/dataset-context/DataSetContext.d.mts +215 -0
  16. package/dist/dataset-context/DataSetContext.mjs +170 -0
  17. package/dist/dataset-context/DataSetContextProvider.d.mts +19 -0
  18. package/dist/dataset-context/DataSetContextProvider.mjs +627 -0
  19. package/dist/dataset-context/DataSetLoader.d.mts +68 -0
  20. package/dist/dataset-context/DataSetLoader.mjs +130 -0
  21. package/dist/dataset-context/data-set-key.d.mts +2 -0
  22. package/dist/dataset-context/data-set-key.mjs +14 -0
  23. package/dist/dataset-context/model-api-url.d.mts +13 -0
  24. package/dist/dataset-context/model-api-url.mjs +27 -0
  25. package/dist/dataset-context/use-data-set-load-state.d.mts +26 -0
  26. package/dist/dataset-context/use-data-set-load-state.mjs +29 -0
  27. package/dist/dataset-context/use-fetch-dataset-resource.d.mts +8 -0
  28. package/dist/dataset-context/use-fetch-dataset-resource.mjs +20 -0
  29. package/dist/dataset-context/use-fetch-waypoints.d.mts +8 -0
  30. package/dist/dataset-context/use-fetch-waypoints.mjs +20 -0
  31. package/dist/dataset-context/use-run-events.d.mts +34 -0
  32. package/dist/dataset-context/use-run-events.mjs +138 -0
  33. package/dist/demo-data/use-demo-data.d.mts +42 -0
  34. package/dist/demo-data/use-demo-data.mjs +187 -0
  35. package/dist/env.d.mts +2 -0
  36. package/dist/env.mjs +4 -0
  37. package/dist/feature-flags/feature-flags.d.mts +34 -0
  38. package/dist/feature-flags/feature-flags.mjs +51 -0
  39. package/dist/feature-flags/use-feature-flag.d.mts +11 -0
  40. package/dist/feature-flags/use-feature-flag.mjs +17 -0
  41. package/dist/http/describe-response.d.mts +9 -0
  42. package/dist/http/describe-response.mjs +13 -0
  43. package/dist/http/models-api-request.d.mts +3 -0
  44. package/dist/http/models-api-request.mjs +20 -0
  45. package/dist/iframe-bridge/iframe-bridge.d.mts +10 -0
  46. package/dist/iframe-bridge/iframe-bridge.mjs +24 -0
  47. package/dist/iframe-bridge/use-iframe-bridge.d.mts +32 -0
  48. package/dist/iframe-bridge/use-iframe-bridge.mjs +200 -0
  49. package/dist/index.d.mts +16 -0
  50. package/dist/index.mjs +14 -0
  51. package/dist/solve-control/use-solve-control.d.mts +16 -0
  52. package/dist/solve-control/use-solve-control.mjs +46 -0
  53. package/dist/theme/prefers-dark.d.mts +11 -0
  54. package/dist/theme/prefers-dark.mjs +43 -0
  55. package/dist/view-channel/view-channel.d.mts +17 -0
  56. package/dist/view-channel/view-channel.mjs +67 -0
  57. package/dist/visualization-provider/VisualizationProvider.d.mts +20 -0
  58. package/dist/visualization-provider/VisualizationProvider.mjs +26 -0
  59. package/package.json +41 -3
@@ -0,0 +1,33 @@
1
+ "use client";
2
+ import { isTrustedMessageOrigin } from "../iframe-bridge/iframe-bridge.mjs";
3
+ import { useEffect, useRef } from "react";
4
+ import { z } from "zod";
5
+ // src/config/credential-channel.ts
6
+ const credentialMessageSchema = z.object({
7
+ type: z.literal("timefold:credential"),
8
+ apiKey: z.string().min(1)
9
+ });
10
+ /**
11
+ * Listens for an inbound credential handshake from the embedding parent, and
12
+ * no-ops entirely when the parent never sends one.
13
+ *
14
+ * @category Hooks
15
+ */
16
+ function useCredentialChannel({ allowlist, enabled = true, onCredential }) {
17
+ const onCredentialRef = useRef(onCredential);
18
+ useEffect(() => {
19
+ onCredentialRef.current = onCredential;
20
+ }, [onCredential]);
21
+ useEffect(() => {
22
+ if (!enabled) return;
23
+ function handleMessage(event) {
24
+ if (!isTrustedMessageOrigin(event, allowlist)) return;
25
+ const result = credentialMessageSchema.safeParse(event.data);
26
+ if (!result.success) return;
27
+ onCredentialRef.current(result.data.apiKey);
28
+ }
29
+ window.addEventListener("message", handleMessage);
30
+ return () => window.removeEventListener("message", handleMessage);
31
+ }, [enabled, allowlist]);
32
+ }
33
+ export { useCredentialChannel };
@@ -0,0 +1,30 @@
1
+ import { DevEmbeddingParams } from "../dataset-context/DataSetContext.mjs";
2
+ import { DistanceUnitSystem } from "@timefoldai/viz-core";
3
+ export type ResolvedEmbeddingParams = {
4
+ apiUrl?: string;
5
+ apiVersion?: string;
6
+ runId?: string;
7
+ tenantId?: string;
8
+ featureFlags: Set<string>;
9
+ apiKey?: string;
10
+ onPlatform: boolean;
11
+ isDevelopment: boolean;
12
+ platformChrome: boolean;
13
+ unitSystem: DistanceUnitSystem;
14
+ };
15
+ /** Reads a host-sent unit system; anything but `"imperial"` renders metric, the default for standalone use. */
16
+ export declare function parseDistanceUnitSystem(raw: string | null | undefined): DistanceUnitSystem;
17
+ /**
18
+ * Resolves every embedding param as `queryParam ?? devDefaults[param]`.
19
+ * Query params always win; `devDefaults` applies only when `isDevBuild`.
20
+ *
21
+ * @param hostname - `window.location.hostname`, read as one half of the
22
+ * `isDevelopment` inference.
23
+ */
24
+ export declare function resolveEmbeddingParams({ queryParams, devDefaults, isDevBuild, hostname, knownFlagParams }: {
25
+ queryParams: URLSearchParams;
26
+ devDefaults: DevEmbeddingParams;
27
+ isDevBuild: boolean;
28
+ hostname: string;
29
+ knownFlagParams?: readonly string[];
30
+ }): ResolvedEmbeddingParams;
@@ -0,0 +1,54 @@
1
+ import { parseBooleanParam, resolveFeatureFlags } from "../feature-flags/feature-flags.mjs";
2
+ import "@timefoldai/viz-core";
3
+ // src/config/embedding-params.ts
4
+ function resolveStringParam(queryParams, key, fallback) {
5
+ const queryValue = queryParams.get(key);
6
+ return queryValue !== null ? queryValue : fallback;
7
+ }
8
+ function isLoopbackHost(hostname) {
9
+ const host = hostname.toLowerCase().replace(/^\[|]$/g, "");
10
+ return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "::1";
11
+ }
12
+ /** Reads a host-sent unit system; anything but `"imperial"` renders metric, the default for standalone use. */
13
+ function parseDistanceUnitSystem(raw) {
14
+ return raw === "imperial" ? "imperial" : "metric";
15
+ }
16
+ function isOnPlatformParam(raw) {
17
+ return raw !== null && raw !== "0" && raw !== "false";
18
+ }
19
+ /**
20
+ * Resolves every embedding param as `queryParam ?? devDefaults[param]`.
21
+ * Query params always win; `devDefaults` applies only when `isDevBuild`.
22
+ *
23
+ * @param hostname - `window.location.hostname`, read as one half of the
24
+ * `isDevelopment` inference.
25
+ */
26
+ function resolveEmbeddingParams({ queryParams, devDefaults, isDevBuild, hostname, knownFlagParams }) {
27
+ const fallback = isDevBuild ? devDefaults : {};
28
+ const apiUrl = resolveStringParam(queryParams, "apiUrl", fallback.apiUrl);
29
+ const apiVersion = queryParams.get("apiVersion") ?? void 0;
30
+ const runId = resolveStringParam(queryParams, "runId", fallback.runId);
31
+ const tenantId = resolveStringParam(queryParams, "tenantId", fallback.tenantId);
32
+ const apiKey = resolveStringParam(queryParams, "apiKey", fallback.apiKey);
33
+ const onPlatform = isOnPlatformParam(queryParams.get("onPlatform"));
34
+ const platformChrome = parseBooleanParam(queryParams.get("platformChrome"));
35
+ const isDevelopment = isDevBuild || isLoopbackHost(hostname) || !onPlatform;
36
+ return {
37
+ apiUrl,
38
+ apiVersion,
39
+ runId,
40
+ tenantId,
41
+ featureFlags: resolveFeatureFlags({
42
+ queryParams,
43
+ fallbackFlags: fallback.featureFlags,
44
+ isDevelopment,
45
+ knownFlagParams
46
+ }),
47
+ apiKey,
48
+ onPlatform,
49
+ platformChrome,
50
+ isDevelopment,
51
+ unitSystem: parseDistanceUnitSystem(queryParams.get("unitSystem"))
52
+ };
53
+ }
54
+ export { parseDistanceUnitSystem, resolveEmbeddingParams };
@@ -0,0 +1,36 @@
1
+ /** The allowlist when an app names none: only the page's own origin is trusted. */
2
+ export declare const SAME_ORIGIN_ONLY: readonly string[];
3
+ /**
4
+ * Checks the `allowedApiHosts` of a config once, where the provider reads it: it trims, lower-cases and drops blanks.
5
+ * It throws on an entry that is not a bare host name, because such an entry can never match a host.
6
+ */
7
+ export declare function resolveAllowedApiHosts(entries?: readonly string[]): readonly string[];
8
+ /**
9
+ * True iff `origin` matches a host of `allowlist` exactly or as a dot-suffix, over `https:` only (`http:` for
10
+ * localhost); default-deny otherwise.
11
+ */
12
+ export declare function isAllowedOrigin(origin: string, allowlist: readonly string[]): boolean;
13
+ /**
14
+ * Resolves the API fetch host, gating any `apiUrl` override through the allowlist. A rejected `apiUrl` keeps the
15
+ * page's own origin and returns `embeddingError`, so the host is never a disallowed origin (default-deny).
16
+ */
17
+ export declare function resolveApiHost({ configHost, apiUrlParam, currentOrigin, allowlist }: {
18
+ configHost?: string;
19
+ apiUrlParam?: string | null;
20
+ currentOrigin: string;
21
+ allowlist: readonly string[];
22
+ }): {
23
+ host: string;
24
+ embeddingError?: string;
25
+ };
26
+ /**
27
+ * Resolves the Models API version: the host's when the platform catalog accepts it, else the app's own.
28
+ * An app without `configVersion` keeps the version in its paths; a malformed host value returns `embeddingError`.
29
+ */
30
+ export declare function resolveApiVersion({ configVersion, hostVersion }: {
31
+ configVersion?: string;
32
+ hostVersion?: string;
33
+ }): {
34
+ apiVersion?: string;
35
+ embeddingError?: string;
36
+ };
@@ -0,0 +1,64 @@
1
+ // src/config/security.ts
2
+ /** The allowlist when an app names none: only the page's own origin is trusted. */
3
+ const SAME_ORIGIN_ONLY = [];
4
+ const BARE_HOST_NAME = /^(?:localhost|[a-z0-9-]+(?:\.[a-z0-9-]+)+)$/;
5
+ const ONE_LABEL = /^[a-z0-9-]+$/;
6
+ /**
7
+ * Checks the `allowedApiHosts` of a config once, where the provider reads it: it trims, lower-cases and drops blanks.
8
+ * It throws on an entry that is not a bare host name, because such an entry can never match a host.
9
+ */
10
+ function resolveAllowedApiHosts(entries = SAME_ORIGIN_ONLY) {
11
+ const hosts = entries.map((entry) => entry.trim()).filter((entry) => entry !== "");
12
+ const invalid = hosts.find((host) => !BARE_HOST_NAME.test(host.toLowerCase()));
13
+ if (invalid !== void 0) throw new Error(ONE_LABEL.test(invalid.toLowerCase()) ? `allowedApiHosts: "${invalid}" has one label, so it would trust a whole top-level domain. List a host such as "api.example.com".` : `allowedApiHosts: "${invalid}" is not a host name. List a host such as "api.example.com", with no scheme, port or path.`);
14
+ return hosts.map((host) => host.toLowerCase());
15
+ }
16
+ /**
17
+ * True iff `origin` matches a host of `allowlist` exactly or as a dot-suffix, over `https:` only (`http:` for
18
+ * localhost); default-deny otherwise.
19
+ */
20
+ function isAllowedOrigin(origin, allowlist) {
21
+ if (!origin || allowlist.length === 0) return false;
22
+ let url;
23
+ try {
24
+ url = new URL(origin);
25
+ } catch {
26
+ return false;
27
+ }
28
+ const { hostname, protocol } = url;
29
+ if (!allowlist.some((base) => hostname === base || hostname.endsWith(`.${base}`))) return false;
30
+ if (protocol === "https:") return true;
31
+ return protocol === "http:" && (hostname === "localhost" || hostname === "127.0.0.1");
32
+ }
33
+ /**
34
+ * Resolves the API fetch host, gating any `apiUrl` override through the allowlist. A rejected `apiUrl` keeps the
35
+ * page's own origin and returns `embeddingError`, so the host is never a disallowed origin (default-deny).
36
+ */
37
+ function resolveApiHost({ configHost, apiUrlParam, currentOrigin, allowlist }) {
38
+ if (configHost) return { host: configHost };
39
+ const trimmed = apiUrlParam?.endsWith("/") ? apiUrlParam.slice(0, -1) : apiUrlParam;
40
+ if (!trimmed) return { host: currentOrigin };
41
+ if (URL.canParse(trimmed, currentOrigin)) {
42
+ const resolved = new URL(trimmed, currentOrigin);
43
+ if (resolved.origin === currentOrigin || isAllowedOrigin(resolved.origin, allowlist)) return { host: trimmed };
44
+ }
45
+ return {
46
+ host: currentOrigin,
47
+ embeddingError: `The API URL "${apiUrlParam}" is not an allowed host. The data loads from this page's own host.`
48
+ };
49
+ }
50
+ const API_VERSION_PATTERN = /^(?:v[0-9]+|[0-9a-f]{1,40}|SNAPSHOT)$/;
51
+ /**
52
+ * Resolves the Models API version: the host's when the platform catalog accepts it, else the app's own.
53
+ * An app without `configVersion` keeps the version in its paths; a malformed host value returns `embeddingError`.
54
+ */
55
+ function resolveApiVersion({ configVersion, hostVersion }) {
56
+ if (configVersion === void 0) return {};
57
+ if (hostVersion === void 0) return { apiVersion: configVersion };
58
+ if (API_VERSION_PATTERN.test(hostVersion)) return { apiVersion: hostVersion };
59
+ return {
60
+ apiVersion: configVersion,
61
+ embeddingError: `The API version "${hostVersion}" is not valid. Using the default API version (${configVersion}).`
62
+ };
63
+ }
64
+ export { SAME_ORIGIN_ONLY, isAllowedOrigin, resolveAllowedApiHosts, resolveApiHost, resolveApiVersion };
@@ -0,0 +1,215 @@
1
+ import { DistanceUnitSystem } from "@timefoldai/viz-core";
2
+ import { Dispatch } from "react";
3
+ /**
4
+ * A loadable item of the `GET {demoDataSetPath}` list: its `id` is both the picker's option id and its label.
5
+ * The list drops an item without an `id`, because nothing can load it.
6
+ */
7
+ export type DemoDataSetSummary = {
8
+ id: string;
9
+ };
10
+ /**
11
+ * The loaded/imported dataset that gets scheduled, POSTed wholesale as the
12
+ * solve request body.
13
+ */
14
+ export type ActiveDataSet<InputType> = {
15
+ id?: string;
16
+ modelInput: InputType;
17
+ };
18
+ /** Embedding params a dev build uses where the query string has none: a local run and its credentials. */
19
+ export type DevEmbeddingParams = {
20
+ apiUrl?: string;
21
+ runId?: string;
22
+ tenantId?: string;
23
+ apiKey?: string;
24
+ featureFlags?: string[];
25
+ };
26
+ /** The `config` of a `VisualizationProvider`: which model API it talks to and how it reads and merges data. */
27
+ export type VisualizationConfig<InputType, OutputType, MergedType = InputType> = {
28
+ apiVersion?: string;
29
+ dataSetPath: string;
30
+ demoDataSetPath: string;
31
+ /** @remarks Receives the API key; `allowedApiHosts` does not gate it, as it gates only the `apiUrl` parameter. */
32
+ host?: string;
33
+ /**
34
+ * @remarks Bare host names that may receive the API key and post to the embed, such as `"api.example.com"`: no
35
+ * scheme, port or path. An entry also trusts its subdomains, so `"example.com"` trusts `api.example.com`.
36
+ * @example
37
+ * ```ts
38
+ * allowedApiHosts: ["example.com", "localhost"]
39
+ * ```
40
+ * @defaultValue `[]`, so only the page's own origin is trusted
41
+ */
42
+ allowedApiHosts?: readonly string[];
43
+ /** @defaultValue {} */
44
+ devDefaults?: DevEmbeddingParams;
45
+ /** @remarks Called with `undefined` output before a solve has output; without it the input is the merged view. */
46
+ mergeData?: (inputData: InputType, outputData: OutputType | undefined) => MergedType;
47
+ validateInputData?: (inputData: InputType) => string | null;
48
+ };
49
+ /** The solver run lifecycle, as reported by the Models API `solverStatus` field. */
50
+ export type SolvingStatus = "DATASET_CREATED" | "DATASET_VALIDATED" | "DATASET_INVALID" | "DATASET_COMPUTED" | "SOLVING_SCHEDULED" | "SOLVING_STARTED" | "SOLVING_ACTIVE" | "SOLVING_COMPLETED" | "SOLVING_INCOMPLETE" | "SOLVING_FAILED" | "SOLVING_STOPPED";
51
+ /**
52
+ * True while the run is still in progress (any non-terminal status).
53
+ *
54
+ * @remarks
55
+ * The pre-solving states (`DATASET_CREATED`/`DATASET_COMPUTED`) count as in progress.
56
+ */
57
+ export declare function isActivelySolving(solverStatus: SolvingStatus): boolean;
58
+ /**
59
+ * True while the app should show a solve at work: the solver runs, or a solve the reader started here is warming up.
60
+ * A pre-built run (`DATASET_COMPUTED`) stays non-terminal so its events are still read, but nothing solves it.
61
+ */
62
+ export declare function isSolveAtWork(status: DataSetStatus, inAppSolveActive: boolean): boolean;
63
+ /** True for the terminal statuses SolveButton renders as "Solve failed". */
64
+ export declare function isSolveFailure(solverStatus: SolvingStatus): boolean;
65
+ /**
66
+ * Unified lifecycle status for the active dataset — the single source of
67
+ * truth for loading a dataset by `runId` and for an in-app solve.
68
+ */
69
+ export type DataSetStatus = {
70
+ phase: "idle";
71
+ } | {
72
+ phase: "loading";
73
+ } | {
74
+ phase: "solving";
75
+ solveId: string;
76
+ solverStatus: SolvingStatus;
77
+ } | {
78
+ phase: "solve-failed";
79
+ solverStatus: SolvingStatus;
80
+ validationErrors?: string[];
81
+ } | {
82
+ phase: "error";
83
+ error: string;
84
+ };
85
+ /**
86
+ * Maps a freshly observed `solverStatus` to the next {@link DataSetStatus}.
87
+ *
88
+ * @remarks
89
+ * A missing/null `solverStatus` degrades to `idle` rather than an error.
90
+ */
91
+ export declare function resolveSolveStatus(solverStatus: SolvingStatus | null | undefined, solveId: string, validationErrors?: string[]): DataSetStatus;
92
+ /** What a page reads of the loaded dataset: its input, output, KPIs, score and run status. */
93
+ export type DataSetState<InputType, OutputType, MergedType = InputType, KpisType = unknown> = {
94
+ readonly isOnPlatform: boolean;
95
+ readonly dataSetId?: string;
96
+ readonly inputData?: InputType;
97
+ readonly outputData?: OutputType;
98
+ readonly mergedData?: MergedType;
99
+ readonly kpis?: KpisType;
100
+ readonly score: string;
101
+ /** @remarks The run lifecycle. To show a solve at work, read `useDataSetLoadState().isSolving`. */
102
+ readonly status: DataSetStatus;
103
+ };
104
+ export type DataSetProviderState<InputType, OutputType, MergedType = InputType, KpisType = unknown> = DataSetState<InputType, OutputType, MergedType, KpisType> & {
105
+ config: VisualizationConfig<InputType, OutputType, MergedType>;
106
+ allowedApiHosts: readonly string[];
107
+ isDevelopment: boolean;
108
+ apiKey?: string;
109
+ tenantId?: string;
110
+ featureFlags: Set<string>;
111
+ platformChrome: boolean;
112
+ embeddingError?: string;
113
+ dataSetName?: string;
114
+ activeDataSet: ActiveDataSet<InputType> | null;
115
+ inAppSolveActive: boolean;
116
+ };
117
+ /** The fixture data a provider starts from, for a test that mounts a page. `inputData` passes `validateInputData`. */
118
+ export type DataSetInitialState<InputType, OutputType, MergedType = InputType> = Partial<Pick<DataSetState<InputType, OutputType, MergedType>, "inputData" | "outputData" | "mergedData" | "kpis" | "score" | "status">>;
119
+ /** An action the dataset reducer handles to change the state of the loaded dataset. */
120
+ export type DataSetAction<InputType, OutputType, KpisType = unknown> = {
121
+ type: "SET_INPUT";
122
+ inputData: InputType;
123
+ source?: "run" | "local";
124
+ } | {
125
+ type: "REJECT_INPUT";
126
+ error: string;
127
+ } | {
128
+ type: "SET_OUTPUT";
129
+ outputData: OutputType;
130
+ kpis?: KpisType;
131
+ } | {
132
+ type: "SET_SCORE";
133
+ score: string;
134
+ } | {
135
+ type: "SET_STATUS";
136
+ status: DataSetStatus;
137
+ } | {
138
+ type: "START_SOLVE";
139
+ } | {
140
+ type: "SET_ACTIVE_DATASET";
141
+ activeDataSet: ActiveDataSet<InputType> | null;
142
+ } | {
143
+ type: "SET_IN_APP_SOLVE_ACTIVE";
144
+ active: boolean;
145
+ } | {
146
+ type: "SET_DATASET_ID";
147
+ dataSetId: string;
148
+ } | {
149
+ type: "SET_DATASET_NAME";
150
+ name: string;
151
+ } | {
152
+ type: "SET_API_KEY";
153
+ apiKey: string;
154
+ } | {
155
+ type: "SET_EMBEDDING_PARAMS";
156
+ tenantId: string;
157
+ dataSetId?: string;
158
+ apiKey: string;
159
+ host: string;
160
+ apiVersion?: string;
161
+ embeddingError?: string;
162
+ featureFlags: Set<string>;
163
+ };
164
+ export declare const DataSetStateContext: import("react").Context<DataSetProviderState<unknown, unknown, unknown, unknown> | null>;
165
+ export declare const DataSetDispatchContext: import("react").Context<Dispatch<DataSetAction<unknown, unknown, unknown>> | null>;
166
+ /** Holds the embedding host's unit system for {@link useDistanceUnitSystem}. */
167
+ export declare const DistanceUnitSystemContext: import("react").Context<DistanceUnitSystem>;
168
+ /**
169
+ * The unit system every distance renders in: the embedding host's choice, or metric when no host sent one.
170
+ *
171
+ * @category Hooks
172
+ */
173
+ export declare function useDistanceUnitSystem(): DistanceUnitSystem;
174
+ /** Holds the free height the embedding host reported, for {@link useViewportHeight}. */
175
+ export declare const HostViewportHeightContext: import("react").Context<number | undefined>;
176
+ /**
177
+ * The height a page may fill: the window standalone; on the platform the host's free height below the frame, or
178
+ * undefined until it reports one, because the frame itself is sized to the content.
179
+ *
180
+ * @category Hooks
181
+ */
182
+ export declare function useViewportHeight(): number | undefined;
183
+ /** The provider's solve controls and input writers, in their own context so a writer reads no state. */
184
+ export type DataSetControls = DataSetWriters<unknown> & {
185
+ startSolve: () => Promise<void>;
186
+ stopSolve: () => void;
187
+ };
188
+ export declare const DataSetControlsContext: import("react").Context<DataSetControls | null>;
189
+ /**
190
+ * The value of `useDataSet()`: the dataset state, the active dataset, and the functions that write them.
191
+ * A page fetches a dataset sub-resource through `useFetchDataSetResource()`, which keeps the key inside the library.
192
+ */
193
+ export type DataSet<InputType, OutputType, MergedType = InputType, KpisType = unknown> = DataSetState<InputType, OutputType, MergedType, KpisType> & {
194
+ isDevelopment: boolean;
195
+ activeDataSet: ActiveDataSet<InputType> | null;
196
+ updateOutputData: (outputData: OutputType, kpis?: KpisType) => void;
197
+ updateInputData: (inputData: InputType, source?: "run" | "local") => void;
198
+ updateActiveDataSet: (activeDataSet: ActiveDataSet<InputType> | null) => void;
199
+ };
200
+ export declare function useDataSetProviderState<InputType, OutputType, MergedType = InputType, KpisType = unknown>(): DataSetProviderState<InputType, OutputType, MergedType, KpisType>;
201
+ /** The `REJECT_INPUT` action naming what `validateInputData` finds wrong with the input, or `null` for valid input. */
202
+ export declare function rejectInvalidInput<InputType, OutputType, MergedType>(config: VisualizationConfig<InputType, OutputType, MergedType>, inputData: InputType): {
203
+ type: "REJECT_INPUT";
204
+ error: string;
205
+ } | null;
206
+ type DataSetWriters<InputType, OutputType = unknown> = Pick<DataSet<InputType, OutputType>, "updateInputData" | "updateActiveDataSet">;
207
+ /** The input writers of a dataset, which reject input that `validateInputData` refuses. */
208
+ export declare function createDataSetWriters<InputType, OutputType, MergedType, KpisType>(config: VisualizationConfig<InputType, OutputType, MergedType>, dispatch: Dispatch<DataSetAction<InputType, OutputType, KpisType>>): DataSetWriters<InputType, OutputType>;
209
+ export declare function useDataSetActions<InputType, OutputType = unknown>(): DataSetWriters<InputType, OutputType> & Pick<DataSetControls, "startSolve" | "stopSolve">;
210
+ /**
211
+ * Reads the loaded dataset from the nearest `VisualizationProvider`, as one object per state, with the
212
+ * `updateOutputData`, `updateInputData` and `updateActiveDataSet` writers a page uses to update it.
213
+ */
214
+ export declare function useDataSet<InputType, OutputType, MergedType = InputType, KpisType = unknown>(): DataSet<InputType, OutputType, MergedType, KpisType>;
215
+ export {};
@@ -0,0 +1,170 @@
1
+ "use client";
2
+ import "@timefoldai/viz-core";
3
+ import { createContext, use, useCallback, useMemo, useSyncExternalStore } from "react";
4
+ // src/dataset-context/DataSetContext.ts
5
+ const TERMINAL_FAILURE_STATUSES = [
6
+ "SOLVING_FAILED",
7
+ "SOLVING_INCOMPLETE",
8
+ "DATASET_INVALID"
9
+ ];
10
+ const TERMINAL_SUCCESS_STATUSES = ["SOLVING_COMPLETED", "SOLVING_STOPPED"];
11
+ function isTerminalStatus(solverStatus) {
12
+ return TERMINAL_FAILURE_STATUSES.includes(solverStatus) || TERMINAL_SUCCESS_STATUSES.includes(solverStatus);
13
+ }
14
+ /**
15
+ * True while the run is still in progress (any non-terminal status).
16
+ *
17
+ * @remarks
18
+ * The pre-solving states (`DATASET_CREATED`/`DATASET_COMPUTED`) count as in progress.
19
+ */
20
+ function isActivelySolving(solverStatus) {
21
+ return !isTerminalStatus(solverStatus);
22
+ }
23
+ const SOLVER_RUNNING_STATUSES = [
24
+ "SOLVING_SCHEDULED",
25
+ "SOLVING_STARTED",
26
+ "SOLVING_ACTIVE"
27
+ ];
28
+ /**
29
+ * True while the app should show a solve at work: the solver runs, or a solve the reader started here is warming up.
30
+ * A pre-built run (`DATASET_COMPUTED`) stays non-terminal so its events are still read, but nothing solves it.
31
+ */
32
+ function isSolveAtWork(status, inAppSolveActive) {
33
+ return status.phase === "solving" && (inAppSolveActive || SOLVER_RUNNING_STATUSES.includes(status.solverStatus));
34
+ }
35
+ /** True for the terminal statuses SolveButton renders as "Solve failed". */
36
+ function isSolveFailure(solverStatus) {
37
+ return TERMINAL_FAILURE_STATUSES.includes(solverStatus);
38
+ }
39
+ /**
40
+ * Maps a freshly observed `solverStatus` to the next {@link DataSetStatus}.
41
+ *
42
+ * @remarks
43
+ * A missing/null `solverStatus` degrades to `idle` rather than an error.
44
+ */
45
+ function resolveSolveStatus(solverStatus, solveId, validationErrors) {
46
+ if (solverStatus && isActivelySolving(solverStatus)) return {
47
+ phase: "solving",
48
+ solveId,
49
+ solverStatus
50
+ };
51
+ if (solverStatus && isSolveFailure(solverStatus)) return {
52
+ phase: "solve-failed",
53
+ solverStatus,
54
+ ...validationErrors && validationErrors.length > 0 ? { validationErrors } : {}
55
+ };
56
+ return { phase: "idle" };
57
+ }
58
+ const DataSetStateContext = createContext(null);
59
+ const DataSetDispatchContext = createContext(null);
60
+ /** Holds the embedding host's unit system for {@link useDistanceUnitSystem}. */
61
+ const DistanceUnitSystemContext = createContext("metric");
62
+ /**
63
+ * The unit system every distance renders in: the embedding host's choice, or metric when no host sent one.
64
+ *
65
+ * @category Hooks
66
+ */
67
+ function useDistanceUnitSystem() {
68
+ return use(DistanceUnitSystemContext);
69
+ }
70
+ /** Holds the free height the embedding host reported, for {@link useViewportHeight}. */
71
+ const HostViewportHeightContext = createContext(void 0);
72
+ function subscribeToWindowResize(onResize) {
73
+ window.addEventListener("resize", onResize);
74
+ return () => window.removeEventListener("resize", onResize);
75
+ }
76
+ /**
77
+ * The height a page may fill: the window standalone; on the platform the host's free height below the frame, or
78
+ * undefined until it reports one, because the frame itself is sized to the content.
79
+ *
80
+ * @category Hooks
81
+ */
82
+ function useViewportHeight() {
83
+ const { isOnPlatform } = useDataSetProviderState();
84
+ const hostHeight = use(HostViewportHeightContext);
85
+ const windowHeight = useSyncExternalStore(subscribeToWindowResize, () => window.innerHeight);
86
+ return isOnPlatform ? hostHeight : windowHeight;
87
+ }
88
+ const DataSetControlsContext = createContext(null);
89
+ const OUTSIDE_PROVIDER = "The dataset context is missing: call this hook inside a VisualizationProvider.";
90
+ function resolveMergedView(state) {
91
+ if (state.mergedData !== void 0) return state.mergedData;
92
+ if (state.inputData === void 0) return void 0;
93
+ return state.inputData;
94
+ }
95
+ function useDataSetProviderState() {
96
+ const state = use(DataSetStateContext);
97
+ const stateWithMergedView = useMemo(() => state === null ? null : {
98
+ ...state,
99
+ mergedData: resolveMergedView(state)
100
+ }, [state]);
101
+ if (stateWithMergedView === null) throw new Error(OUTSIDE_PROVIDER);
102
+ return stateWithMergedView;
103
+ }
104
+ function useDataSetDispatch() {
105
+ const dispatch = use(DataSetDispatchContext);
106
+ if (dispatch === null) throw new Error(OUTSIDE_PROVIDER);
107
+ return dispatch;
108
+ }
109
+ /** The `REJECT_INPUT` action naming what `validateInputData` finds wrong with the input, or `null` for valid input. */
110
+ function rejectInvalidInput(config, inputData) {
111
+ const problem = config.validateInputData?.(inputData);
112
+ return problem ? {
113
+ type: "REJECT_INPUT",
114
+ error: `Could not load the dataset: ${problem}.`
115
+ } : null;
116
+ }
117
+ /** The input writers of a dataset, which reject input that `validateInputData` refuses. */
118
+ function createDataSetWriters(config, dispatch) {
119
+ return {
120
+ updateInputData: (inputData, source) => dispatch(rejectInvalidInput(config, inputData) ?? {
121
+ type: "SET_INPUT",
122
+ inputData,
123
+ source
124
+ }),
125
+ updateActiveDataSet: (activeDataSet) => dispatch({
126
+ type: "SET_ACTIVE_DATASET",
127
+ activeDataSet
128
+ })
129
+ };
130
+ }
131
+ function useDataSetActions() {
132
+ const controls = use(DataSetControlsContext);
133
+ if (controls === null) throw new Error(OUTSIDE_PROVIDER);
134
+ return controls;
135
+ }
136
+ /**
137
+ * Reads the loaded dataset from the nearest `VisualizationProvider`, as one object per state, with the
138
+ * `updateOutputData`, `updateInputData` and `updateActiveDataSet` writers a page uses to update it.
139
+ */
140
+ function useDataSet() {
141
+ const state = useDataSetProviderState();
142
+ const dispatch = useDataSetDispatch();
143
+ const updateOutputData = useCallback((outputData, kpis) => dispatch({
144
+ type: "SET_OUTPUT",
145
+ outputData,
146
+ kpis
147
+ }), [dispatch]);
148
+ const { updateInputData, updateActiveDataSet } = useMemo(() => createDataSetWriters(state.config, dispatch), [state.config, dispatch]);
149
+ return useMemo(() => ({
150
+ isOnPlatform: state.isOnPlatform,
151
+ dataSetId: state.dataSetId,
152
+ inputData: state.inputData,
153
+ outputData: state.outputData,
154
+ mergedData: state.mergedData,
155
+ kpis: state.kpis,
156
+ score: state.score,
157
+ status: state.status,
158
+ isDevelopment: state.isDevelopment,
159
+ activeDataSet: state.activeDataSet,
160
+ updateOutputData,
161
+ updateInputData,
162
+ updateActiveDataSet
163
+ }), [
164
+ state,
165
+ updateOutputData,
166
+ updateInputData,
167
+ updateActiveDataSet
168
+ ]);
169
+ }
170
+ export { DataSetControlsContext, DataSetDispatchContext, DataSetStateContext, DistanceUnitSystemContext, HostViewportHeightContext, createDataSetWriters, isActivelySolving, isSolveAtWork, isSolveFailure, rejectInvalidInput, resolveSolveStatus, useDataSet, useDataSetActions, useDataSetProviderState, useDistanceUnitSystem, useViewportHeight };
@@ -0,0 +1,19 @@
1
+ import { DataSetAction, DataSetInitialState, DataSetProviderState, VisualizationConfig } from "./DataSetContext.mjs";
2
+ import { DistanceUnitSystem } from "@timefoldai/viz-core";
3
+ import { ReactNode } from "react";
4
+ /**
5
+ * The single owner of dataset load and solve state; exported for direct unit
6
+ * testing without mounting the provider.
7
+ */
8
+ export declare function dataSetReducer<InputType, OutputType, MergedType, KpisType>(state: DataSetProviderState<InputType, OutputType, MergedType, KpisType>, action: DataSetAction<InputType, OutputType, KpisType>): DataSetProviderState<InputType, OutputType, MergedType, KpisType>;
9
+ /**
10
+ * Provides the active dataset to descendant visualisation components.
11
+ *
12
+ * @category Providers
13
+ */
14
+ export declare function DataSetContextProvider<InputType, OutputType, MergedType = InputType>({ config, initialState, unitSystem, children }: {
15
+ config: VisualizationConfig<InputType, OutputType, MergedType>;
16
+ initialState?: DataSetInitialState<InputType, OutputType, MergedType>;
17
+ unitSystem?: DistanceUnitSystem;
18
+ children: ReactNode;
19
+ }): import("react").JSX.Element;