Skip to content

Instantly share code, notes, and snippets.

@casperin
Created March 15, 2016 08:21
Show Gist options
  • Save casperin/5d2f3a33f085d467cb74 to your computer and use it in GitHub Desktop.
Save casperin/5d2f3a33f085d467cb74 to your computer and use it in GitHub Desktop.
requirebin sketch
// require() some stuff from npm (like you were using browserify)
// and then hit Run Code to run it on the right
var xhr = require('xhr');
var container = document.querySelector('.time-line');
var books = [];
var earliestDate = Infinity;
function int (date) {
return Number(new Date(date))/(24*60*60*1000);
}
function info (book) {
return book.details.items[0].volumeInfo
}
function dateFormat (date) {
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const d = new Date(date);
const day = d.getDate();
const monthIndex = d.getMonth();
return MONTHS[monthIndex] + ' ' + day;
}
xhr({
url: 'https://rawgit.com/casperin/BOOKBOOKBOOK/master/db.json'
}, function (err, res, body) {
books = JSON.parse(body).books.filter(function (b) { return b.finished }).sort(function (b1, b2) { return int(b1.started) - int(b2.started); });
books.forEach(function (book) {
earliestDate = Math.min(earliestDate, int(book.started));
});
update();
})
function update () {
console.log('---');
books.forEach(function (book, i) {
var el = document.createElement('div');
el.className = 'book';
el.setAttribute('data-started', dateFormat(book.started));
if (book.started !== book.finished) el.setAttribute('data-finished', dateFormat(book.finished));
el.style.top = i * 20 + 'px';
el.style.left = (int(book.started) - earliestDate) * 20 + 'px';
el.style.width = (int(book.finished) - int(book.started) + 1) * 20 + 'px';
el.appendChild(summary(book));
container.appendChild(el);
});
}
function summary (book) {
var el = document.createElement('div');
el.className = 'summary';
var inf = info(book);
var title = document.createElement('h2');
title.innerHTML = inf.title;
el.appendChild(title);
return el;
}
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(global){if(typeof window!=="undefined"){module.exports=window}else if(typeof global!=="undefined"){module.exports=global}else if(typeof self!=="undefined"){module.exports=self}else{module.exports={}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],2:[function(require,module,exports){module.exports=isFunction;var toString=Object.prototype.toString;function isFunction(fn){var string=toString.call(fn);return string==="[object Function]"||typeof fn==="function"&&string!=="[object RegExp]"||typeof window!=="undefined"&&(fn===window.setTimeout||fn===window.alert||fn===window.confirm||fn===window.prompt)}},{}],3:[function(require,module,exports){module.exports=once;once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true})});function once(fn){var called=false;return function(){if(called)return;called=true;return fn.apply(this,arguments)}}},{}],4:[function(require,module,exports){var isFunction=require("is-function");module.exports=forEach;var toString=Object.prototype.toString;var hasOwnProperty=Object.prototype.hasOwnProperty;function forEach(list,iterator,context){if(!isFunction(iterator)){throw new TypeError("iterator must be a function")}if(arguments.length<3){context=this}if(toString.call(list)==="[object Array]")forEachArray(list,iterator,context);else if(typeof list==="string")forEachString(list,iterator,context);else forEachObject(list,iterator,context)}function forEachArray(array,iterator,context){for(var i=0,len=array.length;i<len;i++){if(hasOwnProperty.call(array,i)){iterator.call(context,array[i],i,array)}}}function forEachString(string,iterator,context){for(var i=0,len=string.length;i<len;i++){iterator.call(context,string.charAt(i),i,string)}}function forEachObject(object,iterator,context){for(var k in object){if(hasOwnProperty.call(object,k)){iterator.call(context,object[k],k,object)}}}},{"is-function":2}],5:[function(require,module,exports){exports=module.exports=trim;function trim(str){return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){return str.replace(/^\s*/,"")};exports.right=function(str){return str.replace(/\s*$/,"")}},{}],6:[function(require,module,exports){var trim=require("trim"),forEach=require("for-each"),isArray=function(arg){return Object.prototype.toString.call(arg)==="[object Array]"};module.exports=function(headers){if(!headers)return{};var result={};forEach(trim(headers).split("\n"),function(row){var index=row.indexOf(":"),key=trim(row.slice(0,index)).toLowerCase(),value=trim(row.slice(index+1));if(typeof result[key]==="undefined"){result[key]=value}else if(isArray(result[key])){result[key].push(value)}else{result[key]=[result[key],value]}});return result}},{"for-each":4,trim:5}],7:[function(require,module,exports){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target}},{}],xhr:[function(require,module,exports){"use strict";var window=require("global/window");var once=require("once");var isFunction=require("is-function");var parseHeaders=require("parse-headers");var xtend=require("xtend");module.exports=createXHR;createXHR.XMLHttpRequest=window.XMLHttpRequest||noop;createXHR.XDomainRequest="withCredentials"in new createXHR.XMLHttpRequest?createXHR.XMLHttpRequest:window.XDomainRequest;forEachArray(["get","put","post","patch","head","delete"],function(method){createXHR[method==="delete"?"del":method]=function(uri,options,callback){options=initParams(uri,options,callback);options.method=method.toUpperCase();return _createXHR(options)}});function forEachArray(array,iterator){for(var i=0;i<array.length;i++){iterator(array[i])}}function isEmpty(obj){for(var i in obj){if(obj.hasOwnProperty(i))return false}return true}function initParams(uri,options,callback){var params=uri;if(isFunction(options)){callback=options;if(typeof uri==="string"){params={uri:uri}}}else{params=xtend(options,{uri:uri})}params.callback=callback;return params}function createXHR(uri,options,callback){options=initParams(uri,options,callback);return _createXHR(options)}function _createXHR(options){var callback=options.callback;if(typeof callback==="undefined"){throw new Error("callback argument missing")}callback=once(callback);function readystatechange(){if(xhr.readyState===4){loadFunc()}}function getBody(){var body=undefined;if(xhr.response){body=xhr.response}else if(xhr.responseType==="text"||!xhr.responseType){body=xhr.responseText||xhr.responseXML}if(isJson){try{body=JSON.parse(body)}catch(e){}}return body}var failureResponse={body:undefined,headers:{},statusCode:0,method:method,url:uri,rawRequest:xhr};function errorFunc(evt){clearTimeout(timeoutTimer);if(!(evt instanceof Error)){evt=new Error(""+(evt||"Unknown XMLHttpRequest Error"))}evt.statusCode=0;callback(evt,failureResponse)}function loadFunc(){if(aborted)return;var status;clearTimeout(timeoutTimer);if(options.useXDR&&xhr.status===undefined){status=200}else{status=xhr.status===1223?204:xhr.status}var response=failureResponse;var err=null;if(status!==0){response={body:getBody(),statusCode:status,method:method,headers:{},url:uri,rawRequest:xhr};if(xhr.getAllResponseHeaders){response.headers=parseHeaders(xhr.getAllResponseHeaders())}}else{err=new Error("Internal XMLHttpRequest Error")}callback(err,response,response.body)}var xhr=options.xhr||null;if(!xhr){if(options.cors||options.useXDR){xhr=new createXHR.XDomainRequest}else{xhr=new createXHR.XMLHttpRequest}}var key;var aborted;var uri=xhr.url=options.uri||options.url;var method=xhr.method=options.method||"GET";var body=options.body||options.data||null;var headers=xhr.headers=options.headers||{};var sync=!!options.sync;var isJson=false;var timeoutTimer;if("json"in options){isJson=true;headers["accept"]||headers["Accept"]||(headers["Accept"]="application/json");if(method!=="GET"&&method!=="HEAD"){headers["content-type"]||headers["Content-Type"]||(headers["Content-Type"]="application/json");body=JSON.stringify(options.json)}}xhr.onreadystatechange=readystatechange;xhr.onload=loadFunc;xhr.onerror=errorFunc;xhr.onprogress=function(){};xhr.ontimeout=errorFunc;xhr.open(method,uri,!sync,options.username,options.password);if(!sync){xhr.withCredentials=!!options.withCredentials}if(!sync&&options.timeout>0){timeoutTimer=setTimeout(function(){aborted=true;xhr.abort("timeout");var e=new Error("XMLHttpRequest timeout");e.code="ETIMEDOUT";errorFunc(e)},options.timeout)}if(xhr.setRequestHeader){for(key in headers){if(headers.hasOwnProperty(key)){xhr.setRequestHeader(key,headers[key])}}}else if(options.headers&&!isEmpty(options.headers)){throw new Error("Headers cannot be set on an XDomainRequest object")}if("responseType"in options){xhr.responseType=options.responseType}if("beforeSend"in options&&typeof options.beforeSend==="function"){options.beforeSend(xhr)}xhr.send(body);return xhr}function noop(){}},{"global/window":1,"is-function":2,once:3,"parse-headers":6,xtend:7}]},{},[]);var xhr=require("xhr");var container=document.querySelector(".time-line");var books=[];var earliestDate=Infinity;function int(date){return Number(new Date(date))/(24*60*60*1e3)}function info(book){return book.details.items[0].volumeInfo}function dateFormat(date){const MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];const d=new Date(date);const day=d.getDate();const monthIndex=d.getMonth();return MONTHS[monthIndex]+" "+day}xhr({url:"https://rawgit.com/casperin/BOOKBOOKBOOK/master/db.json"},function(err,res,body){books=JSON.parse(body).books.filter(function(b){return b.finished}).sort(function(b1,b2){return int(b1.started)-int(b2.started)});books.forEach(function(book){earliestDate=Math.min(earliestDate,int(book.started))});update()});function update(){console.log("---");books.forEach(function(book,i){var el=document.createElement("div");el.className="book";el.setAttribute("data-started",dateFormat(book.started));if(book.started!==book.finished)el.setAttribute("data-finished",dateFormat(book.finished));el.style.top=i*20+"px";el.style.left=(int(book.started)-earliestDate)*20+"px";el.style.width=(int(book.finished)-int(book.started)+1)*20+"px";el.appendChild(summary(book));container.appendChild(el)})}function summary(book){var el=document.createElement("div");el.className="summary";var inf=info(book);var title=document.createElement("h2");title.innerHTML=inf.title;el.appendChild(title);return el}
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"xhr": "2.2.0"
}
}
<!-- contents of this file will be placed inside the <body> -->
<div class='time-line'></div>
<!-- contents of this file will be placed inside the <head> -->
<style>
.time-line {
margin: 50px;
position: relative;
}
.book {
position: absolute;
height: 10px;
background: red;
}
.book:before, .book:after {
font-size: 9px;
margin-top: -9px;
position: absolute;
width: 30px;
}
.book:before {
content: attr(data-started);
left: -20px;
}
.book:after {
content: attr(data-finished);
right: -20px;
}
.summary {
display: none;
background: #ffc;
width: 200px;
margin-top: 10px;
}
.summary h2 {
margin: 0;
font-size: 20px;
}
.book:hover {
z-index: 1;
}
.book:hover .summary {
display: block;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment