client/util: refactor Markdown formatter code

This commit is contained in:
rr-
2016-09-10 11:09:24 +02:00
parent 16d04adde0
commit e05e0e5fd2
2 changed files with 139 additions and 64 deletions

View File

@ -1,6 +1,6 @@
'use strict';
const marked = require('marked');
const markdown = require('./markdown.js');
function decamelize(str, sep) {
sep = sep === undefined ? '-' : sep;
@ -92,69 +92,7 @@ function formatRelativeTime(timeString) {
}
function formatMarkdown(text) {
const renderer = new marked.Renderer();
const options = {
renderer: renderer,
breaks: true,
sanitize: true,
smartypants: true,
};
const sjis = [];
const preDecorator = text => {
text = text.replace(
/\[sjis\]((?:[^\[]|\[(?!\/?sjis\]))+)\[\/sjis\]/ig,
(match, capture) => {
var ret = '%%%SJIS' + sjis.length;
sjis.push(capture);
return ret;
});
//prevent ^#... from being treated as headers, due to tag permalinks
text = text.replace(/^#/g, '%%%#');
//fix \ before ~ being stripped away
text = text.replace(/\\~/g, '%%%T');
//post, user and tags premalinks
text = text.replace(
/(^|^\(|(?:[^\]])\(|[\s<>\[\]\)])([+#@][a-zA-Z0-9_-]+)/g,
'$1[$2]($2)');
text = text.replace(/\]\(@(\d+)\)/g, '](/post/$1)');
text = text.replace(/\]\(\+([a-zA-Z0-9_-]+)\)/g, '](/user/$1)');
text = text.replace(/\]\(#([a-zA-Z0-9_-]+)\)/g, '](/posts/query=$1)');
return text;
};
const postDecorator = text => {
//restore fixes
text = text.replace(/%%%T/g, '\\~');
text = text.replace(/%%%#/g, '#');
text = text.replace(
/(?:<p>)?%%%SJIS(\d+)(?:<\/p>)?/,
(match, capture) => {
return '<div class="sjis">' + sjis[capture] + '</div>';
});
//search permalinks
text = text.replace(
/\[search\]((?:[^\[]|\[(?!\/?search\]))+)\[\/search\]/ig,
'<a href="/posts/query=$1"><code>$1</code></a>');
//spoilers
text = text.replace(
/\[spoiler\]((?:[^\[]|\[(?!\/?spoiler\]))+)\[\/spoiler\]/ig,
'<span class="spoiler">$1</span>');
//[small]
text = text.replace(
/\[small\]((?:[^\[]|\[(?!\/?small\]))+)\[\/small\]/ig,
'<small>$1</small>');
//strike-through
text = text.replace(/(^|[^\\])(~~|~)([^~]+)\2/g, '$1<del>$3</del>');
text = text.replace(/\\~/g, '~');
return text;
};
return postDecorator(marked(preDecorator(text), options));
return markdown.formatMarkdown(text);
}
function formatUrlParameters(dict) {