-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmkdocs-charts-plugin.js
246 lines (203 loc) · 7.62 KB
/
mkdocs-charts-plugin.js
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
244
245
246
// Adapted from https://github.com/koaning/justcharts/blob/main/justcharts.js
async function fetchSchema(url){
var resp = await fetch(url);
var schema = await resp.json();
return schema
}
function checkNested(obj /*, level1, level2, ... levelN*/) {
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0; i < args.length; i++) {
if (!obj || !obj.hasOwnProperty(args[i])) {
return false;
}
obj = obj[args[i]];
}
return true;
}
function classnameInParents(el, classname) {
// check if class name in any parents
while (el.parentNode) {
el = el.parentNode;
if (el.classList === undefined) {
continue;
}
if (el.classList.contains(classname) ){
return true;
}
}
return false;
}
function findElementInParents(el, classname) {
while (el.parentNode) {
el = el.parentNode;
if (el.classList === undefined) {
continue;
}
if (el.classList.contains(classname) ){
return el;
}
}
return null;
}
function findProperChartWidth(el) {
// mkdocs-material theme uses 'md-content'
var parent = findElementInParents(el, "md-content")
// mkdocs theme uses 'col-md-9'
if (parent === undefined || parent == null) {
var parent = findElementInParents(el, "col-md-9")
}
if (parent === undefined || parent == null) {
// we can't find a suitable content parent
// 800 width is a good default
return '800'
} else {
// Use full width of parent
// Should bparent.offsetWidth - parseFloat(computedStyle.paddingLeft) - parseFloat(computedStyle.paddingRight) e equilavent to width: 100%
computedStyle = getComputedStyle(parent)
return parent.offsetWidth - parseFloat(computedStyle.paddingLeft) - parseFloat(computedStyle.paddingRight)
}
}
function updateURL(url) {
// detect if absolute UR:
// credits https://stackoverflow.com/a/19709846
var r = new RegExp('^(?:[a-z]+:)?//', 'i');
if (r.test(url)) {
return url;
}
// If 'use_data_path' is set to true
// schema and data urls are relative to
// 'data_path', not the to current page
// We need to update the specified URL
// to point to the actual location relative to current page
// Example:
// Actual location data file: docs/assets/data.csv
// Page: docs/folder/page.md
// data url in page's schema: assets/data.csv
// data_path in plugin settings: ""
// use_data_path in plugin settings: True
// path_to_homepage: ".." (this was detected in plugin on_post_page() event)
// output url: "../assets/data.csv"
if (mkdocs_chart_plugin['use_data_path'] == "True") {
new_url = window.location.href
new_url = new_url.endsWith('/') ? new_url.slice(0, -1) : new_url;
if (mkdocs_chart_plugin['path_to_homepage'] != "") {
new_url += "/" + mkdocs_chart_plugin['path_to_homepage']
}
new_url = new_url.endsWith('/') ? new_url.slice(0, -1) : new_url;
new_url += "/" + url
new_url = new_url.endsWith('/') ? new_url.slice(0, -1) : new_url;
if (mkdocs_chart_plugin['data_path'] != "") {
new_url += "/" + mkdocs_chart_plugin['data_path']
}
return new_url
}
return url;
}
var vegalite_charts = [];
function embedChart(block, schema) {
// Make sure the schema is specified
let baseSchema = {
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
}
schema = Object.assign({}, baseSchema, schema);
// If width is not set at all,
// default is set to 'container'
// Note we inserted <vegachart style='width: 100%'>..
// So 'container' will use 100% width
if (!('width' in schema)) {
schema.width = mkdocs_chart_plugin['vega_width']
}
// Set default height if not specified
// if (!('height' in schema)) {
// schema.height = mkdocs_chart_plugin['default_height']
// }
// charts widths are screwed in content tabs (thinks its zero width)
// https://squidfunk.github.io/mkdocs-material/reference/content-tabs/?h=
// we need to set an explicit, absolute width in those cases
// detect if chart is in tabbed-content:
if (classnameInParents(block, "tabbed-content")) {
var chart_width = schema.width || 'notset';
if (isNaN(chart_width)) {
schema.width = findProperChartWidth(block);
}
}
// Update URL if 'use_data_path' is configured
if (schema?.data?.url !== undefined) {
schema.data.url = updateURL(schema.data.url)
}
if (schema?.spec?.data?.url !== undefined) {
schema.spec.data.url = updateURL(schema.spec.data.url)
}
// see docs/assets/data/geo_choropleth.json for example
if (schema.transform) {
for (const t of schema.transform) {
if (t?.from?.data?.url !== undefined) {
t.from.data.url = updateURL(t.from.data.url)
}
}
}
// Save the block and schema
// This way we can re-render the block
// in a different theme
vegalite_charts.push({'block' : block, 'schema': schema});
// mkdocs-material has a dark mode
// detect which one is being used
var theme = (document.querySelector('body').getAttribute('data-md-color-scheme') == 'slate') ? mkdocs_chart_plugin['vega_theme_dark'] : mkdocs_chart_plugin['vega_theme'];
// Render the chart
vegaEmbed(block, schema, {
actions: false,
"theme": theme,
"renderer": mkdocs_chart_plugin['vega_renderer']
});
}
// Adapted from
// https://facelessuser.github.io/pymdown-extensions/extensions/superfences/#uml-diagram-example
// https://github.com/koaning/justcharts/blob/main/justcharts.js
const chartplugin = className => {
// Find all of our vegalite sources and render them.
const blocks = document.querySelectorAll('vegachart');
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i]
const block_json = JSON.parse(block.textContent);
// get the vegalite JSON
if ('schema-url' in block_json) {
var url = updateURL(block_json['schema-url'])
fetchSchema(url).then(
schema => embedChart(block, schema)
);
} else {
embedChart(block, block_json);
}
}
}
// mkdocs-material has a dark mode including a toggle
// We should watch when dark mode changes and update charts accordingly
var bodyelement = document.querySelector('body');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === "attributes") {
if (mutation.attributeName == "data-md-color-scheme") {
var theme = (bodyelement.getAttribute('data-md-color-scheme') == 'slate') ? mkdocs_chart_plugin['vega_theme_dark'] : mkdocs_chart_plugin['vega_theme'];
for (let i = 0; i < vegalite_charts.length; i++) {
vegaEmbed(vegalite_charts[i].block, vegalite_charts[i].schema, {
actions: false,
"theme": theme,
"renderer": mkdocs_chart_plugin['vega_renderer']
});
}
}
}
});
});
observer.observe(bodyelement, {
attributes: true //configure it to listen to attribute changes
});
// Load when DOM ready
if (typeof document$ !== "undefined") {
// compatibility with mkdocs-material's instant loading feature
document$.subscribe(function() {
chartplugin("vegalite")
})
} else {
document.addEventListener("DOMContentLoaded", () => {chartplugin("vegalite")})
}