hablo/js/domRenderer.js

79 lines
2.2 KiB
JavaScript

function DomRenderer(modules) {
return {
article: article,
articlesList: articlesList,
replaceMarkdown: replaceMarkdown
};
function replaceMarkdown() {
var div = document.getElementById('contents');
if(div.children[0] && div.children[0].tagName.toLowerCase() == 'article') {
convertArticle(div.children[0]);
} else {
var articles = div.getElementsByClassName('articles')[0];
if(articles != undefined) {
for(var i = 0; i < articles.children.length; i++) {
convertArticle(articles.children[i]);
}
} else {
console.log('No articles found for this page');
}
}
}
function convertArticle(article) {
var header = article.getElementsByTagName('header')[0];
var text = article.getElementsByTagName('pre')[0];
if(text != undefined) {
article.replaceChild(getDiv(text.innerText), text);
} else {
console.log('No content found for this article');
}
}
function getDiv(markdown) {
return modules.dom.make('div', {
innerHTML: modules.md.render(markdown)
});
}
function article(url, markdown, limit) {
var headerEnd = markdown.search(/\n\n/);
var header = getDiv(markdown.slice(0, headerEnd));
var lines = markdown.slice(headerEnd+2).split(/\n/);
var div = getDiv(lines.slice(0, limit).join('\n'));
var title = header.getElementsByTagName('h1')[0];
return title == undefined ? null : modules.dom.make('article', {}, [
modules.dom.make('header', {}, [
modules.dom.make('a', {class: (limit != undefined ? 'navigation' : []), href: url}, [title])
]),
div
]);
}
function pageTitle(tag, all) {
return (all ? 'All' : 'Latest') + ' articles' + (tag != undefined ? ' tagged ' + tag : '');
}
function otherUrl(tag, all) {
var path = [tag, all ? null : 'all.html'];
return '/' + path.filter(modules.fun.defined).join('/');
}
function articlesList(tag, all) {
return function(articlePreviews) {
return [
modules.dom.make('h2', {innerText: pageTitle(tag, all)}),
modules.dom.make('p', {}, [
modules.dom.make('a', {
class: 'navigation',
innerText: all ? 'See only latest' : 'See all',
href: otherUrl(tag, all)
})
]),
modules.dom.make('div', {class: 'articles'}, articlePreviews.filter(modules.fun.defined))
];
};
}
}