-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhtml.rkt
More file actions
57 lines (47 loc) · 1.33 KB
/
html.rkt
File metadata and controls
57 lines (47 loc) · 1.33 KB
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
#lang racket
(require racket/format)
(define self-closing
'(br))
(define none-encode-list
'(script))
(define (child-insert-space lst)
(match lst
['() '()]
[(list a) (list a)]
[(list a b ...)
(if (and (string? a) (string? (car b)))
(cons a (child-insert-space b))
(cons a (cons " " (child-insert-space b))))]))
(define (dom->string tag props child)
(if (memv tag self-closing)
(format "<~a>" tag)
(format
"<~a>~a</~a>"
(string-join
(cons (~a tag)
(map (lambda (p) (format "~s=~s" (car p) (cdr p))) props)))
(string-join
(map
(lambda (s)
(domtree->string s (not (memv tag none-encode-list))))
(child-insert-space child))
"")
tag)))
(define (encode-text str)
(apply string-append
(map (lambda (c)
(match c
[#\< "<"]
[#\> ">"]
[#\& "&"]
[x (string x)]))
(string->list str))))
(define (domtree->string tree encode)
(match tree
[(list (list tag props ...) child ...) (dom->string tag props child)]
[(list (? symbol? tag) child ...) (dom->string tag '() child)]
[#t "true"] [#f "false"]
[a (if encode (encode-text (~a a)) (~a a))]))
(define ($html input)
(domtree->string input #t))
(provide $html)