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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
|
<!DOCTYPE html>
<html lang='en'>
<head>
<style id="noFlashbang">
body {
background: #000;
color: #fff;
}
</style>
<meta charset='UTF-8'>
<title>tempo</title>
<link rel="prefetch" href="/tempo.md" as="fetch">
<link rel="prefetch" href="/symbols.txt" as="fetch">
<link rel="stylesheet" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" href="bell.png">
</head>
<body>
<script>
const body = document.body
const savedTheme = localStorage.getItem('theme')
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
body.classList.add('dark-mode')
}
</script>
<div id="themeButton" style="display: none">
<button id="themeToggle" title="change theme">๐</button>
<a href="#table-of-contents"><button id="goBackUp" title="go to table of contents">โคด</button></a>
</div>
<script>
themeButton.style.display = 'block'
if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
themeToggle.textContent = 'โ๏ธ'
}
themeToggle.addEventListener('click', () => {
body.classList.toggle('dark-mode')
if (body.classList.contains('dark-mode')) {
themeToggle.textContent = 'โ๏ธ'
localStorage.setItem('theme', 'dark')
} else {
themeToggle.textContent = '๐'
localStorage.setItem('theme', 'light')
}
})
window.addEventListener('load', () => {
noFlashbang.innerHTML += `*, body, html {
transition: 0.25s color, 0.25s background-color, 0.25s border;
}`
})
</script>
<noscript>
hello.<br>
your browser does not support javascript, it seems.<br>
this means i cannot render the markdown as pretty-printed html for you.<br>
instead, you can read the markdown raw at <a href="tempo.md">this page</a>.<br>
have a great day! :)
<br><br><br><br><br>
</noscript>
<div id='warnings'></div>
<div id='content'>
rendering content...
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<div>
tempo is licensed under creative-commons.
<br>
the terms are, boiled down:<br>
<div style="padding-left: 15px; padding-bottom: 10px;">
- you can use tempo in any way you like, including modifying or adding to it.<br>
- you must credit the <a href="https://tempo.coffin.ir">original tempo document</a> and its <a
href="https://tempo.coffin.ir/cc-by-sa-legalcode.txt">CC-BY-SA license</a>
if you redistribute it.<br>
- that's it.<br>
</div>
  <a href="cc-by-sa-legalcode.txt"><img src="by-sa.png" width="64" alt="creative commons by-sa license">
</a>
</div>
<script>
if ('serviceWorker' in navigator && location.hostname !== 'local.com') {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/serviceWorker.js')
.then(reg => console.log('sw registered'))
.catch(err => console.log('sw register failed', err))
navigator.serviceWorker.addEventListener('message', e => {
if (e.data && e.data.type === 'REFRESH') {
console.log(`updated content found for ${e.data.url}`)
window.location.reload()
}
})
})
} else {
console.log('[warn] no service worker support')
}
</script>
<script>
function escapeHTML(str) {
if (!str) return ''
const a = []
const p = '___A___'
return str
.replace(/<a\s+href="[^"]*"[^>]*>.*?<\/a>/gi, m => (a.push(m), `${p}${a.length - 1}${p}`))
.replace(/&(?!nbsp)/g, '&')
.replace(/<(?!br>)/g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(new RegExp(`${p}(\\d+)${p}`, 'g'), (m, i) => a[i])
}
function parseInline(text) {
const parts = text.split('`')
let html = ''
for (let i = 0; i < parts.length; i++) {
if (i % 2 === 0) {
let chunk = escapeHTML(parts[i])
chunk = chunk.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
chunk = chunk.replace(/\~\~(.*?)\~\~/g, '<s>$1</s>')
chunk = chunk.replace(/__(.*?)__/g, '<u>$1</u>')
chunk = chunk.replace(/\*(.*?)\*/g, '<i>$1</i>')
chunk = chunk.replace(/\[\[(.*?)\]\]/g, '<span style="user-select:none">๐ </span><b>"$1"</b>')
html += chunk
} else {
html += `<code>${escapeHTML(parts[i])}</code>`
}
}
return html
}
async function loadSymbols() {
try {
let response = await fetch('symbols.txt')
if (response.status !== 200) response = await fetch('symbols.txt.html')
if (response.status !== 200) {
console.log('symbols.txt not found, skipping symbol replacement')
return {}
}
const text = await response.text()
const symbols = {}
const symbolAliases = {}
for (const line of text.split('\n')) {
const trimmed = line.trim()
if (!trimmed) continue
const parts = trimmed.split(/\s+/)
if (parts.length >= 2) {
const symbol = parts[0]
const name = parts.slice(1).join(' ')
symbols[name] = symbol
if (!symbolAliases[symbol]) symbolAliases[symbol] = []
symbolAliases[symbol].push(name)
}
}
return { symbols, symbolAliases }
} catch (err) {
console.warn('failed to load symbols.txt:', err)
return { symbols: {}, symbolAliases: {} }
}
}
function applySymbols(text, symbols) {
let result = text
for (const [name, symbol] of Object.entries(symbols)) {
const pattern = new RegExp(`\\\\${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\\\`, 'g')
result = result.replace(pattern, symbol)
}
return result
}
class TempoParser {
constructor(rawText, symbols = {}) {
this.lines = rawText.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n')
this.tokens = []
this.defs = new Set()
this.symbols = symbols
this.reverseSymbols = {}
for (const [name, sym] of Object.entries(symbols)) {
this.reverseSymbols[sym] = name
}
}
tokenize() {
let i = 0
while (i < this.lines.length) {
let line = this.lines[i]
let trimmed = line.trim()
if (trimmed.startsWith('// Timestamp:')) {
const dateStr = trimmed.substring('// Timestamp:'.length).trim()
this.tokens.push({ type: 'timestamp', text: dateStr })
i++
continue
}
if (trimmed.startsWith('```')) {
let codeContent = []
i++
while (i < this.lines.length && !this.lines[i].trim().startsWith('```')) {
codeContent.push(this.lines[i])
i++
}
this.tokens.push({ type: 'codeblock', text: codeContent.join('\n') })
i++
continue
}
if (line.startsWith('#')) {
const match = line.match(/^#+/)[0]
let level = match.length
const text = line.substring(level).trim()
if (level > 6) level = 6
this.tokens.push({ type: 'header', level, text })
i++
continue
}
if (line.startsWith('>')) {
const text = line.substring(1).trim()
this.tokens.push({ type: 'blockquote', text })
i++
continue
}
if (line.startsWith('def ') && (i + 1 < this.lines.length) && this.lines[i + 1].trim().startsWith('^^')) {
const defLine = line
i++
let descLines = []
let firstDescLine = this.lines[i].replace(/^\^\^\s?/, '')
if (firstDescLine) descLines.push(firstDescLine)
i++
while (i < this.lines.length) {
if (this.lines[i].trim() === '') break
if (this.lines[i].startsWith('def ')) break
if (this.lines[i].startsWith('#')) break
descLines.push(this.lines[i])
i++
}
this.tokens.push({
type: 'definition',
header: defLine,
description: descLines.join('\n')
})
continue
}
if (trimmed !== '') {
let pLines = [line]
i++
while (i < this.lines.length) {
let nextLine = this.lines[i]
let nextTrim = nextLine.trim()
if (nextTrim === '') break
if (nextTrim.startsWith('```')) break
if (nextLine.startsWith('#')) break
if (nextLine.startsWith('def ') && (i + 1 < this.lines.length && this.lines[i + 1].trim().startsWith('^^'))) break
if (nextTrim.startsWith('// Timestamp:')) break
pLines.push(nextLine)
i++
}
this.tokens.push({ type: 'paragraph', text: pLines.join('\n') })
} else {
this.tokens.push({ type: 'break' })
i++
}
}
}
render() {
let html = ''
let tocItems = []
for (const token of this.tokens) {
if (token.type === 'definition') {
let line = token.header.substring(4).trim()
let name = ''
const firstTick = line.indexOf('`')
const lastTick = line.lastIndexOf('`')
if (firstTick !== -1 && lastTick !== -1 && lastTick > firstTick) {
name = line.substring(0, firstTick).trim()
} else {
name = line
}
const actualName = token.description.split('\n')[0].replace(/:/g, '')
if (this.reverseSymbols[name]) {
tocItems.push({
symbol: name,
name: actualName,
id: `def-${this.reverseSymbols[name].replace(/\s+/g, '-')}`
})
}
}
}
let tocHtml = ''
// tocItems = tocItems.sort((a, b) => a.name.localeCompare(b.name))
if (tocItems.length > 0) {
tocHtml = `<div id="table-of-contents" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(max(3rem, 3.125%), 1fr)); gap: 0.5rem; margin-bottom: 2rem; border: 1px solid var(--border); padding: 10px; border-radius: 5px;">`
const tocItemNames = tocItems.map(e => e.id)
for (const itemName of [...new Set(tocItemNames)]) {
const item = tocItems.find(e => e.id === itemName)
tocHtml += `<a class="table-item" href="#${item.id}" title="${item.name}">${item.symbol}</a>`
}
tocHtml += `</div>`
}
let tocInserted = false
let i = 0
for (const token of this.tokens) {
// Inject TOC before the first H2
if (!tocInserted && tocHtml && token.type === 'header' && token.level === 2) {
html += tocHtml
tocInserted = true
}
if (token.type === 'header') {
html += `<h${token.level}>${parseInline(token.text)}</h${token.level}>`
}
else if (token.type === 'codeblock') {
html += `<pre><code>${escapeHTML(token.text)}</code></pre>`
}
else if (token.type === 'blockquote') {
html += `<blockquote>${parseInline(token.text)}</blockquote>`
}
else if (token.type === 'paragraph') {
html += `<p>${parseInline(token.text).replace(/\n/g, '<br>')}</p>`
}
else if (token.type === 'timestamp') {
html += `<div class="timestamp-badge" data-time="${escapeHTML(token.text)}"><span class="clock">๐ stamp: </span><span class="rel-time">...</span></div>`
}
else if (token.type === 'definition') {
html += this.renderDefinition(token)
}
else if (token.type === 'break' && this.tokens[i - 1]?.type === 'break') {
html += '<br>'
}
i++
}
// If no h2 found, prepend it (or append to whatever was rendered)
if (!tocInserted && tocHtml) {
html = tocHtml + html
}
return html
}
renderDefinition(token) {
let line = token.header.substring(4).trim()
let name = ''
let code = ''
let eng = ''
const firstTick = line.indexOf('`')
const lastTick = line.lastIndexOf('`')
if (firstTick !== -1 && lastTick !== -1 && lastTick > firstTick) {
name = line.substring(0, firstTick).trim()
if (!this.defs.has(name)) this.defs.add(name)
else if (name !== 'ฮฉ' && name !== 'me') {
console.log('[warn] duplicate symbol', name)
warnings.innerHTML += `Duplicate symbol ${name}!<br>`
warnings.style.display = 'block'
}
code = line.substring(firstTick + 1, lastTick)
let remainder = line.substring(lastTick + 1).trim()
if (remainder.startsWith('[') && remainder.endsWith(']')) {
eng = remainder.substring(1, remainder.length - 1)
} else if (remainder.startsWith('(') && remainder.endsWith(')')) {
eng = remainder.substring(1, remainder.length - 1)
}
} else {
name = line
}
// Determine ID for TOC linking
let idAttr = ''
if (this.reverseSymbols[name]) {
idAttr = ` id="def-${this.reverseSymbols[name].replace(/\s+/g, '-')}"`
}
const descHtml = parseInline(token.description).replace(/\n/g, '<br>').replace(/ /g, ' ')
const deftext = escapeHTML(code)
return `<block${idAttr}>
${name.length === 0 ? '' : `
<header>
<div class='header-left'>
<span>def</span>
<span class='def-name'>${escapeHTML(name)}</span>
${deftext.length === 0 ? `` : `<code>${escapeHTML(code)}</code>`}
</div>
${eng ? `<span class='eng-text'>[${escapeHTML(eng)}]</span>` : ''}
</header>
`}
<desc>${descHtml}</desc>
</block>`
}
}
function validateSymbols(text, symbols, symbolAliases) {
const definedSymbols = new Set()
const missing = new Map()
const lines = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n')
lines.forEach((rawLine, index) => {
const lineNumber = index + 1
let line = rawLine
let ignoreUsages = false
if (line.startsWith('<!>')) {
line = line.substring(3)
ignoreUsages = true
}
const defMatch = line.match(/^def\s+(\S+)/)
if (defMatch) {
definedSymbols.add(defMatch[1].replace(/^\\/g, '').replace(/\\$/g, ''))
}
if (ignoreUsages) return
const usagePattern = /\\([^\\\s]+)\\/g
let match
while ((match = usagePattern.exec(line)) !== null) {
const name = match[1]
if (definedSymbols.has(name)) continue
const sym = symbols[name]
if (sym) {
const aliases = symbolAliases[sym] || []
if (aliases.some(alias => definedSymbols.has(alias))) continue
}
if (!missing.has(name)) missing.set(name, [])
missing.get(name).push(lineNumber)
}
})
if (missing.size > 0) {
let msg = 'undefined symbols detected:'
for (const [name, lineNums] of missing) {
const symChar = symbols[name] || '?'
const linesStr = lineNums.join(', ')
msg += `\n โข (${symChar}) ${name} [line${lineNums.length > 1 ? 's' : ''}: ${linesStr}]`
}
warnings.innerHTML += msg.replace(/\n/g, '<br>')
console.warn('undefined symbols:', missing)
} else if (warnings.innerHTML.length === 0) {
warnings.style.display = 'none'
}
}
async function loadMarkdown() {
try {
const { symbols, symbolAliases } = await loadSymbols()
let response = await fetch('tempo.md')
if (response.status !== 200) response = await fetch('tempo.md.html')
let text = await response.text()
validateSymbols(text, symbols, symbolAliases)
text = text.replace(/((^|\n)<!> *)/g, (e) => e.replace(/<!> */g, ''))
text = applySymbols(text, symbols)
const parser = new TempoParser(text, symbols) // Passed symbols here
parser.tokenize()
const html = parser.render().replace(/{{dict_size}}/g, `<b>${parser.defs.size - 1}</b>`)
// store first 32kb of website in local storage
content.innerHTML = html
try {
localStorage.setItem('rendered', html.substring(0, 32768))
} catch (err) {
console.log('[warn] localStorage caching failed. subsequent loads will not benefit from first-paint rendering.')
}
} catch (err) {
console.error("failed to load tempo file:", err)
document.getElementById('content').innerHTML = "<p>error loading content.</p>"
}
}
const title = document.title
const previousRender = localStorage.getItem('rendered')
if (previousRender) {
document.title = 'contents are stale...'
content.innerHTMl = previousRender
}
loadMarkdown().then(e => document.title = title)
</script>
<script>
const sleep = (time) => new Promise(r => setTimeout(r, time))
async function initTimestamps() {
const update = () => {
const now = new Date()
document.querySelectorAll('.timestamp-badge').forEach(el => {
const timeStr = el.getAttribute('data-time')
const date = new Date(timeStr)
if (date.getTime() > now.getTime() || timeStr === 'future') {
el.querySelector('.rel-time').textContent = 'to be determined.'
el.title = date.toLocaleString()
return
}
if (isNaN(date.getTime()) && timeStr !== 'future') return
let diff = Math.floor((now - date) / 1000)
const years = Math.floor(diff / 31536000)
diff %= 31536000
const months = Math.floor(diff / 2592000)
diff %= 2592000
const days = Math.floor(diff / 86400)
diff %= 86400
const hours = Math.floor(diff / 3600)
diff %= 3600
const minutes = Math.floor(diff / 60)
const seconds = diff % 60
const parts = []
if (years > 0) parts.push(`${years} year${years !== 1 ? 's' : ''}`)
if (months > 0) parts.push(`${months} month${months !== 1 ? 's' : ''}`)
if (days > 0) parts.push(`${days} day${days !== 1 ? 's' : ''}`)
if (hours > 0) parts.push(`${hours} hour${hours !== 1 ? 's' : ''}`)
if (minutes > 0) parts.push(`${minutes} minute${minutes !== 1 ? 's' : ''}`)
if (seconds > 0) parts.push(`${seconds} second${seconds !== 1 ? 's' : ''}`)
el.querySelector('.rel-time').textContent = parts.join(', ') + ' ago'
el.title = date.toLocaleString()
})
}
update()
for (let i = 0; i < 20; i++) {
update()
await sleep(100)
}
setInterval(update, 1000)
}
initTimestamps()
</script>
</body>
</html>
|