2
0
Fork 0
textout/textoutpc/html.py

128 lines
3.9 KiB
Python

#!/usr/bin/env python
# *****************************************************************************
# Copyright (C) 2023 Thomas Touhey <thomas@touhey.fr>
# This file is part of the textoutpc project, which is MIT-licensed.
# *****************************************************************************
"""HTML writer definition for textoutpc."""
from __future__ import annotations
from html import escape
from docutils.writers.html5_polyglot import (
HTMLTranslator as BaseHTMLTranslator,
Writer as BaseWriter,
)
from textoutpc.nodes import progress, spoiler
__all__ = ["Writer"]
class HTMLTranslator(BaseHTMLTranslator):
"""HTML translator with support for BBCode nodes."""
def visit_progress(self, node: progress) -> None:
"""Visit a progress tag.
The format for the progress tag in HTML form is the following::
<div>
{{ content }}
<div style="background-color: white; border: 1px solid black;
width: 50%; margin-top: 2px; text-align: left">
<div style="background-color: #FF3E28; color: black;
font-weight: bold; max-width: 100%;
width: {{ value }}%; height: 18px">
&nbsp;&nbsp;&nbsp;{{ value }}%
</div>
</div>
</div>
:param node: The progress node.
"""
self.body.append(
self.starttag(node, "div"),
)
def depart_progress(self, node: progress) -> None:
"""Depart a progress tag.
:param node: The progress node.
"""
self.body.extend(
(
self.starttag(
node,
"div",
style="background-color: white; border: 1px solid black; "
+ "width: 50%; margin-top: 2px; text-align: left",
),
self.starttag(
node,
"div",
style="background-color: #FF3E28; color: black; "
+ "font-weight: bold; max-width: 100%; "
+ f"width: {node.value}%; height: 18px",
),
f"&nbsp;&nbsp;&nbsp;{node.value}%</div></div></div>",
),
)
def visit_spoiler(self, node: spoiler) -> None:
"""Visit a spoiler tag.
The format for the spoiler tag in HTML form is the following::
<div class="spoiler">
<div class="title on"
onclick="toggleSpoiler(this.parentNode, 'open')">
{{ closed title }}
</div>
<div class="title off"
onclick="toggleSpoiler(this.parentNode, 'close')">
{{ opened title }}
</div>
{{ content }}
</div>
:param node: The spoiler node.
"""
self.body.extend(
(
self.starttag(node, "div", CLASS="spoiler"),
self.starttag(
node,
"div",
CLASS="title on",
onclick="toggleSpoiler(this.parentNode, 'open')",
),
escape(node.closed_title),
"</div>",
self.starttag(
node,
"div",
CLASS="title off",
onclick="toggleSpoiler(this.parentNode, 'close')",
),
escape(node.opened_title),
"</div>",
),
)
def depart_spoiler(self, node: spoiler) -> None:
"""Depart a spoiler tag.
:param node: The spoiler node.
"""
self.body.append("</div>")
class Writer(BaseWriter):
"""HTML writer with support for BBCode nodes."""
def __init__(self, /):
super().__init__()
self.translator_class = HTMLTranslator