import {article, articlesList} from DomRenderer; import blog from Hablo.Config; import * as Async from UnitJS.Async; import * as Cache from UnitJS.Cache; import * as Dom from UnitJS.Dom; import * as Fun from UnitJS.Fun; var articles = Cache.make(function(key) { var url = ["", blog.path.articlesPath, key + '.md'].join('/'); return Async.bind( Async.http({method: 'GET', url: url}), function(queryResult) { if(queryResult.status == 200) { return Async.wrap(queryResult.responseText); } else { return Async.fail( "Could not load article " + url + " (" + queryResult.status + " " + queryResult.statusText + ")" ); } } ); }); window.addEventListener('popstate', function(e) { if(e.state != undefined) { navigate(e.state.url); } }); history.replaceState({url: window.location.pathname}, 'Blog - title', window.location.pathname); return { hijackLinks: hijackLinks }; function hijackLinks(domElem) { domElem = domElem || document; var links = domElem.getElementsByTagName('a'); for(var i = 0; i < links.length; i++) { var a = links[i]; var href = a.getAttribute("href"); if((href[0] == "/" && href.slice(-3) != ".md") || href[0] == "#") { a.addEventListener('click', visit(a.getAttribute("href"))); } } } function visit(url) { return function(e) { e.preventDefault(); if(url[0] == '#') { window.location = url; history.replaceState({url: window.location.pathname}, 'Blog - title', url); } else { navigate(url); history.pushState({url: url}, 'Blog - title', url); } }; } function navigate(url) { var path = decodeURI(url).split("/").slice(1); if(blog.tags[path[0]] != undefined) { show(getArticlesList(path[0], path[1] == "all.html")); } else if(path[0] == blog.path.articlesPath) { show(getArticle(path[1].replace(/\.html$/, ''))); } else { show(getArticlesList(null, path[0] == "all.html")); } } function getArticle(key) { return Async.bind( articles.get(key), Async.map( function(contents) {return [article(key, contents)];} ) ); } function preview(key) { return Async.bind( articles.get(key), function(contents) { return Async.wrap( article(key, contents, blog.skin.previewLinesCount) ); } ); } function articleIds(tag, all) { var ids = tag != undefined ? blog.tags[tag] : Object.keys(blog.articles); var reverseDate = function (id) {return -blog.articles[id].metadata.date;}; ids.sort(Fun.compare(reverseDate)); return ids.slice(0, all ? undefined : blog.skin.previewArticlesCount); } function getArticlesList(tag, all) { return Async.bind( Async.parallel.apply(null, articleIds(tag, all).map(preview)), Async.map(articlesList(tag, all)) ); } function show(contents) { Async.run( Async.bind( contents, Async.map(function (domElems) { domElems = domElems.filter(Fun.defined); var div = document.getElementById('contents'); Dom.clear(div); for(var i = 0; i < domElems.length; i++) { div.appendChild(domElems[i]); } hijackLinks(div); }) ) ); }