Branchwell

Graphley / website / assets / site.js

1// The working preview in the hero: the Graphley Mac window with made-up sample data.
2// Pick a site, change the range, hover the chart, switch the appearance. Below it, the
3// agent session switches between "View only" and "Can make changes". No network calls.
4(function () {
5 var gw = document.querySelector('.gw');
6 if (gw) preview(gw);
7 agentSession();
8 appearance(gw);
9
10 function preview(gw) {
11 // Sample sites: [id, name, base visitors per day, daily growth, downloads per day (0 = website only)]
12 var SITES = [
13 ['harbor', 'Harbor Notes', 70, 0.0045, 1.8],
14 ['field', 'Field Guide', 42, 0.002, 0],
15 ['tidepool', 'Tidepool', 18, 0.011, 4.6],
16 ['lantern', 'Lantern Docs', 19, -0.001, 0],
17 ['drift', 'Driftwood', 13, 0.003, 0]
18 ];
19 var DAYS = 180; // 90 shown at most, plus the 90 before it for comparisons
20 var seed = 20261124;
21 function random() { seed = (seed * 1664525 + 1013904223) % 4294967296; return seed / 4294967296; }
22
23 var data = {};
24 SITES.forEach(function (s, si) {
25 var visitors = [], downloads = [], events = [];
26 for (var d = 0; d < DAYS; d++) {
27 var weekday = (d + 3) % 7;
28 var week = weekday === 5 || weekday === 6 ? 0.72 : 1;
29 var trend = s[2] * Math.pow(1 + s[3], d - DAYS + 90);
30 var wave = 1 + 0.12 * Math.sin((d + si * 9) / 6.5);
31 var spike = s[0] === 'tidepool' && d > DAYS - 21 ? 1 + 1.6 * Math.exp(-(d - (DAYS - 21)) / 5) : 1;
32 var v = Math.max(0, Math.round(trend * week * wave * spike * (0.85 + random() * 0.3)));
33 visitors.push(v);
34 downloads.push(s[4] ? Math.max(0, Math.round(s[4] * spike * (0.4 + random() * 1.2))) : 0);
35 events.push(Math.round(v * (0.03 + random() * 0.03)));
36 }
37 data[s[0]] = { name: s[1], visitors: visitors, downloads: downloads, events: events, app: s[4] > 0 };
38 });
39
40 var state = { site: 'all', days: 30 };
41 var svg = gw.querySelector('.gw-chart svg');
42 var readout = gw.querySelector('.gw-readout');
43 var W = 640, H = 200, PAD = { l: 34, r: 6, t: 10, b: 22 };
44 function measure() {
45 // Draw at the chart's real size so the axis text stays small at every width.
46 W = Math.max(280, Math.round(svg.getBoundingClientRect().width) || 640);
47 H = W < 520 ? 170 : 210;
48 svg.setAttribute('viewBox', '0 0 ' + W + ' ' + H);
49 }
50 var today = new Date();
51
52 function sum(a) { return a.reduce(function (x, y) { return x + y; }, 0); }
53 function last(arr, n, offset) { return arr.slice(arr.length - n - (offset || 0), arr.length - (offset || 0)); }
54 function fmt(n) { return n >= 10000 ? (n / 1000).toFixed(1) + 'k' : n >= 1000 ? (n / 1000).toFixed(1).replace('.0', '') + 'k' : String(n); }
55 function full(n) { return n.toLocaleString('en-US'); }
56 function ids() { return state.site === 'all' ? SITES.map(function (s) { return s[0]; }) : [state.site]; }
57 function total(key, offset) {
58 return sum(ids().map(function (id) { return sum(last(data[id][key], state.days, offset)); }));
59 }
60 function niceMax(v) { if (v <= 5) return 5; var p = Math.pow(10, Math.floor(Math.log10(v))); var m = v / p; return (m <= 2 ? 2 : m <= 5 ? 5 : 10) * p; }
61 function dayLabel(i, n) {
62 var d = new Date(today); d.setDate(d.getDate() - (n - 1 - i));
63 return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
64 }
65 function delta(cur, prev) {
66 if (!prev) return { cls: '', txt: 'new' };
67 var p = Math.round((cur - prev) / prev * 100);
68 return { cls: p >= 0 ? 'up' : 'down', txt: (p >= 0 ? '▲ ' : '▼ ') + Math.abs(p) + '% vs previous' };
69 }
70
71 function render() {
72 measure();
73 var n = state.days;
74 var list = ids();
75 // Header and sidebar
76 gw.querySelector('[data-k="title"]').textContent = state.site === 'all' ? 'All sites' : data[state.site].name;
77 gw.querySelector('[data-k="sub"]').textContent = (state.site === 'all' ? '5 sites and apps' : data[state.site].app ? 'Website and App Store app' : 'Website') + ' · last ' + n + ' days';
78 gw.querySelectorAll('[data-site-to]').forEach(function (b) {
79 var id = b.getAttribute('data-site-to');
80 b.setAttribute('aria-pressed', String(id === state.site));
81 var count = b.querySelector('.n');
82 if (id !== 'all') count.textContent = fmt(sum(last(data[id].visitors, n)));
83 });
84 gw.querySelectorAll('[data-days]').forEach(function (b) { b.setAttribute('aria-pressed', String(+b.getAttribute('data-days') === n)); });
85 gw.querySelectorAll('.gw-legend [data-site]').forEach(function (s) { s.classList.toggle('off', list.indexOf(s.getAttribute('data-site')) < 0); });
86
87 // KPIs
88 ['visitors', 'downloads', 'events'].forEach(function (key, i) {
89 var box = gw.querySelector('.gw-kpi[data-i="' + i + '"]');
90 var hasApp = list.some(function (id) { return data[id].app; });
91 if (key === 'downloads' && !hasApp) {
92 box.querySelector('.v').textContent = '–';
93 var none = box.querySelector('.d'); none.className = 'd'; none.textContent = 'No app linked';
94 return;
95 }
96 var cur = total(key), prev = total(key, n), d = delta(cur, prev);
97 box.querySelector('.v').textContent = full(cur);
98 var el = box.querySelector('.d'); el.className = 'd ' + d.cls; el.textContent = d.txt;
99 });
100
101 // Chart
102 var series = list.map(function (id) { return { id: id, values: last(data[id].visitors, n) }; });
103 var max = niceMax(Math.max.apply(null, series.map(function (s) { return Math.max.apply(null, s.values); })));
104 var iw = W - PAD.l - PAD.r, ih = H - PAD.t - PAD.b;
105 function X(i) { return PAD.l + i * iw / (n - 1); }
106 function Y(v) { return PAD.t + ih - v / max * ih; }
107 var out = '<g class="grid">';
108 [0, 0.5, 1].forEach(function (f) { out += '<line x1="' + PAD.l + '" x2="' + (W - PAD.r) + '" y1="' + Y(max * f) + '" y2="' + Y(max * f) + '"/>'; });
109 out += '</g><g class="axis">';
110 [0, 0.5, 1].forEach(function (f) { out += '<text x="' + (PAD.l - 6) + '" y="' + (Y(max * f) + 4) + '" text-anchor="end">' + fmt(max * f) + '</text>'; });
111 out += '<text x="' + PAD.l + '" y="' + (H - 4) + '">' + dayLabel(0, n) + '</text>';
112 out += '<text x="' + (W - PAD.r) + '" y="' + (H - 4) + '" text-anchor="end">Today</text></g>';
113 SITES.forEach(function (s, si) {
114 var shown = list.indexOf(s[0]) >= 0;
115 var vals = last(data[s[0]].visitors, n);
116 var line = vals.map(function (v, i) { return (i ? 'L' : 'M') + X(i).toFixed(1) + ' ' + Y(Math.min(v, max)).toFixed(1); }).join(' ');
117 var area = line + ' L' + X(n - 1).toFixed(1) + ' ' + Y(0) + ' L' + X(0).toFixed(1) + ' ' + Y(0) + ' Z';
118 var cls = ' k' + (si + 1) + (shown ? '' : ' is-off');
119 out += '<path class="area' + cls + '" d="' + area + '"/><path class="line' + cls + '" d="' + line + '"/>';
120 });
121 out += '<line class="hover-line" x1="0" x2="0" y1="' + PAD.t + '" y2="' + (H - PAD.b) + '" visibility="hidden"/>';
122 svg.innerHTML = out;
123 svg.classList.toggle('all', state.site === 'all');
124 state.X = X; state.Y = Y; state.max = max;
125 showDay(null);
126 }
127
128 function totalsOn(i) {
129 var n = state.days;
130 return sum(ids().map(function (id) { return last(data[id].visitors, n)[i]; }));
131 }
132 function showDay(i) {
133 var n = state.days;
134 var hover = svg.querySelector('.hover-line');
135 if (i === null) {
136 var best = 0;
137 for (var k = 1; k < n; k++) if (totalsOn(k) > totalsOn(best)) best = k;
138 readout.textContent = 'Busiest day: ' + dayLabel(best, n) + ' · ' + full(totalsOn(best)) + ' visitors';
139 hover.setAttribute('visibility', 'hidden');
140 return;
141 }
142 readout.textContent = dayLabel(i, n) + ' · ' + full(totalsOn(i)) + ' visitors';
143 hover.setAttribute('x1', state.X(i)); hover.setAttribute('x2', state.X(i));
144 hover.setAttribute('visibility', 'visible');
145 }
146
147 svg.addEventListener('pointermove', function (e) {
148 var box = svg.getBoundingClientRect();
149 var x = (e.clientX - box.left) / box.width * W;
150 var i = Math.round((x - PAD.l) / (W - PAD.l - PAD.r) * (state.days - 1));
151 showDay(Math.max(0, Math.min(state.days - 1, i)));
152 });
153 svg.addEventListener('pointerleave', function () { showDay(null); });
154
155 gw.addEventListener('click', function (e) {
156 var site = e.target.closest('[data-site-to]');
157 var range = e.target.closest('[data-days]');
158 if (site) { state.site = site.getAttribute('data-site-to'); render(); }
159 if (range) { state.days = +range.getAttribute('data-days'); render(); }
160 });
161 var resizeTimer;
162 window.addEventListener('resize', function () { clearTimeout(resizeTimer); resizeTimer = setTimeout(render, 120); });
163 render();
164 }
165
166 function appearance(gw) {
167 var buttons = document.querySelectorAll('[data-look]');
168 if (!gw || !buttons.length) return;
169 // Start in the visitor's own appearance.
170 var dark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
171 set(dark ? 'dark' : 'light');
172 buttons.forEach(function (b) { b.addEventListener('click', function () { set(b.getAttribute('data-look')); }); });
173 function set(look) {
174 gw.setAttribute('data-appearance', look);
175 buttons.forEach(function (b) { b.setAttribute('aria-pressed', String(b.getAttribute('data-look') === look)); });
176 }
177 }
178
179 function agentSession() {
180 var session = document.querySelector('.session');
181 if (!session) return;
182 session.querySelectorAll('[data-mode-to]').forEach(function (b) {
183 b.addEventListener('click', function () {
184 var mode = b.getAttribute('data-mode-to');
185 session.setAttribute('data-mode', mode);
186 session.querySelectorAll('[data-mode-to]').forEach(function (o) { o.setAttribute('aria-pressed', String(o === b)); });
187 });
188 });
189 }
190})();