Skip to content

Commit 529ab6b

Browse files
authored
Add analytics extension with GoatCounter support (#296)
1 parent 7c1df8c commit 529ab6b

File tree

3 files changed

+323
-0
lines changed

3 files changed

+323
-0
lines changed
Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
// GoatCounter: https://www.goatcounter.com
2+
// This file is released under the ISC license: https://opensource.org/licenses/ISC
3+
;(function() {
4+
'use strict';
5+
6+
if (window.goatcounter && window.goatcounter.vars) // Compatibility with very old version; do not use.
7+
window.goatcounter = window.goatcounter.vars
8+
else
9+
window.goatcounter = window.goatcounter || {}
10+
11+
// Load settings from data-goatcounter-settings.
12+
var s = document.querySelector('script[data-goatcounter]')
13+
if (s && s.dataset.goatcounterSettings) {
14+
try { var set = JSON.parse(s.dataset.goatcounterSettings) }
15+
catch (err) { console.error('invalid JSON in data-goatcounter-settings: ' + err) }
16+
for (var k in set)
17+
if (['no_onload', 'no_events', 'allow_local', 'allow_frame', 'path', 'title', 'referrer', 'event'].indexOf(k) > -1)
18+
window.goatcounter[k] = set[k]
19+
}
20+
21+
var enc = encodeURIComponent
22+
23+
// Get all data we're going to send off to the counter endpoint.
24+
var get_data = function(vars) {
25+
var data = {
26+
p: (vars.path === undefined ? goatcounter.path : vars.path),
27+
r: (vars.referrer === undefined ? goatcounter.referrer : vars.referrer),
28+
t: (vars.title === undefined ? goatcounter.title : vars.title),
29+
e: !!(vars.event || goatcounter.event),
30+
s: [window.screen.width, window.screen.height, (window.devicePixelRatio || 1)],
31+
b: is_bot(),
32+
q: location.search,
33+
}
34+
35+
var rcb, pcb, tcb // Save callbacks to apply later.
36+
if (typeof(data.r) === 'function') rcb = data.r
37+
if (typeof(data.t) === 'function') tcb = data.t
38+
if (typeof(data.p) === 'function') pcb = data.p
39+
40+
if (is_empty(data.r)) data.r = document.referrer
41+
if (is_empty(data.t)) data.t = document.title
42+
if (is_empty(data.p)) data.p = get_path()
43+
44+
if (rcb) data.r = rcb(data.r)
45+
if (tcb) data.t = tcb(data.t)
46+
if (pcb) data.p = pcb(data.p)
47+
return data
48+
}
49+
50+
// Check if a value is "empty" for the purpose of get_data().
51+
var is_empty = function(v) { return v === null || v === undefined || typeof(v) === 'function' }
52+
53+
// See if this looks like a bot; there is some additional filtering on the
54+
// backend, but these properties can't be fetched from there.
55+
var is_bot = function() {
56+
// Headless browsers are probably a bot.
57+
var w = window, d = document
58+
if (w.callPhantom || w._phantom || w.phantom)
59+
return 150
60+
if (w.__nightmare)
61+
return 151
62+
if (d.__selenium_unwrapped || d.__webdriver_evaluate || d.__driver_evaluate)
63+
return 152
64+
if (navigator.webdriver)
65+
return 153
66+
return 0
67+
}
68+
69+
// Object to urlencoded string, starting with a ?.
70+
var urlencode = function(obj) {
71+
var p = []
72+
for (var k in obj)
73+
if (obj[k] !== '' && obj[k] !== null && obj[k] !== undefined && obj[k] !== false)
74+
p.push(enc(k) + '=' + enc(obj[k]))
75+
return '?' + p.join('&')
76+
}
77+
78+
// Show a warning in the console.
79+
var warn = function(msg) {
80+
if (console && 'warn' in console)
81+
console.warn('goatcounter: ' + msg)
82+
}
83+
84+
// Get the endpoint to send requests to.
85+
var get_endpoint = function() {
86+
var s = document.querySelector('script[data-goatcounter]')
87+
if (s && s.dataset.goatcounter)
88+
return s.dataset.goatcounter
89+
return (goatcounter.endpoint || window.counter) // counter is for compat; don't use.
90+
}
91+
92+
// Get current path.
93+
var get_path = function() {
94+
var loc = location,
95+
c = document.querySelector('link[rel="canonical"][href]')
96+
if (c) { // May be relative or point to different domain.
97+
var a = document.createElement('a')
98+
a.href = c.href
99+
if (a.hostname.replace(/^www\./, '') === location.hostname.replace(/^www\./, ''))
100+
loc = a
101+
}
102+
return (loc.pathname + loc.search) || '/'
103+
}
104+
105+
// Run function after DOM is loaded.
106+
var on_load = function(f) {
107+
if (document.body === null)
108+
document.addEventListener('DOMContentLoaded', function() { f() }, false)
109+
else
110+
f()
111+
}
112+
113+
// Filter some requests that we (probably) don't want to count.
114+
goatcounter.filter = function() {
115+
if ('visibilityState' in document && document.visibilityState === 'prerender')
116+
return 'visibilityState'
117+
if (!goatcounter.allow_frame && location !== parent.location)
118+
return 'frame'
119+
if (!goatcounter.allow_local && location.hostname.match(/(localhost$|^127\.|^10\.|^172\.(1[6-9]|2[0-9]|3[0-1])\.|^192\.168\.|^0\.0\.0\.0$)/))
120+
return 'localhost'
121+
if (!goatcounter.allow_local && location.protocol === 'file:')
122+
return 'localfile'
123+
if (localStorage && localStorage.getItem('skipgc') === 't')
124+
return 'disabled with #toggle-goatcounter'
125+
return false
126+
}
127+
128+
// Get URL to send to GoatCounter.
129+
window.goatcounter.url = function(vars) {
130+
var data = get_data(vars || {})
131+
if (data.p === null) // null from user callback.
132+
return
133+
data.rnd = Math.random().toString(36).substr(2, 5) // Browsers don't always listen to Cache-Control.
134+
135+
var endpoint = get_endpoint()
136+
if (!endpoint)
137+
return warn('no endpoint found')
138+
139+
return endpoint + urlencode(data)
140+
}
141+
142+
// Count a hit.
143+
window.goatcounter.count = function(vars) {
144+
var f = goatcounter.filter()
145+
if (f)
146+
return warn('not counting because of: ' + f)
147+
148+
var url = goatcounter.url(vars)
149+
if (!url)
150+
return warn('not counting because path callback returned null')
151+
152+
if (navigator.sendBeacon)
153+
navigator.sendBeacon(url)
154+
else { // Fallback for (very) old browsers.
155+
var img = document.createElement('img')
156+
img.src = url
157+
img.style.position = 'absolute' // Affect layout less.
158+
img.style.bottom = '0px'
159+
img.style.width = '1px'
160+
img.style.height = '1px'
161+
img.loading = 'eager'
162+
img.setAttribute('alt', '')
163+
img.setAttribute('aria-hidden', 'true')
164+
165+
var rm = function() { if (img && img.parentNode) img.parentNode.removeChild(img) }
166+
img.addEventListener('load', rm, false)
167+
document.body.appendChild(img)
168+
}
169+
}
170+
171+
// Get a query parameter.
172+
window.goatcounter.get_query = function(name) {
173+
var s = location.search.substr(1).split('&')
174+
for (var i = 0; i < s.length; i++)
175+
if (s[i].toLowerCase().indexOf(name.toLowerCase() + '=') === 0)
176+
return s[i].substr(name.length + 1)
177+
}
178+
179+
// Track click events.
180+
window.goatcounter.bind_events = function() {
181+
if (!document.querySelectorAll) // Just in case someone uses an ancient browser.
182+
return
183+
184+
var send = function(elem) {
185+
return function() {
186+
goatcounter.count({
187+
event: true,
188+
path: (elem.dataset.goatcounterClick || elem.name || elem.id || ''),
189+
title: (elem.dataset.goatcounterTitle || elem.title || (elem.innerHTML || '').substr(0, 200) || ''),
190+
referrer: (elem.dataset.goatcounterReferrer || elem.dataset.goatcounterReferral || ''),
191+
})
192+
}
193+
}
194+
195+
Array.prototype.slice.call(document.querySelectorAll("*[data-goatcounter-click]")).forEach(function(elem) {
196+
if (elem.dataset.goatcounterBound)
197+
return
198+
var f = send(elem)
199+
elem.addEventListener('click', f, false)
200+
elem.addEventListener('auxclick', f, false) // Middle click.
201+
elem.dataset.goatcounterBound = 'true'
202+
})
203+
}
204+
205+
// Add a "visitor counter" frame or image.
206+
window.goatcounter.visit_count = function(opt) {
207+
on_load(function() {
208+
opt = opt || {}
209+
opt.type = opt.type || 'html'
210+
opt.append = opt.append || 'body'
211+
opt.path = opt.path || get_path()
212+
opt.attr = opt.attr || {width: '200', height: (opt.no_branding ? '60' : '80')}
213+
214+
opt.attr['src'] = get_endpoint() + 'er/' + enc(opt.path) + '.' + enc(opt.type) + '?'
215+
if (opt.no_branding) opt.attr['src'] += '&no_branding=1'
216+
if (opt.style) opt.attr['src'] += '&style=' + enc(opt.style)
217+
if (opt.start) opt.attr['src'] += '&start=' + enc(opt.start)
218+
if (opt.end) opt.attr['src'] += '&end=' + enc(opt.end)
219+
220+
var tag = {png: 'img', svg: 'img', html: 'iframe'}[opt.type]
221+
if (!tag)
222+
return warn('visit_count: unknown type: ' + opt.type)
223+
224+
if (opt.type === 'html') {
225+
opt.attr['frameborder'] = '0'
226+
opt.attr['scrolling'] = 'no'
227+
}
228+
229+
var d = document.createElement(tag)
230+
for (var k in opt.attr)
231+
d.setAttribute(k, opt.attr[k])
232+
233+
var p = document.querySelector(opt.append)
234+
if (!p)
235+
return warn('visit_count: append not found: ' + opt.append)
236+
p.appendChild(d)
237+
})
238+
}
239+
240+
// Make it easy to skip your own views.
241+
if (location.hash === '#toggle-goatcounter') {
242+
if (localStorage.getItem('skipgc') === 't') {
243+
localStorage.removeItem('skipgc', 't')
244+
alert('GoatCounter tracking is now ENABLED in this browser.')
245+
}
246+
else {
247+
localStorage.setItem('skipgc', 't')
248+
alert('GoatCounter tracking is now DISABLED in this browser until ' + location + ' is loaded again.')
249+
}
250+
}
251+
252+
if (!goatcounter.no_onload)
253+
on_load(function() {
254+
// 1. Page is visible, count request.
255+
// 2. Page is not yet visible; wait until it switches to 'visible' and count.
256+
// See #487
257+
if (!('visibilityState' in document) || document.visibilityState === 'visible')
258+
goatcounter.count()
259+
else {
260+
var f = function(e) {
261+
if (document.visibilityState !== 'visible')
262+
return
263+
document.removeEventListener('visibilitychange', f)
264+
goatcounter.count()
265+
}
266+
document.addEventListener('visibilitychange', f)
267+
}
268+
269+
if (!goatcounter.no_events)
270+
goatcounter.bind_events()
271+
})
272+
})();

nbsite/analytics/__init__.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
Analytics extension supporting GoatCounter only.
3+
Should be upstreamed to pydata-sphinx-theme.
4+
"""
5+
6+
from .. import __version__ as nbs_version
7+
8+
9+
def add_analytics(app):
10+
nbsite_analytics = app.config.nbsite_analytics
11+
if nbsite_analytics:
12+
13+
# Process GoatCounter
14+
15+
# goatcounter_holoviz is specific to HoloViz, remove when moving to PyData Sphinx Theme
16+
goatcounter_holoviz = nbsite_analytics.get('goatcounter_holoviz', False)
17+
if goatcounter_holoviz:
18+
hv_default = dict(
19+
goatcounter_url='https://holoviz.goatcounter.com/count',
20+
goatcounter_domain='auto',
21+
)
22+
nbsite_analytics = dict(nbsite_analytics, **hv_default)
23+
goatcounter_url = nbsite_analytics.get('goatcounter_url')
24+
if goatcounter_url:
25+
goatcounter_domain = nbsite_analytics.get('goatcounter_domain')
26+
if goatcounter_domain:
27+
domain = "location.host" if goatcounter_domain == "auto" else f"{goatcounter_domain!r}"
28+
# See https://www.goatcounter.com/help/domains
29+
body = (
30+
"\n window.goatcounter = {\n"
31+
" path: function(p) { return " + domain + " + p }\n"
32+
" }\n"
33+
)
34+
app.add_js_file(None, body=body)
35+
app.add_js_file(
36+
"js/goatcounter.js",
37+
**{"loading_method": "async", "data-goatcounter": goatcounter_url}
38+
)
39+
40+
def setup(app):
41+
"""Setup analytics (goatcounter only!) sphinx extension"""
42+
# In the Pydata Sphinx Theme the config is going to be in the theme
43+
app.add_config_value('nbsite_analytics', {}, 'html')
44+
app.connect('builder-inited', add_analytics)
45+
return {'parallel_read_safe': True, 'version': nbs_version}

site/doc/conf.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
'nbsite.pyodide',
2121
# To build a gallery
2222
'nbsite.gallery',
23+
# To setup GoatCounter
24+
'nbsite.analytics',
2325
# Activate the docstring extension for Numpy: https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html
2426
'sphinx.ext.napoleon',
2527
# See https://github.com/ipython/ipython/issues/13845
@@ -46,6 +48,10 @@
4648
},
4749
}
4850

51+
nbsite_analytics = {
52+
'goatcounter_holoviz': True,
53+
}
54+
4955
# Configure the theme
5056
html_theme_options = {
5157
"github_url": "https://github.com/holoviz-dev/nbsite",

0 commit comments

Comments
 (0)