Debian Codegraph @

sphinx_design/grids.py

raw
1 from docutils import nodes
2 from docutils.parsers.rst import directives
3 from sphinx.application import Sphinx
4 from sphinx.util.logging import getLogger
5
6 from .cards import CardDirective
7 from .shared import (
8 WARNING_TYPE,
9 SdDirective,
10 create_component,
11 is_component,
12 make_choice,
13 margin_option,
14 padding_option,
15 text_align,
16 )
17
18 LOGGER = getLogger(__name__)
19
20
21 DIRECTIVE_NAME_GRID = "grid"
22 DIRECTIVE_NAME_GRID_ITEM = "grid-item"
23 DIRECTIVE_NAME_GRID_ITEM_CARD = "grid-item-card"
24
25
26 def setup_grids(app: Sphinx):
27 """Setup the grid components."""
28 app.add_directive(DIRECTIVE_NAME_GRID, GridDirective)
29 app.add_directive(DIRECTIVE_NAME_GRID_ITEM, GridItemDirective)
30 app.add_directive(DIRECTIVE_NAME_GRID_ITEM_CARD, GridItemCardDirective)
31
32
33 def _media_option(
34 argument: str | None,
35 prefix: str,
36 *,
37 allow_auto: bool = False,
38 min_num: int = 1,
39 max_num: int = 12,
40 ) -> list[str]:
41 """Validate the number of columns (out of 12).
42
43 One or four integers (for "xs sm md lg") between 1 and 12.
44 """
45 validate_error_msg = (
46 "argument must be 1 or 4 (xs sm md lg) values, and each value should be "
47 f"{'either auto or ' if allow_auto else ''}an integer from {min_num} to {max_num}"
48 )
49 if argument is None:
50 raise ValueError(validate_error_msg)
51 values = argument.strip().split()
52 if len(values) == 1:
53 values = [values[0], values[0], values[0], values[0]]
54 if len(values) != 4:
55 raise ValueError(validate_error_msg)
56 for value in values:
57 if allow_auto and value == "auto":
58 continue
59 try:
60 int_value = int(value)
61 except Exception as exc:
62 raise ValueError(validate_error_msg) from exc
63 if not (min_num <= int_value <= max_num):
64 raise ValueError(validate_error_msg)
65 return [f"{prefix}{values[0]}"] + [
66 f"{prefix}{size}-{value}"
67 for size, value in zip(["xs", "sm", "md", "lg"], values, strict=False)
68 ]
69
70
71 def row_columns_option(argument: str | None) -> list[str]:
72 """Validate the number of columns (out of 12) a grid row will have.
73
74 One or four integers (for "xs sm md lg") between 1 and 12 (or 'auto').
75 """
76 return _media_option(argument, "sd-row-cols-", allow_auto=True)
77
78
79 def item_columns_option(argument: str | None) -> list[str]:
80 """Validate the number of columns (out of 12) a grid-item will take up.
81
82 One or four integers (for "xs sm md lg") between 1 and 12 (or 'auto').
83 """
84 return _media_option(argument, "sd-col-", allow_auto=True)
85
86
87 def gutter_option(argument: str | None) -> list[str]:
88 """Validate the gutter size between grid items.
89
90 One or four integers (for "xs sm md lg") between 0 and 5.
91 """
92 return _media_option(argument, "sd-g-", min_num=0, max_num=5)
93
94
95 class GridDirective(SdDirective):
96 """A grid component, which is a container for grid items (i.e. columns)."""
97
98 has_content = True
99 required_arguments = 0
100 optional_arguments = 1 # columns
101 final_argument_whitespace = True
102 option_spec = {
103 "gutter": gutter_option,
104 "margin": margin_option,
105 "padding": padding_option,
106 "outline": directives.flag,
107 "reverse": directives.flag,
108 "class-container": directives.class_option,
109 "class-row": directives.class_option,
110 }
111
112 def run_with_defaults(self) -> list[nodes.Node]:
113 try:
114 column_classes = (
115 row_columns_option(self.arguments[0]) if self.arguments else []
116 )
117 except ValueError as exc:
118 raise self.error(f"Invalid directive argument: {exc}") from exc
119 self.assert_has_content()
120 # container-fluid is 100% width for all breakpoints,
121 # rather than the fixed width of the breakpoint (like container)
122 grid_classes = ["sd-container-fluid", "sd-sphinx-override"]
123 container = create_component(
124 "grid-container",
125 grid_classes
126 + self.options.get("margin", ["sd-mb-4"])
127 + self.options.get("padding", [])
128 + (["sd-border-1"] if "outline" in self.options else [])
129 + self.options.get("class-container", []),
130 )
131 self.set_source_info(container)
132 row = create_component(
133 "grid-row",
134 ["sd-row"]
135 + column_classes
136 + self.options.get("gutter", [])
137 + (["sd-flex-row-reverse"] if "reverse" in self.options else [])
138 + self.options.get("class-row", []),
139 )
140 self.set_source_info(row)
141 container += row
142 self.state.nested_parse(self.content, self.content_offset, row)
143 # each item in a row should be a column
144 for item in row.children:
145 if not is_component(item, "grid-item"):
146 LOGGER.warning(
147 f"All children of a 'grid-row' "
148 f"should be 'grid-item' [{WARNING_TYPE}.grid]",
149 location=item,
150 type=WARNING_TYPE,
151 subtype="grid",
152 )
153 break
154 return [container]
155
156
157 class GridItemDirective(SdDirective):
158 """An item within a grid row.
159
160 Can "occupy" 1 to 12 columns.
161 """
162
163 has_content = True
164 option_spec = {
165 "columns": item_columns_option,
166 "margin": margin_option,
167 "padding": padding_option,
168 "child-direction": make_choice(["column", "row"]),
169 "child-align": make_choice(["start", "end", "center", "justify", "spaced"]),
170 "outline": directives.flag,
171 "class": directives.class_option,
172 }
173
174 def run_with_defaults(self) -> list[nodes.Node]:
175 if not is_component(self.state_machine.node, "grid-row"):
176 LOGGER.warning(
177 f"The parent of a 'grid-item' should be a 'grid-row' [{WARNING_TYPE}.grid]",
178 location=(self.env.docname, self.lineno),
179 type=WARNING_TYPE,
180 subtype="grid",
181 )
182 column = create_component(
183 "grid-item",
184 [
185 "sd-col",
186 f"sd-d-flex-{self.options.get('child-direction', 'column')}",
187 ]
188 + self.options.get("columns", [])
189 + self.options.get("margin", [])
190 + self.options.get("padding", [])
191 + (
192 [f"sd-align-major-{self.options['child-align']}"]
193 if "child-align" in self.options
194 else []
195 )
196 + (["sd-border-1"] if "outline" in self.options else [])
197 + self.options.get("class", []),
198 )
199 self.set_source_info(column)
200 self.state.nested_parse(self.content, self.content_offset, column)
201 return [column]
202
203
204 class GridItemCardDirective(SdDirective):
205 """An item within a grid row, with an internal card."""
206
207 has_content = True
208 required_arguments = 0
209 optional_arguments = 1 # card title
210 final_argument_whitespace = True
211 option_spec = {
212 "columns": item_columns_option,
213 "margin": margin_option,
214 "padding": padding_option,
215 "class-item": directives.class_option,
216 # The options below must be sync'ed with CardDirective.option_spec (minus margin).
217 "width": make_choice(["auto", "25%", "50%", "75%", "100%"]),
218 "text-align": text_align,
219 "img-background": directives.uri,
220 "img-top": directives.uri,
221 "img-bottom": directives.uri,
222 "img-alt": directives.unchanged,
223 "link": directives.uri,
224 "link-type": make_choice(["url", "any", "ref", "doc"]),
225 "link-alt": directives.unchanged,
226 "shadow": make_choice(["none", "sm", "md", "lg"]),
227 "class-card": directives.class_option,
228 "class-body": directives.class_option,
229 "class-title": directives.class_option,
230 "class-header": directives.class_option,
231 "class-footer": directives.class_option,
232 "class-img-top": directives.class_option,
233 "class-img-bottom": directives.class_option,
234 }
235
236 def run_with_defaults(self) -> list[nodes.Node]:
237 if not is_component(self.state_machine.node, "grid-row"):
238 LOGGER.warning(
239 f"The parent of a 'grid-item' should be a 'grid-row' [{WARNING_TYPE}.grid]",
240 location=(self.env.docname, self.lineno),
241 type=WARNING_TYPE,
242 subtype="grid",
243 )
244 column = create_component(
245 "grid-item",
246 [
247 "sd-col",
248 "sd-d-flex-row",
249 *self.options.get("columns", []),
250 *self.options.get("margin", []),
251 *self.options.get("padding", []),
252 *self.options.get("class-item", []),
253 ],
254 )
255 card_options = {
256 key: value
257 for key, value in self.options.items()
258 if key
259 in [
260 "width",
261 "text-align",
262 "img-background",
263 "img-top",
264 "img-bottom",
265 "img-alt",
266 "link",
267 "link-type",
268 "link-alt",
269 "shadow",
270 "class-card",
271 "class-body",
272 "class-title",
273 "class-header",
274 "class-footer",
275 "class-img-top",
276 "class-img-bottom",
277 ]
278 }
279 if "width" not in card_options:
280 card_options["width"] = "100%"
281 card_options["margin"] = []
282 card = CardDirective.create_card(self, self.arguments, card_options)
283 column += card
284 return [column]