aboutsummaryrefslogtreecommitdiff
path: root/html_render.py
blob: 533ae7caf2ef740bff404dfae1fe7698f71b5e0c (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
import html
from typing import (
    TypeAlias,
    Union,
    Callable,
    Optional,
    cast,
)

HTML: TypeAlias = Union[tuple, list, Callable[[], str], None,
                        str, int, float]


standalones = ['hr', 'br', 'meta']


def _render_document(document: HTML) -> str:
    if type(document) == tuple:
        tag, *body = document
        if body and type(body[0]) == dict:
            print(body[0])
            attributes = ' '.join(f'{a}="{html.escape(b)}"'
                                  for a, b in body[0].items())
            body = body[1:]
            start = f'<{tag} {attributes}>'
        else:
            start = f'<{tag}>'
        if tag in standalones:
            return start
        else:
            items = ''.join(_render_document(b) for b in body)
            return start + f'{items}</{tag}>'
    elif callable(document):
        return str(document())
    elif type(document) == list:
        return ''.join(_render_document(e) for e in document)
    elif document is None:
        return ''
    else:
        # strings, and everything else
        return html.escape(str(document))


def render_document(document: HTML) -> str:
    return '<!doctype html>\n' + _render_document(document)