| 1 |
import re |
| 2 |
from typing import NamedTuple |
| 3 |
|
| 4 |
from docutils import nodes |
| 5 |
from docutils.parsers.rst import directives |
| 6 |
from docutils.statemachine import StringList |
| 7 |
from sphinx import addnodes |
| 8 |
from sphinx.application import Sphinx |
| 9 |
from sphinx.util.docutils import SphinxDirective |
| 10 |
from sphinx.util.logging import getLogger |
| 11 |
|
| 12 |
from ._compat import findall |
| 13 |
from .shared import ( |
| 14 |
WARNING_TYPE, |
| 15 |
PassthroughTextElement, |
| 16 |
SdDirective, |
| 17 |
create_component, |
| 18 |
is_component, |
| 19 |
make_choice, |
| 20 |
margin_option, |
| 21 |
text_align, |
| 22 |
) |
| 23 |
|
| 24 |
LOGGER = getLogger(__name__) |
| 25 |
|
| 26 |
DIRECTIVE_NAME_CARD = "card" |
| 27 |
DIRECTIVE_NAME_CAROUSEL = "card-carousel" |
| 28 |
REGEX_HEADER = re.compile(r"^\^{3,}\s*$") |
| 29 |
REGEX_FOOTER = re.compile(r"^\+{3,}\s*$") |
| 30 |
|
| 31 |
|
| 32 |
def setup_cards(app: Sphinx) -> None: |
| 33 |
"""Setup the card components.""" |
| 34 |
app.add_directive(DIRECTIVE_NAME_CARD, CardDirective) |
| 35 |
app.add_directive(DIRECTIVE_NAME_CAROUSEL, CardCarouselDirective) |
| 36 |
|
| 37 |
|
| 38 |
class CardContent(NamedTuple): |
| 39 |
"""Split card into header (optional), body, footer (optional). |
| 40 |
|
| 41 |
(offset, content) |
| 42 |
""" |
| 43 |
|
| 44 |
body: tuple[int, StringList] |
| 45 |
header: tuple[int, StringList] | None = None |
| 46 |
footer: tuple[int, StringList] | None = None |
| 47 |
|
| 48 |
|
| 49 |
class CardDirective(SdDirective): |
| 50 |
"""A card component.""" |
| 51 |
|
| 52 |
has_content = True |
| 53 |
required_arguments = 0 |
| 54 |
optional_arguments = 1 # card title |
| 55 |
final_argument_whitespace = True |
| 56 |
option_spec = { |
| 57 |
"width": make_choice(["auto", "25%", "50%", "75%", "100%"]), |
| 58 |
"margin": margin_option, |
| 59 |
"text-align": text_align, |
| 60 |
"img-top": directives.uri, |
| 61 |
"img-bottom": directives.uri, |
| 62 |
"img-background": directives.uri, |
| 63 |
"img-alt": directives.unchanged, |
| 64 |
"link": directives.uri, |
| 65 |
"link-type": make_choice(["url", "any", "ref", "doc"]), |
| 66 |
"link-alt": directives.unchanged, |
| 67 |
"shadow": make_choice(["none", "sm", "md", "lg"]), |
| 68 |
"class-card": directives.class_option, |
| 69 |
"class-header": directives.class_option, |
| 70 |
"class-body": directives.class_option, |
| 71 |
"class-title": directives.class_option, |
| 72 |
"class-footer": directives.class_option, |
| 73 |
"class-img-top": directives.class_option, |
| 74 |
"class-img-bottom": directives.class_option, |
| 75 |
} |
| 76 |
|
| 77 |
def run_with_defaults(self) -> list[nodes.Node]: |
| 78 |
return [self.create_card(self, self.arguments, self.options)] |
| 79 |
|
| 80 |
@classmethod |
| 81 |
def create_card( # noqa: PLR0915 |
| 82 |
cls, inst: SphinxDirective, arguments: list | None, options: dict |
| 83 |
) -> nodes.Node: |
| 84 |
"""Run the directive.""" |
| 85 |
# TODO better degradation for latex |
| 86 |
card_classes = ["sd-card", "sd-sphinx-override"] |
| 87 |
if "width" in options: |
| 88 |
card_classes += [f"sd-w-{options['width'].rstrip('%')}"] |
| 89 |
card_classes += options.get("margin", ["sd-mb-3"]) |
| 90 |
card_classes += [f"sd-shadow-{options.get('shadow', 'sm')}"] |
| 91 |
if "link" in options: |
| 92 |
card_classes += ["sd-card-hover"] |
| 93 |
card = create_component( |
| 94 |
"card", |
| 95 |
card_classes |
| 96 |
+ options.get("text-align", []) |
| 97 |
+ options.get("class-card", []), |
| 98 |
) |
| 99 |
inst.set_source_info(card) |
| 100 |
|
| 101 |
img_alt = options.get("img-alt") or "" |
| 102 |
|
| 103 |
container = card |
| 104 |
if "img-background" in options: |
| 105 |
card.append( |
| 106 |
nodes.image( |
| 107 |
uri=options["img-background"], |
| 108 |
classes=["sd-card-img"], |
| 109 |
alt=img_alt, |
| 110 |
) |
| 111 |
) |
| 112 |
overlay = create_component("card-overlay", ["sd-card-img-overlay"]) |
| 113 |
inst.set_source_info(overlay) |
| 114 |
card += overlay |
| 115 |
container = overlay |
| 116 |
|
| 117 |
if "img-top" in options: |
| 118 |
image_top = nodes.image( |
| 119 |
"", |
| 120 |
uri=options["img-top"], |
| 121 |
alt=img_alt, |
| 122 |
classes=["sd-card-img-top", *options.get("class-img-top", [])], |
| 123 |
) |
| 124 |
container.append(image_top) |
| 125 |
|
| 126 |
components = cls.split_content(inst.content, inst.content_offset) |
| 127 |
|
| 128 |
if components.header: |
| 129 |
container.append( |
| 130 |
cls._create_component( |
| 131 |
inst, "header", options, components.header[0], components.header[1] |
| 132 |
) |
| 133 |
) |
| 134 |
|
| 135 |
body = cls._create_component( |
| 136 |
inst, "body", options, components.body[0], components.body[1] |
| 137 |
) |
| 138 |
if arguments: |
| 139 |
title = create_component( |
| 140 |
"card-title", |
| 141 |
[ |
| 142 |
"sd-card-title", |
| 143 |
"sd-font-weight-bold", |
| 144 |
*options.get("class-title", []), |
| 145 |
], |
| 146 |
) |
| 147 |
textnodes, _ = inst.state.inline_text(arguments[0], inst.lineno) |
| 148 |
title_container = PassthroughTextElement() |
| 149 |
title_container.extend(textnodes) |
| 150 |
inst.set_source_info(title_container) |
| 151 |
title.append(title_container) |
| 152 |
body.insert(0, title) |
| 153 |
container.append(body) |
| 154 |
|
| 155 |
if components.footer: |
| 156 |
container.append( |
| 157 |
cls._create_component( |
| 158 |
inst, "footer", options, components.footer[0], components.footer[1] |
| 159 |
) |
| 160 |
) |
| 161 |
|
| 162 |
if "img-bottom" in options: |
| 163 |
image_bottom = nodes.image( |
| 164 |
"", |
| 165 |
uri=options["img-bottom"], |
| 166 |
alt=img_alt, |
| 167 |
classes=["sd-card-img-bottom", *options.get("class-img-bottom", [])], |
| 168 |
) |
| 169 |
container.append(image_bottom) |
| 170 |
|
| 171 |
if "link" in options: |
| 172 |
link_container = PassthroughTextElement() |
| 173 |
_classes = ["sd-stretched-link", "sd-hide-link-text"] |
| 174 |
_rawtext = options.get("link-alt") or options["link"] |
| 175 |
if options.get("link-type", "url") == "url": |
| 176 |
link = nodes.reference( |
| 177 |
_rawtext, |
| 178 |
"", |
| 179 |
nodes.inline(_rawtext, _rawtext), |
| 180 |
refuri=options["link"], |
| 181 |
classes=_classes, |
| 182 |
) |
| 183 |
else: |
| 184 |
options = { |
| 185 |
# TODO the presence of classes raises an error if the link cannot be found |
| 186 |
"classes": _classes, |
| 187 |
"reftarget": options["link"], |
| 188 |
"refdoc": inst.env.docname, |
| 189 |
"refdomain": "" if options["link-type"] == "any" else "std", |
| 190 |
"reftype": options["link-type"], |
| 191 |
"refexplicit": "link-alt" in options, |
| 192 |
"refwarn": True, |
| 193 |
} |
| 194 |
link = addnodes.pending_xref( |
| 195 |
_rawtext, nodes.inline(_rawtext, _rawtext), **options |
| 196 |
) |
| 197 |
inst.set_source_info(link) |
| 198 |
link_container += link |
| 199 |
container.append(link_container) |
| 200 |
|
| 201 |
return card |
| 202 |
|
| 203 |
@staticmethod |
| 204 |
def split_content(content: StringList, offset: int) -> CardContent: |
| 205 |
"""Split the content into header, body and footer.""" |
| 206 |
header_index, footer_index, header, footer = None, None, None, None |
| 207 |
body_offset = offset |
| 208 |
for index, line in enumerate(content): |
| 209 |
# match the first occurrence of a header regex |
| 210 |
if (header_index is None) and REGEX_HEADER.match(line): |
| 211 |
header_index = index |
| 212 |
# match the final occurrence of a footer regex |
| 213 |
if REGEX_FOOTER.match(line): |
| 214 |
footer_index = index |
| 215 |
if header_index is not None: |
| 216 |
header = (offset, content[:header_index]) |
| 217 |
body_offset += header_index + 1 |
| 218 |
if footer_index is not None: |
| 219 |
footer = (offset + footer_index + 1, content[footer_index + 1 :]) |
| 220 |
body = ( |
| 221 |
body_offset, |
| 222 |
content[ |
| 223 |
(header_index + 1 if header_index is not None else None) : footer_index |
| 224 |
], |
| 225 |
) |
| 226 |
return CardContent(body, header, footer) |
| 227 |
|
| 228 |
@classmethod |
| 229 |
def _create_component( |
| 230 |
cls, |
| 231 |
inst: SphinxDirective, |
| 232 |
name: str, |
| 233 |
options: dict, |
| 234 |
offset: int, |
| 235 |
content: StringList, |
| 236 |
) -> nodes.container: |
| 237 |
"""Create the header, body, or footer.""" |
| 238 |
component = create_component( |
| 239 |
f"card-{name}", [f"sd-card-{name}", *options.get(f"class-{name}", [])] |
| 240 |
) |
| 241 |
inst.set_source_info(component) # TODO set proper lines |
| 242 |
inst.state.nested_parse(content, offset, component) |
| 243 |
cls.add_card_child_classes(component) |
| 244 |
return component |
| 245 |
|
| 246 |
@staticmethod |
| 247 |
def add_card_child_classes(node): |
| 248 |
"""Add classes to specific child nodes.""" |
| 249 |
for para in findall(node)(nodes.paragraph): |
| 250 |
para["classes"] = [*para.get("classes", []), "sd-card-text"] |
| 251 |
# for title in findall(node)(nodes.title): |
| 252 |
# title["classes"] = ([] if "classes" not in title else title["classes"]) + [ |
| 253 |
# "sd-card-title" |
| 254 |
# ] |
| 255 |
|
| 256 |
|
| 257 |
class CardCarouselDirective(SdDirective): |
| 258 |
"""A component, which is a container for cards in a single scrollable row.""" |
| 259 |
|
| 260 |
has_content = True |
| 261 |
required_arguments = 1 # columns |
| 262 |
optional_arguments = 0 |
| 263 |
option_spec = { |
| 264 |
"class": directives.class_option, |
| 265 |
} |
| 266 |
|
| 267 |
def run_with_defaults(self) -> list[nodes.Node]: |
| 268 |
self.assert_has_content() |
| 269 |
try: |
| 270 |
cols = make_choice([str(i) for i in range(1, 13)])( |
| 271 |
self.arguments[0].strip() |
| 272 |
) |
| 273 |
except ValueError as exc: |
| 274 |
raise self.error(f"Invalid directive argument: {exc}") from exc |
| 275 |
container = create_component( |
| 276 |
"card-carousel", |
| 277 |
[ |
| 278 |
"sd-sphinx-override", |
| 279 |
"sd-cards-carousel", |
| 280 |
f"sd-card-cols-{cols}", |
| 281 |
*self.options.get("class", []), |
| 282 |
], |
| 283 |
) |
| 284 |
self.set_source_info(container) |
| 285 |
self.state.nested_parse(self.content, self.content_offset, container) |
| 286 |
for item in container.children: |
| 287 |
if not is_component(item, "card"): |
| 288 |
LOGGER.warning( |
| 289 |
"All children of a 'card-carousel' " |
| 290 |
f"should be 'card' [{WARNING_TYPE}.card]", |
| 291 |
location=item, |
| 292 |
type=WARNING_TYPE, |
| 293 |
subtype="card", |
| 294 |
) |
| 295 |
break |
| 296 |
return [container] |