-
Notifications
You must be signed in to change notification settings - Fork 86
/
embed.ts
521 lines (434 loc) · 15.4 KB
/
embed.ts
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import {applyPatch, Operation} from 'fast-json-patch';
import stringify from 'json-stringify-pretty-compact';
import {satisfies} from 'semver';
import * as vegaImport from 'vega';
import {
AutoSize,
Config as VgConfig,
EncodeEntryName,
isBoolean,
isString,
Loader,
LoaderOptions,
mergeConfig,
Renderers,
Spec as VgSpec,
TooltipHandler,
View,
} from 'vega';
import * as vegaLiteImport from 'vega-lite';
import {Config as VlConfig, TopLevelSpec as VlSpec} from 'vega-lite';
import schemaParser from 'vega-schema-url-parser';
import * as themes from 'vega-themes';
import {Handler, Options as TooltipOptions} from 'vega-tooltip';
import post from './post';
import embedStyle from './style';
import {Config, Mode} from './types';
import {mergeDeep} from './util';
export * from './types';
export const vega = vegaImport;
export let vegaLite = vegaLiteImport;
// For backwards compatibility with Vega-Lite before v4.
const w = (typeof window !== 'undefined' ? window : undefined) as any;
if (vegaLite === undefined && w?.['vl']?.compile) {
vegaLite = w['vl'];
}
export interface Actions {
export?: boolean | {svg?: boolean; png?: boolean};
source?: boolean;
compiled?: boolean;
editor?: boolean;
}
export const DEFAULT_ACTIONS = {export: {svg: true, png: true}, source: true, compiled: true, editor: true};
export interface Hover {
hoverSet?: EncodeEntryName;
updateSet?: EncodeEntryName;
}
export type PatchFunc = (spec: VgSpec) => VgSpec;
const I18N = {
CLICK_TO_VIEW_ACTIONS: 'Click to view actions',
COMPILED_ACTION: 'View Compiled Vega',
EDITOR_ACTION: 'Open in Vega Editor',
PNG_ACTION: 'Save as PNG',
SOURCE_ACTION: 'View Source',
SVG_ACTION: 'Save as SVG',
};
export interface EmbedOptions<S = string, R = Renderers> {
bind?: HTMLElement | string;
actions?: boolean | Actions;
mode?: Mode;
theme?: 'excel' | 'ggplot2' | 'quartz' | 'vox' | 'dark';
defaultStyle?: boolean | string;
logLevel?: number;
loader?: Loader | LoaderOptions;
renderer?: R;
tooltip?: TooltipHandler | TooltipOptions | boolean;
patch?: S | PatchFunc | Operation[];
width?: number;
height?: number;
padding?: number | {left?: number; right?: number; top?: number; bottom?: number};
scaleFactor?: number;
config?: S | Config;
sourceHeader?: string;
sourceFooter?: string;
editorUrl?: string;
hover?: boolean | Hover;
i18n?: Partial<typeof I18N>;
downloadFileName?: string;
formatLocale?: Record<string, unknown>;
timeFormatLocale?: Record<string, unknown>;
ast?: boolean;
viewClass?: typeof View;
}
const NAMES: {[key in Mode]: string} = {
vega: 'Vega',
'vega-lite': 'Vega-Lite',
};
const VERSION = {
vega: vega.version,
'vega-lite': vegaLite ? vegaLite.version : 'not available',
};
const PREPROCESSOR: {[mode in Mode]: (spec: any, config?: Config) => VgSpec} = {
vega: (vgSpec: VgSpec) => vgSpec,
'vega-lite': (vlSpec, config) => vegaLite.compile(vlSpec as VlSpec, {config: config as VlConfig}).spec,
};
const SVG_CIRCLES = `
<svg viewBox="0 0 16 16" fill="currentColor" stroke="none" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
<circle r="2" cy="8" cx="2"></circle>
<circle r="2" cy="8" cx="8"></circle>
<circle r="2" cy="8" cx="14"></circle>
</svg>`;
const CHART_WRAPPER_CLASS = 'chart-wrapper';
export type VisualizationSpec = VlSpec | VgSpec;
export interface Result {
/** The Vega view. */
view: View;
/** The input specification. */
spec: VisualizationSpec;
/** The compiled and patched Vega specification. */
vgSpec: VgSpec;
/** Removes references to unwanted behaviors and memory leaks. Calls Vega's `view.finalize`. */
finalize: () => void;
}
function isTooltipHandler(h?: boolean | TooltipOptions | TooltipHandler): h is TooltipHandler {
return typeof h === 'function';
}
function viewSource(source: string, sourceHeader: string, sourceFooter: string, mode: Mode) {
const header = `<html><head>${sourceHeader}</head><body><pre><code class="json">`;
const footer = `</code></pre>${sourceFooter}</body></html>`;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const win = window.open('')!;
win.document.write(header + source + footer);
win.document.title = `${NAMES[mode]} JSON Source`;
}
/**
* Try to guess the type of spec.
*
* @param spec Vega or Vega-Lite spec.
*/
export function guessMode(spec: VisualizationSpec, providedMode?: Mode): Mode {
// Decide mode
if (spec.$schema) {
const parsed = schemaParser(spec.$schema);
if (providedMode && providedMode !== parsed.library) {
console.warn(
`The given visualization spec is written in ${NAMES[parsed.library]}, but mode argument sets ${
NAMES[providedMode] ?? providedMode
}.`
);
}
const mode = parsed.library as Mode;
if (!satisfies(VERSION[mode], `^${parsed.version.slice(1)}`)) {
console.warn(
`The input spec uses ${NAMES[mode]} ${parsed.version}, but the current version of ${NAMES[mode]} is v${VERSION[mode]}.`
);
}
return mode;
}
// try to guess from the provided spec
if (
'mark' in spec ||
'encoding' in spec ||
'layer' in spec ||
'hconcat' in spec ||
'vconcat' in spec ||
'facet' in spec ||
'repeat' in spec
) {
return 'vega-lite';
}
if ('marks' in spec || 'signals' in spec || 'scales' in spec || 'axes' in spec) {
return 'vega';
}
return providedMode ?? 'vega';
}
function isLoader(o?: LoaderOptions | Loader): o is Loader {
return !!(o && 'load' in o);
}
function createLoader(opts?: Loader | LoaderOptions) {
return isLoader(opts) ? opts : vega.loader(opts);
}
function embedOptionsFromUsermeta(parsedSpec: VisualizationSpec) {
return (parsedSpec.usermeta && (parsedSpec.usermeta as any)['embedOptions']) ?? {};
}
/**
* Embed a Vega visualization component in a web page. This function returns a promise.
*
* @param el DOM element in which to place component (DOM node or CSS selector).
* @param spec String : A URL string from which to load the Vega specification.
* Object : The Vega/Vega-Lite specification as a parsed JSON object.
* @param opts A JavaScript object containing options for embedding.
*/
export default async function embed(
el: HTMLElement | string,
spec: VisualizationSpec | string,
opts: EmbedOptions = {}
): Promise<Result> {
let parsedSpec: VisualizationSpec;
let loader: Loader | undefined;
if (isString(spec)) {
loader = createLoader(opts.loader);
parsedSpec = JSON.parse(await loader.load(spec));
} else {
parsedSpec = spec;
}
const usermetaLoader = embedOptionsFromUsermeta(parsedSpec).loader;
// either create the loader for the first time or create a new loader if the spec has new loader options
if (!loader || usermetaLoader) {
loader = createLoader(opts.loader ?? usermetaLoader);
}
const usermetaOpts = await loadOpts(embedOptionsFromUsermeta(parsedSpec), loader);
const parsedOpts = await loadOpts(opts, loader);
const mergedOpts = {
...mergeDeep(parsedOpts, usermetaOpts),
config: mergeConfig(parsedOpts.config ?? {}, usermetaOpts.config ?? {}),
};
return await _embed(el, parsedSpec, mergedOpts, loader);
}
async function loadOpts(opt: EmbedOptions, loader: Loader): Promise<EmbedOptions<never>> {
const config: Config = isString(opt.config) ? JSON.parse(await loader.load(opt.config)) : opt.config ?? {};
const patch: PatchFunc | Operation[] = isString(opt.patch) ? JSON.parse(await loader.load(opt.patch)) : opt.patch;
return {
...(opt as any),
...(patch ? {patch} : {}),
...(config ? {config} : {}),
};
}
function getRoot(el: Element) {
const possibleRoot = el.getRootNode ? el.getRootNode() : document;
if (possibleRoot instanceof ShadowRoot) {
return {root: possibleRoot, rootContainer: possibleRoot};
} else {
return {root: document, rootContainer: document.head ?? document.body};
}
}
async function _embed(
el: HTMLElement | string,
spec: VisualizationSpec,
opts: EmbedOptions<never> = {},
loader: Loader
): Promise<Result> {
const config = opts.theme ? mergeConfig(themes[opts.theme], opts.config ?? {}) : opts.config;
const actions = isBoolean(opts.actions) ? opts.actions : mergeDeep<Actions>({}, DEFAULT_ACTIONS, opts.actions ?? {});
const i18n = {...I18N, ...opts.i18n};
const renderer = opts.renderer ?? 'canvas';
const logLevel = opts.logLevel ?? vega.Warn;
const downloadFileName = opts.downloadFileName ?? 'visualization';
const element = typeof el === 'string' ? document.querySelector(el) : el;
if (!element) {
throw new Error(`${el} does not exist`);
}
if (opts.defaultStyle !== false) {
// Add a default stylesheet to the head of the document.
const ID = 'vega-embed-style';
const {root, rootContainer} = getRoot(element);
if (!root.getElementById(ID)) {
const style = document.createElement('style');
style.id = ID;
style.innerText =
opts.defaultStyle === undefined || opts.defaultStyle === true
? (embedStyle ?? '').toString()
: opts.defaultStyle;
rootContainer.appendChild(style);
}
}
const mode = guessMode(spec, opts.mode);
let vgSpec: VgSpec = PREPROCESSOR[mode](spec, config);
if (mode === 'vega-lite') {
if (vgSpec.$schema) {
const parsed = schemaParser(vgSpec.$schema);
if (!satisfies(VERSION.vega, `^${parsed.version.slice(1)}`)) {
console.warn(`The compiled spec uses Vega ${parsed.version}, but current version is v${VERSION.vega}.`);
}
}
}
element.classList.add('vega-embed');
if (actions) {
element.classList.add('has-actions');
}
element.innerHTML = ''; // clear container
let container = element;
if (actions) {
const chartWrapper = document.createElement('div');
chartWrapper.classList.add(CHART_WRAPPER_CLASS);
element.appendChild(chartWrapper);
container = chartWrapper;
}
const patch = opts.patch;
if (patch) {
if (patch instanceof Function) {
vgSpec = patch(vgSpec);
} else {
vgSpec = applyPatch(vgSpec, patch, true, false).newDocument;
}
}
// Set locale. Note that this is a global setting.
if (opts.formatLocale) {
vega.formatLocale(opts.formatLocale);
}
if (opts.timeFormatLocale) {
vega.timeFormatLocale(opts.timeFormatLocale);
}
const {ast} = opts;
// Do not apply the config to Vega when we have already applied it to Vega-Lite.
// This call may throw an Error if parsing fails.
const runtime = vega.parse(vgSpec, mode === 'vega-lite' ? {} : (config as VgConfig), {ast});
const view = new (opts.viewClass || vega.View)(runtime, {
loader,
logLevel,
renderer,
...(ast ? {expr: (vega as any).expressionInterpreter} : {}),
});
view.addSignalListener('autosize', (_, autosize: Exclude<AutoSize, string>) => {
const {type} = autosize;
if (type == 'fit-x') {
container.classList.add('fit-x');
container.classList.remove('fit-y');
} else if (type == 'fit-y') {
container.classList.remove('fit-x');
container.classList.add('fit-y');
} else if (type == 'fit') {
container.classList.add('fit-x', 'fit-y');
} else {
container.classList.remove('fit-x', 'fit-y');
}
});
if (opts.tooltip !== false) {
let handler: TooltipHandler;
if (isTooltipHandler(opts.tooltip)) {
handler = opts.tooltip;
} else {
// user provided boolean true or tooltip options
handler = new Handler(opts.tooltip === true ? {} : opts.tooltip).call;
}
view.tooltip(handler);
}
let {hover} = opts;
if (hover === undefined) {
hover = mode === 'vega';
}
if (hover) {
const {hoverSet, updateSet} = (typeof hover === 'boolean' ? {} : hover) as Hover;
view.hover(hoverSet, updateSet);
}
if (opts) {
if (opts.width != null) {
view.width(opts.width);
}
if (opts.height != null) {
view.height(opts.height);
}
if (opts.padding != null) {
view.padding(opts.padding);
}
}
await view.initialize(container, opts.bind).runAsync();
let documentClickHandler: ((this: Document, ev: MouseEvent) => void) | undefined;
if (actions !== false) {
let wrapper = element;
if (opts.defaultStyle !== false) {
const details = document.createElement('details');
details.title = i18n.CLICK_TO_VIEW_ACTIONS;
element.append(details);
wrapper = details;
const summary = document.createElement('summary');
summary.innerHTML = SVG_CIRCLES;
details.append(summary);
documentClickHandler = (ev: MouseEvent) => {
if (!details.contains(ev.target as any)) {
details.removeAttribute('open');
}
};
document.addEventListener('click', documentClickHandler);
}
const ctrl = document.createElement('div');
wrapper.append(ctrl);
ctrl.classList.add('vega-actions');
// add 'Export' action
if (actions === true || actions.export !== false) {
for (const ext of ['svg', 'png'] as const) {
if (actions === true || actions.export === true || (actions.export as {svg?: boolean; png?: boolean})[ext]) {
const i18nExportAction = (i18n as {[key: string]: string})[`${ext.toUpperCase()}_ACTION`];
const exportLink = document.createElement('a');
exportLink.text = i18nExportAction;
exportLink.href = '#';
exportLink.target = '_blank';
exportLink.download = `${downloadFileName}.${ext}`;
// add link on mousedown so that it's correct when the click happens
exportLink.addEventListener('mousedown', async function (this, e) {
e.preventDefault();
const url = await view.toImageURL(ext, opts.scaleFactor);
this.href = url;
});
ctrl.append(exportLink);
}
}
}
// add 'View Source' action
if (actions === true || actions.source !== false) {
const viewSourceLink = document.createElement('a');
viewSourceLink.text = i18n.SOURCE_ACTION;
viewSourceLink.href = '#';
viewSourceLink.addEventListener('click', function (this, e) {
viewSource(stringify(spec), opts.sourceHeader ?? '', opts.sourceFooter ?? '', mode);
e.preventDefault();
});
ctrl.append(viewSourceLink);
}
// add 'View Compiled' action
if (mode === 'vega-lite' && (actions === true || actions.compiled !== false)) {
const compileLink = document.createElement('a');
compileLink.text = i18n.COMPILED_ACTION;
compileLink.href = '#';
compileLink.addEventListener('click', function (this, e) {
viewSource(stringify(vgSpec), opts.sourceHeader ?? '', opts.sourceFooter ?? '', 'vega');
e.preventDefault();
});
ctrl.append(compileLink);
}
// add 'Open in Vega Editor' action
if (actions === true || actions.editor !== false) {
const editorUrl = opts.editorUrl ?? 'https://vega.github.io/editor/';
const editorLink = document.createElement('a');
editorLink.text = i18n.EDITOR_ACTION;
editorLink.href = '#';
editorLink.addEventListener('click', function (this, e) {
post(window, editorUrl, {
config: config as Config,
mode,
renderer,
spec: stringify(spec),
});
e.preventDefault();
});
ctrl.append(editorLink);
}
}
function finalize() {
if (documentClickHandler) {
document.removeEventListener('click', documentClickHandler);
}
view.finalize();
}
return {view, spec, vgSpec, finalize};
}