aboutsummaryrefslogtreecommitdiff
path: root/index.html
blob: 04f7bc367e014f16b84c7714a4abf9aa7e64344f (plain) (blame)
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
<!DOCTYPE html>
<html lang='en'>

<head>
    <style>
        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="styles3.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">🌙</button>
    </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')
            }
        })
    </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...
    </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>
        &nbsp&nbsp<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) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('/serviceWorker.js')
                    .then(reg => console.log('Service Worker registered'))
                    .catch(err => console.log('SW registration failed', err))
            })
        } 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, '&amp;')
                .replace(/<(?!br>)/g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;')
                .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, '<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 = {}

                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
                    }
                }

                return symbols
            } catch (err) {
                console.warn('failed to load symbols.txt:', err)
                return {}
            }
        }

        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) {
                this.lines = rawText.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n')
                this.tokens = []
            }

            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 i = 0
                for (const token of this.tokens) {
                    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++
                }
                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()
                    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
                }

                const descHtml = parseInline(token.description).replace(/\n/g, '<br>').replace(/  /g, '&nbsp;&nbsp;')
                const deftext = escapeHTML(code)

                return `<block>
            <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) {
            const usagePattern = /\\([^\\\s]+)\\/g
            const usedSymbols = new Set()
            let match

            while ((match = usagePattern.exec(text)) !== null) {
                usedSymbols.add(match[1])
            }

            const definedSymbols = new Set()
            const defPattern = /^def\s+(\S+)/gm

            while ((match = defPattern.exec(text)) !== null) {
                // console.log('defined:', match[1])
                definedSymbols.add(match[1].replace(/^\\/g, '').replace(/\\$/g, ''))
            }

            const missing = []
            for (const name of usedSymbols) {
                if (definedSymbols.has(name)) continue

                const symbol = symbols[name]
                if (symbol && definedSymbols.has(symbol)) continue

                missing.push(name)
            }

            if (missing.length > 0) {
                const msg = `undefined symbols detected:\n${missing.map(s => `  • (${symbols[s]}) ${s}`).join('\n')}`
                warnings.innerHTML += msg.replace(/\n/g, '<br>')
                console.warn('undefined symbols:', missing)
            } else {
                warnings.style.display = 'none'
            }
        }

        async function loadMarkdown() {
            try {
                const symbols = 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)
                text = applySymbols(text, symbols)

                const parser = new TempoParser(text)
                parser.tokenize()
                const html = parser.render()

                // store first 4kb of website in local storage
                document.getElementById('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>