forked from GoogleWebComponents/google-chart
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle-chart-loader.js
More file actions
460 lines (442 loc) · 14.2 KB
/
Copy pathgoogle-chart-loader.js
File metadata and controls
460 lines (442 loc) · 14.2 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
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
/**
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at https://polymer.github.io/LICENSE.txt
The complete set of authors may be found at https://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at https://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at https://polymer.github.io/PATENTS.txt
*/
import { Polymer } from '@polymer/polymer/lib/legacy/polymer-fn.js';
/** @type {string} Most charts use this package. */
var DEFACTO_CHART_PACKAGE = 'corechart';
/** @enum {string} Namespaces that contain chart constructors. */
var Namespace = {
CHARTS: 'charts',
VIS: 'visualization'
};
/**
* A collection of chart type details.
*
* @type {!Object<string, {ctor: string, namespace: (!Namespace|undefined), pkg: (string|undefined)}>}
*/
var CHART_CONSTRUCTORS = {
'area': {
ctor: 'AreaChart',
},
'bar': {
ctor: 'BarChart',
},
'md-bar': {
ctor: 'Bar',
pkg: 'bar',
},
'bubble': {
ctor: 'BubbleChart',
},
'calendar': {
ctor: 'Calendar',
pkg: 'calendar',
},
'candlestick': {
ctor: 'CandlestickChart',
},
'column': {
ctor: 'ColumnChart',
},
'combo': {
ctor: 'ComboChart',
},
'gauge': {
ctor: 'Gauge',
pkg: 'gauge',
},
'geo': {
ctor: 'GeoChart',
},
'histogram': {
ctor: 'Histogram',
},
'line': {
ctor: 'LineChart',
},
'md-line': {
ctor: 'Line',
pkg: 'line',
},
'org': {
ctor: 'OrgChart',
pkg: 'orgchart',
},
'pie': {
ctor: 'PieChart',
},
'sankey': {
ctor: 'Sankey',
pkg: 'sankey',
},
'scatter': {
ctor: 'ScatterChart',
},
'md-scatter': {
ctor: 'Scatter',
pkg: 'scatter',
},
'stepped-area': {
ctor: 'SteppedAreaChart',
},
'table': {
ctor: 'Table',
pkg: 'table',
},
'timeline': {
ctor: 'Timeline',
pkg: 'timeline',
},
'treemap': {
ctor: 'TreeMap',
pkg: 'treemap',
},
'wordtree': {
ctor: 'WordTree',
namespace: Namespace.VIS,
pkg: 'wordtree',
}
};
/**
* The Google Charts constructor namespace inferred from the given chart type.
* @param {string} type the type of the chart
* @return {!Object} the namespace that contains the chart's constructor
*/
function namespaceForType(type) {
return google[type.indexOf('md-') === 0 ? Namespace.CHARTS : Namespace.VIS];
}
/**
* Promise that resolves when the gviz loader script is loaded, which
* provides access to the Google Charts loading API.
* @type {!Promise}
*/
var loaderPromise = new Promise(function(resolve, reject) {
// Resolve immediately if the loader script has been added already and
// `google.charts.load` is available. Adding the loader script twice throws
// an error.
if (typeof google !== 'undefined' && google.charts &&
typeof google.charts.load === 'function') {
resolve();
} else {
// Try to find existing loader script.
var loaderScript = document.querySelector(
'script[src="https://www.gstatic.com/charts/loader.js"]');
if (!loaderScript) {
// If the loader is not present, add it.
loaderScript =
/** @type {!HTMLScriptElement} */ (document.createElement('script'));
// Specify URL directly to pass JS compiler conformance checks.
loaderScript.src = 'https://www.gstatic.com/charts/loader.js';
document.head.appendChild(loaderScript);
}
loaderScript.addEventListener('load', resolve);
loaderScript.addEventListener('error', reject);
}
});
/** @type {!Object<string, boolean>} set-like object of gviz packages to load */
var packagesToLoad = {};
/** @type {!Object<string, !Promise>} promises for the various packages */
var promises = {};
/** @type {!Object<string, function(!Object)>} resolves for the package promises */
var resolves = {};
/**
* @typedef {{
* version: (string|undefined),
* packages: (!Array<string>|undefined),
* language: (string|undefined),
* mapsApiKey: (string|undefined),
* }}
*/
var LoadSettings;
/**
* Loads Google Charts API with the selected settings or using defaults.
*
* The following settings are available:
* - version: which version of library to load, default: 'current',
* - packages: which chart packages to load, default: ['corechart'],
* - language: what language to load library in, default: `lang` attribute on
* `<html>` or 'en' if not specified,
* - mapsApiKey: key to use for maps API.
*
* @param {!LoadSettings=} settings
* @return {!Promise}
*/
export async function load(settings = {}) {
await loaderPromise;
const {
version = 'current',
packages = [DEFACTO_CHART_PACKAGE],
language = document.documentElement.lang || 'en',
mapsApiKey,
} = settings;
return google.charts.load(version, {
'packages': packages,
'language': language,
'mapsApiKey': mapsApiKey,
});
}
Polymer({
is: 'google-chart-loader',
properties: {
/**
* Adds packages to the list of packages to load.
*
* This is an array consisting of any Google Visualization package names.
*
* @type {!Array<string>}
*/
packages: {
type: Array,
value: function() { return []; },
observer: '_loadPackages',
},
/**
* Loads the package for the chart type specified.
*
* This may be any of the supported `google-chart` types.
* This is mainly used by the `google-chart` element internally.
*
* @type {string}
*/
type: {
type: String,
observer: '_loadPackageForType',
},
},
/**
* Gets a promise for the `corechart` package being loaded.
* @return {!Promise<!Object>} google.visualization package promise
* @private
*/
get _corePackage() {
if (promises[DEFACTO_CHART_PACKAGE]) {
return promises[DEFACTO_CHART_PACKAGE];
}
return this._loadPackages([DEFACTO_CHART_PACKAGE]).then(function(pkgs) {
return pkgs[0];
});
},
/**
* Debounces the actual call to load the packages requested.
* We debounce so that load is only called once.
* @private
*/
_loadPackagesDebounce: function() {
this.debounce('loadPackages', () => {
var packages = Object.keys(packagesToLoad);
if (!packages.length) {
return;
}
packagesToLoad = {};
loaderPromise.then(() => load({packages})).then(() => {
packages.forEach((pkg) => {
this.fire('loaded', pkg);
resolves[pkg](google.visualization);
});
});
}, 100);
},
/**
* Adds a list of packages to load.
*
* @param {!Array<string>} pkgs list of packages to load
* @return {!Promise} Promise resolved when all packages are loaded
* @private
*/
_loadPackages: function(pkgs) {
var returns = [];
pkgs.forEach(function(pkg) {
if (!promises[pkg]) {
packagesToLoad[pkg] = true;
promises[pkg] = new Promise(function(resolve) {
resolves[pkg] = resolve;
});
this._loadPackagesDebounce();
}
returns.push(promises[pkg]);
}.bind(this));
return Promise.all(returns);
},
/**
* Adds a package to load for the given type.
*
* @param {string} type the chart type for which we should load the package
* @return {!Promise<!Function>} Promise for the chart type constructor
* @private
*/
_loadPackageForType: function(type) {
var chartData = CHART_CONSTRUCTORS[type];
if (!chartData) {
return Promise.reject(
'This chart type is not yet supported: ' + type);
}
return this._loadPackages([chartData.pkg || DEFACTO_CHART_PACKAGE])
.then(function() {
var namespace = google[chartData.namespace] || namespaceForType(type);
return namespace[chartData.ctor];
});
},
/**
* Creates a chart object by type in the specified element.
* Use *only* if you need total control of a chart object.
* Most should just use the `google-chart` element.
*
* @param {string} type the type of chart to create
* @param {!Element} el the element in which to create the chart
* @return {!Promise<!Object>} promise for the created chart object
* @override
* @suppress {checkTypes} This function accidentally overrides `create` from
* Polymer_LegacyElementMixin.
*/
create: function(type, el) {
return this._loadPackageForType(type).then(function(ctor) {
return new ctor(el);
});
},
/**
* Begins firing Polymer events for the requested chart event.
* Use *only* if you have control of a chart object.
* Most should just use the `google-chart` element.
*
* Events fired all have the same detail object:
* {{
* chart: !Object, // The chart target object
* data: (Object|undefined), // The chart event details
* }}
*
* @param {!Object} chart the chart object to which we should listen
* @param {string} eventName the name of the chart event
* @param {boolean=} opt_once whether to listen only one time
* @return {!Promise<void>} promise resolved when listener is attached
*/
fireOnChartEvent: function(chart, eventName, opt_once) {
return this._corePackage.then(function(viz) {
var adder = opt_once ?
viz.events.addOneTimeListener : viz.events.addListener;
adder(chart, eventName, function(event) {
this.fire('google-chart-' + eventName, {
chart: chart,
data: event,
});
}.bind(this));
}.bind(this));
},
/**
* Creates a DataTable object for use with a chart.
*
* Multiple different argument types are supported. This is because the
* result of loading the JSON data URL is fed into this function for
* DataTable construction and its format is unknown.
*
* The data argument can be one of a few options:
*
* - null/undefined: An empty DataTable is created. Columns must be added
* - !DataTable: The object is simply returned
* - {{cols: !Array, rows: !Array}}: A DataTable in object format
* - {{cols: !Array}}: A DataTable in object format without rows
* - !Array<!Array>: A DataTable in 2D array format
*
* Un-supported types:
*
* - Empty !Array<!Array>: (e.g. `[]`) While technically a valid data
* format, this is rejected as charts will not render empty DataTables.
* DataTables must at least have columns specified. An empty array is most
* likely due to a bug or bad data. If one wants an empty DataTable, pass
* no arguments.
* - Anything else
*
* See <a href="https://developers.google.com/chart/interactive/docs/reference#datatable-class">the docs</a> for more details.
*
* @param {!Array|{cols: !Array, rows: (!Array<!Array>|undefined)}|undefined} data
* the data with which we should use to construct the new DataTable object
* @return {!Promise<!google.visualization.DataTable>} promise for the created DataTable
*/
dataTable: function(data) {
return dataTable(data);
},
/**
* Creates a DataView object from a DataTable for use with a chart.
*
* See <a href="https://developers.google.com/chart/interactive/docs/reference#dataview-class">the docs</a> for more details.
*
* @param {!google.visualization.DataTable} data the DataTable to use
* @return {!Promise<!google.visualization.DataView>} promise for the created DataView
*/
dataView: function(data) {
return this._corePackage.then(function(viz) {
return new viz.DataView(data);
});
},
/**
* Creates a Query object to be sent to a DataSource protocol implementation.
*
* See <a href="https://developers.google.com/chart/interactive/docs/reference#query-classes">the docs</a> for more details.
*
* @param {string} url the URL of the DataSource protocol implementer
* @param {!Object=} opt_options options for the Query object
* @return {!Promise<!google.visualization.Query>} promise for the created DataView
*/
query: function(url, opt_options) {
return this._corePackage.then(function(viz) {
return new viz.Query(url, opt_options);
});
}
});
/**
* Creates a DataTable object for use with a chart.
*
* Multiple different argument types are supported. This is because the
* result of loading the JSON data URL is fed into this function for
* DataTable construction and its format is unknown.
*
* The data argument can be one of a few options:
*
* - null/undefined: An empty DataTable is created. Columns must be added
* - !DataTable: The object is simply returned
* - {{cols: !Array, rows: !Array}}: A DataTable in object format
* - {{cols: !Array}}: A DataTable in object format without rows
* - !Array<!Array>: A DataTable in 2D array format
*
* Un-supported types:
*
* - Empty !Array<!Array>: (e.g. `[]`) While technically a valid data
* format, this is rejected as charts will not render empty DataTables.
* DataTables must at least have columns specified. An empty array is most
* likely due to a bug or bad data. If one wants an empty DataTable, pass
* no arguments.
* - Anything else
*
* See <a href="https://developers.google.com/chart/interactive/docs/reference#datatable-class">the docs</a> for more details.
*
* @param {!Array|{cols: !Array, rows: (!Array<!Array>|undefined)}|undefined} data
* the data with which we should use to construct the new DataTable object
* @return {!Promise<!google.visualization.DataTable>} promise for the created DataTable
*/
export async function dataTable(data) {
// Ensure that `google.visualization` namespace is added to the document.
await load();
if (data == null) {
return new google.visualization.DataTable();
} else if (data.getNumberOfRows) {
// Data is already a DataTable
return /** @type {!google.visualization.DataTable} */ (data);
} else if (data.cols) { // data.rows may also be specified
// Data is in the form of object DataTable structure
return new google.visualization.DataTable(data);
} else if (data.length > 0) {
// Data is in the form of a two dimensional array.
return google.visualization.arrayToDataTable(data);
} else if (data.length === 0) {
// Chart data was empty.
// We throw instead of creating an empty DataTable because most
// (if not all) charts will render a sticky error in this situation.
throw new Error('Data was empty.');
}
throw new Error('Data format was not recognized.');
}