Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="container">
  
  <h1>Live event streams</h1>
  <select id="source-url-select">
    <option value="https://stream.wikimedia.org" selected>stream.wikimedia.org</option>
    <option value="https://stream-beta.wmflabs.org">stream-beta.wmflabs.org (not yet working)</option>
  </select>
  
  <hr>
  
  <div id="ui">  
    <div>
      <label for="streams">Available streams</label>
    </div>
    <select id="streams" multiple></select>
  </div>
  
  <div id="rate-div">
    <span>Messages in the last second: <span id="rate-min">..</span>
    (average so far: <span id="rate-avg">..</span>/s)</span>
  </div>
  <div id="prettyprint-div">
    <input type="checkbox" id="prettyprint-checkbox" name="prettyprint-checkbox">
    <label for="prettyprint-checkbox">Pretty print?</label>
    </input>
  </div>

  <pre id="feed"></pre>
</div>

              
            
!

CSS

              
                #source-url-select, option {
  font-size: 1.4em;
}

#ui {
  float: left;
  margin-right: 10px;
}

#rate-div {
  float: left;
}

#prettyprint-div {
  text-align: right;
}


              
            
!

JS

              
                var eventStreamsUri;
var eventsource;

var sourceUrlNode = document.getElementById("source-url-select");
var feedNode = document.getElementById('feed');
var rateMinNode = document.getElementById('rate-min');
var rateAvgNode = document.getElementById('rate-avg');
var errorNode = document.createElement('div');
errorNode.className = 'alert alert-danger';
var infoNode = document.createElement('div');
infoNode.className = 'alert alert-info';
var updateBuffer = makeDisplayBuffer(20);
var freq;

sourceUrlNode.onchange = start;
window.onload = start;

function start() {
  eventStreamsUri = sourceUrlNode.value;
  getStreams(populateStreamSelect);
}

function getStreams(cb) {
  specUrl = eventStreamsUri + "?spec"
  $.getJSON(specUrl, function(data, status) {
    var streams = [];
    for (path in data.paths) {
      var stream = path.split("/v2/stream/")[1];
      if (stream != '{streams}') {
        streams.push(stream);
      }
    }
    cb(streams)
  });
}


function populateStreamSelect(streams) {
  var streamSelector = document.getElementById('streams');
  
  streams.forEach(function(stream) {
    var option = document.createElement('option');
    option.appendChild( document.createTextNode(stream) );
    option.value = stream;    
    streamSelector.appendChild(option); 
  });
  streamSelector.size = streams.length;
  
  streamSelector.onchange = consumedSelectedStreams;
  consumedSelectedStreams();
}


function consumedSelectedStreams() {
  var selected = document.querySelectorAll('#streams option:checked');
  var streams = Array.from(selected).map(el => el.value);

  consumeEvents(streams);
}; 


function consumeEvents(streams) {
  if (eventsource) {
    eventsource.close();
  }
  delete eventsource;
 
  streams = streams.join(',');
  if (streams.length == 0) {
    printEvent({type: 'info', message: 'No streams selected'});
    return;
  }

  var streamsUrl = eventStreamsUri + "/v2/stream/" + streams;
  printEvent({type: 'info', message: 'Connecting to ' + streamsUrl});  
  eventsource = new EventSource(streamsUrl);
  
  eventsource.onopen = onOpen;
  eventsource.onmessage = onMessage;
  eventsource.onerror = onError;
}

function onOpen() {
  freq = new Frequency(1000, function (count, average) {
    rateMinNode.textContent = count;
    rateAvgNode.textContent = average;
  });
}

function onMessage(msg) {
  if (freq) { freq.add(1); }
  printEvent({type: 'message', data: msg.data});
};

function onError(msg) {
  // Don't print {isTrusted: true}.  (Is this an error?)
  if (!msg.isTrusted) {
    printEvent({type: 'error', data: msg});
  }
}

function printEvent(event) {
    var node;
    if (event.type === 'message') {
      var eventData = event.data;
      if (document.getElementById("prettyprint-checkbox").checked) {
        eventData = JSON.stringify(JSON.parse(event.data), null, 2);
      }
      
      var node = document.createTextNode(eventData + '\n');
      feedNode.prepend(node);
      updateBuffer(node);
    } 
    else if (event.type === 'error') {
      $(errorNode).empty().text('ERROR: ' + JSON.stringify(event.data));
      if (!errorNode.parentNode) {
        $(feedNode).before(errorNode);
      }
    }
    else if (event.type === 'info') {
      $(infoNode).text(event.message);
      if (!infoNode.parentNode) {
        $(feedNode).prepend(infoNode);
        updateBuffer(infoNode);
      }
    }
  }


function makeDisplayBuffer(size) {
  var buffer = [];
  return function (element) {
    buffer.push(element);
    if (buffer.length > size) {
      var popped = buffer.shift();
      popped.parentNode.removeChild(popped);
    }
  }
}

function Frequency(interval, callback) {
  var freq = this;
  var rAF = window.requestAnimationFrame || setTimeout;

  this.interval = interval;
  this.callback = callback;
  this.count = 0;
  this.total = 0;
  this.since = this.start = this.now();
  function checker() {
    freq.check();
    rAF(checker);
  }
  rAF(checker);
}
Frequency.prototype.now = ( function () {
  var perf = window.performance;
  return perf.now ?
    function () { return perf.now(); } :
    function () { return +new Date(); };
}() );
Frequency.prototype.add = function (count) {
  this.count += count;
  this.total += count;
  this.check();
};
Frequency.prototype.check = function () {
  var count, avg, ellapsedTotal;
  var ellapsed = this.now() - this.since;
  if (ellapsed >= this.interval) {
    ellapsedTotal = this.now() - this.start;
    count = this.count;
    // One optional digit
    avg = (this.total / (ellapsedTotal / this.interval)).toFixed(1).replace('.0', '');
    this.since = this.now();
    this.count = 0;
    this.callback(count, avg);
  }
};

              
            
!
999px

Console