pull/1/head
Yax 5 years ago
parent 0ee840ac81
commit d9a5a5bc00

@ -0,0 +1,8 @@
<div>
<img src="https://www.gravatar.com/avatar/{{ avatar }}.jpg" style="float:left; margin-right:10px" height="32"
width="32">
<span>{{ author }}</span>
<span>{{ site }}</span>
<span> - {{ date }}</span>
<p>{{ content }}</p>
</div>

@ -1,5 +1,5 @@
<div class="article"> <div class="article">
<h1><a href="/{{ year }}/{{ slug }}.html">{{ title }}</a></h1> <h1><a href="/{{ year }}/{{ slug }}.html">{{ title }}</a></h1>
<p class="meta">{{ category_label}}<span>{{ friendly_date }}</span></p> <p class="meta">{{ category_label}}<span>{{ friendly_date }}</span><span class="comment-indicator">{{ comment_label }}</span></p>
<p class="summary">{{ summary }}</p> <p class="summary">{{ summary }}</p>
</div> </div>

@ -6,6 +6,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="/css/knacss.css"> <link rel="stylesheet" type="text/css" href="/css/knacss.css">
<link rel="stylesheet" type="text/css" href="/css/style.css"> <link rel="stylesheet" type="text/css" href="/css/style.css">
@ -24,6 +25,10 @@
<!-- RSS --> <!-- RSS -->
<link type="application/atom+xml" rel="alternate" href="{{ site_url }}/rss.xml" title="{{ title }}" /> <link type="application/atom+xml" rel="alternate" href="{{ site_url }}/rss.xml" title="{{ title }}" />
<script src="{{ site_url }}/js/md5.js" async></script>
<script src="{{ site_url }}/js/markdown.min.js" async></script>
<script src="{{ site_url }}/js/page.js" async></script>
</head> </head>
<body> <body>

@ -2,4 +2,65 @@
<h1>{{ title }}</h1> <h1>{{ title }}</h1>
<p class="meta">{{ category_label}}<span>{{ friendly_date }}</span></p> <p class="meta">{{ category_label}}<span>{{ friendly_date }}</span></p>
{{ content }} {{ content }}
{{ comments }}
<div id="comment-form">
<strong>Votre commentaire</strong>
<form role="form" action="/newcomment" autocomplete="off" method="post">
<fieldset>
<input id="author" name="author" type="text" placeholder="Nom ou Surnom" required>
<input id="site" name="site" type="text" placeholder="Site Web">
<input style="display:none" id="email" name="email" type="text"
placeholder="Adresse email pour Gravatar (non publié)" onchange="grabatar()">
<img src="" id="gravatar" height="32" width="32" style="display:none">
<input class="hidden" id="token" name="token" type="text" placeholder="Blog"
value="{{ stacosys_token }}">
<input class="hidden" id="url" name="url" type="text" placeholder="Article"
value="{{ year }}/{{ slug }}">
<input class="hidden" id="captcha" name="captcha" type="text"
placeholder="Etes vous humain ?">
</fieldset>
<fieldset>
<textarea id="message" name="message" rows="4"
placeholder="Votre commentaire (texte simple ou Markdown)" required></textarea>
<div id="preview-container" style="display:none">
<p>Prévisualisation :</p>
<div id="preview" class="preview-markdown"></div>
</div>
</fieldset>
<fieldset>
<div>
<em>Le site Web est optionel</em><br>
<em>Le message peut être rédigé au format <a href="http://daringfireball.net/projects/markdown/"
target="_blank">Markdown</a></em>
</div>
<div id="helpgravatar" style="display:none">
<em>L'e-mail sert uniquement à retrouver votre <a href="https://fr.gravatar.com/">Gravatar</a></em>
</div>
</fieldset>
<button type="submit" class="button--primary">Envoyer</button>
<button id="markdown" style="display:none" onclick="preview_markdown(); return false"
class="button--info">Prévisualiser</button>
</form>
</div>
</div> </div>
<script type="text/javascript"><!--
function grabatar() {
var gravatar = document.getElementById("gravatar");
var email = document.getElementById("email");
var md5avatar = md5(email.value);
gravatar.src = "http://www.gravatar.com/avatar/" + md5avatar + ".jpg";
email.value = md5avatar;
gravatar.style.display = '';
}
function showbonus() {
document.getElementById("email").style.display = '';
document.getElementById("markdown").style.display = '';
document.getElementById("helpgravatar").style.display = '';
}
window.onload = showbonus;
--></script>

@ -26,12 +26,11 @@
"""Make static website/blog with Python.""" """Make static website/blog with Python."""
import sys
import os import os
import shutil import shutil
import re import re
import glob import glob
import sys
import json import json
import datetime import datetime
import time import time
@ -39,6 +38,9 @@ from email import utils
from pathlib import Path from pathlib import Path
import unicodedata import unicodedata
import locale import locale
import requests
import commonmark
# set user locale # set user locale
locale.setlocale(locale.LC_ALL, "") locale.setlocale(locale.LC_ALL, "")
@ -114,19 +116,15 @@ def read_content(filename):
for key, val, end in read_headers(text): for key, val, end in read_headers(text):
content[key] = val content[key] = val
# slugify post title
content['slug'] = slugify(content['title'])
# Separate content from headers. # Separate content from headers.
text = text[end:] text = text[end:]
# Convert Markdown content to HTML. # Convert Markdown content to HTML.
if filename.endswith((".md", ".mkd", ".mkdn", ".mdown", ".markdown")): if filename.endswith((".md", ".mkd", ".mkdn", ".mdown", ".markdown")):
try:
if _test == "ImportError":
raise ImportError("Error forced by test")
import commonmark
text = commonmark.commonmark(text) text = commonmark.commonmark(text)
except ImportError as e:
log("WARNING: Cannot render Markdown in {}: {}", filename, str(e))
# Update the dictionary with content and RFC 2822 date. # Update the dictionary with content and RFC 2822 date.
content.update({"content": text, "rfc_2822_date": rfc_2822_format(content["date"])}) content.update({"content": text, "rfc_2822_date": rfc_2822_format(content["date"])})
@ -186,7 +184,7 @@ def get_friendly_date(date_str):
return dt.strftime("%d %b %Y") return dt.strftime("%d %b %Y")
def make_posts(src, src_pattern, dst, layout, category_layout, **params): def make_posts(src, src_pattern, dst, layout, category_layout, comment_layout, **params):
"""Generate posts from posts directory.""" """Generate posts from posts directory."""
items = [] items = []
@ -216,10 +214,30 @@ def make_posts(src, src_pattern, dst, layout, category_layout, **params):
render(page_params["content"][:summary_index], **page_params) render(page_params["content"][:summary_index], **page_params)
) )
# stacosys comments
page_params['comment_count'] = 0
if params['stacosys_url']:
req_url = params['stacosys_url'] + '/comments'
query_params = dict(
token=params['stacosys_token'],
url='/' + page_params['year'] + '/' + page_params['slug']
)
resp = requests.get(url=req_url, params=query_params)
comments = resp.json()['data']
out_comments = []
for comment in comments:
out_comment = render(comment_layout, author=comment['author'], avatar=comment.get('avatar',''), site=comment.get('site', ''),
date=comment['date'], content=commonmark.commonmark(comment['content']))
out_comments.append(out_comment)
page_params["comments"] = "".join(out_comments)
page_params['comment_count'] = len(comments)
content["year"] = page_params["year"] content["year"] = page_params["year"]
content["categories"] = page_params["categories"] content["categories"] = page_params["categories"]
content["category_label"] = page_params["category_label"] content["category_label"] = page_params["category_label"]
content["friendly_date"] = page_params["friendly_date"] content["friendly_date"] = page_params["friendly_date"]
content["comment_count"] = page_params["comment_count"]
items.append(content) items.append(content)
# TODO DEBUG # TODO DEBUG
@ -261,6 +279,13 @@ def make_list(
item_params = dict(params, **post) item_params = dict(params, **post)
if "summary" not in item_params: if "summary" not in item_params:
item_params["summary"] = truncate(post["content"]) item_params["summary"] = truncate(post["content"])
if "comment_count" in item_params and item_params['comment_count']:
if item_params['comment_count'] == 1:
item_params['comment_label'] = '1 commentaire'
else:
item_params['comment_label'] = str(item_params['comment_count']) + ' commentaires'
else:
item_params['comment_label'] = ''
item = render(item_layout, **item_params) item = render(item_layout, **item_params)
items.append(item) items.append(item)
params["content"] = "".join(items) params["content"] = "".join(items)
@ -284,6 +309,8 @@ def main():
"author": "Admin", "author": "Admin",
"site_url": "http://localhost:8000", "site_url": "http://localhost:8000",
"current_year": datetime.datetime.now().year, "current_year": datetime.datetime.now().year,
"stacosys_token": "",
"stacosys_url": ""
} }
# If params.json exists, load it. # If params.json exists, load it.
@ -293,14 +320,15 @@ def main():
# Load layouts. # Load layouts.
banner_layout = fread("layout/banner.html") banner_layout = fread("layout/banner.html")
paging_layout = fread("layout/paging.html") paging_layout = fread("layout/paging.html")
category_title_layout = fread("layout/category_title.html")
archive_title_layout = fread("layout/archives.html") archive_title_layout = fread("layout/archives.html")
page_layout = fread("layout/page.html") page_layout = fread("layout/page.html")
post_layout = fread("layout/post.html") post_layout = fread("layout/post.html")
list_layout = fread("layout/list.html") list_layout = fread("layout/list.html")
item_layout = fread("layout/item.html") item_layout = fread("layout/item.html")
item_nosummary_layout = fread("layout/item_nosummary.html") item_nosummary_layout = fread("layout/item_nosummary.html")
category_title_layout = fread("layout/category_title.html")
category_layout = fread("layout/category.html") category_layout = fread("layout/category.html")
comment_layout = fread("layout/comment.html")
rss_xml = fread("layout/rss.xml") rss_xml = fread("layout/rss.xml")
rss_item_xml = fread("layout/rss_item.xml") rss_item_xml = fread("layout/rss_item.xml")
sitemap_xml = fread("layout/sitemap.xml") sitemap_xml = fread("layout/sitemap.xml")
@ -317,6 +345,7 @@ def main():
"_site/{{ year }}/{{ slug }}.html", "_site/{{ year }}/{{ slug }}.html",
post_layout, post_layout,
category_layout, category_layout,
comment_layout,
**params **params
) )

@ -1,5 +1,7 @@
{ {
"title": "Le blog du Yax", "title": "Le blog du Yax",
"subtitle": "GNU, Linux, BSD et autres libertés", "subtitle": "GNU, Linux, BSD et autres libertés",
"author": "Yax" "author": "Yax",
"stacosys_token": "9fb3fc042c572cb831005fd16186126765140fa2bd9bb2d4a28e47a9457dc26c",
"stacosys_url": "http://localhost:8100"
} }

@ -0,0 +1,12 @@
appdirs==1.4.3
attrs==19.1.0
black==19.3b0
certifi==2019.6.16
chardet==3.0.4
Click==7.0
commonmark==0.9.0
future==0.17.1
idna==2.8
requests==2.22.0
toml==0.10.0
urllib3==1.25.3

@ -152,6 +152,14 @@ a:hover, a:active {
margin-right: 10px; margin-right: 10px;
} }
.hidden {
display: none;
}
.comment-indicator {
color: coral;
}
/* Footer */ /* Footer */
footer { footer {
background: #f0f0f0; background: #f0f0f0;

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -0,0 +1,184 @@
function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i=64; i<=s.length; i+=64) {
md5cycle(state, md5blk(s.substring(i-64, i)));
}
s = s.substring(i-64);
var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
for (i=0; i<s.length; i++)
tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3);
tail[i>>2] |= 0x80 << ((i%4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i=0; i<16; i++) tail[i] = 0;
}
tail[14] = n*8;
md5cycle(state, tail);
return state;
}
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
function md5blk(s) { /* I figured global was faster. */
var md5blks = [], i; /* Andy King said do it this way. */
for (i=0; i<64; i+=4) {
md5blks[i>>2] = s.charCodeAt(i)
+ (s.charCodeAt(i+1) << 8)
+ (s.charCodeAt(i+2) << 16)
+ (s.charCodeAt(i+3) << 24);
}
return md5blks;
}
var hex_chr = '0123456789abcdef'.split('');
function rhex(n)
{
var s='', j=0;
for(; j<4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
+ hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}
function hex(x) {
for (var i=0; i<x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}
function md5(s) {
return hex(md51(s));
}
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
function add32(a, b) {
return (a + b) & 0xFFFFFFFF;
}
if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') {
function add32(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
}

@ -0,0 +1,586 @@
/*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*/
/*global define: false*/
(function (global, factory) {
if (typeof exports === "object" && exports) {
factory(exports); // CommonJS
} else if (typeof define === "function" && define.amd) {
define(['exports'], factory); // AMD
} else {
factory(global.Mustache = {}); // <script>
}
}(this, function (mustache) {
var Object_toString = Object.prototype.toString;
var isArray = Array.isArray || function (object) {
return Object_toString.call(object) === '[object Array]';
};
function isFunction(object) {
return typeof object === 'function';
}
function escapeRegExp(string) {
return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
// See https://github.com/janl/mustache.js/issues/189
var RegExp_test = RegExp.prototype.test;
function testRegExp(re, string) {
return RegExp_test.call(re, string);
}
var nonSpaceRe = /\S/;
function isWhitespace(string) {
return !testRegExp(nonSpaceRe, string);
}
var entityMap = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': '&quot;',
"'": '&#39;',
"/": '&#x2F;'
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
var whiteRe = /\s*/;
var spaceRe = /\s+/;
var equalsRe = /\s*=/;
var curlyRe = /\s*\}/;
var tagRe = /#|\^|\/|>|\{|&|=|!/;
/**
* Breaks up the given `template` string into a tree of tokens. If the `tags`
* argument is given here it must be an array with two string values: the
* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
* course, the default is to use mustaches (i.e. mustache.tags).
*
* A token is an array with at least 4 elements. The first element is the
* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
* did not contain a symbol (i.e. {{myValue}}) this element is "name". For
* all text that appears outside a symbol this element is "text".
*
* The second element of a token is its "value". For mustache tags this is
* whatever else was inside the tag besides the opening symbol. For text tokens
* this is the text itself.
*
* The third and fourth elements of the token are the start and end indices,
* respectively, of the token in the original template.
*
* Tokens that are the root node of a subtree contain two more elements: 1) an
* array of tokens in the subtree and 2) the index in the original template at
* which the closing tag for that section begins.
*/
function parseTemplate(template, tags) {
if (!template)
return [];
var sections = []; // Stack to hold section tokens
var tokens = []; // Buffer to hold the tokens
var spaces = []; // Indices of whitespace tokens on the current line
var hasTag = false; // Is there a {{tag}} on the current line?
var nonSpace = false; // Is there a non-space char on the current line?
// Strips all whitespace tokens array for the current line
// if there was a {{#tag}} on it and otherwise only space.
function stripSpace() {
if (hasTag && !nonSpace) {
while (spaces.length)
delete tokens[spaces.pop()];
} else {
spaces = [];
}
hasTag = false;
nonSpace = false;
}
var openingTagRe, closingTagRe, closingCurlyRe;
function compileTags(tags) {
if (typeof tags === 'string')
tags = tags.split(spaceRe, 2);
if (!isArray(tags) || tags.length !== 2)
throw new Error('Invalid tags: ' + tags);
openingTagRe = new RegExp(escapeRegExp(tags[0]) + '\\s*');
closingTagRe = new RegExp('\\s*' + escapeRegExp(tags[1]));
closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tags[1]));
}
compileTags(tags || mustache.tags);
var scanner = new Scanner(template);
var start, type, value, chr, token, openSection;
while (!scanner.eos()) {
start = scanner.pos;
// Match any text between tags.
value = scanner.scanUntil(openingTagRe);
if (value) {
for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
chr = value.charAt(i);
if (isWhitespace(chr)) {
spaces.push(tokens.length);
} else {
nonSpace = true;
}
tokens.push([ 'text', chr, start, start + 1 ]);
start += 1;
// Check for whitespace on the current line.
if (chr === '\n')
stripSpace();
}
}
// Match the opening tag.
if (!scanner.scan(openingTagRe))
break;
hasTag = true;
// Get the tag type.
type = scanner.scan(tagRe) || 'name';
scanner.scan(whiteRe);
// Get the tag value.
if (type === '=') {
value = scanner.scanUntil(equalsRe);
scanner.scan(equalsRe);
scanner.scanUntil(closingTagRe);
} else if (type === '{') {
value = scanner.scanUntil(closingCurlyRe);
scanner.scan(curlyRe);
scanner.scanUntil(closingTagRe);
type = '&';
} else {
value = scanner.scanUntil(closingTagRe);
}
// Match the closing tag.
if (!scanner.scan(closingTagRe))
throw new Error('Unclosed tag at ' + scanner.pos);
token = [ type, value, start, scanner.pos ];
tokens.push(token);
if (type === '#' || type === '^') {
sections.push(token);
} else if (type === '/') {
// Check section nesting.
openSection = sections.pop();
if (!openSection)
throw new Error('Unopened section "' + value + '" at ' + start);
if (openSection[1] !== value)
throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
} else if (type === 'name' || type === '{' || type === '&') {
nonSpace = true;
} else if (type === '=') {
// Set the tags for the next time around.
compileTags(value);
}
}
// Make sure there are no open sections when we're done.
openSection = sections.pop();
if (openSection)
throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
return nestTokens(squashTokens(tokens));
}
/**
* Combines the values of consecutive text tokens in the given `tokens` array
* to a single token.
*/
function squashTokens(tokens) {
var squashedTokens = [];
var token, lastToken;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
token = tokens[i];
if (token) {
if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
lastToken[1] += token[1];
lastToken[3] = token[3];
} else {
squashedTokens.push(token);
lastToken = token;
}
}
}
return squashedTokens;
}
/**
* Forms the given array of `tokens` into a nested tree structure where
* tokens that represent a section have two additional items: 1) an array of
* all tokens that appear in that section and 2) the index in the original
* template that represents the end of that section.
*/
function nestTokens(tokens) {
var nestedTokens = [];
var collector = nestedTokens;
var sections = [];
var token, section;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
token = tokens[i];
switch (token[0]) {
case '#':
case '^':
collector.push(token);
sections.push(token);
collector = token[4] = [];
break;
case '/':
section = sections.pop();
section[5] = token[2];
collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
break;
default:
collector.push(token);
}
}
return nestedTokens;
}
/**
* A simple string scanner that is used by the template parser to find
* tokens in template strings.
*/
function Scanner(string) {
this.string = string;
this.tail = string;
this.pos = 0;
}
/**
* Returns `true` if the tail is empty (end of string).
*/
Scanner.prototype.eos = function () {
return this.tail === "";
};
/**
* Tries to match the given regular expression at the current position.
* Returns the matched text if it can match, the empty string otherwise.
*/
Scanner.prototype.scan = function (re) {
var match = this.tail.match(re);
if (!match || match.index !== 0)
return '';
var string = match[0];
this.tail = this.tail.substring(string.length);
this.pos += string.length;
return string;
};
/**
* Skips all text until the given regular expression can be matched. Returns
* the skipped string, which is the entire tail if no match can be made.
*/
Scanner.prototype.scanUntil = function (re) {
var index = this.tail.search(re), match;
switch (index) {
case -1:
match = this.tail;
this.tail = "";
break;
case 0:
match = "";
break;
default:
match = this.tail.substring(0, index);
this.tail = this.tail.substring(index);
}
this.pos += match.length;
return match;
};
/**
* Represents a rendering context by wrapping a view object and
* maintaining a reference to the parent context.
*/
function Context(view, parentContext) {
this.view = view == null ? {} : view;
this.cache = { '.': this.view };
this.parent = parentContext;
}
/**
* Creates a new context using the given view with this context
* as the parent.
*/
Context.prototype.push = function (view) {
return new Context(view, this);
};
/**
* Returns the value of the given name in this context, traversing
* up the context hierarchy if the value is absent in this context's view.
*/
Context.prototype.lookup = function (name) {
var cache = this.cache;
var value;
if (name in cache) {
value = cache[name];
} else {
var context = this, names, index;
while (context) {
if (name.indexOf('.') > 0) {
value = context.view;
names = name.split('.');
index = 0;
while (value != null && index < names.length)
value = value[names[index++]];
} else if (typeof context.view == 'object') {
value = context.view[name];
}
if (value != null)
break;
context = context.parent;
}
cache[name] = value;
}
if (isFunction(value))
value = value.call(this.view);
return value;
};
/**
* A Writer knows how to take a stream of tokens and render them to a
* string, given a context. It also maintains a cache of templates to
* avoid the need to parse the same template twice.
*/
function Writer() {
this.cache = {};
}
/**
* Clears all cached templates in this writer.
*/
Writer.prototype.clearCache = function () {
this.cache = {};
};
/**
* Parses and caches the given `template` and returns the array of tokens
* that is generated from the parse.
*/
Writer.prototype.parse = function (template, tags) {
var cache = this.cache;
var tokens = cache[template];
if (tokens == null)
tokens = cache[template] = parseTemplate(template, tags);
return tokens;
};
/**
* High-level method that is used to render the given `template` with
* the given `view`.
*
* The optional `partials` argument may be an object that contains the
* names and templates of partials that are used in the template. It may
* also be a function that is used to load partial templates on the fly
* that takes a single argument: the name of the partial.
*/
Writer.prototype.render = function (template, view, partials) {
var tokens = this.parse(template);
var context = (view instanceof Context) ? view : new Context(view);
return this.renderTokens(tokens, context, partials, template);
};
/**
* Low-level method that renders the given array of `tokens` using
* the given `context` and `partials`.
*
* Note: The `originalTemplate` is only ever used to extract the portion
* of the original template that was contained in a higher-order section.
* If the template doesn't use higher-order sections, this argument may
* be omitted.
*/
Writer.prototype.renderTokens = function (tokens, context, partials, originalTemplate) {
var buffer = '';
var token, symbol, value;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
value = undefined;
token = tokens[i];
symbol = token[0];
if (symbol === '#') value = this._renderSection(token, context, partials, originalTemplate);
else if (symbol === '^') value = this._renderInverted(token, context, partials, originalTemplate);
else if (symbol === '>') value = this._renderPartial(token, context, partials, originalTemplate);
else if (symbol === '&') value = this._unescapedValue(token, context);
else if (symbol === 'name') value = this._escapedValue(token, context);
else if (symbol === 'text') value = this._rawValue(token);
if (value !== undefined)
buffer += value;
}
return buffer;
};
Writer.prototype._renderSection = function (token, context, partials, originalTemplate) {
var self = this;
var buffer = '';
var value = context.lookup(token[1]);
// This function is used to render an arbitrary template
// in the current context by higher-order sections.
function subRender(template) {
return self.render(template, context, partials);
}
if (!value) return;
if (isArray(value)) {
for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
}
} else if (typeof value === 'object' || typeof value === 'string') {
buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
} else if (isFunction(value)) {
if (typeof originalTemplate !== 'string')
throw new Error('Cannot use higher-order sections without the original template');
// Extract the portion of the original template that the section contains.
value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
if (value != null)
buffer += value;
} else {
buffer += this.renderTokens(token[4], context, partials, originalTemplate);
}
return buffer;
};
Writer.prototype._renderInverted = function(token, context, partials, originalTemplate) {
var value = context.lookup(token[1]);
// Use JavaScript's definition of falsy. Include empty arrays.
// See https://github.com/janl/mustache.js/issues/186
if (!value || (isArray(value) && value.length === 0))
return this.renderTokens(token[4], context, partials, originalTemplate);
};
Writer.prototype._renderPartial = function(token, context, partials) {
if (!partials) return;
var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
if (value != null)
return this.renderTokens(this.parse(value), context, partials, value);
};
Writer.prototype._unescapedValue = function(token, context) {
var value = context.lookup(token[1]);
if (value != null)
return value;
};
Writer.prototype._escapedValue = function(token, context) {
var value = context.lookup(token[1]);
if (value != null)
return mustache.escape(value);
};
Writer.prototype._rawValue = function(token) {
return token[1];
};
mustache.name = "mustache.js";
mustache.version = "1.1.0";
mustache.tags = [ "{{", "}}" ];
// All high-level mustache.* functions use this writer.
var defaultWriter = new Writer();
/**
* Clears all cached templates in the default writer.
*/
mustache.clearCache = function () {
return defaultWriter.clearCache();
};
/**
* Parses and caches the given template in the default writer and returns the
* array of tokens it contains. Doing this ahead of time avoids the need to
* parse templates on the fly as they are rendered.
*/
mustache.parse = function (template, tags) {
return defaultWriter.parse(template, tags);
};
/**
* Renders the `template` with the given `view` and `partials` using the
* default writer.
*/
mustache.render = function (template, view, partials) {
return defaultWriter.render(template, view, partials);
};
// This is here for backwards compatibility with 0.4.x.
mustache.to_html = function (template, view, partials, send) {
var result = mustache.render(template, view, partials);
if (isFunction(send)) {
send(result);
} else {
return result;
}
};
// Export the escaping function so that the user may override it.
// See https://github.com/janl/mustache.js/issues/244
mustache.escape = escapeHtml;
// Export these mainly for testing, but also for advanced usage.
mustache.Scanner = Scanner;
mustache.Context = Context;
mustache.Writer = Writer;
}));

File diff suppressed because one or more lines are too long

@ -0,0 +1,32 @@
// --------------------------------------------------------------------------
// Common functions
// --------------------------------------------------------------------------
function show_hide(panel_id, button_id){
if (document.getElementById(panel_id).style.display == 'none'){
document.getElementById(panel_id).style.display = '';
document.getElementById(button_id).style.display = 'none';
} else {
document.getElementById(panel_id).style.display = 'none';
}
}
// --------------------------------------------------------------------------
// Markdown preview
// --------------------------------------------------------------------------
function preview_markdown() {
if (document.getElementById('preview-container').style.display == 'none'){
document.getElementById('preview-container').style.display = '';
}
var $ = function (id) { return document.getElementById(id); };
new Editor($("message"), $("preview"));
}
function Editor(input, preview) {
this.update = function () {
preview.innerHTML = markdown.toHTML(input.value);
};
input.editor = this;
this.update();
}

@ -0,0 +1,4 @@
function show_hide(panel_id,button_id){if(document.getElementById(panel_id).style.display=='none'){document.getElementById(panel_id).style.display='';document.getElementById(button_id).style.display='none'}else{document.getElementById(panel_id).style.display='none'}}
function preview_markdown(){if(document.getElementById('preview-container').style.display=='none'){document.getElementById('preview-container').style.display=''}
var $=function(id){return document.getElementById(id)};new Editor($("message"),$("preview"))}
function Editor(input,preview){this.update=function(){preview.innerHTML=markdown.toHTML(input.value)};input.editor=this;this.update()}
Loading…
Cancel
Save