-
Notifications
You must be signed in to change notification settings - Fork 432
Expand file tree
/
Copy pathwidgets.ts
More file actions
243 lines (224 loc) · 7.76 KB
/
widgets.ts
File metadata and controls
243 lines (224 loc) · 7.76 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
* widgets.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
// deno-lint-ignore-file camelcase
import { mergeConfigs } from "../config.ts";
import { lines } from "../lib/text.ts";
import {
kApplicationJavascript,
kApplicationJupyterWidgetState,
kApplicationJupyterWidgetView,
kTextHtml,
} from "../mime.ts";
import { isDisplayData } from "./display-data.ts";
import {
JupyterNotebook,
JupyterOutputDisplayData,
JupyterWidgetDependencies,
JupyterWidgetsState,
} from "./types.ts";
export function extractJupyterWidgetDependencies(
nb: JupyterNotebook,
): JupyterWidgetDependencies {
// a 'javascript' widget doesn't use the jupyter widgets protocol, but rather just injects
// text/html or application/javascript directly. futhermore these 'widgets' often assume
// that require.js and jquery are available. for example, see:
// - https://github.com/mwouts/itables
// - https://plotly.com/python/
const jsWidgets = haveOutputType(
nb,
[kApplicationJavascript, kTextHtml],
);
// jupyter widgets confirm to the jupyter widget embedding protocol:
// https://ipywidgets.readthedocs.io/en/latest/embedding.html#embeddable-html-snippet
const jupyterWidgets = haveOutputType(
nb,
[kApplicationJupyterWidgetView],
);
// see if there are html libraries that need to be hoisted up into the head
const htmlLibraries: string[] = [];
nb.cells.forEach((cell) => {
if (cell.cell_type === "code") {
cell.outputs = cell.outputs?.filter((output) => {
if (isDisplayData(output)) {
const displayOutput = output as JupyterOutputDisplayData;
const html = displayOutput.data[kTextHtml];
const htmlText = Array.isArray(html) ? html.join("") : html as string;
if (html && isWidgetIncludeHtml(htmlText)) {
htmlLibraries.push(htmlLibrariesText(htmlText));
return false;
}
}
return true;
});
}
});
return {
jsWidgets,
jupyterWidgets,
htmlLibraries,
widgetsState: nb.metadata.widgets
?.[kApplicationJupyterWidgetState] as JupyterWidgetsState,
};
}
export function includesForJupyterWidgetDependencies(
dependencies: JupyterWidgetDependencies[],
tempDir: string,
) {
// combine all of the dependencies
let haveJavascriptWidgets = false;
let haveJupyterWidgets = false;
const htmlLibraries: string[] = [];
let widgetsState: JupyterWidgetsState | undefined;
for (const dependency of dependencies) {
haveJavascriptWidgets = haveJavascriptWidgets || dependency.jsWidgets;
haveJupyterWidgets = haveJupyterWidgets || dependency.jupyterWidgets;
for (const htmlLib of dependency.htmlLibraries) {
if (!htmlLibraries.includes(htmlLib)) {
htmlLibraries.push(htmlLib);
}
}
if (dependency.widgetsState) {
if (!widgetsState) {
widgetsState = dependency.widgetsState;
} else {
widgetsState = mergeConfigs(widgetsState, dependency.widgetsState);
}
}
}
// write required dependencies into head
const head: string[] = [];
if (haveJavascriptWidgets || haveJupyterWidgets) {
head.push(
'<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous"></script>',
);
head.push(
'<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous" data-relocate-top="true"></script>',
);
head.push(
"<script type=\"application/javascript\">define('jquery', [],function() {return window.jQuery;})</script>",
);
}
// html libraries (e.g. plotly)
head.push(...htmlLibraries);
// jupyter widget runtime
if (haveJupyterWidgets) {
head.push(
'<script src="https://unpkg.com/@jupyter-widgets/html-manager@*/dist/embed-amd.js" crossorigin="anonymous"></script>',
);
}
// write jupyter widget state after body if it exists
const afterBody: string[] = [];
if (haveJupyterWidgets && widgetsState) {
const stateStr = JSON.stringify(widgetsState);
// https://github.com/quarto-dev/quarto-cli/issues/8433
if (stateStr.includes("</script>")) {
afterBody.push(`<script>
(() => {
const scriptTag = document.createElement("script");
const base64State = "${btoa(encodeURIComponent(stateStr))}";
scriptTag.type = "${kApplicationJupyterWidgetState}";
scriptTag.textContent = decodeURIComponent(atob(base64State));
document.body.appendChild(scriptTag);
})();
</script>`);
} else {
afterBody.push(`<script type=${kApplicationJupyterWidgetState}>`);
afterBody.push(JSON.stringify(widgetsState));
afterBody.push("</script>");
}
}
// create pandoc includes for our head and afterBody
const widgetTempFile = (lines: string[]) => {
const tempFile = Deno.makeTempFileSync(
{ dir: tempDir, prefix: "jupyter-widgets-", suffix: ".html" },
);
Deno.writeTextFileSync(tempFile, lines.join("\n") + "\n");
return tempFile;
};
const result = {
inHeader: "",
afterBody: "",
};
if (head.length > 0) {
result.inHeader = widgetTempFile(head);
}
if (afterBody.length > 0) {
result.afterBody = widgetTempFile(afterBody);
}
return result;
}
function haveOutputType(nb: JupyterNotebook, mimeTypes: string[]) {
return nb.cells.some((cell) => {
if (cell.cell_type === "code" && cell.outputs) {
return cell.outputs.some((output) => {
if (isDisplayData(output)) {
const outputTypes = Object.keys(
(output as JupyterOutputDisplayData).data,
);
return outputTypes.some((type) => mimeTypes.includes(type));
} else {
return false;
}
});
} else {
return false;
}
});
}
function isWidgetIncludeHtml(html: string) {
return isPlotlyLibrary(html);
}
function isPlotlyLibrary(html: string) {
// Plotly before version 6 used require.js to load the library
const hasRequireScript = (
html: string,
) => (/^\s*<script type="text\/javascript">/.test(html) &&
(/require\.undef\(["']plotly["']\)/.test(html) ||
/define\('plotly'/.test(html)));
// Plotly 6+ uses the new module syntax
const hasModuleScript = (html: string) =>
/\s*<script type=\"module\">import .*plotly.*<\/script>/.test(html);
// notebook mode non connected embed plotly.js scripts like this:
// * plotly.js v3.0.1
// * Copyright 2012-2025, Plotly, Inc.
// * All rights reserved.
// * Licensed under the MIT license
const hasEmbedScript = (
html: string,
) => (/\* plotly\.js v\d+\.\d+\.\d+\s*\n\s*\* Copyright \d{4}-\d{4}, Plotly, Inc\.\s*\n\s*\* All rights reserved\.\s*\n\s*\* Licensed under the MIT license/
.test(html));
return hasRequireScript(html) ||
// also handle new module syntax from plotly.py 6+
hasModuleScript(html) ||
// detect plotly by its copyright header
hasEmbedScript(html);
}
function htmlLibrariesText(htmlText: string) {
// strip leading space off of the content so it isn't seen as code by e.g. hugo
const htmlLines = lines(htmlText);
const leadingSpace = htmlLines.reduce<number>(
(leading: number, line: string) => {
const spaces = line.search(/\S/);
if (spaces !== -1) {
return Math.min(leading, spaces);
} else {
return leading;
}
},
Number.MAX_SAFE_INTEGER,
);
if (leadingSpace !== Number.MAX_SAFE_INTEGER) {
return htmlLines.map((line) => {
if (line.trim().length === 0) {
return "";
} else {
return line.replace(" ".repeat(leadingSpace), "");
}
}).join("\n");
} else {
return htmlText;
}
}