JSFiddle - React, Tailwind, and code Playground

by Scott Kaye

JavaScript

class Heatmap {
  constructor() {
    this.queue = "";
    this.debounce;

    window.addEventListener("mousemove", (e) => {
      clearTimeout(this.debounce);
      this.debounce = setTimeout(this.mouseMove.bind(this, e), 100);
    }, false);

    window.addEventListener("click", this.mouseClick.bind(this), false);
  }

  enqueue(obj) {
    obj.time = window.performance.now() | 0;
    this.queue += this.toRecord(obj);
    clearTimeout(this.debounce);
    this.debounce = setTimeout(this.save.bind(this), 100);
  }

  save() {
    let events = window.sessionStorage.heatmap || "";
    events += this.queue;
		window.sessionStorage.heatmap = events;
    this.queue = "";
  }
  
  toRecord(obj) {
  	return [ obj.time, obj.x, obj.y, obj.type ]
    	.map(val => val.toString(36))
      .join(",") + ";";
  }

  mouseMove(e) {
    this.enqueue({
      x: e.pageX,
      y: e.pageY,
      type: Heatmap.prototype.TYPE_MOVE
    });
  }

  mouseClick(e) {
    this.enqueue({
      x: e.pageX,
      y: e.pageY,
      type: Heatmap.prototype.TYPE_CLICK
    });
  }
}

Heatmap.prototype.TYPE_CLICK = 1;
Heatmap.prototype.TYPE_MOVE = 2;

console.clear();
const h = new Heatmap();