-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathexport-utils.ts
More file actions
196 lines (184 loc) · 5.68 KB
/
Copy pathexport-utils.ts
File metadata and controls
196 lines (184 loc) · 5.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import {
THEME_CSS,
SVG_CLASSES_CSS,
FORM_STYLES_WITH_STAGGER_CSS as FORM_STYLES_CSS,
IMPORTMAP_SCRIPT_TAG,
} from "@repo/design-system";
const CHART_COLORS = [
"#3b82f6",
"#8b5cf6",
"#ec4899",
"#f59e0b",
"#10b981",
"#06b6d4",
"#f97316",
];
export interface StandaloneActivityContent {
css?: string;
html?: string[];
jsFunctions?: string;
jsExpressions?: string[];
}
const WEBSANDBOX_STUB = `window.Websandbox = { connection: { remote: { sendPrompt: async () => {}, openLink: async ({ url }) => { if (/^https:/.test(url)) window.open(url, "_blank", "noopener,noreferrer"); } } } };`;
function escapeScriptClose(js: string): string {
return js.replace(/<\/script/gi, "<\\/script");
}
function escapeStyleClose(css: string): string {
return css.replace(/<\/style/gi, "<\\/style");
}
/**
* Wrap an open-generative-ui activity payload in a standalone document that
* works when opened in a browser: importmap first, then the same design-system
* css composition the live renderer injects, then the generated css, a
* Websandbox stub so exported bridge calls degrade gracefully, the joined html
* chunks, and finally the generated js in ONE classic (non-module) script:
* jsFunctions at top level — so function declarations become window globals,
* matching the live websandbox rail where inline onclick="fn()" handlers
* resolve them — followed by the jsExpressions inside an async IIFE so they
* can use `await` (dynamic import() still resolves via the importmap in
* classic scripts).
*/
export function assembleStandaloneHtmlFromActivity(
content: StandaloneActivityContent,
title = "generated-widget"
): string {
const body = content.html?.join("") ?? "";
const expressions = content.jsExpressions ?? [];
const scriptParts = [
...(content.jsFunctions ? [escapeScriptClose(content.jsFunctions)] : []),
...(expressions.length > 0
? [
`(async () => {
${expressions.map(escapeScriptClose).join("\n")}
})();`,
]
: []),
];
const generatedScript =
scriptParts.length > 0
? `<script>
${scriptParts.join("\n")}
</script>`
: "";
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)}</title>
${IMPORTMAP_SCRIPT_TAG}
<style>
${THEME_CSS}
${SVG_CLASSES_CSS}
${FORM_STYLES_CSS}
</style>${content.css ? `\n <style>${escapeStyleClose(content.css)}</style>` : ""}
<script>${WEBSANDBOX_STUB}</script>
</head>
<body>
${body}
${generatedScript}
</body>
</html>`;
}
/**
* Generate a standalone HTML file that renders a chart using Chart.js from CDN.
*/
export function chartToStandaloneHtml(
type: "bar" | "pie",
data: { title: string; description: string; data: Array<{ label: string; value: number }> }
): string {
const labels = JSON.stringify(data.data.map((d) => d.label));
const values = JSON.stringify(data.data.map((d) => d.value));
const colors = JSON.stringify(
data.data.map((_, i) => CHART_COLORS[i % CHART_COLORS.length])
);
const chartConfig =
type === "bar"
? `{
type: 'bar',
data: {
labels: ${labels},
datasets: [{
data: ${values},
backgroundColor: ${colors},
borderRadius: 4,
}]
},
options: {
responsive: true,
plugins: {
legend: { display: false },
tooltip: { backgroundColor: '#1f2937', titleColor: '#fff', bodyColor: '#fff', cornerRadius: 8, padding: 10 }
},
scales: {
x: { grid: { display: false } },
y: { grid: { color: 'rgba(0,0,0,0.06)' } }
}
}
}`
: `{
type: 'pie',
data: {
labels: ${labels},
datasets: [{
data: ${values},
backgroundColor: ${colors},
}]
},
options: {
responsive: true,
plugins: {
legend: { position: 'bottom', labels: { padding: 16, usePointStyle: true } },
tooltip: { backgroundColor: '#1f2937', titleColor: '#fff', bodyColor: '#fff', cornerRadius: 8, padding: 10 }
}
}
}`;
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(data.title)}</title>
<style>
${THEME_CSS}
body { font-family: system-ui, -apple-system, sans-serif; padding: 24px; max-width: 640px; margin: 0 auto; }
h3 { font-size: 20px; font-weight: 700; margin: 0 0 4px; color: var(--color-text-primary); }
p { font-size: 14px; color: var(--color-text-secondary); margin: 0 0 20px; }
canvas { max-height: 360px; }
</style>
</head>
<body>
<h3>${escapeHtml(data.title)}</h3>
<p>${escapeHtml(data.description)}</p>
<canvas id="chart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script>
new Chart(document.getElementById('chart'), ${chartConfig});
</script>
</body>
</html>`;
}
export function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
export function triggerDownload(htmlString: string, filename: string): void {
const blob = new Blob([htmlString], { type: "text/html" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}