aboutsummaryrefslogtreecommitdiff
path: root/muppet/tabs.py
blob: 702a49171dddc5ac2992227933ca1f93f78d5e1e (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
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
"""Thingies for an HTML tab widget."""

from dataclasses import dataclass
from jinja2 import (
    Environment,
    # PackageLoader,
    FileSystemLoader,
)


env = Environment(
    loader=FileSystemLoader('templates'),
    autoescape=False,
)


@dataclass
class Tab:
    """
    A single tab part of a tab group.

    :parameters:
        title - Display name of the tab
        id - Internal reference ID, must be globaly unique
        content - contents of the tab
    """

    title: str
    id: str
    content: str


@dataclass
class TabGroup:
    """A collection of tabs."""

    id: str
    tabs: list[Tab]


def tab_widget(tabgroup: TabGroup) -> str:
    """
    Render a HTML tab widget.

    The argument is the list of tabs, nothing is returned, but instead
    written to stdout.
    """
    template = env.get_template('tabset.html')
    return template.render(tabset=tabgroup)


__counter = 0


def next_id(prefix: str = 'id') -> str:
    """Return a new unique id."""
    global __counter
    __counter += 1
    return f'{prefix}-{__counter}'


def tabs(panes: dict[str, str]) -> str:
    """
    Build a tab widget from given dictionary.

    Keys are used as tab names, values as tab content.
    Id's are generated.
    """
    tabs = []
    for title, content in panes.items():
        tabs.append(Tab(title=title, content=content, id=next_id('tab')))

    return tab_widget(TabGroup(id=next_id('tabgroup'), tabs=tabs))