blob: de71a2dae71813b7e0e7c3d0088b79150d69b654 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
/* cgit.js: javacript functions for cgit
 *
 * Copyright (C) 2006-2018 cgit Development Team <cgit@lists.zx2c4.com>
 *
 * Licensed under GNU General Public License v2
 *   (see LICENSE.txt for full license text)
 */

(function () {

/* This follows the logic and suffixes used in ui-shared.c */

var age_classes = [ "age-mins", "age-hours", "age-days",    "age-weeks",    "age-months",    "age-years" ];
var age_suffix =  [ "min.",     "hours",     "days",        "weeks",        "months",        "years",         "years" ];
var age_next =    [ 60,         3600,        24 * 3600,     7 * 24 * 3600,  30 * 24 * 3600,  365 * 24 * 3600, 365 * 24 * 3600 ];
var age_limit =   [ 7200,       24 * 7200,   7 * 24 * 7200, 30 * 24 * 7200, 365 * 25 * 7200, 365 * 25 * 7200 ];
var update_next = [ 10,         5 * 60,      1800,          24 * 3600,      24 * 3600,       24 * 3600,       24 * 3600 ];

function render_age(e, age) {
	var t, n;

	for (n = 0; n < age_classes.length; n++)
		if (age < age_limit[n])
			break;

	t = Math.round(age / age_next[n]) + " " + age_suffix[n];

	if (e.textContent != t) {
		e.textContent = t;
		if (n == age_classes.length)
			n--;
		if (e.className != age_classes[n])
			e.className = age_classes[n];
	}
}

function aging() {
	var n, next = 24 * 3600,
	    now_ut = Math.round((new Date().getTime() / 1000));

	for (n = 0; n < age_classes.length; n++) {
		var m, elems = document.getElementsByClassName(age_classes[n]);

		if (elems.length && update_next[n] < next)
			next = update_next[n];

		for (m = 0; m < elems.length; m++) {
			var age = now_ut - elems[m].getAttribute("data-ut");

			/* A commit dated ahead of the viewer's clock would
			 * otherwise render as a negative age; ui-shared.c
			 * clamps the same way. */
			if (age < 0)
				age = 0;

			render_age(elems[m], age);
		}
	}

	/*
	 * We only need to come back when the age might have changed.
	 * Eg, if everything is counted in hours already, once per
	 * 5 minutes is accurate enough.
	 */

	window.setTimeout(aging, next * 1000);
}

document.addEventListener("DOMContentLoaded", function() {
	/* we can do the aging on DOM content load since no layout dependency */
	aging();
}, false);

})();

/* Selects marked data-autosubmit reload the page with the new setting.
 * Wired here instead of inline onchange handlers, which a strict
 * Content-Security-Policy blocks. Without scripting the forms keep
 * their noscript reload button. */

(function () {

document.addEventListener("DOMContentLoaded", function () {
	var i, els = document.querySelectorAll("select[data-autosubmit]");

	for (i = 0; i < els.length; i++)
		els[i].addEventListener("change", function () {
			this.form.submit();
		});
}, false);

})();

/* Colour theme toggle: cycles auto -> light -> dark and remembers the
 * choice. "auto" leaves the page following the system preference via CSS. */

(function () {

var KEY = "cgit-theme";
var ORDER = [ "auto", "light", "dark" ];
var ICONS = {
	auto:  '<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 0 0 18z" fill="currentColor" stroke="none"/></svg>',
	light: '<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><path d="M12 1v3M12 20v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M1 12h3M20 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1"/></svg>',
	dark:  '<svg viewBox="0 0 24 24"><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8z"/></svg>'
};

function saved() {
	try { return localStorage.getItem(KEY); } catch (e) { return null; }
}

function persist(value) {
	try { localStorage.setItem(KEY, value); } catch (e) { }
}

function apply(theme, root, btn) {
	if (theme === "auto")
		root.removeAttribute("data-theme");
	else
		root.setAttribute("data-theme", theme);
	/* Keep the standalone page background in sync with the choice. */
	document.documentElement.style.colorScheme = (theme === "auto") ? "" : theme;
	if (btn) {
		btn.innerHTML = ICONS[theme];
		btn.title = "Colour theme: " + theme;
	}
}

document.addEventListener("DOMContentLoaded", function () {
	var root = document.getElementById("cgit");
	if (!root)
		return;
	var btn = root.querySelector(".theme-toggle");
	var theme = saved();
	if (ORDER.indexOf(theme) < 0)
		theme = "auto";

	apply(theme, root, btn);
	if (!btn)
		return;
	btn.hidden = false;
	btn.addEventListener("click", function () {
		theme = ORDER[(ORDER.indexOf(theme) + 1) % ORDER.length];
		persist(theme);
		apply(theme, root, btn);
	});
}, false);

})();

/* Built-in Markdown rendering for the about page. When no about-filter is
 * configured, cgit escapes a markdown readme into a data-markdown container
 * (see cgit_print_repo_readme) and this renders a deliberately small, safe
 * subset client-side: headings, lists, blockquotes, rules, fenced and inline
 * code, pipe tables, links, images and emphasis. Every run of text is escaped
 * before any markup is added, and link and image URLs are restricted to http,
 * https, mailto and relative targets, so a hostile readme cannot inject markup
 * or scripts. Fenced code carries its language in data-lang as a styling
 * hook. Without JavaScript the escaped source stays readable as plain text.
 *
 * This is intentionally a subset, not CommonMark: no reference links, raw HTML
 * passthrough, nested lists or setext headings. Configure an about-filter to
 * replace it, or set enable-markdown=0 to turn it off. */

(function () {

var MAX_BYTES = 400000;

function esc(s) {
	return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

function escAttr(s) {
	return esc(s).replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}

/* Return the url if its scheme is safe, else "". Whitespace and control bytes
 * are stripped before the scheme is read because browsers ignore them when
 * resolving it, so "java\nscript:..." must still be caught as javascript. */
function safeUrl(url) {
	url = (url || "").replace(/[\u0000-\u0020]+/g, "");
	var scheme = /^([a-z][a-z0-9+.\-]*):/i.exec(url);
	if (scheme && !/^(https?|mailto)$/i.test(scheme[1]))
		return "";
	return url;
}

function link(text, url, image) {
	var u = safeUrl(url);
	if (!u)
		return image ? esc("![" + text + "]") : inline(text);
	if (image)
		return "<img src='" + escAttr(u) + "' alt='" + escAttr(text) + "'/>";
	return "<a href='" + escAttr(u) + "'>" + inline(text) + "</a>";
}

/* Inline rendering over one block of text. Scans to the next marker character
 * and bulk-escapes the plain text in between, so it stays roughly linear. */
function inline(s) {
	var out = "", i = 0, n = s.length, marker = /[`!\[*_]/g, m, rest;
	while (i < n) {
		marker.lastIndex = i;
		m = marker.exec(s);
		if (!m) { out += esc(s.slice(i)); break; }
		if (m.index > i) { out += esc(s.slice(i, m.index)); i = m.index; }
		rest = s.slice(i);
		if ((m = /^`([^`]+)`/.exec(rest)))
			out += "<code>" + esc(m[1]) + "</code>";
		else if ((m = /^!\[([^\]]*)\]\(\s*([^)\s]+)[^)]*\)/.exec(rest)))
			out += link(m[1], m[2], true);
		else if ((m = /^\[([^\]]*)\]\(\s*([^)\s]+)[^)]*\)/.exec(rest)))
			out += link(m[1], m[2], false);
		else if ((m = /^(\*\*|__)([\s\S]+?)\1/.exec(rest)))
			out += "<strong>" + inline(m[2]) + "</strong>";
		else if ((m = /^(\*|_)([^\s][\s\S]*?)\1/.exec(rest)))
			out += "<em>" + inline(m[2]) + "</em>";
		else { out += esc(s.charAt(i)); i++; continue; }
		i += m[0].length;
	}
	return out;
}

function cells(row) {
	return row.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map(function (c) {
		return c.trim();
	});
}

function render(src) {
	var lines = src.replace(/\r\n?/g, "\n").split("\n");
	var out = "", i = 0, n = lines.length, line, m, k;
	while (i < n) {
		line = lines[i];
		if (/^\s*$/.test(line)) { i++; continue; }
		if ((m = /^\s*(`{3,}|~{3,})\s*([\w.+#-]*)/.exec(line))) {
			var fence = m[1].charAt(0) === "`" ? /^\s*`{3,}\s*$/ : /^\s*~{3,}\s*$/;
			var lang = m[2], code = "";
			for (i++; i < n && !fence.test(lines[i]); i++)
				code += lines[i] + "\n";
			i++;
			out += "<pre><code" + (lang ? " data-lang='" + escAttr(lang) + "'" : "") +
				">" + esc(code) + "</code></pre>";
			continue;
		}
		if ((m = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line))) {
			k = m[1].length;
			out += "<h" + k + ">" + inline(m[2]) + "</h" + k + ">";
			i++; continue;
		}
		if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { out += "<hr/>"; i++; continue; }
		if (/^\s*>/.test(line)) {
			var q = "";
			for (; i < n && /^\s*>/.test(lines[i]); i++)
				q += lines[i].replace(/^\s*>\s?/, "") + "\n";
			out += "<blockquote>" + render(q) + "</blockquote>";
			continue;
		}
		if (line.indexOf("|") >= 0 && i + 1 < n &&
		    /^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-+:?\s*\|?\s*$/.test(lines[i + 1])) {
			var head = cells(line), t = "<table><thead><tr>";
			for (k = 0; k < head.length; k++)
				t += "<th>" + inline(head[k]) + "</th>";
			t += "</tr></thead><tbody>";
			for (i += 2; i < n && lines[i].indexOf("|") >= 0 && !/^\s*$/.test(lines[i]); i++) {
				var row = cells(lines[i]);
				t += "<tr>";
				for (k = 0; k < row.length; k++)
					t += "<td>" + inline(row[k]) + "</td>";
				t += "</tr>";
			}
			out += t + "</tbody></table>";
			continue;
		}
		if (/^\s*([-*+]|\d+[.)])\s+/.test(line)) {
			var ordered = /^\s*\d/.test(line), tag = ordered ? "ol" : "ul";
			out += "<" + tag + ">";
			for (; i < n && (m = /^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(lines[i])); i++) {
				if ((/\d/.test(m[1])) !== ordered) break;
				out += "<li>" + inline(m[2]) + "</li>";
			}
			out += "</" + tag + ">";
			continue;
		}
		/* Always consume the current line so i advances even when it
		 * matched none of the block branches above. */
		var para = lines[i++];
		for (; i < n && !/^\s*$/.test(lines[i]) &&
		       !/^\s*(#{1,6}\s|>|`{3,}|~{3,}|([-*+]|\d+[.)])\s)/.test(lines[i]); i++)
			para += "\n" + lines[i];
		out += "<p>" + inline(para).replace(/\n/g, "<br/>") + "</p>";
	}
	return out;
}

document.addEventListener("DOMContentLoaded", function () {
	var nodes = document.querySelectorAll("div#cgit [data-markdown]"), i, el, text;
	for (i = 0; i < nodes.length; i++) {
		el = nodes[i];
		text = el.textContent;
		if (!text || text.length > MAX_BYTES)
			continue;
		try {
			el.innerHTML = render(text);
			/* The attribute doubles as the style hook for the
			 * unrendered source, so drop it once rendered. */
			el.removeAttribute("data-markdown");
		} catch (e) {
			/* leave the escaped source in place on any failure */
		}
	}
}, false);

})();