Debian Codegraph @

doc/sphinx/_extensions/flex_grid.py

raw symbols SCIP
1 '''
2 Copyright (C) 2020 by Jeremy Tan
3
4 Distributed under the original FontForge BSD 3-clause license.
5 Based on the docutils table code, which is released into the public domain.
6
7 -------------------------------------------------------------------------------
8
9 Adds (HTML only) support for a flex-grid directive that allows writing
10 out elements in a generic grid fashion.
11
12 Example:
13
14 .. flex-grid::
15 :class: custom_class
16
17 * - Row 1 Col 1
18 - Row 1 Col 2
19 - Row 1 col 3
20 * :flex-widths: 1 2
21 - Row 2 Col 1
22 - Row 2 Col 2
23
24 The syntax is very similar to the docutils list-table directive. However the
25 number of columns per row does *not* need to be homogeneous.
26
27 The flex-widths parameter is specified on a per-row basis. It should be a list
28 of numbers whose length is equal to the number of columns in that row. It
29 represents the ratio of space taken by that column. For example, with two
30 columns and a flex-widths of '1 2', the proportion of space taken is 1:2
31 between the first and second columns. A value of 0 disables flexing that
32 column.
33 '''
34
35 from docutils import nodes, statemachine
36 from docutils.utils import SystemMessagePropagation
37 from docutils.parsers.rst import Directive
38 from docutils.parsers.rst import directives
39
40
41 class flex_grid(nodes.General, nodes.Element): pass
42 class flex_row(nodes.Part, nodes.Element): pass
43 class flex_col(nodes.Part, nodes.Element): pass
44
45
46 class FlexGrid(Directive):
47
48 final_argument_whitespace = True
49 option_spec = {'class': directives.class_option, 'name': directives.unchanged}
50 has_content = True
51 valid_flexes = set((0, 1, 2, 3, 4, 5))
52
53 def run(self):
54 if not self.content:
55 error = self.state_machine.reporter.error(
56 'The "%s" directive is empty; content required.' % self.name,
57 nodes.literal_block(self.block_text, self.block_text),
58 line=self.lineno)
59 return [error]
60
61 node = nodes.Element() # anonymous container for parsing
62 self.state.nested_parse(self.content, self.content_offset, node)
63
64 try:
65 grid_data = self.get_grid(node)
66 except SystemMessagePropagation as detail:
67 return [detail.args[0]]
68
69 grid_node = self.build_grid_node(grid_data)
70 return [grid_node]
71
72 def get_grid(self, node):
73 if len(node) != 1 or not isinstance(node[0], nodes.bullet_list):
74 error = self.state_machine.reporter.error(
75 'Error parsing content block for the "%s" directive: '
76 'exactly one bullet list expected.' % self.name,
77 nodes.literal_block(self.block_text, self.block_text),
78 line=self.lineno)
79 raise SystemMessagePropagation(error)
80
81 grid = []
82 list_node = node[0]
83
84 for item_index in range(len(list_node)):
85 item = list_node[item_index]
86 nitems = len(item)
87 if not nitems or nitems > 2 or not isinstance(item[-1], nodes.bullet_list):
88 error = self.state_machine.reporter.error(
89 'Error parsing content block for the "%s" directive: '
90 'two-level bullet list expected, but row %s does not '
91 'contain a second-level bullet list.'
92 % (self.name, item_index + 1), nodes.literal_block(
93 self.block_text, self.block_text), line=self.lineno)
94 raise SystemMessagePropagation(error)
95 elif nitems == 2 and not isinstance(item[0], nodes.field_list):
96 error = self.state_machine.reporter.error(
97 'Error parsing content block for the "%s" directive: '
98 'expected options as a field list, but row %s does not '
99 'start with a field list.'
100 % (self.name, item_index + 1), nodes.literal_block(
101 self.block_text, self.block_text), line=self.lineno)
102 raise SystemMessagePropagation(error)
103
104 if nitems == 1:
105 row = ({}, [col.children for col in item[0]])
106 else:
107 opts = {}
108 for opt in item[0]:
109 key = opt[0].rawsource
110 value = opt[1].rawsource.strip()
111
112 if key != 'flex-widths':
113 error = self.state_machine.reporter.error(
114 'Error parsing content block for the "%s" directive: '
115 'received "%s" but only "flex-widths" is supported as '
116 'an option on row %s.'
117 % (self.name, key, item_index + 1), nodes.literal_block(
118 self.block_text, self.block_text), line=self.lineno)
119 raise SystemMessagePropagation(error)
120
121 try:
122 sep = ',' if ',' in value else ' '
123 fwidths = [int(x) for x in value.split(sep)]
124 if any(x not in self.valid_flexes for x in fwidths) or len(fwidths) != len(item[1]):
125 raise ValueError('invalid flex widths')
126 opts['flex-widths'] = fwidths
127 except:
128 error = self.state_machine.reporter.error(
129 'Error parsing content block for the "%s" directive: '
130 '"flex-widths" expects a list of %s widths with possible values of (1,2,3,4,5).'
131 'The input "%s" for row %s is malformed.'
132 % (self.name, len(item[1]), value, item_index + 1), nodes.literal_block(
133 self.block_text, self.block_text), line=self.lineno)
134 raise SystemMessagePropagation(error)
135 row = (opts, [col.children for col in item[1]])
136 grid.append(row)
137 return grid
138
139 def build_grid_node(self, grid_data):
140 grid = flex_grid()
141 self.add_name(grid)
142 grid['classes'] += ['flex-container']
143 grid['classes'] += self.options.get('class', [])
144 for row_opts, row in grid_data:
145 row_node = flex_row()
146 row_node['classes'] += ['flex-row']
147 widths = row_opts.get('flex-widths')
148
149 for i, cell in enumerate(row):
150 entry = flex_col()
151 entry['classes'] += ['flex-col']
152 if widths:
153 width = widths[i]
154 if width == 0:
155 entry['classes'] += ['flex-none']
156 elif width != 1:
157 entry['classes'] += ['flex-{}'.format(width)]
158 entry += cell
159 row_node += entry
160 grid += row_node
161 return grid
162
163
164 def visit_flex_node(self, node):
165 self.body.append(self.starttag(node, 'div'))
166
167 def depart_flex_node(self, node):
168 self.body.append('</div>\n')
169
170
171 def setup(app):
172 app.add_directive('flex-grid', FlexGrid)
173 app.add_node(flex_grid, html=(visit_flex_node, depart_flex_node))
174 app.add_node(flex_row, html=(visit_flex_node, depart_flex_node))
175 app.add_node(flex_col, html=(visit_flex_node, depart_flex_node))
176
177 return {
178 'version': '1.0.0',
179 'env_version': 1,
180 'parallel_read_safe': True
181 }