@timefoldai/viz-platform 0.0.0 → 0.2.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 (58) hide show
  1. package/README.md +69 -1
  2. package/dist/analytics/use-analytics-bridge.d.mts +6 -0
  3. package/dist/analytics/use-analytics-bridge.mjs +21 -0
  4. package/dist/assignability/assignability.d.mts +97 -0
  5. package/dist/assignability/assignability.mjs +51 -0
  6. package/dist/assignability/use-assignability.d.mts +32 -0
  7. package/dist/assignability/use-assignability.mjs +151 -0
  8. package/dist/config/credential-channel.d.mts +13 -0
  9. package/dist/config/credential-channel.mjs +33 -0
  10. package/dist/config/embedding-params.d.mts +30 -0
  11. package/dist/config/embedding-params.mjs +54 -0
  12. package/dist/config/security.d.mts +36 -0
  13. package/dist/config/security.mjs +64 -0
  14. package/dist/dataset-context/DataSetContext.d.mts +215 -0
  15. package/dist/dataset-context/DataSetContext.mjs +170 -0
  16. package/dist/dataset-context/DataSetContextProvider.d.mts +19 -0
  17. package/dist/dataset-context/DataSetContextProvider.mjs +627 -0
  18. package/dist/dataset-context/DataSetLoader.d.mts +68 -0
  19. package/dist/dataset-context/DataSetLoader.mjs +130 -0
  20. package/dist/dataset-context/data-set-key.d.mts +2 -0
  21. package/dist/dataset-context/data-set-key.mjs +14 -0
  22. package/dist/dataset-context/model-api-url.d.mts +13 -0
  23. package/dist/dataset-context/model-api-url.mjs +27 -0
  24. package/dist/dataset-context/use-data-set-load-state.d.mts +26 -0
  25. package/dist/dataset-context/use-data-set-load-state.mjs +29 -0
  26. package/dist/dataset-context/use-fetch-dataset-resource.d.mts +8 -0
  27. package/dist/dataset-context/use-fetch-dataset-resource.mjs +20 -0
  28. package/dist/dataset-context/use-fetch-waypoints.d.mts +8 -0
  29. package/dist/dataset-context/use-fetch-waypoints.mjs +20 -0
  30. package/dist/dataset-context/use-run-events.d.mts +34 -0
  31. package/dist/dataset-context/use-run-events.mjs +138 -0
  32. package/dist/demo-data/use-demo-data.d.mts +42 -0
  33. package/dist/demo-data/use-demo-data.mjs +187 -0
  34. package/dist/env.d.mts +2 -0
  35. package/dist/env.mjs +4 -0
  36. package/dist/feature-flags/feature-flags.d.mts +34 -0
  37. package/dist/feature-flags/feature-flags.mjs +51 -0
  38. package/dist/feature-flags/use-feature-flag.d.mts +11 -0
  39. package/dist/feature-flags/use-feature-flag.mjs +17 -0
  40. package/dist/http/describe-response.d.mts +9 -0
  41. package/dist/http/describe-response.mjs +13 -0
  42. package/dist/http/models-api-request.d.mts +3 -0
  43. package/dist/http/models-api-request.mjs +20 -0
  44. package/dist/iframe-bridge/iframe-bridge.d.mts +10 -0
  45. package/dist/iframe-bridge/iframe-bridge.mjs +24 -0
  46. package/dist/iframe-bridge/use-iframe-bridge.d.mts +32 -0
  47. package/dist/iframe-bridge/use-iframe-bridge.mjs +200 -0
  48. package/dist/index.d.mts +16 -0
  49. package/dist/index.mjs +14 -0
  50. package/dist/solve-control/use-solve-control.d.mts +16 -0
  51. package/dist/solve-control/use-solve-control.mjs +46 -0
  52. package/dist/theme/prefers-dark.d.mts +11 -0
  53. package/dist/theme/prefers-dark.mjs +43 -0
  54. package/dist/view-channel/view-channel.d.mts +17 -0
  55. package/dist/view-channel/view-channel.mjs +67 -0
  56. package/dist/visualization-provider/VisualizationProvider.d.mts +20 -0
  57. package/dist/visualization-provider/VisualizationProvider.mjs +26 -0
  58. package/package.json +36 -5
@@ -0,0 +1,187 @@
1
+ "use client";
2
+ import { useDataSetActions, useDataSetProviderState } from "../dataset-context/DataSetContext.mjs";
3
+ import { demoDataSetUrl, resourceUrl } from "../dataset-context/model-api-url.mjs";
4
+ import { describeResponse } from "../http/describe-response.mjs";
5
+ import { modelsApiRequest } from "../http/models-api-request.mjs";
6
+ import { useCallback, useEffect, useRef, useState } from "react";
7
+ import { z } from "zod";
8
+ // src/demo-data/use-demo-data.ts
9
+ const importEnvelope = z.object({
10
+ id: z.string().optional(),
11
+ modelInput: z.record(z.string(), z.unknown())
12
+ });
13
+ const demoDataSetList = z.array(z.looseObject({ id: z.string().optional() }));
14
+ const demoDataSetEnvelope = z.looseObject({
15
+ id: z.string().optional(),
16
+ modelInput: z.record(z.string(), z.unknown())
17
+ });
18
+ /**
19
+ * Owns the demo-data lifecycle: fetching the list, loading one by id,
20
+ * auto-loading on mount, and validating + applying a file import.
21
+ */
22
+ function useDemoData({ enabled = true } = {}) {
23
+ const { config, apiKey, dataSetId, dataSetName } = useDataSetProviderState();
24
+ const { updateInputData, updateActiveDataSet, stopSolve } = useDataSetActions();
25
+ const [demoDataSets, setDemoDataSets] = useState(null);
26
+ const [pickedLabel, setPickedLabel] = useState(null);
27
+ const [isLoadingDataSet, setLoadingDataSet] = useState(false);
28
+ const [importError, setImportError] = useState(null);
29
+ const latestChoice = useRef(0);
30
+ const latestImport = useRef(0);
31
+ const importFile = useCallback((file) => {
32
+ const choiceAtStart = latestChoice.current;
33
+ const read = ++latestImport.current;
34
+ const reader = new FileReader();
35
+ reader.onload = () => {
36
+ if (read !== latestImport.current) return;
37
+ if (choiceAtStart !== latestChoice.current) return;
38
+ let raw;
39
+ try {
40
+ raw = JSON.parse(reader.result);
41
+ } catch {
42
+ setImportError({ message: "Could not import file: invalid JSON." });
43
+ return;
44
+ }
45
+ const parsed = importEnvelope.safeParse(raw);
46
+ if (!parsed.success) {
47
+ setImportError({ message: "Could not import file: not a valid dataset." });
48
+ return;
49
+ }
50
+ const modelInput = parsed.data.modelInput;
51
+ const problem = config.validateInputData?.(modelInput);
52
+ if (problem) {
53
+ setImportError({ message: `Could not import file: ${problem}.` });
54
+ return;
55
+ }
56
+ latestChoice.current += 1;
57
+ setImportError(null);
58
+ setPickedLabel(nameWithoutExtension(file.name));
59
+ stopSolve();
60
+ updateActiveDataSet(parsed.data);
61
+ updateInputData(modelInput, "local");
62
+ };
63
+ reader.readAsText(file);
64
+ }, [
65
+ config,
66
+ updateInputData,
67
+ updateActiveDataSet,
68
+ stopSolve
69
+ ]);
70
+ const applyDemoDataSet = useCallback(async (id, choice) => {
71
+ let demoDataSet;
72
+ try {
73
+ demoDataSet = await loadDemoDataSet(config, apiKey, id);
74
+ } catch (error) {
75
+ if (choice !== latestChoice.current) return;
76
+ setImportError({ message: `Could not load dataset "${id}": ${error.message}` });
77
+ return;
78
+ }
79
+ if (choice !== latestChoice.current) return;
80
+ const problem = config.validateInputData?.(demoDataSet.modelInput);
81
+ if (problem) {
82
+ setImportError({ message: `Could not load dataset "${id}": ${problem}.` });
83
+ return;
84
+ }
85
+ setImportError(null);
86
+ setPickedLabel(id);
87
+ stopSolve();
88
+ updateInputData(demoDataSet.modelInput, "local");
89
+ updateActiveDataSet(demoDataSet);
90
+ }, [
91
+ config,
92
+ apiKey,
93
+ updateInputData,
94
+ updateActiveDataSet,
95
+ stopSolve
96
+ ]);
97
+ const showDemoDataSet = useCallback((id, choice) => {
98
+ setLoadingDataSet(true);
99
+ return applyDemoDataSet(id, choice).finally(() => {
100
+ setLoadingDataSet(false);
101
+ });
102
+ }, [applyDemoDataSet]);
103
+ const loadDataSet = useCallback((id) => showDemoDataSet(id, ++latestChoice.current), [showDemoDataSet]);
104
+ const dataSetIdRef = useRef(dataSetId);
105
+ useEffect(() => {
106
+ dataSetIdRef.current = dataSetId;
107
+ }, [dataSetId]);
108
+ const autoLoadedRef = useRef(false);
109
+ const loadDemoDataSets = useCallback(async () => {
110
+ const choiceBeforeList = latestChoice.current;
111
+ const sets = await fetchDemoData(config, apiKey);
112
+ setDemoDataSets(sets);
113
+ if (autoLoadedRef.current) return;
114
+ autoLoadedRef.current = true;
115
+ if (dataSetIdRef.current || choiceBeforeList !== latestChoice.current) return;
116
+ const first = sets[0];
117
+ if (first) await showDemoDataSet(first.id, latestChoice.current);
118
+ }, [
119
+ config,
120
+ apiKey,
121
+ showDemoDataSet
122
+ ]);
123
+ useEffect(() => {
124
+ if (!enabled) return;
125
+ loadDemoDataSets().catch((error) => {
126
+ setImportError({ message: `Could not load demo datasets: ${error.message}` });
127
+ });
128
+ }, [enabled, loadDemoDataSets]);
129
+ return {
130
+ demoDataSets,
131
+ label: resolveDataLabel({
132
+ isLoadingDataSet,
133
+ pickedLabel,
134
+ dataSetId,
135
+ dataSetName,
136
+ demoDataSets,
137
+ hasImportError: importError !== null
138
+ }),
139
+ importError,
140
+ loadDataSet,
141
+ importFile
142
+ };
143
+ }
144
+ /**
145
+ * What the data picker calls the dataset on screen.
146
+ *
147
+ * @param isLoadingDataSet - A demo dataset is being fetched right now, so no
148
+ * label yet describes what the reader is about to see.
149
+ * @param pickedLabel - The label a demo choice or a file import wrote, which
150
+ * outranks the loaded dataset's own name.
151
+ * @param dataSetName - `undefined` while the loaded dataset's metadata is
152
+ * still coming, `""` once it arrived without a name.
153
+ */
154
+ function resolveDataLabel({ isLoadingDataSet, pickedLabel, dataSetId, dataSetName, demoDataSets, hasImportError }) {
155
+ if (isLoadingDataSet) return LOADING_LABEL;
156
+ if (pickedLabel) return pickedLabel;
157
+ if (dataSetId) {
158
+ if (dataSetName === void 0) return LOADING_LABEL;
159
+ return dataSetName || `Dataset ${shortDataSetId(dataSetId)}`;
160
+ }
161
+ if (demoDataSets === null && !hasImportError) return LOADING_LABEL;
162
+ return "Select dataset";
163
+ }
164
+ const LOADING_LABEL = "Loading…";
165
+ function shortDataSetId(dataSetId) {
166
+ return dataSetId.split("-")[0] ?? dataSetId;
167
+ }
168
+ function nameWithoutExtension(fileName) {
169
+ return fileName.replace(/\.[^.]+$/, "") || fileName;
170
+ }
171
+ async function fetchDemoData(config, apiKey) {
172
+ const response = await modelsApiRequest(demoDataSetUrl(config), apiKey);
173
+ if (!response.ok) throw new Error(`Failed to fetch demo datasets: ${describeResponse(response)}`);
174
+ const json = await response.json();
175
+ const parsed = demoDataSetList.safeParse(json);
176
+ if (!parsed.success) throw new Error("not a valid list of datasets");
177
+ return parsed.data.flatMap(({ id }) => id ? [{ id }] : []);
178
+ }
179
+ async function loadDemoDataSet(config, apiKey, id) {
180
+ const response = await modelsApiRequest(resourceUrl(demoDataSetUrl(config), id), apiKey);
181
+ if (!response.ok) throw new Error(`Failed to fetch demo input dataset: ${describeResponse(response)}`);
182
+ const json = await response.json();
183
+ const parsed = demoDataSetEnvelope.safeParse(json);
184
+ if (!parsed.success) throw new Error("not a valid dataset");
185
+ return parsed.data;
186
+ }
187
+ export { resolveDataLabel, useDemoData };
package/dist/env.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ /** True in a Vite dev or test build; false in a production build and under a bundler that defines no `import.meta.env`. */
2
+ export declare const isDevBuild: boolean;
package/dist/env.mjs ADDED
@@ -0,0 +1,4 @@
1
+ // src/env.ts
2
+ /** True in a Vite dev or test build; false in a production build and under a bundler that defines no `import.meta.env`. */
3
+ const isDevBuild = typeof import.meta.env !== "undefined" && import.meta.env.DEV === true;
4
+ export { isDevBuild };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Feature flags the platform passes as individual query params (`<name>=1|0`),
3
+ * not the `featureFlags` comma-list.
4
+ *
5
+ * @remarks
6
+ * A flag the platform sends but that is missing here resolves to off.
7
+ */
8
+ export declare const KNOWN_FLAG_PARAMS: readonly string[];
9
+ /**
10
+ * Boolean query-param convention: only `"1"`/`"true"` is true — deliberately
11
+ * NOT `queryParams.has(key)`, since the platform sends `?flag=0` for OFF.
12
+ */
13
+ export declare function parseBooleanParam(raw: string | null): boolean;
14
+ /**
15
+ * Resolves the active feature flags from the query string, an optional fallback
16
+ * list, and the environment's default for a flag nothing mentions.
17
+ *
18
+ * @remarks
19
+ * An explicit discrete param always wins: `?flag=0` turns a flag off even in
20
+ * development and even when the comma-list names it, which is how a developer
21
+ * previews a gated-off page locally.
22
+ *
23
+ * @param fallbackFlags - used only when the query string carries no `featureFlags` param.
24
+ * Callers gate this on the build mode; see resolveEmbeddingParams.
25
+ * @param isDevelopment - the default for a known flag the query string does not
26
+ * mention. `resolveEmbeddingParams` infers it from the build mode, the hostname,
27
+ * and whether anything is embedding the app.
28
+ */
29
+ export declare function resolveFeatureFlags({ queryParams, fallbackFlags, isDevelopment, knownFlagParams }: {
30
+ queryParams: URLSearchParams;
31
+ fallbackFlags?: readonly string[];
32
+ isDevelopment: boolean;
33
+ knownFlagParams?: readonly string[];
34
+ }): Set<string>;
@@ -0,0 +1,51 @@
1
+ // src/feature-flags/feature-flags.ts
2
+ const FLAG_LIST_PARAM = "featureFlags";
3
+ /**
4
+ * Feature flags the platform passes as individual query params (`<name>=1|0`),
5
+ * not the `featureFlags` comma-list.
6
+ *
7
+ * @remarks
8
+ * A flag the platform sends but that is missing here resolves to off.
9
+ */
10
+ const KNOWN_FLAG_PARAMS = [
11
+ "intelligence-layer-efficiency-xray",
12
+ "intelligence-layer-assignability-analysis",
13
+ "intelligence-layer-demand"
14
+ ];
15
+ /**
16
+ * Boolean query-param convention: only `"1"`/`"true"` is true — deliberately
17
+ * NOT `queryParams.has(key)`, since the platform sends `?flag=0` for OFF.
18
+ */
19
+ function parseBooleanParam(raw) {
20
+ return raw === "1" || raw === "true";
21
+ }
22
+ function parseFlagList(raw) {
23
+ return new Set(raw.split(",").map((flag) => flag.trim()).filter(Boolean));
24
+ }
25
+ /**
26
+ * Resolves the active feature flags from the query string, an optional fallback
27
+ * list, and the environment's default for a flag nothing mentions.
28
+ *
29
+ * @remarks
30
+ * An explicit discrete param always wins: `?flag=0` turns a flag off even in
31
+ * development and even when the comma-list names it, which is how a developer
32
+ * previews a gated-off page locally.
33
+ *
34
+ * @param fallbackFlags - used only when the query string carries no `featureFlags` param.
35
+ * Callers gate this on the build mode; see resolveEmbeddingParams.
36
+ * @param isDevelopment - the default for a known flag the query string does not
37
+ * mention. `resolveEmbeddingParams` infers it from the build mode, the hostname,
38
+ * and whether anything is embedding the app.
39
+ */
40
+ function resolveFeatureFlags({ queryParams, fallbackFlags = [], isDevelopment, knownFlagParams = KNOWN_FLAG_PARAMS }) {
41
+ const flags = queryParams.has(FLAG_LIST_PARAM) ? parseFlagList(queryParams.get(FLAG_LIST_PARAM) ?? "") : new Set(fallbackFlags);
42
+ for (const name of knownFlagParams) {
43
+ const raw = queryParams.get(name);
44
+ if (raw === null) {
45
+ if (isDevelopment) flags.add(name);
46
+ } else if (parseBooleanParam(raw)) flags.add(name);
47
+ else flags.delete(name);
48
+ }
49
+ return flags;
50
+ }
51
+ export { KNOWN_FLAG_PARAMS, parseBooleanParam, resolveFeatureFlags };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Whether a feature flag is on for this visualisation.
3
+ *
4
+ * @example
5
+ * ```tsx
6
+ * if (useFeatureFlag("intelligence-layer-efficiency-xray")) {
7
+ * pages.push({ key: "efficiency", content: <Efficiency /> });
8
+ * }
9
+ * ```
10
+ */
11
+ export declare function useFeatureFlag(name: string): boolean;
@@ -0,0 +1,17 @@
1
+ "use client";
2
+ import { useDataSetProviderState } from "../dataset-context/DataSetContext.mjs";
3
+ // src/feature-flags/use-feature-flag.ts
4
+ /**
5
+ * Whether a feature flag is on for this visualisation.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * if (useFeatureFlag("intelligence-layer-efficiency-xray")) {
10
+ * pages.push({ key: "efficiency", content: <Efficiency /> });
11
+ * }
12
+ * ```
13
+ */
14
+ function useFeatureFlag(name) {
15
+ return useDataSetProviderState().featureFlags.has(name);
16
+ }
17
+ export { useFeatureFlag };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Human-readable cause for a failed HTTP response.
3
+ *
4
+ * @remarks
5
+ * `statusText` alone is not usable: HTTP/2 removes the reason phrase, so it is
6
+ * empty for every response served over h2. The numeric status always leads;
7
+ * the reason phrase is appended only when the server actually sent one.
8
+ */
9
+ export declare function describeResponse(response: Response): string;
@@ -0,0 +1,13 @@
1
+ // src/http/describe-response.ts
2
+ /**
3
+ * Human-readable cause for a failed HTTP response.
4
+ *
5
+ * @remarks
6
+ * `statusText` alone is not usable: HTTP/2 removes the reason phrase, so it is
7
+ * empty for every response served over h2. The numeric status always leads;
8
+ * the reason phrase is appended only when the server actually sent one.
9
+ */
10
+ function describeResponse(response) {
11
+ return response.statusText ? `HTTP ${response.status} ${response.statusText}` : `HTTP ${response.status}`;
12
+ }
13
+ export { describeResponse };
@@ -0,0 +1,3 @@
1
+ /** A JSON request to the Models API, with `X-API-KEY` only when there is a key: a proxied embed has none.
2
+ * @remarks The caller gets one plain message for each `TypeError` of `fetch`; the original error stays in `cause`. */
3
+ export declare function modelsApiRequest(url: string, apiKey: string | undefined, init?: Omit<RequestInit, "headers" | "redirect">): Promise<Response>;
@@ -0,0 +1,20 @@
1
+ // src/http/models-api-request.ts
2
+ /** A JSON request to the Models API, with `X-API-KEY` only when there is a key: a proxied embed has none.
3
+ * @remarks The caller gets one plain message for each `TypeError` of `fetch`; the original error stays in `cause`. */
4
+ async function modelsApiRequest(url, apiKey, init = {}) {
5
+ try {
6
+ return await fetch(url, {
7
+ ...init,
8
+ headers: {
9
+ "Content-Type": "application/json",
10
+ Accept: "application/json",
11
+ ...apiKey ? { "X-API-KEY": apiKey } : {}
12
+ },
13
+ redirect: "error"
14
+ });
15
+ } catch (error) {
16
+ if (error instanceof TypeError) throw new Error("The request to the server failed.", { cause: error });
17
+ throw error;
18
+ }
19
+ }
20
+ export { modelsApiRequest };
@@ -0,0 +1,10 @@
1
+ /** Shared `source` discriminator for every outbound message on these channels. */
2
+ export declare const VISUALIZATION_MESSAGE_SOURCE = "timefold-visualization";
3
+ /**
4
+ * True iff an inbound `message` event may be trusted enough to have its
5
+ * payload parsed at all (see EMBEDDING.md's Trust rules).
6
+ */
7
+ export declare function isTrustedMessageOrigin(event: MessageEvent, allowlist: readonly string[]): boolean;
8
+ /** Posts `{ source: VISUALIZATION_MESSAGE_SOURCE, type, ...payload }` to the
9
+ * embedding parent. */
10
+ export declare function postToParent(type: string, payload: Record<string, unknown>, targetOrigin: string): void;
@@ -0,0 +1,24 @@
1
+ import { isAllowedOrigin } from "../config/security.mjs";
2
+ // src/iframe-bridge/iframe-bridge.ts
3
+ /** Shared `source` discriminator for every outbound message on these channels. */
4
+ const VISUALIZATION_MESSAGE_SOURCE = "timefold-visualization";
5
+ /**
6
+ * True iff an inbound `message` event may be trusted enough to have its
7
+ * payload parsed at all (see EMBEDDING.md's Trust rules).
8
+ */
9
+ function isTrustedMessageOrigin(event, allowlist) {
10
+ if (event.origin === "null") return false;
11
+ if (event.origin !== window.location.origin && !isAllowedOrigin(event.origin, allowlist)) return false;
12
+ if (event.source && event.source !== window.parent) return false;
13
+ return true;
14
+ }
15
+ /** Posts `{ source: VISUALIZATION_MESSAGE_SOURCE, type, ...payload }` to the
16
+ * embedding parent. */
17
+ function postToParent(type, payload, targetOrigin) {
18
+ window.parent.postMessage({
19
+ source: VISUALIZATION_MESSAGE_SOURCE,
20
+ type,
21
+ ...payload
22
+ }, targetOrigin);
23
+ }
24
+ export { VISUALIZATION_MESSAGE_SOURCE, isTrustedMessageOrigin, postToParent };
@@ -0,0 +1,32 @@
1
+ import { ColorScheme, DistanceUnitSystem } from "@timefoldai/viz-core";
2
+ /**
3
+ * Connection parameters an embedding host can hand the embed via `init`,
4
+ * instead of the query string. Extra string fields pass through unchanged.
5
+ */
6
+ export interface IframeData {
7
+ tenantId: string;
8
+ runId: string;
9
+ apiUrl: string;
10
+ apiKey: string;
11
+ [key: string]: string;
12
+ }
13
+ export interface UseIframeBridgeOptions {
14
+ /** @defaultValue false */
15
+ resize?: boolean;
16
+ onInit?: (data: IframeData) => void;
17
+ onUnitSystem?: (unitSystem: DistanceUnitSystem) => void;
18
+ onColorScheme?: (colorScheme: ColorScheme) => void;
19
+ /** @param height - CSS pixels the host shows below the frame's top edge. */
20
+ onViewport?: (height: number) => void;
21
+ /** @defaultValue [] */
22
+ allowlist?: readonly string[];
23
+ /** @defaultValue window.location.origin */
24
+ targetOrigin?: string;
25
+ }
26
+ /**
27
+ * The generic cross-frame `postMessage` bridge to a visualisation's embedding
28
+ * host: content-height reporting, the `init` handshake, and live unit-system, color-scheme and viewport updates.
29
+ *
30
+ * @category Hooks
31
+ */
32
+ export declare function useIframeBridge({ resize, onInit, onUnitSystem, onColorScheme, onViewport, allowlist, targetOrigin }: UseIframeBridgeOptions): void;
@@ -0,0 +1,200 @@
1
+ "use client";
2
+ import { SAME_ORIGIN_ONLY } from "../config/security.mjs";
3
+ import { VISUALIZATION_MESSAGE_SOURCE, isTrustedMessageOrigin, postToParent } from "./iframe-bridge.mjs";
4
+ import { OVERLAY_ATTRIBUTE } from "@timefoldai/viz-core";
5
+ import { useEffect, useRef } from "react";
6
+ import { z } from "zod";
7
+ // src/iframe-bridge/use-iframe-bridge.ts
8
+ const initMessageSchema = z.object({
9
+ source: z.literal(VISUALIZATION_MESSAGE_SOURCE),
10
+ type: z.literal("init"),
11
+ data: z.object({
12
+ tenantId: z.string().min(1),
13
+ runId: z.string().min(1),
14
+ apiUrl: z.string().min(1),
15
+ apiKey: z.string().min(1),
16
+ apiVersion: z.unknown().optional().transform((value) => value === void 0 || typeof value === "string" ? value : JSON.stringify(value))
17
+ }).catchall(z.string())
18
+ });
19
+ const unitSystemMessageSchema = z.object({
20
+ source: z.literal(VISUALIZATION_MESSAGE_SOURCE),
21
+ type: z.literal("unit-system"),
22
+ data: z.object({ unitSystem: z.enum(["metric", "imperial"]) })
23
+ });
24
+ const colorSchemeMessageSchema = z.object({
25
+ source: z.literal(VISUALIZATION_MESSAGE_SOURCE),
26
+ type: z.literal("color-scheme"),
27
+ data: z.object({ colorScheme: z.enum(["light", "dark"]) })
28
+ });
29
+ const viewportMessageSchema = z.object({
30
+ source: z.literal(VISUALIZATION_MESSAGE_SOURCE),
31
+ type: z.literal("viewport"),
32
+ data: z.object({ height: z.int().positive() })
33
+ });
34
+ const OVERLAY_SELECTOR = `[${OVERLAY_ATTRIBUTE}]`;
35
+ const FLIP_CLEARANCE_PX = 12;
36
+ const MAX_CUT_CARD_GROWTHS = 2;
37
+ function openOverlays() {
38
+ return [...document.querySelectorAll(OVERLAY_SELECTOR)];
39
+ }
40
+ function nextHold(rect, hold) {
41
+ const height = Math.max(hold.height, rect.bottom + window.scrollY);
42
+ const grownHeight = window.innerHeight + rect.height + FLIP_CLEARANCE_PX;
43
+ return rect.top < 0 && grownHeight > height && hold.cutGrowths < MAX_CUT_CARD_GROWTHS ? {
44
+ ...hold,
45
+ height: grownHeight,
46
+ cutGrowths: hold.cutGrowths + 1
47
+ } : {
48
+ ...hold,
49
+ height
50
+ };
51
+ }
52
+ function isSameList(next, previous) {
53
+ return next.length === previous.length && next.every((element, index) => element === previous[index]);
54
+ }
55
+ function watchContent(onChange) {
56
+ const sizes = new ResizeObserver(onChange);
57
+ const moves = new MutationObserver(onChange);
58
+ let watched = [];
59
+ const watchOverlays = (overlays) => {
60
+ watched = overlays;
61
+ sizes.disconnect();
62
+ moves.disconnect();
63
+ sizes.observe(document.body);
64
+ for (const overlay of overlays) {
65
+ sizes.observe(overlay);
66
+ for (let node = overlay; node && node !== document.body; node = node.parentElement) moves.observe(node, { attributeFilter: ["style", OVERLAY_ATTRIBUTE] });
67
+ }
68
+ };
69
+ const watchNewOverlays = () => {
70
+ const overlays = openOverlays();
71
+ if (isSameList(overlays, watched)) return;
72
+ watchOverlays(overlays);
73
+ onChange();
74
+ };
75
+ const mounts = new MutationObserver(watchNewOverlays);
76
+ sizes.observe(document.body);
77
+ watchNewOverlays();
78
+ mounts.observe(document.body, {
79
+ childList: true,
80
+ subtree: true
81
+ });
82
+ document.addEventListener("animationend", onChange, true);
83
+ return () => {
84
+ document.removeEventListener("animationend", onChange, true);
85
+ mounts.disconnect();
86
+ moves.disconnect();
87
+ sizes.disconnect();
88
+ };
89
+ }
90
+ function useResizeReporting(enabled) {
91
+ useEffect(() => {
92
+ if (!enabled || typeof ResizeObserver === "undefined") return;
93
+ let lastHeight = -1e400;
94
+ const holds = /* @__PURE__ */ new WeakMap();
95
+ let frame = 0;
96
+ const heldHeight = () => {
97
+ let highest = 0;
98
+ for (const overlay of openOverlays()) {
99
+ const rect = overlay.getBoundingClientRect();
100
+ if (rect.height === 0) {
101
+ holds.delete(overlay);
102
+ continue;
103
+ }
104
+ const key = overlay.getAttribute(OVERLAY_ATTRIBUTE) ?? "";
105
+ const held = holds.get(overlay);
106
+ const hold = nextHold(rect, held?.key === key ? held : {
107
+ key,
108
+ height: 0,
109
+ cutGrowths: 0
110
+ });
111
+ holds.set(overlay, hold);
112
+ highest = Math.max(highest, hold.height);
113
+ }
114
+ return highest;
115
+ };
116
+ const post = () => {
117
+ const height = Math.round(Math.max(document.body.getBoundingClientRect().height, heldHeight()));
118
+ if (Math.abs(height - lastHeight) <= 1) return;
119
+ lastHeight = height;
120
+ postToParent("resize", { height }, "*");
121
+ };
122
+ const stopWatching = watchContent(() => {
123
+ cancelAnimationFrame(frame);
124
+ frame = requestAnimationFrame(post);
125
+ });
126
+ post();
127
+ return () => {
128
+ cancelAnimationFrame(frame);
129
+ stopWatching();
130
+ };
131
+ }, [enabled]);
132
+ }
133
+ function useInitHandshake({ onInit, allowlist, targetOrigin }) {
134
+ const onInitRef = useRef(onInit);
135
+ useEffect(() => {
136
+ onInitRef.current = onInit;
137
+ }, [onInit]);
138
+ const enabled = onInit !== void 0;
139
+ useEffect(() => {
140
+ if (!enabled) return;
141
+ function handleMessage(event) {
142
+ if (!isTrustedMessageOrigin(event, allowlist)) return;
143
+ const envelope = event.data;
144
+ if (typeof envelope !== "object" || envelope === null || envelope.source !== "timefold-visualization" || envelope.type !== "init") return;
145
+ const result = initMessageSchema.safeParse(event.data);
146
+ if (!result.success) {
147
+ postToParent("init-response", { success: false }, targetOrigin);
148
+ return;
149
+ }
150
+ onInitRef.current?.(result.data.data);
151
+ postToParent("init-response", { success: true }, targetOrigin);
152
+ }
153
+ window.addEventListener("message", handleMessage);
154
+ return () => window.removeEventListener("message", handleMessage);
155
+ }, [
156
+ enabled,
157
+ allowlist,
158
+ targetOrigin
159
+ ]);
160
+ }
161
+ function useHostUpdates(schema, onMessage, allowlist) {
162
+ const onMessageRef = useRef(onMessage);
163
+ useEffect(() => {
164
+ onMessageRef.current = onMessage;
165
+ }, [onMessage]);
166
+ const enabled = onMessage !== void 0;
167
+ useEffect(() => {
168
+ if (!enabled) return;
169
+ function handleMessage(event) {
170
+ if (!isTrustedMessageOrigin(event, allowlist)) return;
171
+ const result = schema.safeParse(event.data);
172
+ if (!result.success) return;
173
+ onMessageRef.current?.(result.data);
174
+ }
175
+ window.addEventListener("message", handleMessage);
176
+ return () => window.removeEventListener("message", handleMessage);
177
+ }, [
178
+ enabled,
179
+ schema,
180
+ allowlist
181
+ ]);
182
+ }
183
+ /**
184
+ * The generic cross-frame `postMessage` bridge to a visualisation's embedding
185
+ * host: content-height reporting, the `init` handshake, and live unit-system, color-scheme and viewport updates.
186
+ *
187
+ * @category Hooks
188
+ */
189
+ function useIframeBridge({ resize = false, onInit, onUnitSystem, onColorScheme, onViewport, allowlist = SAME_ORIGIN_ONLY, targetOrigin = window.location.origin }) {
190
+ useResizeReporting(resize);
191
+ useInitHandshake({
192
+ onInit,
193
+ allowlist,
194
+ targetOrigin
195
+ });
196
+ useHostUpdates(unitSystemMessageSchema, onUnitSystem && ((message) => onUnitSystem(message.data.unitSystem)), allowlist);
197
+ useHostUpdates(colorSchemeMessageSchema, onColorScheme && ((message) => onColorScheme(message.data.colorScheme)), allowlist);
198
+ useHostUpdates(viewportMessageSchema, onViewport && ((message) => onViewport(message.data.height)), allowlist);
199
+ }
200
+ export { useIframeBridge };
@@ -0,0 +1,16 @@
1
+ import { ActiveDataSet, DataSet, DataSetInitialState, DataSetState, DataSetStatus, DemoDataSetSummary, DevEmbeddingParams, SolvingStatus, VisualizationConfig, useDataSet, useDistanceUnitSystem, useViewportHeight } from "./dataset-context/DataSetContext.mjs";
2
+ import { Waypoints } from "./dataset-context/DataSetLoader.mjs";
3
+ import { useFetchDataSetResource } from "./dataset-context/use-fetch-dataset-resource.mjs";
4
+ import { useFetchWaypoints } from "./dataset-context/use-fetch-waypoints.mjs";
5
+ import { dataSetKey } from "./dataset-context/data-set-key.mjs";
6
+ import { DataSetLoadState, UseDataSetLoadStateOptions, useDataSetLoadState } from "./dataset-context/use-data-set-load-state.mjs";
7
+ import { VisualizationProvider, VisualizationProviderProps } from "./visualization-provider/VisualizationProvider.mjs";
8
+ import { SolveControl, SolveControlPhase, useSolveControl } from "./solve-control/use-solve-control.mjs";
9
+ import { DemoDataError, UseDemoDataOptions, useDemoData } from "./demo-data/use-demo-data.mjs";
10
+ import { applyPreferredColorScheme } from "./theme/prefers-dark.mjs";
11
+ import { UseViewChannelOptions, useViewChannel } from "./view-channel/view-channel.mjs";
12
+ import { AssignabilityDetail, AssignabilityReport, AssignabilitySummary, AssignmentAnalysis } from "./assignability/assignability.mjs";
13
+ import { UseAssignabilityDetailResult, UseAssignabilityReportOptions, UseAssignabilityReportResult, useAssignabilityDetail, useAssignabilityReport } from "./assignability/use-assignability.mjs";
14
+ import { useAnalyticsBridge } from "./analytics/use-analytics-bridge.mjs";
15
+ import { useFeatureFlag } from "./feature-flags/use-feature-flag.mjs";
16
+ export { type ActiveDataSet, type AssignabilityDetail, type AssignabilityReport, type AssignabilitySummary, type AssignmentAnalysis, type DataSet, type DataSetInitialState, DataSetLoadState, type DataSetState, type DataSetStatus, type DemoDataError, type DemoDataSetSummary, type DevEmbeddingParams, SolveControl, SolveControlPhase, type SolvingStatus, UseAssignabilityDetailResult, UseAssignabilityReportOptions, UseAssignabilityReportResult, UseDataSetLoadStateOptions, type UseDemoDataOptions, UseViewChannelOptions, type VisualizationConfig, VisualizationProvider, type VisualizationProviderProps, type Waypoints, applyPreferredColorScheme, dataSetKey, useAnalyticsBridge, useAssignabilityDetail, useAssignabilityReport, useDataSet, useDataSetLoadState, useDemoData, useDistanceUnitSystem, useFeatureFlag, useFetchDataSetResource, useFetchWaypoints, useSolveControl, useViewChannel, useViewportHeight };
package/dist/index.mjs ADDED
@@ -0,0 +1,14 @@
1
+ import { useDataSet, useDistanceUnitSystem, useViewportHeight } from "./dataset-context/DataSetContext.mjs";
2
+ import { useFetchDataSetResource } from "./dataset-context/use-fetch-dataset-resource.mjs";
3
+ import { useFetchWaypoints } from "./dataset-context/use-fetch-waypoints.mjs";
4
+ import { dataSetKey } from "./dataset-context/data-set-key.mjs";
5
+ import { useDataSetLoadState } from "./dataset-context/use-data-set-load-state.mjs";
6
+ import { VisualizationProvider } from "./visualization-provider/VisualizationProvider.mjs";
7
+ import { useSolveControl } from "./solve-control/use-solve-control.mjs";
8
+ import { useDemoData } from "./demo-data/use-demo-data.mjs";
9
+ import { applyPreferredColorScheme } from "./theme/prefers-dark.mjs";
10
+ import { useViewChannel } from "./view-channel/view-channel.mjs";
11
+ import { useAssignabilityDetail, useAssignabilityReport } from "./assignability/use-assignability.mjs";
12
+ import { useAnalyticsBridge } from "./analytics/use-analytics-bridge.mjs";
13
+ import { useFeatureFlag } from "./feature-flags/use-feature-flag.mjs";
14
+ export { VisualizationProvider, applyPreferredColorScheme, dataSetKey, useAnalyticsBridge, useAssignabilityDetail, useAssignabilityReport, useDataSet, useDataSetLoadState, useDemoData, useDistanceUnitSystem, useFeatureFlag, useFetchDataSetResource, useFetchWaypoints, useSolveControl, useViewChannel, useViewportHeight };