aboutsummaryrefslogtreecommitdiffstats
path: root/webstats/stats.paren
blob: 6733ff403c811d4a29a0215641426dc0b04aa4e4 (plain)
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
;; -*- mode: lisp; -*-
;; (pushnew '(SLYNK:*STRING-ELISION-LENGTH* . nil) slynk:*slynk-pprint-bindings* :test #'equal)

(in-package :webstats-js)

(defun register-visit (data)
  (fetch "http://localhost:4252/visit"
            (create :method "POST"
                    :headers (create "Content-Type" "application/x-www-form-urlencoded")
                    :body (new (-u-r-l-search-params data)))))

(defun instrument-links ()
  (chain document (query-selector-all "a")
         (for-each (lambda (link)
                     (setf (getprop link 'onclick)
                           (lambda (event)
                             (chain console (log event (@ event which)))
                             (chain event (prevent-default))
                             (when (or (= 1 (@ event which))
                                       (= 2 (@ event which)))
                               (chain console (warn "in req"))
                               (chain
                                (register-visit (create :click (getprop link 'href)
                                                        :page (@ document location href)))
                                (finally (lambda ()
                                           (if (= 1 (@ event which))
                                               (setf (@ window location href) (getprop link 'href))
                                               (chain window (open (getprop link 'href) "_blank"))))))))

                           )))))

(defun register-page-load ()
  (let ((data (create :title (@ document title)
                      :page (@ document location href)
                      :referer (@ document referrer))))
    (chain
     (register-visit data)
     (then (lambda (r)
             ((@ console log) r)
             ((@ r text))))
     (then (@ console log)))))

(add-event-listener
 "load"
 (lambda ()
   (instrument-links)
   (register-page-load)))