/* Client-side companion script for the Nikola recent
   post plug-in. Check out this page first for context,
   https://www.ctrl.blog/entry/nikola-recent-posts-plugin
*/

// Check to see that this place exist,
// (eg. that we are on a post page and it has a bottom)
var postend=document.querySelector(".postpage .postend");
if (postend) {

  // make <aside class="postpromo">
  var postpromo = document.createElement("aside");
  postpromo.classList.add("postpromo");

  // Download the /index.json file (only modern browsers!)
  if ("XMLHttpRequest" in window) {
    var xhr=new XMLHttpRequest();
    xhr.open("GET","/index.json", true);
    xhr.send();

    // Check that download succeeded
    xhr.onload = function (e) {
      if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status == 304)) {

        // Read the downloaded data as JSON. If there
        // is anything wrong with the downloaded data
        // the script stops here without making 
        // any changes to the document
        var posts=JSON.parse(xhr.responseText);

        // Create a list and label
        var i=0, list=document.createElement("ul"),
          label=document.createElement("h6"),
          labelText=document.createTextNode("Recent posts");
        label.appendChild(labelText);
        postpromo.appendChild(label);

        // Read title and loc properties from JSON.
        // Note that the number here is the max number
        // of posts to display.
        for(post in posts) {
          if (i==5) continue;
          var post=posts[post],
              title=post["title"],
               link=post["loc"];

          // Skip the post if its address is the
          // same as the current page’s address.
          // (Don’t promote re-reading the same page.)
          // Set RECENT_POSTS_JSON_LENGTH=6 even though
          // only 5 are displayed (set above) as one
          // post may be filtered out and we always want
          // five to display.
          if (link == window.location.pathname)
            continue;
          i=i + 1;

          // Create a list item and append to list
          var item=document.createElement("li"),
           linkElm=document.createElement("a"),
          linkText=document.createTextNode(title);
          linkElm.href=link;
          linkElm.appendChild(linkText);
          item.appendChild(linkElm);
          list.appendChild(item);
        }

        // Put the post list in the <aside> and
        // insert the whole thing into the document.
        postpromo.appendChild(list);
        postend.appendChild(postpromo);
} };} }

// Pro-tip: Load this as <script async src="this.js">
// for the best prformance. In your CSS, don’t assume
// this script will ever run and that the post list
// will included in your layout. The browser wouldn’t
// wait for it to finish (asyncronous), it may never
// finish, or one of those rare noscript users visited.