-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcfrs.html
706 lines (659 loc) · 20.6 KB
/
cfrs.html
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
<!--
CFRS[] 0.3.0-dev
Copyright (c) 2023-2025 Susam Pal
Source: https://github.com/susam/cfrs
License: MIT
-->
<!DOCTYPE html>
<html lang="en">
<head>
<title>CFRS[]</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="An extremely minimal drawing and animation language consisting of only six simple commands: C, F, R, S, [, and ].">
<style>
body {
background: #111;
margin: 0;
}
canvas, section, pre, input, button {
background: #000;
box-sizing: border-box;
border: 1px solid #333;
}
canvas, section, pre, input {
display: block;
margin: 0 auto;
}
section, pre, input, button, a {
font-family: monospace,monospace;
font-size: 1em;
color: #999;
}
pre, input {
padding-left: 8px;
}
canvas {
image-rendering: pixelated;
}
section {
padding: 0 1em;
overflow: auto;
}
pre {
overflow: auto hidden;
}
input {
color: #ccc;
border-color: #666;
text-transform: uppercase;
}
input::placeholder {
text-transform: none;
}
input:focus {
outline: none;
}
button {
color: #999;
font-weight: bold;
vertical-align: middle;
user-select: none;
-webkit-user-select: none;
}
button:active {
background: #222;
}
div, footer {
text-align: center;
}
a {
color: #69c;
}
footer a {
line-height: 5;
margin-right: 1.5em;
}
footer a:last-child {
margin-right: 0;
}
</style>
<script>
'use strict'
const LOGGING = false
const COLORS = ['#000', '#36f', '#0c0', '#0cc',
'#c00', '#c0c', '#cc0', '#ccc']
const GRID_SIZE = 256
const SLEEP_INTERVAL = 20
const SCALE = 4
const PADDING = 8
const PANEL_HEIGHT = 40
const MAX_CODE_LEN = 256
const MAX_DIST_LEN = 64
const DEMOS = {
0: '[[[[[[[[[[[[[[[FF]]]]]]]SRRF[RRR]]]]]]C]]]',
1: '[[[[[[[[[[[[[[[FF]]]]C]]]SRRF[RRR]F]]]]]]]]',
2: 'R[[[[[[[[[[[[[[FF]]]]]]]RRF[RRR]SC]]]]]]]',
3: '[[[[[[[[[[[[[[F]]]]RCC]]]SRR[FFF][RRR][FF]]]]]]]]',
4: '[[[[[[[[[[[[FF]]]]RR]][[[FFF]]]SRR[[F]][RRR]CC]]]]]]',
5: '[[[[[[[[[[[[[[[FF]]]]RR]][[[FFF]]]RR[[F]][RRR]CC]]S]]]]R]]]'
}
let startTime = null
let canvas
let canvasSize
let ctx
let info
let status
let text
let buttonColor
let buttonForward
let buttonRotate
let buttonSleep
let buttonBlock
let buttonRepeat
let buttonDelete
let buttonHelp
let buttons
let prevText
let questioned = false
function init () {
// Look up elements.
canvas = document.getElementById('canvas')
info = document.getElementById('info')
status = document.getElementById('status')
text = document.getElementById('text')
// Initialize canvas.
ctx = canvas.getContext('2d')
canvas.width = GRID_SIZE * SCALE
canvas.height = GRID_SIZE * SCALE
// Initialize buttons.
buttonColor = document.getElementById('color')
buttonForward = document.getElementById('forward')
buttonRotate = document.getElementById('rotate')
buttonSleep = document.getElementById('sleep')
buttonBlock = document.getElementById('block')
buttonRepeat = document.getElementById('repeat')
buttonDelete = document.getElementById('delete')
buttonHelp = document.getElementById('help')
buttons = [buttonColor, buttonForward, buttonRotate, buttonSleep,
buttonBlock, buttonRepeat, buttonDelete, buttonHelp]
// Add event listeners for text.
text.addEventListener('keyup', actionKey)
text.addEventListener('paste', actionKey)
text.addEventListener('cut', actionKey)
// Add event listeners for buttons.
buttonColor.addEventListener('click', actionColor)
buttonForward.addEventListener('click', actionForward)
buttonRotate.addEventListener('click', actionRotate)
buttonBlock.addEventListener('click', actionBlock)
buttonRepeat.addEventListener('click', actionRepeat)
buttonSleep.addEventListener('click', actionSleep)
buttonDelete.addEventListener('click', actionDelete)
buttonHelp.addEventListener('click', actionHelp)
window.addEventListener('hashchange', actionHash)
window.addEventListener('resize', resize)
// Initialize input code and output.
resize()
clearHelp()
actionHash()
text.setSelectionRange(text.value.length, text.value.length)
}
function resize () {
document.body.style.padding = PADDING + 'px'
const availableWidth = document.documentElement.clientWidth - 2 * PADDING
const availableHeight = document.documentElement.clientHeight - 2 * PANEL_HEIGHT - 4 * PADDING
// Resize canvas.
canvasSize = Math.floor(Math.min(availableWidth, availableHeight))
canvas.style.width = canvasSize + 'px'
canvas.style.height = canvasSize + 'px'
info.style.width = canvasSize + 'px'
info.style.height = canvasSize + 'px'
// Resize status panel.
status.style.width = canvasSize + 'px'
status.style.height = PANEL_HEIGHT + 'px'
status.style.lineHeight = PANEL_HEIGHT + 'px'
status.style.marginTop = PADDING + 'px'
// Resize code text panel.
text.style.width = canvasSize + 'px'
text.style.height = PANEL_HEIGHT + 'px'
text.style.marginTop = PADDING + 'px'
// Resize buttons.
const buttonsInRow = buttons.length / 2
const buttonWidth = Math.floor(
(canvasSize - (buttonsInRow - 1) * PADDING) / buttonsInRow)
for (let i = 0; i < buttons.length; ++i) {
const button = buttons[i]
button.style.marginTop = PADDING + 'px'
button.style.width = buttonWidth + 'px'
button.style.height = PANEL_HEIGHT + 'px'
button.style.marginLeft = (i % buttonsInRow === 0 ? 0 : PADDING) + 'px'
}
log('resized: canvas: ' + canvasSize + '; button: ' + buttonWidth)
}
function draw () {
if (prevText === text.value) {
log('skipping draw since no change in code')
return
}
clearHelp()
log('draw', text.value)
stopLooper()
ctx.fillStyle = COLORS[0]
ctx.fillRect(0, 0, GRID_SIZE * SCALE, GRID_SIZE * SCALE)
evaluate()
prevText = text.value
log('draw complete')
}
let idx
let x
let y
let color
let heading
let ops
let stack
let looperTimer = null
let lastUpdate = 0
function evaluate () {
x = Math.floor((GRID_SIZE - 1) / 2)
y = Math.floor((GRID_SIZE - 1) / 2)
color = 7
heading = 0
ops = 0
idx = 0
stack = []
startTime = Date.now()
logOp(ops, '-', idx, 'BEGIN', color, x, y, heading)
if (text.value.length > MAX_CODE_LEN) {
error('Code contains ' + text.value.length +
' bytes; must not exceed ' + MAX_CODE_LEN)
return
}
looper()
}
function looper () {
looperTimer = null
let loop = true
while (loop && idx < text.value.length) {
loop = iterate()
}
if (loop === null) {
return
}
if (idx < text.value.length) {
looperTimer = window.setTimeout(looper, SLEEP_INTERVAL)
}
if (ops === 0) {
status.innerHTML = 'READY. Type ‘?’ for help.'
} else {
const now = Date.now()
if (now - lastUpdate > 100 || idx === text.value.length) {
const ms = now - startTime
const bytes = text.value.length + (text.value.length === 1 ? ' byte' : ' bytes')
const opss = ops + (ops === 1 ? ' op' : ' ops')
const duration = (ms / 1000).toFixed(3) + ' s'
const rate = (ms === 0 ? '-' : (1000 * ops / ms).toFixed(1)) + ' ops/s'
const msg = bytes + ', ' + opss + ', ' + duration + ', ' + rate
status.innerHTML = msg
lastUpdate = now
}
}
}
function stopLooper () {
if (looperTimer !== null) {
window.clearTimeout(looperTimer)
looperTimer = null
}
}
function iterate () {
const execIdx = idx
const op = text.value.charAt(idx)
let loop = true
if (op === 'C') {
color = (color + 1) % COLORS.length
++idx
} else if (op === 'F') {
if (heading === 1 || heading === 2 || heading === 3) {
x = (x + 1) % GRID_SIZE
} else if (heading === 5 || heading === 6 || heading === 7) {
x = (x - 1 + GRID_SIZE) % GRID_SIZE
}
if (heading === 7 || heading === 0 || heading === 1) {
y = (y - 1 + GRID_SIZE) % GRID_SIZE
} else if (heading === 3 || heading === 4 || heading === 5) {
y = (y + 1) % GRID_SIZE
}
ctx.fillStyle = COLORS[color]
ctx.fillRect(x * SCALE, y * SCALE, SCALE, SCALE)
++idx
} else if (op === 'R') {
heading = (heading + 1) % 8
++idx
} else if (op === 'S') {
loop = false
++idx
} else if (op === '[') {
stack.push([idx + 1, 1])
++idx
} else if (op === ']') {
if (stack.length === 0) {
error('Unexpected ‘]’')
return null
}
const [jmpIdx, count] = stack.pop()
if (count !== 0) {
stack.push([jmpIdx, count - 1])
idx = jmpIdx
} else {
++idx
}
} else {
error('Unknown operation')
return null
}
logOp(ops, execIdx, idx, op, color, x, y, heading)
++ops
return loop
}
function error (msg) {
ctx.fillStyle = COLORS[4]
ctx.fillRect(0, 0, GRID_SIZE * SCALE, GRID_SIZE * SCALE)
status.innerHTML = 'ERROR: ' + msg
}
function actionHash () {
if (window.location.hash.length > 1) {
const code = urlDecode(window.location.hash.substring(1))
if (code === null) {
return
}
if (code !== text.value) {
text.value = code
log('set code from hash:', text.value)
}
}
normalizeDraw()
}
function updateHash () {
if (text.value.length > MAX_DIST_LEN) {
window.history.replaceState(null, '', '#')
} else {
const encoded = urlEncode(text.value)
const hash = window.location.hash
const fragment = hash === '' ? '' : hash.substring(1)
if (encoded !== fragment) {
window.history.replaceState(null, '', '#' + encoded)
log('set hash from code:', window.location.hash)
}
}
}
function actionKey (e) {
if (e.key !== 'Shift') {
window.setTimeout(normalizeDraw, 10)
}
}
function normalizeDraw () {
lookupDemo()
sanitizeText()
updateHash()
draw()
if (questioned) {
toggleHelp()
questioned = false
}
}
function lookupDemo () {
const code = DEMOS[text.value]
if (typeof code !== 'undefined') {
text.value = code
}
}
function actionColor (e) {
e.preventDefault()
insertText('C')
draw()
}
function actionForward (e) {
e.preventDefault()
insertText('F')
draw()
}
function actionRotate (e) {
e.preventDefault()
insertText('R')
draw()
}
function actionBlock (e) {
e.preventDefault()
insertText('[')
draw()
}
function actionRepeat (e) {
e.preventDefault()
insertText(']')
draw()
}
function actionSleep (e) {
e.preventDefault()
insertText('S')
draw()
}
function actionDelete (e) {
e.preventDefault()
deleteText()
draw()
}
function actionHelp (e) {
e.preventDefault()
toggleHelp()
text.focus()
}
function toggleHelp () {
if (info.style.display === 'none') {
stopLooper()
canvas.style.display = 'none'
info.style.display = 'block'
buttonHelp.title = 'Hide help'
status.innerHTML = 'Type ‘?’ or code to hide help.'
log('help displayed')
} else {
log('forcing redraw to clear help')
prevText = null // Force redraw to clear help.
draw()
}
}
function clearHelp () {
canvas.style.display = 'block'
info.style.display = 'none'
buttonHelp.title = 'Show help'
log('help cleared')
}
function insertText (ch) {
const cursorStart = text.selectionStart
const left = text.value.substring(0, cursorStart)
const right = text.value.substring(text.selectionEnd)
text.value = left + ch + right
text.focus()
text.setSelectionRange(cursorStart + 1, cursorStart + 1)
updateHash()
}
function deleteText () {
let cursorStart = text.selectionStart
let left
const right = text.value.substring(text.selectionEnd)
if (text.selectionEnd > cursorStart) {
left = text.value.substring(0, cursorStart)
} else if (cursorStart > 0) {
left = text.value.substring(0, cursorStart - 1)
--cursorStart
} else {
left = ''
}
text.value = left + right
text.focus()
text.setSelectionRange(cursorStart, cursorStart)
updateHash()
}
function sanitizeText () {
let cursorStart = text.selectionStart
let cursorEnd = text.selectionEnd
const cursorDir = text.selectionDirection
let result = ''
for (let i = 0; i < text.value.length; ++i) {
const ch = text.value.charAt(i).toUpperCase()
if (ch === 'C' || ch === 'F' || ch === 'R' || ch === 'S' ||
ch === '[' || ch === ']') {
result += ch
continue
}
if (ch === '?') {
questioned = true
}
// Since non-command characters are being removed from the
// code, adjust the cursor position accordingly.
if (i < cursorStart) {
--cursorStart
}
if (i < cursorEnd) {
--cursorEnd
}
}
if (result !== text.value) {
text.value = result
text.setSelectionRange(cursorStart, cursorEnd, cursorDir)
}
}
function urlEncode (s) {
s = s.replaceAll('[', 'B').replaceAll(']', 'E')
let result = ''
const match = s.match(/(.)\1*/g)
if (match !== null) {
for (let i = 0; i < match.length; ++i) {
result += match[i][0] + (match[i].length > 1 ? match[i].length : '')
}
}
return result
}
function urlDecode (s) {
s = s.replaceAll('B', '[').replaceAll('E', ']')
let result = ''
const match = s.match(/\D+|\d+/g)
const errMsg = 'Code embedded in URL exceeds ' + MAX_DIST_LEN +
' bytes on expansion'
if (match !== null) {
for (let i = 0; i < match.length; ++i) {
if (/\D/.test(match[i][0]) || result === '') {
result += match[i]
} else {
const count = +match[i]
if (count > MAX_DIST_LEN) {
error(errMsg)
return null
}
result += result.charAt(result.length - 1).repeat(count - 1)
}
if (result.length > MAX_DIST_LEN) {
error(errMsg)
return null
}
}
}
return result
}
function log () {
if (LOGGING) {
const args = Array.prototype.slice.call(arguments)
let ts
if (startTime === null) {
ts = '-'
} else {
ts = ((Date.now() - startTime) / 1000)
}
console.log('[' + ts + '] ' + args.join(' '))
}
}
function logOp (ops, execIdx, nextIdx, op, color, x, y, heading) {
if (LOGGING) {
log('(' + ops + ') ' + execIdx + ': ' + op + '; color: ' + color +
'; x: ' + x + '; y: ' + y + '; next: ' + nextIdx)
}
}
window.addEventListener('load', init)
</script>
</head>
<body>
<canvas id="canvas"></canvas>
<section id="info">
<p><strong>COMMANDS</strong></p>
<ul>
<li>
<p>
<strong>C</strong> - Change colour to the next one from
the cyclic sequence:
<span style="background: #999; color: #000; padding: 0 2px">black</span>,
<span style="color: #36f">blue</span>,
<span style="color: #0c0">green</span>,
<span style="color: #0cc">cyan</span>,
<span style="color: #c00">red</span>,
<span style="color: #c0c">magenta</span>,
<span style="color: #cc0">yellow</span>, and
<span style="color: #ccc">white</span>.
</p>
</li>
<li>
<p>
<strong>F</strong> - Move forward by one cell and paint
the new cell.
</p>
</li>
<li>
<p>
<strong>R</strong> - Rotate clockwise by 45°.
</p>
</li>
<li>
<p>
<strong>S</strong> - Sleep for 20 ms.
</p>
</li>
<li>
<p>
<strong>[</strong> - Begin a repeatable block and continue
executing subsequent code normally.
</p>
</li>
<li>
<p>
<strong>]</strong> - Go back to the beginning of the
current repeatable block, execute it again, and exit the
block. Thus a block bounded by
‘<strong>[</strong>’ and
‘<strong>]</strong>’ is a loop that runs twice
before the block exits.
</p>
</ul>
<p><strong>EXAMPLES</strong></p>
<ul>
<li>
<p>
<strong>[FFF]</strong> - A column of 6 white cells.
</p>
</li>
<li>
<p>
<strong>CC[[[[[[FS]]]]]]</strong> - A gradually rising
column of 64 cells.
</p>
</li>
<li>
<p>
<strong>[[[[[[[[FFF]]R]]][[[SSS]]]CC]]]</strong> - An
octagon that changes colours 8 times.
</p>
</li>
</ul>
<p><strong>MORE</strong></p>
<ul>
<li>
<p>
Documentation:
<a href="https://github.com/susam/cfrs">github.com/susam/cfrs</a>
</p>
</li>
<li>
<p>
Built-in demos:
<a href="#0">#0</a>,
<a href="#1">#1</a>,
<a href="#2">#2</a>,
<a href="#3">#3</a>,
<a href="#4">#4</a>,
<a href="#5">#5</a>
</p>
</li>
<li>
<p>
Community demos:
<a href="https://susam.github.io/cfrs/demo.html">susam.github.io/cfrs/demo.html</a>
</p>
</li>
</ul>
</section>
<pre id="status"></pre>
<input id="text" inputmode="none" autofocus placeholder="Type code here.">
<div>
<button id="color" title="Change colour">C</button><!--
--><button id="forward" title="Move forward and paint cell">F</button><!--
--><button id="rotate" title="Rotate by 45°">R</button><!--
--><button id="sleep" title="Sleep for 20 ms">S</button>
</div>
<div>
<button id="block" title="Begin block">[</button><!--
--><button id="repeat" title="Repeat block once">]</button><!--
--><button id="delete" title="Delete command">←</button><!--
--><button id="help" title="Show help">?</button>
</div>
<footer>
<a href="https://github.com/susam/cfrs">GitHub</a>
<a href="https://mastodon.social/@susam">Mastodon</a>
<a href="https://susam.net/fxyt.html">FXYT</a>
</footer>
</body>
</html>