-
Notifications
You must be signed in to change notification settings - Fork 79
/
google-analytics-chart.html
440 lines (394 loc) · 11.1 KB
/
google-analytics-chart.html
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
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../google-chart/google-chart.html">
<link rel="import" href="../promise-polyfill/promise-polyfill-lite.html">
<link rel="import" href="google-analytics-query.html">
<link rel="import" href="google-analytics-loader.html">
<!--
Element for displaying the results of a Google Analytics query in a
Google Chart.
##### Example
<google-analytics-chart
type="column"
ids="ga:1174"
metrics="ga:sessions"
dimensions="ga:country"
sort="-ga:sessions"
max-results="5">
</google-analytics-chart>
@element google-analytics-chart
@demo
@homepage https://googlewebcomponents.github.io/google-analytics
-->
<dom-module is="google-analytics-chart">
<style>
:host {
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
width: 400px;
height: 300px;
}
:host > * {
-webkit-flex: 0 0 auto;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
}
:host > google-chart {
-webkit-flex: 1 0 0%;
-ms-flex: 1 0 0%;
flex: 1 0 0%;
width: auto;
}
</style>
<template>
<google-analytics-loader all-ready="{{setupReady}}"></google-analytics-loader>
<google-analytics-query id="query"
loading="{{loading}}"
get-data-response-handler="{{_boundResponseHandler}}"
data="{{data}}"
ids="{{ids}}"
start-date="{{startDate}}"
end-date="{{endDate}}"
metrics="{{metrics}}"
dimensions="{{dimensions}}"
sort="{{sort}}"
filters="{{filters}}"
segment="{{segment}}"
sampling-level="{{samplingLevel}}"
start-index="{{startIndex}}"
max-results="{{maxResults}}"
output="dataTable"
src-param="gwc-ga-chart"
></google-analytics-query>
<content select="header,h1,h2,h3,h4,h5,h6"></content>
<google-chart id="chart"
type="{{type}}"
data="{{data.dataTable}}">
</google-chart>
<content select="footer"></content>
</template>
</dom-module>
<script>
(function() {
'use strict';
Polymer({
is: 'google-analytics-chart',
properties: {
/**
* Sets the type of the chart.
*
* Should be one of:
* - `area`, `bar`, `column`, `line`, `pie`, `geo`.
*
* @attribute type
* @default 'area'
* @type string
*/
type: {
type: String,
value: 'area'
},
/**
* Sets the options for the chart.
*
* Example:
* <pre>{
* title: "Chart title goes here",
* hAxis: {title: "Categories"},
* vAxis: {title: "Values", minValue: 0, maxValue: 2},
* legend: "none"
* };</pre>
* See <a href="https://google-developers.appspot.com/chart/interactive/docs/gallery">Google Visualization API reference (Chart Gallery)</a>
* for the options available to each chart type.
*
* @attribute options
* @default null
* @type object
*/
options: {
type: Object,
value: function() { return null; }
},
/**
* True after the chart has been rendered for the first time.
*
* @attribute rendered
* @type boolean
*/
rendered: {
type: Boolean,
value: false,
notify: true,
reflectToAttribute: true
},
/**
* True if the chart is currently loading data.
*
* @attribute loading
* @type boolean
*/
loading: {
type: Boolean,
value: false,
notify: true,
reflectToAttribute: true
},
/**
* True if setup is ready
*
* @attribute setupReady
* @type Boolean
*/
setupReady: {
type: Boolean,
observer: 'setupReadyChanged'
},
/**
* google-analytics-query passthrough properties
* See google-analytics-query for documentation
* startDate, endDate, data, ids, metrics, dimensions, sort, filters, segment, samplingLevel, startIndex, maxResults
*/
startDate: {
type: String,
},
endDate: {
type: String
},
data: {
type: Object
},
ids: {
type: String
},
metrics: {
type: String
},
dimensions: {
type: String
},
sort: {
type: String
},
filters: {
type: String
},
segment: {
type: String
},
samplingLevel: {
type: String
},
startIndex: {
type: Number
},
maxResults: {
type: Number
}
},
ready: function() {
this._boundResponseHandler = this.handleResponse.bind(this);
this.$.chart.options = this.$.chart.options || {};
merge(this.$.chart.options, getChartOptions(this.type), this.options);
},
setupReadyChanged: function(newVal, oldVal) {
if (newVal) {
metadata.get();
}
},
handleResponse: function(response) {
this.rendered = true;
metadata.get().then(function(map) {
switchApiNamesToDisplayNames(response.dataTable, map);
ensureProperDataTableTypes(response.dataTable);
this.$.query.setData(response);
}.bind(this));
}
});
/**
* @module metadata
*/
var metadata = (function() {
var promise;
function queryMetadataAPI() {
if (!gapi || !gapi.client || !gapi.client.analytics) {
console.warn("Library not loaded yet!");
return;
}
return new Promise(function(resolve, reject) {
gapi.client.analytics
gapi.client.analytics.metadata.columns
.list({
reportType: 'ga',
_src: 'gwc-ga-chart'
})
.execute(function(response) {
if (response.error) {
reject(response.error);
}
else {
var map = {};
response.items.forEach(function(item) {
map[item.id] = item.attributes.uiName;
});
resolve(map);
}
});
});
}
return {
/**
* Return the `queryMetadataAPI` promise. If the promise exists,
* return it to avoid multiple requests. If the promise does not
* exist, initiate the request and cache the promise.
*/
get: function() {
promise = promise || queryMetadataAPI();
return promise.catch(function(err) {
console.error(err.stack || err);
});
}
};
}());
/**
* Return an options object for the specified chart type.
* These are options suitable to pass to a Google Chart instance.
* @return {Object} The chart options.
*/
function getChartOptions(type) {
var chartOptions = {
base: {
fontSize: 11,
chartArea: {
width: '100%'
},
legend: {
position: 'top',
alignment: 'start'
}
},
area: {
pointSize: 6,
lineWidth: 4,
areaOpacity: 0.1,
colors: ['#058dc7', '#aadff3'],
hAxis: {
format: 'MMM d',
gridlines: {
color: 'transparent'
},
baselineColor: 'transparent'
},
vAxis: {
gridlines: {
color: '#e8e8e8',
logScale: true,
count: 3
},
textPosition: 'in'
}
},
bar: {
colors: ['#058dc7', '#50b432', '#ed561b'],
hAxis: {
gridlines: {
color: '#e8e8e8'
}
},
vAxis: {
textPosition: 'in',
textStyle: {
strokeWidth: 4,
}
}
},
column: {
colors: ['#058dc7', '#50b432', '#ed561b'],
hAxis: {
gridlines: {
color: 'transparent'
},
baselineColor: 'transparent'
},
vAxis: {
gridlines: {
color: '#e8e8e8',
},
textPosition: 'in'
},
},
geo: {
colorAxis: {
minValue: 0,
colors: ['#aadff3', '#058dc7']
}
},
pie: {
legend: {
position: 'right'
},
pieHole: 0.4
}
};
return merge({}, chartOptions.base, chartOptions[type]);
}
/**
* Use data from the Metadata API to change api names
* (e.g. `ga:sessions`) to their display names (e.g. "Sessions").
* @param {Object} dataTable - The dataTable data.
* @param {Object} map - A key/value store where the keys are the
* api names and the values are the display names.
*/
function switchApiNamesToDisplayNames(dataTable, map) {
dataTable.cols.forEach(function(col) {
col.label = map[col.id] || col.label;
});
}
/**
* The analytics api erroneously return some values as strings that are
* supposed to be numbers. This function fixes that.
* @param {Object} dataTable - The dataTable data.
*/
function ensureProperDataTableTypes(dataTable) {
for (var i = 0; i < dataTable.rows.length; i++) {
var row = dataTable.rows[i];
for (var j = 0; j < row.c.length; j++) {
if (dataTable.cols[j].type === 'number') {
row.c[j].v = Number(row.c[j].v);
}
}
}
}
/**
* Merge the source objects, in order, onto the destination object.
* Recursively merge nested, plain objects, everything else copy by
* reference.
* @param {Object} target - The object to receive the merged values.
* @param {...Object} source - The object(s) to provide values to the
* target. Later sources override previous sources.
* @return {Object} The merged target object.
*/
function merge(target) {
var sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function(source) {
// Only merge objects.
if (!(source && typeof sources == 'object')) return;
Object.keys(source).forEach(function(key) {
// If the source's key is a 'plain' object, recursively merge.
if (typeof source[key] == 'object' &&
Object.getPrototypeOf(source[key]) == Object.prototype) {
target[key] = target[key] == null ?
merge({}, source[key]) : merge(target[key], source[key]);
}
// Otherwise just copy by reference.
else if (typeof source[key] != 'undefined') {
target[key] = source[key];
}
});
});
return target;
}
}());
</script>