pyreportkit 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.
Files changed (222) hide show
  1. pyreportkit-0.1.0.dist-info/METADATA +187 -0
  2. pyreportkit-0.1.0.dist-info/RECORD +222 -0
  3. pyreportkit-0.1.0.dist-info/WHEEL +5 -0
  4. pyreportkit-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. pyreportkit-0.1.0.dist-info/top_level.txt +1 -0
  6. reportkit/__init__.py +0 -0
  7. reportkit/components/__init__.py +45 -0
  8. reportkit/components/document/__init__.py +6 -0
  9. reportkit/components/document/footer.py +12 -0
  10. reportkit/components/document/header.py +12 -0
  11. reportkit/components/document/page.py +18 -0
  12. reportkit/components/document/report.py +12 -0
  13. reportkit/components/information/__init__.py +4 -0
  14. reportkit/components/information/info_grid.py +23 -0
  15. reportkit/components/information/key_value.py +28 -0
  16. reportkit/components/layout/__init__.py +9 -0
  17. reportkit/components/layout/box.py +10 -0
  18. reportkit/components/layout/column.py +15 -0
  19. reportkit/components/layout/divider.py +10 -0
  20. reportkit/components/layout/grid.py +12 -0
  21. reportkit/components/layout/row.py +15 -0
  22. reportkit/components/layout/section.py +10 -0
  23. reportkit/components/layout/spacer.py +12 -0
  24. reportkit/components/media/__init__.py +4 -0
  25. reportkit/components/media/chart.py +14 -0
  26. reportkit/components/media/image.py +25 -0
  27. reportkit/components/pagination/__init__.py +5 -0
  28. reportkit/components/pagination/page_break.py +10 -0
  29. reportkit/components/pagination/page_count.py +10 -0
  30. reportkit/components/pagination/page_number.py +21 -0
  31. reportkit/components/table/__init__.py +7 -0
  32. reportkit/components/table/cell.py +27 -0
  33. reportkit/components/table/column.py +29 -0
  34. reportkit/components/table/row.py +25 -0
  35. reportkit/components/table/style.py +18 -0
  36. reportkit/components/table/table.py +27 -0
  37. reportkit/components/typography/__init__.py +6 -0
  38. reportkit/components/typography/heading.py +13 -0
  39. reportkit/components/typography/rich_text.py +23 -0
  40. reportkit/components/typography/text.py +12 -0
  41. reportkit/components/typography/text_span.py +24 -0
  42. reportkit/core/__init__.py +4 -0
  43. reportkit/core/component.py +12 -0
  44. reportkit/core/container.py +66 -0
  45. reportkit/core/exceptions.py +0 -0
  46. reportkit/core/factory.py +53 -0
  47. reportkit/core/registry.py +50 -0
  48. reportkit/core/serializer.py +90 -0
  49. reportkit/exporters/__init__.py +0 -0
  50. reportkit/exporters/base.py +17 -0
  51. reportkit/exporters/excel/__init__.py +8 -0
  52. reportkit/exporters/excel/exceptions.py +4 -0
  53. reportkit/exporters/excel/exporter.py +68 -0
  54. reportkit/exporters/excel/renderers/__init__.py +34 -0
  55. reportkit/exporters/excel/renderers/base.py +27 -0
  56. reportkit/exporters/excel/renderers/information.py +55 -0
  57. reportkit/exporters/excel/renderers/layout/__init__.py +7 -0
  58. reportkit/exporters/excel/renderers/layout/columns.py +48 -0
  59. reportkit/exporters/excel/renderers/layout/data.py +46 -0
  60. reportkit/exporters/excel/renderers/layout/page.py +24 -0
  61. reportkit/exporters/excel/renderers/layout/spacing.py +30 -0
  62. reportkit/exporters/excel/renderers/layout/stack.py +13 -0
  63. reportkit/exporters/excel/renderers/media.py +46 -0
  64. reportkit/exporters/excel/renderers/registry.py +22 -0
  65. reportkit/exporters/excel/renderers/table/__init__.py +4 -0
  66. reportkit/exporters/excel/renderers/table/cells.py +17 -0
  67. reportkit/exporters/excel/renderers/table/data.py +38 -0
  68. reportkit/exporters/excel/renderers/table/renderer.py +64 -0
  69. reportkit/exporters/excel/renderers/table/widths.py +29 -0
  70. reportkit/exporters/excel/renderers/text.py +40 -0
  71. reportkit/exporters/excel/styles.py +130 -0
  72. reportkit/exporters/excel/values/__init__.py +5 -0
  73. reportkit/exporters/excel/values/cells.py +60 -0
  74. reportkit/exporters/excel/values/components.py +16 -0
  75. reportkit/exporters/excel/values/formats.py +31 -0
  76. reportkit/exporters/excel/values/numbers.py +19 -0
  77. reportkit/exporters/excel/workbook/__init__.py +5 -0
  78. reportkit/exporters/excel/workbook/data.py +48 -0
  79. reportkit/exporters/excel/workbook/formatted.py +63 -0
  80. reportkit/exporters/excel/workbook/styles.py +27 -0
  81. reportkit/exporters/excel/workbook/workbook.py +65 -0
  82. reportkit/exporters/excel/worksheet/__init__.py +5 -0
  83. reportkit/exporters/excel/worksheet/borders.py +30 -0
  84. reportkit/exporters/excel/worksheet/cells.py +38 -0
  85. reportkit/exporters/excel/worksheet/constants.py +12 -0
  86. reportkit/exporters/excel/worksheet/data.py +51 -0
  87. reportkit/exporters/excel/worksheet/formatted.py +158 -0
  88. reportkit/exporters/excel/worksheet/page.py +23 -0
  89. reportkit/exporters/html/__init__.py +6 -0
  90. reportkit/exporters/html/assets.py +87 -0
  91. reportkit/exporters/html/direction.py +15 -0
  92. reportkit/exporters/html/engine.py +37 -0
  93. reportkit/exporters/html/exporter.py +38 -0
  94. reportkit/exporters/html/page/__init__.py +3 -0
  95. reportkit/exporters/html/page/components.py +47 -0
  96. reportkit/exporters/html/page/margins.py +24 -0
  97. reportkit/exporters/html/page/numbering.py +31 -0
  98. reportkit/exporters/html/page/resolver.py +37 -0
  99. reportkit/exporters/html/page/running.py +30 -0
  100. reportkit/exporters/html/page/styles.py +22 -0
  101. reportkit/exporters/html/page/validator.py +76 -0
  102. reportkit/exporters/html/registry.py +45 -0
  103. reportkit/exporters/html/renderers/__init__.py +37 -0
  104. reportkit/exporters/html/renderers/base.py +20 -0
  105. reportkit/exporters/html/renderers/document/__init__.py +6 -0
  106. reportkit/exporters/html/renderers/document/footer.py +18 -0
  107. reportkit/exporters/html/renderers/document/header.py +18 -0
  108. reportkit/exporters/html/renderers/document/page.py +17 -0
  109. reportkit/exporters/html/renderers/document/report.py +16 -0
  110. reportkit/exporters/html/renderers/information/__init__.py +4 -0
  111. reportkit/exporters/html/renderers/information/info_grid.py +26 -0
  112. reportkit/exporters/html/renderers/information/key_value.py +18 -0
  113. reportkit/exporters/html/renderers/layout/__init__.py +9 -0
  114. reportkit/exporters/html/renderers/layout/box.py +17 -0
  115. reportkit/exporters/html/renderers/layout/column.py +41 -0
  116. reportkit/exporters/html/renderers/layout/divider.py +16 -0
  117. reportkit/exporters/html/renderers/layout/grid.py +48 -0
  118. reportkit/exporters/html/renderers/layout/row.py +35 -0
  119. reportkit/exporters/html/renderers/layout/section.py +17 -0
  120. reportkit/exporters/html/renderers/layout/spacer.py +18 -0
  121. reportkit/exporters/html/renderers/media/__init__.py +3 -0
  122. reportkit/exporters/html/renderers/media/image.py +18 -0
  123. reportkit/exporters/html/renderers/pagination/__init__.py +4 -0
  124. reportkit/exporters/html/renderers/pagination/page_break.py +15 -0
  125. reportkit/exporters/html/renderers/pagination/page_number.py +15 -0
  126. reportkit/exporters/html/renderers/table/__init__.py +4 -0
  127. reportkit/exporters/html/renderers/table/cell.py +77 -0
  128. reportkit/exporters/html/renderers/table/table.py +69 -0
  129. reportkit/exporters/html/renderers/typography/__init__.py +5 -0
  130. reportkit/exporters/html/renderers/typography/heading.py +18 -0
  131. reportkit/exporters/html/renderers/typography/rich_text.py +28 -0
  132. reportkit/exporters/html/renderers/typography/text.py +16 -0
  133. reportkit/exporters/html/static/base.css +45 -0
  134. reportkit/exporters/html/static/information.css +83 -0
  135. reportkit/exporters/html/static/layout.css +81 -0
  136. reportkit/exporters/html/static/media.css +10 -0
  137. reportkit/exporters/html/static/pdf.css +96 -0
  138. reportkit/exporters/html/static/print.css +91 -0
  139. reportkit/exporters/html/static/table.css +222 -0
  140. reportkit/exporters/html/static/tokens.css +68 -0
  141. reportkit/exporters/html/static/typography.css +54 -0
  142. reportkit/exporters/html/styles.py +167 -0
  143. reportkit/exporters/html/templates/components/document/footer.html +3 -0
  144. reportkit/exporters/html/templates/components/document/header.html +3 -0
  145. reportkit/exporters/html/templates/components/document/page.html +8 -0
  146. reportkit/exporters/html/templates/components/document/report.html +3 -0
  147. reportkit/exporters/html/templates/components/information/info_grid.html +6 -0
  148. reportkit/exporters/html/templates/components/information/key_value.html +9 -0
  149. reportkit/exporters/html/templates/components/layout/box.html +3 -0
  150. reportkit/exporters/html/templates/components/layout/column.html +3 -0
  151. reportkit/exporters/html/templates/components/layout/divider.html +1 -0
  152. reportkit/exporters/html/templates/components/layout/grid.html +3 -0
  153. reportkit/exporters/html/templates/components/layout/row.html +3 -0
  154. reportkit/exporters/html/templates/components/layout/section.html +3 -0
  155. reportkit/exporters/html/templates/components/layout/spacer.html +1 -0
  156. reportkit/exporters/html/templates/components/media/image.html +8 -0
  157. reportkit/exporters/html/templates/components/pagination/page_break.html +1 -0
  158. reportkit/exporters/html/templates/components/pagination/page_number.html +4 -0
  159. reportkit/exporters/html/templates/components/table/cell.html +7 -0
  160. reportkit/exporters/html/templates/components/table/table.html +34 -0
  161. reportkit/exporters/html/templates/components/typography/heading.html +1 -0
  162. reportkit/exporters/html/templates/components/typography/rich_text.html +5 -0
  163. reportkit/exporters/html/templates/components/typography/text.html +1 -0
  164. reportkit/exporters/html/templates/document.html +17 -0
  165. reportkit/exporters/html/templates.py +30 -0
  166. reportkit/exporters/json.py +0 -0
  167. reportkit/exporters/pdf/__init__.py +8 -0
  168. reportkit/exporters/pdf/conversion.py +104 -0
  169. reportkit/exporters/pdf/dependencies.py +12 -0
  170. reportkit/exporters/pdf/exceptions.py +4 -0
  171. reportkit/exporters/pdf/exporter.py +16 -0
  172. reportkit/exporters/pdf/resources/__init__.py +4 -0
  173. reportkit/exporters/pdf/resources/fetcher.py +37 -0
  174. reportkit/exporters/pdf/resources/policy.py +60 -0
  175. reportkit/exporters/registry.py +50 -0
  176. reportkit/exporters/word/__init__.py +8 -0
  177. reportkit/exporters/word/document/__init__.py +4 -0
  178. reportkit/exporters/word/document/document.py +74 -0
  179. reportkit/exporters/word/document/engine.py +71 -0
  180. reportkit/exporters/word/exceptions.py +4 -0
  181. reportkit/exporters/word/exporter.py +32 -0
  182. reportkit/exporters/word/renderers/__init__.py +24 -0
  183. reportkit/exporters/word/renderers/base.py +56 -0
  184. reportkit/exporters/word/renderers/information.py +30 -0
  185. reportkit/exporters/word/renderers/layout/__init__.py +6 -0
  186. reportkit/exporters/word/renderers/layout/columns.py +82 -0
  187. reportkit/exporters/word/renderers/layout/page.py +38 -0
  188. reportkit/exporters/word/renderers/layout/spacing.py +33 -0
  189. reportkit/exporters/word/renderers/layout/stack.py +50 -0
  190. reportkit/exporters/word/renderers/media.py +49 -0
  191. reportkit/exporters/word/renderers/registry.py +22 -0
  192. reportkit/exporters/word/renderers/table/__init__.py +3 -0
  193. reportkit/exporters/word/renderers/table/cells.py +39 -0
  194. reportkit/exporters/word/renderers/table/renderer.py +95 -0
  195. reportkit/exporters/word/renderers/table/widths.py +12 -0
  196. reportkit/exporters/word/renderers/text.py +40 -0
  197. reportkit/exporters/word/styles/__init__.py +3 -0
  198. reportkit/exporters/word/styles/text.py +90 -0
  199. reportkit/exporters/word/styles/xml.py +147 -0
  200. reportkit/exporters/word/values.py +36 -0
  201. reportkit/formatting/__init__.py +0 -0
  202. reportkit/formatting/cell.py +12 -0
  203. reportkit/formatting/cells.py +41 -0
  204. reportkit/formatting/values.py +106 -0
  205. reportkit/rendering/__init__.py +0 -0
  206. reportkit/rendering/context.py +31 -0
  207. reportkit/rendering/table.py +56 -0
  208. reportkit/rendering/tracks.py +51 -0
  209. reportkit/rendering/visitor.py +55 -0
  210. reportkit/report.py +0 -0
  211. reportkit/styles/__init__.py +0 -0
  212. reportkit/styles/borders.py +6 -0
  213. reportkit/styles/style.py +117 -0
  214. reportkit/styles/table.py +37 -0
  215. reportkit/styles/theme.py +45 -0
  216. reportkit/styles/tokens.py +29 -0
  217. reportkit/validators/__init__.py +3 -0
  218. reportkit/validators/table/__init__.py +3 -0
  219. reportkit/validators/table/cell.py +38 -0
  220. reportkit/validators/table/column.py +62 -0
  221. reportkit/validators/table/row.py +37 -0
  222. reportkit/validators/table/table.py +63 -0
@@ -0,0 +1,147 @@
1
+ import re
2
+
3
+ from docx.oxml import OxmlElement
4
+ from docx.oxml.ns import qn
5
+
6
+ from ..exceptions import WordExportError
7
+
8
+ BORDER_LINES = {"solid": "single", "dashed": "dashed", "dotted": "dotted", "double": "double", "none": "nil"}
9
+ SIDES = ("left", "right", "top", "bottom")
10
+ SCHEMA_ORDER = {
11
+ "pPr": ["pStyle", "keepNext", "keepLines", "pageBreakBefore", "framePr", "widowControl", "numPr", "suppressLineNumbers", "pBdr", "shd", "tabs", "suppressAutoHyphens", "kinsoku", "wordWrap", "overflowPunct", "topLinePunct", "autoSpaceDE", "autoSpaceDN", "bidi", "adjustRightInd", "snapToGrid", "spacing", "ind", "contextualSpacing", "mirrorIndents", "suppressOverlap", "jc", "textDirection", "textAlignment", "textboxTightWrap", "outlineLvl", "divId", "cnfStyle", "rPr", "sectPr", "pPrChange"],
12
+ "rPr": ["rStyle", "rFonts", "b", "bCs", "i", "iCs", "caps", "smallCaps", "strike", "dstrike", "outline", "shadow", "emboss", "imprint", "noProof", "snapToGrid", "vanish", "webHidden", "color", "spacing", "w", "kern", "position", "sz", "szCs", "highlight", "u", "effect", "bdr", "shd", "fitText", "vertAlign", "rtl", "cs", "em", "lang", "eastAsianLayout", "specVanish", "oMath"],
13
+ "tcPr": ["cnfStyle", "tcW", "gridSpan", "hMerge", "vMerge", "tcBorders", "shd", "noWrap", "tcMar", "textDirection", "tcFitText", "vAlign", "hideMark"],
14
+ "tblPr": ["tblStyle", "tblpPr", "tblOverlap", "bidiVisual", "tblStyleRowBandSize", "tblStyleColBandSize", "tblW", "jc", "tblCellSpacing", "tblInd", "tblBorders", "shd", "tblLayout", "tblCellMar", "tblLook"],
15
+ "trPr": ["cnfStyle", "divId", "gridBefore", "gridAfter", "wBefore", "wAfter", "cantSplit", "trHeight", "tblHeader", "tblCellSpacing", "jc", "hidden"],
16
+ "tcBorders": ["top", "start", "left", "bottom", "end", "right", "insideH", "insideV", "tl2br", "tr2bl"],
17
+ "tblBorders": ["top", "start", "left", "bottom", "end", "right", "insideH", "insideV"],
18
+ "tblCellMar": ["top", "start", "left", "bottom", "end", "right"],
19
+ "pBdr": ["top", "left", "bottom", "right", "between", "bar"],
20
+ }
21
+
22
+
23
+ def child(parent, tag):
24
+ """
25
+ Return the first child with a tag, creating it at its schema position when missing (Word rejects misordered XML).
26
+ """
27
+ found = parent.find(qn(tag))
28
+ if found is None:
29
+ found, order = OxmlElement(tag), SCHEMA_ORDER[parent.tag.split("}")[1]]
30
+ successors = {qn(f"w:{name}") for name in order[order.index(tag[2:]) + 1:]}
31
+ position = next((index for index, existing in enumerate(parent) if existing.tag in successors), len(parent))
32
+ parent.insert(position, found)
33
+ return found
34
+
35
+
36
+ def set_attributes(element, **values):
37
+ """
38
+ Set w: attributes on an element.
39
+ """
40
+ for name, value in values.items():
41
+ element.set(qn(f"w:{name}"), str(value))
42
+ return element
43
+
44
+
45
+ def hex_color(color):
46
+ """
47
+ Convert a #rgb or #rrggbb color into the RRGGBB form Word uses.
48
+ """
49
+ match = re.fullmatch(r"#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})", (color or "").strip())
50
+ if not match:
51
+ raise WordExportError(f"Word export supports #rgb and #rrggbb colors only, got {color!r}.")
52
+ digits = match.group(1)
53
+ return (digits if len(digits) == 6 else "".join(character * 2 for character in digits)).upper()
54
+
55
+
56
+ def border_attributes(value):
57
+ """
58
+ Convert a CSS border such as "1px solid #dddddd" into Word border attributes (size in eighths of a point).
59
+ """
60
+ width, line, color = (value.split() + ["", "", ""])[:3]
61
+ pixels = float(re.sub(r"[^\d.]", "", width) or 1)
62
+ return {"val": BORDER_LINES.get(line, "single"), "sz": max(2, round(pixels * 0.75 * 8)), "space": 0, "color": hex_color(color) if color else "auto"}
63
+
64
+
65
+ def set_borders(properties, container_tag, sides):
66
+ """
67
+ Write the given CSS borders (side name to value) into a tcBorders, tblBorders or pBdr element.
68
+ """
69
+ borders = child(properties, container_tag)
70
+ for side, value in sides.items():
71
+ if value:
72
+ set_attributes(child(borders, f"w:{side}"), **border_attributes(value))
73
+
74
+
75
+ def set_shading(properties, color):
76
+ """
77
+ Fill a cell or paragraph background.
78
+ """
79
+ set_attributes(child(properties, "w:shd"), val="clear", color="auto", fill=hex_color(color))
80
+
81
+
82
+ def set_cell_width(cell, width):
83
+ """
84
+ Fix a cell width in twips, since Word ignores column widths alone.
85
+ """
86
+ set_attributes(child(cell._tc.get_or_add_tcPr(), "w:tcW"), w=int(width.twips), type="dxa")
87
+
88
+
89
+ def set_bidi_table(table):
90
+ """
91
+ Lay a table out right to left, so its first column sits on the right.
92
+ """
93
+ child(table._tbl.tblPr, "w:bidiVisual")
94
+
95
+
96
+ def set_fixed_layout(table):
97
+ """
98
+ Keep the declared column widths instead of Word's automatic fit.
99
+ """
100
+ set_attributes(child(table._tbl.tblPr, "w:tblLayout"), type="fixed")
101
+
102
+
103
+ def clear_table_borders(table):
104
+ """
105
+ Remove every table border, for layout grids.
106
+ """
107
+ set_borders(table._tbl.tblPr, "w:tblBorders", {side: "0px none" for side in (*SIDES, "insideH", "insideV")})
108
+
109
+
110
+ def set_cell_margins(table, vertical):
111
+ """
112
+ Pad every cell of a table above and below, in twips.
113
+ """
114
+ margins = child(table._tbl.tblPr, "w:tblCellMar")
115
+ for side in ("top", "bottom"):
116
+ set_attributes(child(margins, f"w:{side}"), w=vertical, type="dxa")
117
+
118
+
119
+ def set_row_flags(row, repeat_header=False, cant_split=False):
120
+ """
121
+ Mark a row as a repeated header and/or as not splitting across pages.
122
+ """
123
+ properties = row._tr.get_or_add_trPr()
124
+ if repeat_header:
125
+ child(properties, "w:tblHeader")
126
+ if cant_split:
127
+ child(properties, "w:cantSplit")
128
+
129
+
130
+ def set_bidi_paragraph(paragraph):
131
+ """
132
+ Make a paragraph right to left.
133
+ """
134
+ child(paragraph._p.get_or_add_pPr(), "w:bidi")
135
+
136
+
137
+ def add_field(paragraph, instruction):
138
+ """
139
+ Append a simple field such as PAGE or NUMPAGES.
140
+ """
141
+ field = set_attributes(OxmlElement("w:fldSimple"), instr=instruction)
142
+ run = OxmlElement("w:r")
143
+ text = OxmlElement("w:t")
144
+ text.text = "1"
145
+ run.append(text)
146
+ field.append(run)
147
+ paragraph._p.append(field)
@@ -0,0 +1,36 @@
1
+ from ...components.information import KeyValue
2
+ from ...components.table import TableCell
3
+ from ...components.typography import Heading, RichText, Text
4
+ from ...formatting.cells import TableCellFormatter
5
+ from .exceptions import WordExportError
6
+
7
+
8
+ def cell_text(content, column):
9
+ """
10
+ Return the display text of a table entry, formatted by its column like the HTML output.
11
+ """
12
+ if isinstance(content, TableCell):
13
+ return "\n".join(component_text(child) for child in content.children) if content.children else display(content.value, column)
14
+ return display(content, column)
15
+
16
+
17
+ def display(value, column):
18
+ """
19
+ Format a plain value with the column rules, or as text for explicit cells.
20
+ """
21
+ if column is None:
22
+ return "" if value is None else str(value)
23
+ return TableCellFormatter.format(value, column).display
24
+
25
+
26
+ def component_text(component):
27
+ """
28
+ Return the text of a component placed inside a table cell.
29
+ """
30
+ if isinstance(component, (Text, Heading)):
31
+ return component.value
32
+ if isinstance(component, RichText):
33
+ return "".join(span.value for span in component.spans)
34
+ if isinstance(component, KeyValue):
35
+ return f"{component.label}: {'' if component.value is None else component.value}"
36
+ raise WordExportError(f"{type(component).__name__} cannot be shown inside a Word table cell.")
File without changes
@@ -0,0 +1,12 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True, kw_only=True)
5
+ class FormattedTableCell:
6
+ """
7
+ Hold a plain value formatted for display; tone is 'positive', 'negative' or None.
8
+ """
9
+
10
+ display: str
11
+ align: str = "start"
12
+ tone: str | None = None
@@ -0,0 +1,41 @@
1
+ from decimal import Decimal
2
+
3
+ from .cell import FormattedTableCell
4
+ from .values import ValueFormatter
5
+
6
+
7
+ class TableCellFormatter:
8
+ """
9
+ Format plain table values using their column rules.
10
+ """
11
+
12
+ @classmethod
13
+ def format(cls, value, column):
14
+ """
15
+ Build the display text, alignment and numeric tone.
16
+ """
17
+ date_format = column.date_format or ("%Y-%m-%d %H:%M" if column.format == "datetime" else "%Y-%m-%d")
18
+ display = ValueFormatter.format(value, format_type=column.format, decimals=column.decimals, currency=column.currency, date_format=date_format)
19
+ return FormattedTableCell(display=display, align=column.align, tone=cls.resolve_tone(value, column))
20
+
21
+ @staticmethod
22
+ def resolve_tone(value, column):
23
+ """
24
+ Return 'negative' or 'positive' for signed numeric values.
25
+ """
26
+ if column.format not in {"number", "currency"} or value is None:
27
+ return None
28
+
29
+ try:
30
+ number = Decimal(str(value))
31
+ except (ValueError, TypeError, ArithmeticError):
32
+ return None
33
+
34
+ if not number.is_finite():
35
+ return None
36
+ if number < 0:
37
+ return "negative"
38
+ if number > 0:
39
+ return "positive"
40
+
41
+ return None
@@ -0,0 +1,106 @@
1
+ from datetime import date, datetime
2
+ from decimal import Decimal, InvalidOperation
3
+
4
+
5
+ class ValueFormatter:
6
+ """
7
+ Format values for report presentation.
8
+ """
9
+
10
+ @classmethod
11
+ def format(
12
+ cls,
13
+ value,
14
+ format_type=None,
15
+ decimals=2,
16
+ currency=None,
17
+ date_format=None,
18
+ ):
19
+ """
20
+ Format a value using its requested presentation type.
21
+ """
22
+ if value is None:
23
+ return ""
24
+
25
+ if format_type in {None, "text"}:
26
+ return str(value)
27
+ if format_type == "number":
28
+ return cls.number(value, decimals)
29
+ if format_type == "currency":
30
+ return cls.currency(value, decimals, currency)
31
+ if format_type == "percent":
32
+ return cls.percent(value, decimals)
33
+ if format_type == "date":
34
+ return cls.date(value, date_format or "%Y-%m-%d")
35
+ if format_type == "datetime":
36
+ return cls.datetime(value, date_format or "%Y-%m-%d %H:%M")
37
+
38
+ raise ValueError("Invalid format type.")
39
+
40
+ @staticmethod
41
+ def number(value, decimals=2):
42
+ """
43
+ Format a finite numeric value.
44
+ """
45
+ if isinstance(value, bool):
46
+ raise ValueError("Boolean values cannot be formatted as numbers.")
47
+
48
+ if (
49
+ not isinstance(decimals, int)
50
+ or isinstance(decimals, bool)
51
+ or not 0 <= decimals <= 12
52
+ ):
53
+ raise ValueError("Decimals must be an integer between 0 and 12.")
54
+
55
+ try:
56
+ number = Decimal(str(value))
57
+ except (InvalidOperation, ValueError, TypeError):
58
+ raise ValueError("Invalid numeric value.") from None
59
+
60
+ if not number.is_finite():
61
+ raise ValueError("Numeric values must be finite.")
62
+
63
+ return f"{number:,.{decimals}f}"
64
+
65
+ @classmethod
66
+ def currency(cls, value, decimals=2, currency=None):
67
+ """
68
+ Format monetary values with an optional currency label.
69
+ """
70
+ formatted = cls.number(value, decimals)
71
+ return f"{formatted} {currency}" if currency else formatted
72
+
73
+ @classmethod
74
+ def percent(cls, value, decimals=2):
75
+ """
76
+ Format fractional values as percentages.
77
+ """
78
+ try:
79
+ number = Decimal(str(value))
80
+ except (InvalidOperation, ValueError, TypeError):
81
+ raise ValueError("Invalid numeric value.") from None
82
+
83
+ if not number.is_finite():
84
+ raise ValueError("Percentage must be finite.")
85
+
86
+ return f"{cls.number(number * 100, decimals)}%"
87
+
88
+ @staticmethod
89
+ def date(value, date_format="%Y-%m-%d"):
90
+ """
91
+ Format a date value.
92
+ """
93
+ if not isinstance(value, (date, datetime)):
94
+ raise TypeError("Expected a date or datetime instance.")
95
+
96
+ return value.strftime(date_format)
97
+
98
+ @staticmethod
99
+ def datetime(value, date_format="%Y-%m-%d %H:%M"):
100
+ """
101
+ Format a datetime value.
102
+ """
103
+ if not isinstance(value, datetime):
104
+ raise TypeError("Expected a datetime instance.")
105
+
106
+ return value.strftime(date_format)
File without changes
@@ -0,0 +1,31 @@
1
+ from dataclasses import dataclass, field
2
+
3
+ from ..core.component import Component
4
+ from ..styles.style import Style
5
+ from ..styles.theme import Theme
6
+
7
+
8
+ @dataclass
9
+ class RenderingContext:
10
+ """
11
+ Manage shared rendering settings and component styles.
12
+ """
13
+ language: str = "en"
14
+ direction: str = "ltr"
15
+ theme: Theme = field(default_factory=Theme)
16
+
17
+ def resolve_style(self, component: Component, style_name: str | None = None) -> Style:
18
+ """
19
+ Resolve the final style for a component.
20
+ """
21
+ if not isinstance(component, Component):
22
+ raise TypeError("Expected a Component instance.")
23
+
24
+ style = self.theme.get(style_name) if style_name else Style()
25
+ return style.merge(component.style)
26
+
27
+ def with_language(self, language: str, direction: str | None = None) -> "RenderingContext":
28
+ """
29
+ Create a context with updated language settings.
30
+ """
31
+ return RenderingContext(language=language, direction=direction or self.direction, theme=self.theme)
@@ -0,0 +1,56 @@
1
+ from ..components.table import TableCell
2
+
3
+
4
+ def get_entries(component, table_row):
5
+ """
6
+ Pair each value or explicit cell with its column definition (None for explicit cells).
7
+ """
8
+ if table_row.cells is not None:
9
+ return [(cell, None) for cell in table_row.cells]
10
+ return [(table_row.values.get(column.key), column) for column in component.columns]
11
+
12
+
13
+ def place_cells(entries, start, row, occupied):
14
+ """
15
+ Yield (column, entry, colspan, rowspan) in order, skipping positions held by earlier row spans.
16
+ """
17
+ column = start
18
+ for entry in entries:
19
+ column = skip_occupied(column, row, occupied)
20
+ colspan, rowspan = get_spans(entry)
21
+ check_free(column, colspan, row, occupied)
22
+ occupied.update((row + offset, column + shift) for offset in range(1, rowspan) for shift in range(colspan))
23
+ yield column, entry, colspan, rowspan
24
+ column += colspan
25
+ occupied.difference_update({position for position in occupied if position[0] == row})
26
+
27
+
28
+ def skip_occupied(column, row, occupied):
29
+ """
30
+ Move past the positions a row span from an earlier row still holds.
31
+ """
32
+ while (row, column) in occupied:
33
+ column += 1
34
+ return column
35
+
36
+
37
+ def check_free(column, colspan, row, occupied):
38
+ """
39
+ Refuse a column span that would overlap a row span from an earlier row.
40
+ """
41
+ if any((row, column + shift) in occupied for shift in range(colspan)):
42
+ raise ValueError(f"A cell spanning {colspan} columns overlaps a row span from an earlier row (row {row}).")
43
+
44
+
45
+ def get_spans(entry):
46
+ """
47
+ Return the colspan and rowspan of an entry; plain values span one cell.
48
+ """
49
+ return (entry[0].colspan, entry[0].rowspan) if isinstance(entry[0], TableCell) else (1, 1)
50
+
51
+
52
+ def header_text(column, separator):
53
+ """
54
+ Join a column title and subtitle.
55
+ """
56
+ return f"{column.title}{separator}{column.subtitle}" if column.subtitle else column.title
@@ -0,0 +1,51 @@
1
+ import re
2
+
3
+ AUTO_TRACK = 0.6
4
+ MIN_COLUMN_CHARACTERS = 12
5
+
6
+
7
+ def distribute(shares, total):
8
+ """
9
+ Turn shares into whole grid columns (at least one each) that add up to the total.
10
+ """
11
+ exact = [share / sum(shares) * total for share in shares]
12
+ widths = [max(1, int(value)) for value in exact]
13
+ for index in sorted(range(len(exact)), key=lambda index: exact[index] - int(exact[index]), reverse=True)[:max(0, total - sum(widths))]:
14
+ widths[index] += 1
15
+ return widths
16
+
17
+
18
+ def track_shares(tracks, content_pixels):
19
+ """
20
+ Convert CSS tracks (fr, auto, %, px) into shares of the width: fixed tracks first, fr tracks share the rest.
21
+ """
22
+ fixed = [fixed_share(track, content_pixels) for track in tracks]
23
+ weights = [0 if share is not None else fraction(track) for track, share in zip(tracks, fixed)]
24
+ rest = max(0.0, 1 - sum(share for share in fixed if share is not None))
25
+ return [share if share is not None else rest * weight / (sum(weights) or 1) for share, weight in zip(fixed, weights)]
26
+
27
+
28
+ def fixed_share(track, content_pixels):
29
+ """
30
+ Return the share of a % or px track, or None for flexible tracks.
31
+ """
32
+ if track.endswith("%"):
33
+ return float(track[:-1]) / 100
34
+ if track.endswith("px"):
35
+ return float(track[:-2]) / content_pixels
36
+ return None
37
+
38
+
39
+ def fraction(track):
40
+ """
41
+ Return the flexible weight of an fr or auto track.
42
+ """
43
+ match = re.fullmatch(r"(\d+(?:\.\d+)?)fr", track)
44
+ return float(match.group(1)) if match else AUTO_TRACK
45
+
46
+
47
+ def column_tracks(columns):
48
+ """
49
+ Return CSS tracks for table columns: declared widths first, the rest weighted by header length like the HTML auto layout.
50
+ """
51
+ return [column.width or f"{max(len(column.title), len(column.subtitle or ''), MIN_COLUMN_CHARACTERS)}fr" for column in columns]
@@ -0,0 +1,55 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ from ..core.component import Component
4
+ from ..core.container import Container
5
+ from ..core.registry import ComponentRegistry
6
+ from .context import RenderingContext
7
+
8
+
9
+ class ComponentVisitor(ABC):
10
+ """
11
+ Visit report components using registered component types.
12
+ """
13
+
14
+ def visit(self, component: Component, context: RenderingContext):
15
+ """
16
+ Dispatch a component to its matching visitor method.
17
+ """
18
+ if not isinstance(component, Component):
19
+ raise TypeError("Expected a Component instance.")
20
+
21
+ component_type = self.resolve_type(component)
22
+
23
+ method = getattr(self, f"visit_{component_type}", None)
24
+
25
+ if method is None:
26
+ return self.visit_default(component, context)
27
+
28
+ return method(component, context)
29
+
30
+ def visit_children(self, container: Container, context: RenderingContext):
31
+ """
32
+ Visit all child components in their original order.
33
+ """
34
+ if not isinstance(container, Container):
35
+ raise TypeError("Expected a Container instance.")
36
+
37
+ return [self.visit(child, context) for child in container.children]
38
+
39
+ @staticmethod
40
+ def resolve_type(component: Component) -> str:
41
+ """
42
+ Resolve the registered type of a component.
43
+ """
44
+ for name, component_class in ComponentRegistry.all().items():
45
+ if type(component) is component_class:
46
+ return name
47
+
48
+ raise ValueError(f"Component '{type(component).__name__}' is not registered.")
49
+
50
+ @abstractmethod
51
+ def visit_default(self, component: Component, context: RenderingContext):
52
+ """
53
+ Handle components without a specialized visitor method.
54
+ """
55
+ raise NotImplementedError
reportkit/report.py ADDED
File without changes
File without changes
@@ -0,0 +1,6 @@
1
+ def edge_borders(style):
2
+ """
3
+ Return the left, right, top and bottom borders of a component style.
4
+ """
5
+ whole = f"{style.border_width or 1}px {style.border_style or 'solid'} {style.border_color}" if style.border_color else None
6
+ return [side or whole for side in (style.border_left, style.border_right, style.border_top, style.border_bottom)]
@@ -0,0 +1,117 @@
1
+ from dataclasses import dataclass, fields
2
+
3
+
4
+ @dataclass(frozen=True, kw_only=True)
5
+ class Style:
6
+ """
7
+ Define reusable visual properties for report components.
8
+ """
9
+
10
+ # Typography
11
+ font_family: str | None = None
12
+ font_size: float | None = None
13
+ font_weight: str | int | None = None
14
+ font_style: str | None = None
15
+ line_height: float | None = None
16
+ letter_spacing: float | None = None
17
+ color: str | None = None
18
+ text_align: str | None = None
19
+ text_decoration: str | None = None
20
+ text_transform: str | None = None
21
+ vertical_align: str | None = None
22
+ direction: str | None = None
23
+ white_space: str | None = None
24
+
25
+ # Layout
26
+ display: str | None = None
27
+ position: str | None = None
28
+ top: float | None = None
29
+ right: float | None = None
30
+ bottom: float | None = None
31
+ left: float | None = None
32
+ width: float | None = None
33
+ min_width: float | None = None
34
+ max_width: float | None = None
35
+ height: float | None = None
36
+ min_height: float | None = None
37
+ max_height: float | None = None
38
+ flex_direction: str | None = None
39
+ flex_wrap: str | None = None
40
+ flex: str | float | None = None
41
+ flex_grow: float | None = None
42
+ flex_shrink: float | None = None
43
+ justify_content: str | None = None
44
+ align_items: str | None = None
45
+ align_content: str | None = None
46
+ align_self: str | None = None
47
+ gap: float | None = None
48
+ row_gap: float | None = None
49
+ column_gap: float | None = None
50
+ grid_template_columns: str | None = None
51
+ grid_template_rows: str | None = None
52
+ grid_column: str | None = None
53
+ grid_row: str | None = None
54
+ background_color: str | None = None
55
+ opacity: float | None = None
56
+
57
+ # Spacing
58
+ padding: float | None = None
59
+ padding_top: float | None = None
60
+ padding_right: float | None = None
61
+ padding_bottom: float | None = None
62
+ padding_left: float | None = None
63
+ margin: float | None = None
64
+ margin_top: float | None = None
65
+ margin_right: float | None = None
66
+ margin_bottom: float | None = None
67
+ margin_left: float | None = None
68
+
69
+ # Borders
70
+ border_width: float | None = None
71
+ border_color: str | None = None
72
+ border_style: str | None = None
73
+ border_radius: float | None = None
74
+ border_top: str | None = None
75
+ border_right: str | None = None
76
+ border_bottom: str | None = None
77
+ border_left: str | None = None
78
+
79
+ # Effects
80
+ box_shadow: str | None = None
81
+ overflow: str | None = None
82
+
83
+ def merge(self, other: "Style") -> "Style":
84
+ """
85
+ Merge styles while prioritizing explicitly defined values.
86
+ """
87
+ if not isinstance(other, Style):
88
+ raise TypeError("Expected a Style instance.")
89
+
90
+ values = self.to_dict()
91
+ values.update(other.to_dict())
92
+ return Style(**values)
93
+
94
+ def to_dict(self) -> dict:
95
+ """
96
+ Return explicitly defined style properties.
97
+ """
98
+ return {
99
+ field.name: getattr(self, field.name)
100
+ for field in fields(self)
101
+ if getattr(self, field.name) is not None
102
+ }
103
+
104
+ @classmethod
105
+ def from_dict(cls, data: dict) -> "Style":
106
+ """
107
+ Create a style from a dictionary.
108
+ """
109
+ if not isinstance(data, dict):
110
+ raise TypeError("Style definition must be a dictionary.")
111
+
112
+ allowed = {field.name for field in fields(cls)}
113
+ unknown = set(data) - allowed
114
+ if unknown:
115
+ raise ValueError(f"Unknown style properties: {', '.join(sorted(unknown))}")
116
+
117
+ return cls(**data)