hablo/share/js/domRenderer.js

95 lines
3.0 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') {
var re = new RegExp('/' + blog.path.articlesPath + '/([^.]+)\.html');
var key = decodeURI(document.location.pathname.replace(re, '$1'));
convertArticle(div.children[0], key);
} 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, key) {
var header = article.getElementsByTagName('header')[0];
var text = article.getElementsByTagName('pre')[0];
if(text != undefined) {
article.replaceChild(getDiv(text.innerText), text);
if(key != undefined) {
modules.comments.get(key).forEach(article.appendChild.bind(article));
}
} else {
console.log('No content found for this article');
}
}
function getDiv(markdown) {
var d= modules.dom.make('div', {
innerHTML: modules.md.render(markdown)
});
var scripts = d.getElementsByTagName('script');
for(var i = 0; i < scripts.length; i++) {
var run = modules.dom.make('script',
{type: 'text/javascript', src: scripts[i].src, textContent: scripts[i].textContent}
);
scripts[i].parentNode.replaceChild(run, scripts[i]);
}
return d;
}
function article(key, markdown, limit) {
var url = ["", blog.path.articlesPath, key + (limit != undefined ? '.html' : '.md')].join('/');
var lines = markdown.split(/\n/).slice(blog.articles[key].bodyOffset);
var div = getDiv(lines.slice(0, limit).join('\n'));
return modules.dom.make('article', {}, [
modules.dom.make('header', {}, [
modules.dom.make('a', {class: (limit != undefined ? 'navigation' : []), href: url}, [
modules.dom.make('h1', {innerText: blog.articles[key].title})
])
]),
div
].concat(limit != undefined ? [] : modules.comments.get(key)));
}
function pageTitle(tag, all) {
if(tag != undefined) {
var template = blog.wording[all ? 'allTaggedPage' : 'latestTaggedPage'];
return template.replace(/([^$]|^)\$(?:{tag}|tag([^a-zA-Z]|$))/, '$1' + tag + '$2');
} else {
return blog.wording[all ? 'allPage' : 'latestPage'];
}
}
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('a', {
class: 'navigation',
innerText: all ? blog.wording.latestLink : blog.wording.allLink,
href: otherUrl(tag, all)
}),
modules.dom.make('div', {class: 'articles'}, articlePreviews.filter(modules.fun.defined))
];
};
}
}