-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
461 lines (402 loc) · 12.6 KB
/
index.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
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
import {
Chart,
Filler,
LinearScale,
LineController,
LineElement,
PointElement,
TimeScale,
Title,
Tooltip,
} from "chart.js";
import "chartjs-adapter-date-fns";
import cloneDeep from "lodash.clonedeep";
import { colors, docs, host, options } from "./constants";
import { log, prefix } from "./logger";
import {
removeChildren,
k,
getSetting,
addOpacity,
createSVGLogo,
} from "./utils";
// Stop script when it's included already
if (window.saEmbedScriptLoaded) {
throw new Error(`${prefix} Only embed our script once.`);
} else {
window.saEmbedScriptLoaded = true;
}
Chart.register(
Filler,
LinearScale,
LineController,
LineElement,
PointElement,
TimeScale,
Title,
Tooltip
);
const headers = { "Content-Type": "application/json" };
const cdnUrl = '[src="https://scripts.simpleanalyticscdn.com/embed.js"]';
const localUrl = '[src$="/embed.js"]';
const currentScript =
document.currentScript ||
document.querySelector(cdnUrl) ||
document.querySelector(localUrl);
const mainDataset = currentScript?.dataset || {};
let siteTextColor, siteFontFamily, siteFontSize;
const dataset = {
fill: "origin",
borderWidth: 2,
pointRadius: 0,
hoverBorderWidth: 2,
};
let userTimezone;
try {
userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch (error) {
/* Do nothing */
}
const generateChart = async (chartOptions) => {
const {
legacy,
element,
start,
end,
pages,
hostname,
color,
yMax,
expose,
timezone,
pageViewsElement,
visitorsElement,
} = chartOptions;
element.style.display = "flex";
element.style.alignItems = "center";
element.style.justifyContent = "center";
element.style.textAlign = "center";
const p = element.querySelector("p");
if (p) p.textContent = "Simple Analytics chart is loading...";
if (typeof Proxy !== "function") {
if (p) p.textContent = "Can not load chart in this browser.";
return log("Can not load chart in this browser", "error");
}
const params = new URLSearchParams([
["info", "false"],
["version", "5"],
["fields", "histogram,pageviews,visitors"],
]);
if (start) params.set("start", start);
if (end) params.set("end", end);
if (pages) params.set("pages", pages);
if (timezone || userTimezone)
params.set("timezone", timezone || userTimezone);
const url = `${host}/${hostname}.json?${params}`;
const response = await fetch(url, { headers });
const json = await response.json();
const labels = json?.histogram.map(({ date }) => date);
const pageViews = json?.histogram.map((day) => day.pageviews);
const visitors = json?.histogram.map((day) => day.visitors);
const borderWidth = getSetting({
default: "2",
value: chartOptions.borderWidth || mainDataset.borderWidth,
regex: /[0-9]{1,2}/i,
warning: 'Invalid border width, enter a number in pixels, eg: "2"',
});
dataset.borderWidth = borderWidth;
dataset.hoverBorderWidth = borderWidth;
const borderColorPageViews = getSetting({
default: colors.pageViews.border,
value: chartOptions.pageViewsColor || mainDataset.pageViewsColor || color,
regex: /[0-9a-f]{6}/i,
warning: 'Invalid page views color, enter a hex color, eg: "66ff00"',
normalize: (value) => "#" + value.replace("#", ""),
});
const borderColorVisitors = getSetting({
default: colors.visitors.border,
value: chartOptions.visitorsColor || mainDataset.visitorsColor || color,
regex: /[0-9a-f]{6}/i,
warning: 'Invalid visitors color, enter a hex color, eg: "66ff00"',
normalize: (value) => "#" + value.replace("#", ""),
});
const areaOpacityPercent = getSetting({
default: "20",
value: chartOptions.areaOpacity || mainDataset.areaOpacity,
regex: /(100|[0-9]{1,2})/i,
warning: 'Invalid opacity, enter a number between 1-100, eg: "50"',
});
const backgroundColorPageViews = addOpacity(
borderColorPageViews,
areaOpacityPercent
);
const backgroundColorVisitors = addOpacity(
borderColorVisitors,
areaOpacityPercent
);
const textColor = getSetting({
default: siteTextColor || "#000000",
value: chartOptions.textColor || mainDataset.textColor,
regex: /[0-9a-f]{6}/i,
warning: 'Invalid visitors color, enter a hex color, eg: "66ff00"',
normalize: (value) => "#" + value.replace("#", ""),
});
const types = getSetting({
default: legacy ? ["pageviews"] : ["visitors"],
value: chartOptions.types || mainDataset.types,
regex: /[a-z, ]+/i,
warning: 'Invalid types, try: "pageviews,visitors"',
normalize: (value) => value.split(",").map((value) => value.trim()),
});
const showLogo = getSetting({
default: !legacy,
value: chartOptions.showLogo || mainDataset.showLogo,
regex: /(true|false|yes|no)/i,
warning: 'Invalid show logo, try: "false"',
normalize: (value) => ["true", "yes"].includes(value),
});
if (!types.length) types.push("visitors");
const datasets = [];
if (types.includes("pageviews")) {
datasets.push({
...dataset,
order: 2,
label: "Page views",
borderColor: [borderColorPageViews],
backgroundColor: [backgroundColorPageViews],
data: pageViews,
});
}
if (types.includes("visitors"))
datasets.push({
...dataset,
order: 1,
label: "Visitors",
borderColor: [borderColorVisitors],
backgroundColor: [backgroundColorVisitors],
data: visitors,
});
const data = { labels, datasets };
// Make sure these chart options are not applied to other charts
const optionsCopy = cloneDeep(options);
if (yMax) optionsCopy.scales.y.max = yMax;
// Do DOM manupilations
removeChildren(element);
const canvas = document.createElement("canvas");
canvas.ariaLabel = `Chart with visitors data from ${hostname}`;
element.appendChild(canvas);
element.style.aspectRatio = "unset";
Chart.defaults.color = textColor;
Chart.defaults.borderColor = addOpacity(textColor, 7);
if (siteFontFamily)
Chart.defaults.font = {
family: siteFontFamily,
size: Math.max(siteFontSize, 12) - 2 || 12,
};
const chart = new Chart(canvas, {
type: "line",
data,
options: optionsCopy,
});
// Show numbers in HTML elements if they exist
if (pageViewsElement) pageViewsElement.textContent = k(json.pageviews);
if (visitorsElement) visitorsElement.textContent = k(json.visitors);
// Expose so customer can modify Chart instance
if (expose && expose !== "false") window[expose] = chart;
// Update text color on dark mode change
const updateTextColor = () => {
const p = document.querySelector("p");
const { color } = getComputedStyle(p) || {};
if (color === chart.options.scales.y.ticks.color) return;
chart.options.scales.y.ticks.color = color;
chart.options.scales.x.ticks.color = color;
chart.update();
};
// Listen for dark mode change
if (window.matchMedia)
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", (event) => {
window.setTimeout(() => updateTextColor(), 0);
window.setTimeout(() => updateTextColor(), 500);
});
// Only draw when parent element has a valid position
const { position } = getComputedStyle(element) || {};
if (!showLogo || !["static", "relative"].includes(position)) return;
// Make container relative
element.style.position = "relative";
// Get margins
const marginTop = chart.scales.y?._margins?.top || 10;
const boxSize = 40;
const boxSpacing = 25;
const top = marginTop + boxSpacing;
// Create link element
const box = document.createElement("a");
box.style.all = "unset";
box.style.position = "absolute";
box.style.top = `${top}px`;
box.style.left = `${chart.scales.y.width + boxSpacing}px`;
box.style.height = `${boxSize}px`;
box.style.width = `${boxSize}px`;
box.style.borderRadius = "5px";
box.style.color = borderColorVisitors;
box.style.backgroundColor = backgroundColorVisitors;
box.style.border = `${borderWidth}px solid ${borderColorVisitors}`;
box.style.opacity = "0.5";
box.style.cursor = "pointer";
box.style.display = "flex";
box.style.justifyContent = "center";
box.style.alignItems = "center";
// Link to public dashboard
box.title = `Go to Simple Analytics dashboard`;
box.ariaLabel = "Open public dashboard of this chart on Simple Analytics";
box.href = `${host}/${hostname}?utm_source=${hostname}&utm_medium=embed`;
box.referrerPolicy = "no-referrer-when-downgrade";
box.target = "_blank";
box.rel = "noopener";
// Bind hover styles
box.addEventListener("mouseenter", () => {
box.style.opacity = "1";
});
box.addEventListener("mouseleave", () => {
box.style.opacity = "0.5";
});
// Attach to DOM
const svg = createSVGLogo({ fill: borderColorVisitors });
svg.ariaLabel = "Simple Analytics logo";
box.appendChild(svg);
element.appendChild(box);
};
const triggerOnload = (ok = false) => {
const onload = mainDataset?.onload;
if (!onload) return;
if (!/[a-z0-9_]+/i.test(onload)) {
return log(`data-onload should only contain function name`, "error");
} else if (typeof window[onload] !== "function") {
return log(
`function name in data-onload does not link to function type`,
"error"
);
} else {
window[onload](ok);
}
};
function onReady() {
// Grab default text color of host website
const p = document.querySelector("p");
const { color, fontFamily, fontSize } = getComputedStyle(p) || {};
siteTextColor = color;
siteFontFamily = fontFamily;
siteFontSize = fontSize;
// Get legacy elements
const legacyElements = document.querySelectorAll("[data-sa-graph-url]");
if (legacyElements.length)
log(
`You're using the legacy embed feature, upgrade when you have time: ${docs}`,
"warn"
);
// Get latest elements
const elements = document.querySelectorAll(mainDataset?.chartSelectors);
// Stop when no elements are found
if (!legacyElements.length && !elements.length) {
triggerOnload(false);
return log("No elements found for chart selectors.", "error");
}
// Create a list of charts
const charts = [];
// Normalize legacy chart elements
legacyElements.forEach((element) => {
try {
const { dataset } = element;
const { saGraphUrl, saPageViewsSelector } = dataset;
const { pathname, searchParams } = new URL(saGraphUrl);
const hostname = pathname.slice(1);
const color = searchParams.get("color");
const yMax = searchParams.get("y-limit") || searchParams.get("max_y");
const start = searchParams.get("start");
const end = searchParams.get("end");
charts.push({
legacy: true,
element,
hostname,
color,
yMax,
start,
end,
pageViewsElement: document.querySelector(saPageViewsSelector),
});
} catch (error) {
triggerOnload(false);
throw new Error(`${prefix} ${error.message}`);
}
});
// Normalize latest chart elements
elements.forEach((element) => {
try {
const { dataset } = element;
const {
hostname,
color,
yMax,
start,
end,
pages,
timezone,
expose = "saChart",
pageViewsSelector,
visitorsSelector,
borderWidth,
textColor,
pageViewsColor,
visitorsColor,
areaOpacity,
types,
showLogo,
} = dataset;
charts.push({
legacy: false,
element,
hostname,
color,
yMax,
start,
end,
pages,
expose,
timezone: mainDataset.timezone || timezone || null,
pageViewsElement: document.querySelector(pageViewsSelector),
visitorsElement: document.querySelector(visitorsSelector),
borderWidth,
textColor,
pageViewsColor,
visitorsColor,
areaOpacity,
types,
showLogo,
});
} catch (error) {
triggerOnload(false);
throw new Error(`${prefix} ${error.message}`);
}
});
// Run generate chart on every chart in the list
Promise.all(charts.map(generateChart))
.then(() => triggerOnload(true))
.catch((message) => {
triggerOnload(false);
log(message, "error");
});
}
// Load embed script when page is ready
(function saInitEmbed(window) {
// Skip server side rendered pages
if (typeof window === "undefined" || typeof document === "undefined")
return triggerOnload(false);
if (document.readyState === "ready" || document.readyState === "complete") {
onReady();
} else {
document.addEventListener("readystatechange", function (event) {
if (event.target.readyState === "complete") onReady();
});
}
})(window);