doxtr-smart-table 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doxtr_smart_table/__init__.py +124 -0
- doxtr_smart_table/ast_builder.py +290 -0
- doxtr_smart_table/builders/__init__.py +14 -0
- doxtr_smart_table/builders/confluence.py +74 -0
- doxtr_smart_table/builders/epub.py +21 -0
- doxtr_smart_table/builders/html.py +113 -0
- doxtr_smart_table/builders/latex.py +101 -0
- doxtr_smart_table/directive.py +458 -0
- doxtr_smart_table/exporters.py +288 -0
- doxtr_smart_table/formulas.py +348 -0
- doxtr_smart_table/pipeline.py +797 -0
- doxtr_smart_table/static/smart-table.css +189 -0
- doxtr_smart_table/static/smart-table.js +238 -0
- doxtr_smart_table/theme_adapter.py +142 -0
- doxtr_smart_table-0.1.0.dist-info/METADATA +43 -0
- doxtr_smart_table-0.1.0.dist-info/RECORD +19 -0
- doxtr_smart_table-0.1.0.dist-info/WHEEL +5 -0
- doxtr_smart_table-0.1.0.dist-info/licenses/LICENSE +21 -0
- doxtr_smart_table-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Unified Sphinx smart-table extension."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Dict
|
|
8
|
+
|
|
9
|
+
from docutils.parsers.rst import directives as rst_directives
|
|
10
|
+
from sphinx.util import logging
|
|
11
|
+
|
|
12
|
+
from doxtr_data_core import add_config_value_if_missing
|
|
13
|
+
|
|
14
|
+
from .builders import (
|
|
15
|
+
SmartTableConfluencePostTransform,
|
|
16
|
+
SmartTableEpubPostTransform,
|
|
17
|
+
SmartTableHtmlPostTransform,
|
|
18
|
+
SmartTableLatexPostTransform,
|
|
19
|
+
register_latex_preamble,
|
|
20
|
+
)
|
|
21
|
+
from .directive import (
|
|
22
|
+
CSVTableWithTotalCompatDirective,
|
|
23
|
+
SmartTableCsvDirective,
|
|
24
|
+
SmartTableDirective,
|
|
25
|
+
SmartTableListDirective,
|
|
26
|
+
SmartTableSheetDirective,
|
|
27
|
+
)
|
|
28
|
+
from .exporters import copy_exports_to_outdir
|
|
29
|
+
|
|
30
|
+
__version__ = "0.1.0"
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _autoload_theme_core(app: Any) -> None:
|
|
36
|
+
if not getattr(app.config, "doxtr_smart_table_autoload_theme_core", True):
|
|
37
|
+
return
|
|
38
|
+
if importlib.util.find_spec("doxtr_theme_core") is None:
|
|
39
|
+
return
|
|
40
|
+
try:
|
|
41
|
+
app.setup_extension("doxtr_theme_core")
|
|
42
|
+
except Exception as exc: # pragma: no cover
|
|
43
|
+
logger.debug("[doxtr-smart-table] could not auto-load doxtr_theme_core: %s", exc)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _register_dynacsv_compat(app: Any, config: Any) -> None:
|
|
47
|
+
if not getattr(config, "doxtr_smart_table_dynacsv_compat", True):
|
|
48
|
+
return
|
|
49
|
+
exts = getattr(config, "extensions", None) or []
|
|
50
|
+
if "doxtr_dynacsv" in exts:
|
|
51
|
+
return
|
|
52
|
+
# Avoid overriding an already-registered directive (e.g. if doxtr_dynacsv loaded directly)
|
|
53
|
+
existing = getattr(rst_directives, "_directives", {})
|
|
54
|
+
if "csv-table-with-total" in existing:
|
|
55
|
+
return
|
|
56
|
+
app.add_directive("csv-table-with-total", CSVTableWithTotalCompatDirective)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _register_static_assets(app: Any) -> None:
|
|
60
|
+
builder = getattr(app, "builder", None)
|
|
61
|
+
bname = getattr(builder, "name", "") if builder else ""
|
|
62
|
+
bfmt = getattr(builder, "format", "") if builder else ""
|
|
63
|
+
|
|
64
|
+
static_dir = str((Path(__file__).resolve().parent / "static"))
|
|
65
|
+
if hasattr(app.config, "html_static_path"):
|
|
66
|
+
if static_dir not in app.config.html_static_path:
|
|
67
|
+
app.config.html_static_path.append(static_dir)
|
|
68
|
+
|
|
69
|
+
if bfmt == "html" or bname in ("html", "dirhtml", "singlehtml", "readthedocs", "epub", "epub3"):
|
|
70
|
+
app.add_css_file("smart-table.css")
|
|
71
|
+
|
|
72
|
+
if bname in ("html", "dirhtml", "singlehtml", "readthedocs"):
|
|
73
|
+
app.add_js_file("smart-table.js")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _reset_export_registry(app: Any) -> None:
|
|
77
|
+
if getattr(app, "env", None) is not None:
|
|
78
|
+
app.env._doxtr_smart_table_exports = {}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def setup(app: Any) -> Dict[str, Any]:
|
|
82
|
+
"""Sphinx extension entry point for ``doxtr_smart_table``."""
|
|
83
|
+
try:
|
|
84
|
+
app.setup_extension("doxtr_data_core")
|
|
85
|
+
except Exception as exc: # pragma: no cover
|
|
86
|
+
logger.debug("[doxtr-smart-table] could not setup doxtr_data_core: %s", exc)
|
|
87
|
+
|
|
88
|
+
add_config_value_if_missing(app, "doxtr_smart_table_interactive", True, "env")
|
|
89
|
+
add_config_value_if_missing(app, "doxtr_smart_table_export", [], "env", types=(list, tuple))
|
|
90
|
+
add_config_value_if_missing(app, "doxtr_smart_table_dynacsv_compat", True, "env", types=(bool,))
|
|
91
|
+
add_config_value_if_missing(app, "doxtr_smart_table_functions", {}, "env", types=(dict,))
|
|
92
|
+
add_config_value_if_missing(app, "doxtr_smart_table_query_fail_open", False, "env", types=(bool,))
|
|
93
|
+
add_config_value_if_missing(app, "doxtr_smart_table_period_calendars", {}, "env", types=(dict,))
|
|
94
|
+
add_config_value_if_missing(app, "doxtr_smart_table_period_calendars_options", {}, "env", types=(dict,))
|
|
95
|
+
add_config_value_if_missing(app, "doxtr_smart_table_period_resolver_hooks", [], "env", types=(list, tuple))
|
|
96
|
+
add_config_value_if_missing(app, "doxtr_smart_table_business_days", None, "env")
|
|
97
|
+
add_config_value_if_missing(app, "doxtr_smart_table_autoload_theme_core", True, "env", types=(bool,))
|
|
98
|
+
add_config_value_if_missing(app, "doxtr_smart_table_use_theme_core", "auto", "env")
|
|
99
|
+
add_config_value_if_missing(app, "doxtr_smart_table_csv_bom", False, "env", types=(bool,))
|
|
100
|
+
|
|
101
|
+
_autoload_theme_core(app)
|
|
102
|
+
|
|
103
|
+
app.add_directive("smart-table", SmartTableDirective)
|
|
104
|
+
app.add_directive("smart-table-csv", SmartTableCsvDirective)
|
|
105
|
+
app.add_directive("smart-table-list", SmartTableListDirective)
|
|
106
|
+
app.add_directive("smart-table-sheet", SmartTableSheetDirective)
|
|
107
|
+
|
|
108
|
+
app.add_post_transform(SmartTableHtmlPostTransform)
|
|
109
|
+
app.add_post_transform(SmartTableLatexPostTransform)
|
|
110
|
+
app.add_post_transform(SmartTableEpubPostTransform)
|
|
111
|
+
app.add_post_transform(SmartTableConfluencePostTransform)
|
|
112
|
+
|
|
113
|
+
app.connect("config-inited", _register_dynacsv_compat, priority=910)
|
|
114
|
+
app.connect("config-inited", register_latex_preamble, priority=920)
|
|
115
|
+
app.connect("builder-inited", _reset_export_registry)
|
|
116
|
+
app.connect("builder-inited", _register_static_assets)
|
|
117
|
+
app.connect("env-updated", copy_exports_to_outdir)
|
|
118
|
+
app.connect("build-finished", copy_exports_to_outdir)
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
"version": __version__,
|
|
122
|
+
"parallel_read_safe": True,
|
|
123
|
+
"parallel_write_safe": True,
|
|
124
|
+
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""Docutils ``nodes.table`` AST builder for ``doxtr-smart-table``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import logging
|
|
7
|
+
from typing import Any, Dict, List, Optional, Sequence, Set
|
|
8
|
+
|
|
9
|
+
from docutils import nodes
|
|
10
|
+
from docutils.statemachine import ViewList
|
|
11
|
+
|
|
12
|
+
from doxtr_data_core.links import XLinkResolver
|
|
13
|
+
from doxtr_data_core.model import Cell, Row, TableModel, resolve_column_index
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _resolve_xlink_node_class():
|
|
19
|
+
try:
|
|
20
|
+
from doxtr_xlink import xlink_reference
|
|
21
|
+
return xlink_reference
|
|
22
|
+
except ImportError:
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _parse_rst_into_entry(
|
|
27
|
+
state: Any,
|
|
28
|
+
text: str,
|
|
29
|
+
entry: nodes.entry,
|
|
30
|
+
source_name: str,
|
|
31
|
+
) -> None:
|
|
32
|
+
if not text:
|
|
33
|
+
return
|
|
34
|
+
vl = ViewList()
|
|
35
|
+
for idx, line in enumerate(text.splitlines()):
|
|
36
|
+
vl.append(line, source_name, idx)
|
|
37
|
+
state.nested_parse(vl, 0, entry)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _wrap_summary_strong(entry: nodes.entry) -> None:
|
|
41
|
+
"""Ensure summary-row entry text renders bold across all Sphinx builders."""
|
|
42
|
+
for child in entry.children:
|
|
43
|
+
if isinstance(child, nodes.paragraph):
|
|
44
|
+
already_strong = (
|
|
45
|
+
len(child.children) == 1 and isinstance(child.children[0], nodes.strong)
|
|
46
|
+
)
|
|
47
|
+
if not already_strong and child.children:
|
|
48
|
+
strong = nodes.strong()
|
|
49
|
+
for gchild in list(child.children):
|
|
50
|
+
strong += gchild
|
|
51
|
+
del child[:]
|
|
52
|
+
child += strong
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _render_xlink_column_cell(
|
|
56
|
+
raw: str,
|
|
57
|
+
entry: nodes.entry,
|
|
58
|
+
resolver: Optional[XLinkResolver],
|
|
59
|
+
app: Any,
|
|
60
|
+
state: Any,
|
|
61
|
+
source_name: str,
|
|
62
|
+
*,
|
|
63
|
+
is_summary: bool,
|
|
64
|
+
) -> None:
|
|
65
|
+
text = (raw or "").strip()
|
|
66
|
+
if not text:
|
|
67
|
+
return
|
|
68
|
+
|
|
69
|
+
# If author already wrote explicit :xlink:`...` or RST markup, parse as RST
|
|
70
|
+
if ":xlink:`" in text or "xlink:`" in text:
|
|
71
|
+
_parse_rst_into_entry(state, text, entry, source_name)
|
|
72
|
+
return
|
|
73
|
+
|
|
74
|
+
if resolver is not None:
|
|
75
|
+
resolved = resolver.resolve_id(text)
|
|
76
|
+
if resolved is not None:
|
|
77
|
+
url, title = resolved
|
|
78
|
+
label = title or url
|
|
79
|
+
config = getattr(getattr(app, "env", None), "config", None)
|
|
80
|
+
builder_name = getattr(getattr(app, "builder", None), "name", "")
|
|
81
|
+
show_icon = bool(getattr(config, "xlink_render_link_icon", True))
|
|
82
|
+
latex_style = getattr(config, "xlink_latex_show_urls", "no")
|
|
83
|
+
|
|
84
|
+
p = nodes.paragraph()
|
|
85
|
+
if show_icon and builder_name == "html":
|
|
86
|
+
icon = nodes.inline(
|
|
87
|
+
classes=["xlink-icon", "fa-solid", "fa-arrow-up-right-from-square"]
|
|
88
|
+
)
|
|
89
|
+
icon += nodes.Text(" ")
|
|
90
|
+
p += icon
|
|
91
|
+
|
|
92
|
+
xlink_cls = _resolve_xlink_node_class()
|
|
93
|
+
if xlink_cls is not None:
|
|
94
|
+
ref_node = xlink_cls("", label, refuri=url, classes=["xlink-link"], target="_blank")
|
|
95
|
+
ref_node["xlink_latex_style"] = latex_style
|
|
96
|
+
else:
|
|
97
|
+
ref_node = nodes.reference("", label, refuri=url, classes=["xlink-link"], target="_blank")
|
|
98
|
+
|
|
99
|
+
if is_summary:
|
|
100
|
+
strong = nodes.strong()
|
|
101
|
+
strong += ref_node
|
|
102
|
+
p += strong
|
|
103
|
+
else:
|
|
104
|
+
p += ref_node
|
|
105
|
+
entry += p
|
|
106
|
+
return
|
|
107
|
+
|
|
108
|
+
_parse_rst_into_entry(state, text, entry, source_name)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def parse_xlink_columns_option(
|
|
112
|
+
raw: Optional[str],
|
|
113
|
+
header_names: List[str],
|
|
114
|
+
) -> Set[int]:
|
|
115
|
+
"""Resolve ``:xlink-columns:`` (comma-separated indices or names) into column indices."""
|
|
116
|
+
if not raw or not raw.strip():
|
|
117
|
+
return set()
|
|
118
|
+
indices: Set[int] = set()
|
|
119
|
+
for part in raw.split(","):
|
|
120
|
+
tok = part.strip()
|
|
121
|
+
if not tok:
|
|
122
|
+
continue
|
|
123
|
+
indices.add(resolve_column_index(tok, header_names))
|
|
124
|
+
return indices
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def build_table_node(
|
|
128
|
+
model: TableModel,
|
|
129
|
+
*,
|
|
130
|
+
state: Any,
|
|
131
|
+
app: Any,
|
|
132
|
+
table_id: str,
|
|
133
|
+
user_classes: Sequence[str] = (),
|
|
134
|
+
align: Optional[str] = None,
|
|
135
|
+
width: Optional[str] = None,
|
|
136
|
+
widths_mode: Optional[str] = None,
|
|
137
|
+
xlink_col_indices: Set[int] = frozenset(),
|
|
138
|
+
interactive_mode: Any = True,
|
|
139
|
+
exports_meta: Sequence[Dict[str, str]] = (),
|
|
140
|
+
source_name: str = "<smart-table>",
|
|
141
|
+
) -> nodes.table:
|
|
142
|
+
"""Build a clean, unwrapped docutils ``nodes.table`` from *model*."""
|
|
143
|
+
model.ensure_rectangular()
|
|
144
|
+
ncols = model.num_cols
|
|
145
|
+
|
|
146
|
+
table = nodes.table()
|
|
147
|
+
classes = list(table.get("classes", []))
|
|
148
|
+
classes.append("doxtr-smart-table")
|
|
149
|
+
for cls in user_classes:
|
|
150
|
+
if cls not in classes:
|
|
151
|
+
classes.append(cls)
|
|
152
|
+
|
|
153
|
+
if widths_mode == "auto":
|
|
154
|
+
if "colwidths-auto" not in classes:
|
|
155
|
+
classes.append("colwidths-auto")
|
|
156
|
+
elif model.col_widths is not None:
|
|
157
|
+
if "colwidths-given" not in classes:
|
|
158
|
+
classes.append("colwidths-given")
|
|
159
|
+
else:
|
|
160
|
+
if "colwidths-auto" not in classes:
|
|
161
|
+
classes.append("colwidths-auto")
|
|
162
|
+
table["classes"] = classes
|
|
163
|
+
|
|
164
|
+
if align:
|
|
165
|
+
table["align"] = align
|
|
166
|
+
if width:
|
|
167
|
+
table["width"] = width
|
|
168
|
+
|
|
169
|
+
if model.title:
|
|
170
|
+
table += nodes.title("", model.title)
|
|
171
|
+
|
|
172
|
+
# Store strictly pickle-safe metadata on the table node for PostTransforms
|
|
173
|
+
table["doxtr_smart_table_meta"] = {
|
|
174
|
+
"table_id": str(table_id),
|
|
175
|
+
"interactive": interactive_mode,
|
|
176
|
+
"exports": [dict(e) for e in exports_meta],
|
|
177
|
+
"summary_count": len(model.summary_rows),
|
|
178
|
+
"body_count": len(model.rows),
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if ncols == 0:
|
|
182
|
+
tgroup = nodes.tgroup(cols=1)
|
|
183
|
+
tgroup += nodes.colspec(colwidth=100)
|
|
184
|
+
tbody = nodes.tbody()
|
|
185
|
+
empty_row = nodes.row()
|
|
186
|
+
empty_row += nodes.entry()
|
|
187
|
+
tbody += empty_row
|
|
188
|
+
tgroup += tbody
|
|
189
|
+
table += tgroup
|
|
190
|
+
return table
|
|
191
|
+
|
|
192
|
+
tgroup = nodes.tgroup(cols=ncols)
|
|
193
|
+
table += tgroup
|
|
194
|
+
|
|
195
|
+
equal_width = max(1, round(100 / ncols))
|
|
196
|
+
for idx in range(ncols):
|
|
197
|
+
colspec = nodes.colspec()
|
|
198
|
+
if model.col_widths is not None and idx < len(model.col_widths):
|
|
199
|
+
colspec["colwidth"] = model.col_widths[idx]
|
|
200
|
+
else:
|
|
201
|
+
colspec["colwidth"] = equal_width
|
|
202
|
+
if idx < model.stub_columns:
|
|
203
|
+
colspec["stub"] = 1
|
|
204
|
+
tgroup += colspec
|
|
205
|
+
|
|
206
|
+
resolver = XLinkResolver(app, warned_env_key="_doxtr_smart_table_warned") if xlink_col_indices and app is not None else None
|
|
207
|
+
|
|
208
|
+
def _build_row_node(row: Row, *, is_header: bool) -> nodes.row:
|
|
209
|
+
rnode = nodes.row()
|
|
210
|
+
rclasses = list(rnode.get("classes", []))
|
|
211
|
+
for cls in row.classes:
|
|
212
|
+
if cls not in rclasses:
|
|
213
|
+
rclasses.append(cls)
|
|
214
|
+
if row.is_summary and "doxtr-smart-table-summary" not in rclasses:
|
|
215
|
+
rclasses.append("doxtr-smart-table-summary")
|
|
216
|
+
if row.tone:
|
|
217
|
+
tcls = f"doxtr-tone-{row.tone}"
|
|
218
|
+
if tcls not in rclasses:
|
|
219
|
+
rclasses.append(tcls)
|
|
220
|
+
if rclasses:
|
|
221
|
+
rnode["classes"] = rclasses
|
|
222
|
+
|
|
223
|
+
for col_idx, cell in enumerate(row.cells):
|
|
224
|
+
if cell.is_covered:
|
|
225
|
+
continue
|
|
226
|
+
entry = nodes.entry()
|
|
227
|
+
if cell.colspan > 1:
|
|
228
|
+
entry["morecols"] = cell.colspan - 1
|
|
229
|
+
if cell.rowspan > 1:
|
|
230
|
+
entry["morerows"] = cell.rowspan - 1
|
|
231
|
+
if cell.align:
|
|
232
|
+
entry["align"] = cell.align
|
|
233
|
+
eclasses = list(entry.get("classes", []))
|
|
234
|
+
if cell.tone:
|
|
235
|
+
eclasses.append(f"doxtr-tone-{cell.tone}")
|
|
236
|
+
elif row.tone and not is_header:
|
|
237
|
+
# Propagate row tone marker for simpler cell styling across backends
|
|
238
|
+
eclasses.append(f"doxtr-row-tone-{row.tone}")
|
|
239
|
+
if row.is_summary:
|
|
240
|
+
eclasses.append("doxtr-smart-table-summary-cell")
|
|
241
|
+
if eclasses:
|
|
242
|
+
entry["classes"] = eclasses
|
|
243
|
+
|
|
244
|
+
if not is_header and col_idx in xlink_col_indices:
|
|
245
|
+
_render_xlink_column_cell(
|
|
246
|
+
cell.raw,
|
|
247
|
+
entry,
|
|
248
|
+
resolver,
|
|
249
|
+
app,
|
|
250
|
+
state,
|
|
251
|
+
source_name,
|
|
252
|
+
is_summary=row.is_summary,
|
|
253
|
+
)
|
|
254
|
+
elif cell.nodes is not None:
|
|
255
|
+
for preserved in cell.nodes:
|
|
256
|
+
entry += (preserved.deepcopy() if hasattr(preserved, "deepcopy") else copy.deepcopy(preserved))
|
|
257
|
+
elif model.literal_cells:
|
|
258
|
+
if cell.raw:
|
|
259
|
+
entry += nodes.paragraph("", cell.raw)
|
|
260
|
+
else:
|
|
261
|
+
_parse_rst_into_entry(state, cell.raw, entry, source_name)
|
|
262
|
+
|
|
263
|
+
if row.is_summary:
|
|
264
|
+
_wrap_summary_strong(entry)
|
|
265
|
+
|
|
266
|
+
rnode += entry
|
|
267
|
+
return rnode
|
|
268
|
+
|
|
269
|
+
if model.headers:
|
|
270
|
+
thead = nodes.thead()
|
|
271
|
+
for hrow in model.headers:
|
|
272
|
+
thead += _build_row_node(hrow, is_header=True)
|
|
273
|
+
tgroup += thead
|
|
274
|
+
|
|
275
|
+
tbody = nodes.tbody()
|
|
276
|
+
for brow in model.rows:
|
|
277
|
+
tbody += _build_row_node(brow, is_header=False)
|
|
278
|
+
for srow in model.summary_rows:
|
|
279
|
+
tbody += _build_row_node(srow, is_header=False)
|
|
280
|
+
|
|
281
|
+
# Ensure tbody always has at least one row so LaTeX/Confluence writers stay valid
|
|
282
|
+
if not model.rows and not model.summary_rows:
|
|
283
|
+
empty_row = nodes.row(classes=["doxtr-smart-table-empty"])
|
|
284
|
+
first_entry = nodes.entry(morecols=ncols - 1) if ncols > 1 else nodes.entry()
|
|
285
|
+
first_entry += nodes.paragraph("", "No matching rows.")
|
|
286
|
+
empty_row += first_entry
|
|
287
|
+
tbody += empty_row
|
|
288
|
+
|
|
289
|
+
tgroup += tbody
|
|
290
|
+
return table
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Builder-specific Sphinx PostTransforms for ``doxtr-smart-table``."""
|
|
2
|
+
|
|
3
|
+
from .confluence import SmartTableConfluencePostTransform
|
|
4
|
+
from .epub import SmartTableEpubPostTransform
|
|
5
|
+
from .html import SmartTableHtmlPostTransform
|
|
6
|
+
from .latex import SmartTableLatexPostTransform, register_latex_preamble
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"SmartTableConfluencePostTransform",
|
|
10
|
+
"SmartTableEpubPostTransform",
|
|
11
|
+
"SmartTableHtmlPostTransform",
|
|
12
|
+
"SmartTableLatexPostTransform",
|
|
13
|
+
"register_latex_preamble",
|
|
14
|
+
]
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Confluence PostTransform keeping Storage XHTML clean and attaching exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import posixpath
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Dict, List
|
|
8
|
+
|
|
9
|
+
from docutils import nodes
|
|
10
|
+
from sphinx.addnodes import download_reference
|
|
11
|
+
from sphinx.transforms.post_transforms import SphinxPostTransform
|
|
12
|
+
|
|
13
|
+
from ..exporters import EXPORT_DIR_NAME
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _downgrade_xlink_nodes_in_table(table_node: nodes.table) -> None:
|
|
17
|
+
"""Replace any ``xlink_reference`` nodes and strip HTML-only FA icon spans."""
|
|
18
|
+
for inline in list(table_node.findall(nodes.inline)):
|
|
19
|
+
if "xlink-icon" in inline.get("classes", []):
|
|
20
|
+
inline.parent.remove(inline)
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
from doxtr_xlink import xlink_reference
|
|
24
|
+
except ImportError:
|
|
25
|
+
return
|
|
26
|
+
|
|
27
|
+
for xnode in list(table_node.findall(xlink_reference)):
|
|
28
|
+
ref = nodes.reference(**xnode.attributes)
|
|
29
|
+
ref.extend(xnode.children)
|
|
30
|
+
xnode.replace_self(ref)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SmartTableConfluencePostTransform(SphinxPostTransform):
|
|
34
|
+
"""Keep smart tables valid for ``sphinxcontrib-confluencebuilder``."""
|
|
35
|
+
|
|
36
|
+
default_priority = 450
|
|
37
|
+
builders = ("confluence", "singleconfluence")
|
|
38
|
+
|
|
39
|
+
def run(self, **kwargs: Any) -> None:
|
|
40
|
+
docname = getattr(self.env, "docname", "index")
|
|
41
|
+
docdir = Path(docname).parent.as_posix()
|
|
42
|
+
start_dir = "." if docdir in ("", ".") else docdir
|
|
43
|
+
|
|
44
|
+
for table_node in list(self.document.findall(nodes.table)):
|
|
45
|
+
if "doxtr-smart-table" not in table_node.get("classes", []):
|
|
46
|
+
continue
|
|
47
|
+
if table_node.get("_doxtr_smart_table_conf_done"):
|
|
48
|
+
continue
|
|
49
|
+
table_node["_doxtr_smart_table_conf_done"] = True
|
|
50
|
+
|
|
51
|
+
_downgrade_xlink_nodes_in_table(table_node)
|
|
52
|
+
|
|
53
|
+
meta: Dict[str, Any] = table_node.get("doxtr_smart_table_meta") or {}
|
|
54
|
+
exports: List[Dict[str, str]] = meta.get("exports") or []
|
|
55
|
+
if exports and table_node.parent is not None:
|
|
56
|
+
p = nodes.paragraph(classes=["doxtr-smart-table-confluence-exports"])
|
|
57
|
+
p += nodes.strong("", "Exports: ")
|
|
58
|
+
for idx, exp in enumerate(exports):
|
|
59
|
+
if idx > 0:
|
|
60
|
+
p += nodes.Text(" | ")
|
|
61
|
+
fmt = str(exp.get("format", "")).upper()
|
|
62
|
+
fname = str(exp.get("filename", ""))
|
|
63
|
+
rel_target = posixpath.relpath(f"{EXPORT_DIR_NAME}/{fname}", start=start_dir)
|
|
64
|
+
dl = download_reference(
|
|
65
|
+
"",
|
|
66
|
+
f"{fmt} ({fname})",
|
|
67
|
+
reftarget=rel_target,
|
|
68
|
+
refdoc=docname,
|
|
69
|
+
refexplicit=True,
|
|
70
|
+
)
|
|
71
|
+
p += dl
|
|
72
|
+
parent = table_node.parent
|
|
73
|
+
t_idx = parent.index(table_node)
|
|
74
|
+
parent.insert(t_idx + 1, p)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""EPUB PostTransform ensuring static, clean table rendering without JS/exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from docutils import nodes
|
|
8
|
+
from sphinx.transforms.post_transforms import SphinxPostTransform
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SmartTableEpubPostTransform(SphinxPostTransform):
|
|
12
|
+
"""Ensure ``doxtr-smart-table`` renders cleanly in static EPUB builds."""
|
|
13
|
+
|
|
14
|
+
default_priority = 450
|
|
15
|
+
builders = ("epub", "epub3")
|
|
16
|
+
|
|
17
|
+
def run(self, **kwargs: Any) -> None:
|
|
18
|
+
for table_node in list(self.document.findall(nodes.table)):
|
|
19
|
+
if "doxtr-smart-table" not in table_node.get("classes", []):
|
|
20
|
+
continue
|
|
21
|
+
table_node["_doxtr_smart_table_epub_done"] = True
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""HTML PostTransform adding interactive sorting, filtering, and export links."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html as html_lib
|
|
6
|
+
import posixpath
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, List
|
|
9
|
+
|
|
10
|
+
from docutils import nodes
|
|
11
|
+
from sphinx.transforms.post_transforms import SphinxPostTransform
|
|
12
|
+
from sphinx.util.osutil import relative_uri
|
|
13
|
+
|
|
14
|
+
from ..exporters import EXPORT_DIR_NAME
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _compute_export_uri(app: Any, docname: str, filename: str) -> str:
|
|
18
|
+
builder = getattr(app, "builder", None)
|
|
19
|
+
if builder is not None and hasattr(builder, "get_target_uri"):
|
|
20
|
+
target_uri = builder.get_target_uri(docname)
|
|
21
|
+
return relative_uri(target_uri, f"{EXPORT_DIR_NAME}/{filename}") or f"{EXPORT_DIR_NAME}/{filename}"
|
|
22
|
+
depth = len(Path(docname).parts) - 1
|
|
23
|
+
prefix = "../" * max(0, depth)
|
|
24
|
+
return f"{prefix}{EXPORT_DIR_NAME}/{filename}"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class SmartTableHtmlPostTransform(SphinxPostTransform):
|
|
28
|
+
"""Wrap ``doxtr-smart-table`` nodes in interactive/export containers for HTML."""
|
|
29
|
+
|
|
30
|
+
default_priority = 450
|
|
31
|
+
builders = ("html", "dirhtml", "singlehtml", "readthedocs")
|
|
32
|
+
|
|
33
|
+
def run(self, **kwargs: Any) -> None:
|
|
34
|
+
import warnings
|
|
35
|
+
|
|
36
|
+
docname = getattr(self.env, "docname", "index")
|
|
37
|
+
with warnings.catch_warnings():
|
|
38
|
+
warnings.simplefilter("ignore")
|
|
39
|
+
app = getattr(self, "app", None)
|
|
40
|
+
|
|
41
|
+
for table_node in list(self.document.findall(nodes.table)):
|
|
42
|
+
if "doxtr-smart-table" not in table_node.get("classes", []):
|
|
43
|
+
continue
|
|
44
|
+
if table_node.get("_doxtr_smart_table_html_done"):
|
|
45
|
+
continue
|
|
46
|
+
table_node["_doxtr_smart_table_html_done"] = True
|
|
47
|
+
|
|
48
|
+
meta: Dict[str, Any] = table_node.get("doxtr_smart_table_meta") or {}
|
|
49
|
+
interactive = meta.get("interactive", True)
|
|
50
|
+
exports: List[Dict[str, str]] = meta.get("exports") or []
|
|
51
|
+
table_id = str(meta.get("table_id", "smart-table"))
|
|
52
|
+
body_count = int(meta.get("body_count", 0))
|
|
53
|
+
|
|
54
|
+
sort_enabled = interactive in (True, "true", "sort")
|
|
55
|
+
filter_enabled = interactive in (True, "true", "filter")
|
|
56
|
+
|
|
57
|
+
if not (sort_enabled or filter_enabled or exports):
|
|
58
|
+
# Still wrap in scroll container so wide tables never clip layout
|
|
59
|
+
scroll = nodes.container(classes=["doxtr-smart-table-scroll"])
|
|
60
|
+
parent = table_node.parent
|
|
61
|
+
if parent is not None:
|
|
62
|
+
idx = parent.index(table_node)
|
|
63
|
+
parent[idx] = scroll
|
|
64
|
+
scroll += table_node
|
|
65
|
+
continue
|
|
66
|
+
|
|
67
|
+
container_classes = ["doxtr-smart-table-container"]
|
|
68
|
+
if sort_enabled:
|
|
69
|
+
container_classes.append("doxtr-smart-table-sortable")
|
|
70
|
+
if filter_enabled:
|
|
71
|
+
container_classes.append("doxtr-smart-table-filterable")
|
|
72
|
+
|
|
73
|
+
container = nodes.container(classes=container_classes, ids=[f"st-{table_id}"])
|
|
74
|
+
|
|
75
|
+
if filter_enabled or exports:
|
|
76
|
+
toolbar_parts: List[str] = ['<div class="doxtr-smart-table-toolbar">']
|
|
77
|
+
if filter_enabled:
|
|
78
|
+
toolbar_parts.append(
|
|
79
|
+
'<div class="doxtr-smart-table-filter-wrap">'
|
|
80
|
+
'<label class="doxtr-smart-table-filter-label">'
|
|
81
|
+
'<span class="doxtr-smart-table-sr-only">Filter table rows</span>'
|
|
82
|
+
'<input type="search" class="doxtr-smart-table-filter-input" '
|
|
83
|
+
'placeholder="Filter rows (use !term to exclude)..." '
|
|
84
|
+
'aria-label="Filter table rows" />'
|
|
85
|
+
"</label>"
|
|
86
|
+
f'<span class="doxtr-smart-table-count" aria-live="polite">{body_count} rows</span>'
|
|
87
|
+
"</div>"
|
|
88
|
+
)
|
|
89
|
+
if exports:
|
|
90
|
+
toolbar_parts.append('<div class="doxtr-smart-table-exports">')
|
|
91
|
+
toolbar_parts.append('<span class="doxtr-smart-table-export-label">Export:</span>')
|
|
92
|
+
for exp in exports:
|
|
93
|
+
fmt = str(exp.get("format", "")).upper()
|
|
94
|
+
fname = str(exp.get("filename", ""))
|
|
95
|
+
uri = _compute_export_uri(app, docname, fname)
|
|
96
|
+
esc_uri = html_lib.escape(uri, quote=True)
|
|
97
|
+
esc_fname = html_lib.escape(posixpath.basename(fname), quote=True)
|
|
98
|
+
esc_fmt = html_lib.escape(fmt)
|
|
99
|
+
toolbar_parts.append(
|
|
100
|
+
f'<a class="doxtr-smart-table-export-btn" href="{esc_uri}" '
|
|
101
|
+
f'download="{esc_fname}">{esc_fmt}</a>'
|
|
102
|
+
)
|
|
103
|
+
toolbar_parts.append("</div>")
|
|
104
|
+
toolbar_parts.append("</div>")
|
|
105
|
+
container += nodes.raw("", "\n".join(toolbar_parts), format="html")
|
|
106
|
+
|
|
107
|
+
scroll = nodes.container(classes=["doxtr-smart-table-scroll"])
|
|
108
|
+
parent = table_node.parent
|
|
109
|
+
if parent is not None:
|
|
110
|
+
idx = parent.index(table_node)
|
|
111
|
+
parent[idx] = container
|
|
112
|
+
scroll += table_node
|
|
113
|
+
container += scroll
|