flexablelib 2.0.8__tar.gz → 2.0.10__tar.gz

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 (43) hide show
  1. {flexablelib-2.0.8 → flexablelib-2.0.10}/CHANGELOG.md +17 -0
  2. {flexablelib-2.0.8/flexablelib.egg-info → flexablelib-2.0.10}/PKG-INFO +2 -2
  3. {flexablelib-2.0.8 → flexablelib-2.0.10}/README.md +1 -1
  4. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/colors.py +98 -0
  5. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/merges.py +16 -2
  6. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/style_compositions.py +44 -0
  7. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/table.py +40 -2
  8. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/writers.py +144 -9
  9. {flexablelib-2.0.8 → flexablelib-2.0.10/flexablelib.egg-info}/PKG-INFO +2 -2
  10. {flexablelib-2.0.8 → flexablelib-2.0.10}/package.json +1 -1
  11. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_features.py +60 -0
  12. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_styles.py +28 -3
  13. {flexablelib-2.0.8 → flexablelib-2.0.10}/LICENSE +0 -0
  14. {flexablelib-2.0.8 → flexablelib-2.0.10}/MANIFEST.in +0 -0
  15. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/__init__.py +0 -0
  16. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/_speedups.c +0 -0
  17. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/_width_tables.h +0 -0
  18. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/cells.py +0 -0
  19. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/columns.py +0 -0
  20. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/fast.py +0 -0
  21. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/options.py +0 -0
  22. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/readers.py +0 -0
  23. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/table_strings.py +0 -0
  24. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/text_width.py +0 -0
  25. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib/utils.py +0 -0
  26. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib.egg-info/SOURCES.txt +0 -0
  27. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib.egg-info/dependency_links.txt +0 -0
  28. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib.egg-info/requires.txt +0 -0
  29. {flexablelib-2.0.8 → flexablelib-2.0.10}/flexablelib.egg-info/top_level.txt +0 -0
  30. {flexablelib-2.0.8 → flexablelib-2.0.10}/setup.cfg +0 -0
  31. {flexablelib-2.0.8 → flexablelib-2.0.10}/setup.py +0 -0
  32. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_cells.py +0 -0
  33. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_columns.py +0 -0
  34. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_excel.py +0 -0
  35. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_issues.py +0 -0
  36. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_merge_edge_matrix.py +0 -0
  37. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_merges.py +0 -0
  38. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_readme_examples.py +0 -0
  39. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_text_width.py +0 -0
  40. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_two_pass_measurement.py +0 -0
  41. {flexablelib-2.0.8 → flexablelib-2.0.10}/tests/test_upstream_issues.py +0 -0
  42. {flexablelib-2.0.8 → flexablelib-2.0.10}/tools/benchmark.py +0 -0
  43. {flexablelib-2.0.8 → flexablelib-2.0.10}/tools/generate_width_tables.py +0 -0
@@ -2,6 +2,23 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ## [2.0.10] - 2026-10-28
6
+
7
+ ### Added
8
+ - ``flush`` style: full unicode grid whose cell backgrounds meet the border
9
+ glyphs with no interior gap and never paint over them (pad-then-paint
10
+ contract; recommended for coloured cells and coloured merges).
11
+ - ``merge_cells(..., color=...)`` paints the whole merge span (ANSI + HTML +
12
+ Excel). When omitted, merges inherit the top-left cell's row/column/cell
13
+ colour so existing colour APIs fill merges instead of leaving dark holes.
14
+
15
+ ## [2.0.9] - 2026-10-28
16
+
17
+ ### Added
18
+ - New ``blocks`` style: background-colour cells only — no outer/inner borders
19
+ and no junctions. Column gaps are a single space spacer; cell margin kept so
20
+ ANSI / Excel fills read as solid blocks.
21
+
5
22
  ## [2.0.8] - 2026-10-28
6
23
 
7
24
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flexablelib
3
- Version: 2.0.8
3
+ Version: 2.0.10
4
4
  Summary: Flexible console and HTML tables for Python
5
5
  Home-page: https://github.com/Opus-Perpetuus/flexablelib
6
6
  Download-URL:
@@ -355,7 +355,7 @@ flexablelib/ # GitHub repository
355
355
  ├── docs/ issue history and design notes
356
356
  ├── logos/ brand assets — see logos/README.md
357
357
  ├── ARCHITECTURE.md how it all fits together
358
- ├── style_examples.md all 42 styles rendered
358
+ ├── style_examples.md all 44 styles rendered
359
359
  ├── package.json canonical version number; drives the release
360
360
  └── setup.py reads the version from package.json
361
361
  ```
@@ -306,7 +306,7 @@ flexablelib/ # GitHub repository
306
306
  ├── docs/ issue history and design notes
307
307
  ├── logos/ brand assets — see logos/README.md
308
308
  ├── ARCHITECTURE.md how it all fits together
309
- ├── style_examples.md all 42 styles rendered
309
+ ├── style_examples.md all 44 styles rendered
310
310
  ├── package.json canonical version number; drives the release
311
311
  └── setup.py reads the version from package.json
312
312
  ```
@@ -193,3 +193,101 @@ __all__ = [
193
193
  'ATTRIBUTES',
194
194
  'RESET',
195
195
  ]
196
+
197
+
198
+ # Named ANSI background → approximate sRGB for HTML / Excel fills.
199
+ _BG_HEX = {
200
+ 'black': '1F2937',
201
+ 'red': 'DC2626',
202
+ 'green': '16A34A',
203
+ 'yellow': 'CA8A04',
204
+ 'blue': '2563EB',
205
+ 'magenta': 'C026D3',
206
+ 'cyan': '0891B2',
207
+ 'white': 'F3F4F6',
208
+ 'bright_black': '4B5563',
209
+ 'grey': '6B7280',
210
+ 'gray': '6B7280',
211
+ 'bright_red': 'EF4444',
212
+ 'bright_green': '22C55E',
213
+ 'bright_yellow': 'EAB308',
214
+ 'bright_blue': '3B82F6',
215
+ 'bright_magenta': 'E879F9',
216
+ 'bright_cyan': '22D3EE',
217
+ 'bright_white': 'FFFFFF',
218
+ }
219
+
220
+ _FG_HEX = {
221
+ 'black': '111827',
222
+ 'red': '991B1B',
223
+ 'green': '14532D',
224
+ 'yellow': '713F12',
225
+ 'blue': '1E3A8A',
226
+ 'magenta': '86198F',
227
+ 'cyan': '155E75',
228
+ 'white': 'F9FAFB',
229
+ 'bright_black': '374151',
230
+ 'grey': '6B7280',
231
+ 'gray': '6B7280',
232
+ 'bright_red': 'B91C1C',
233
+ 'bright_green': '15803D',
234
+ 'bright_yellow': 'A16207',
235
+ 'bright_blue': '1D4ED8',
236
+ 'bright_magenta': 'A21CAF',
237
+ 'bright_cyan': '0E7490',
238
+ 'bright_white': 'FFFFFF',
239
+ }
240
+
241
+
242
+ def _split_spec(spec: Union[str, int, None]):
243
+ if spec is None or spec == '':
244
+ return [], None
245
+ if isinstance(spec, int):
246
+ return [], None
247
+ foreground_part, _, background_part = str(spec).lower().partition(' on ')
248
+ fg_tokens = foreground_part.split()
249
+ bg_token = None
250
+ if background_part:
251
+ parts = background_part.split()
252
+ bg_token = parts[0] if parts else None
253
+ return fg_tokens, bg_token
254
+
255
+
256
+ def background_hex(spec: Union[str, int, None]) -> Optional[str]:
257
+ """sRGB hex (no ``#``) for the background half of a colour spec, if any."""
258
+ _fg, bg = _split_spec(spec)
259
+ if bg is None:
260
+ return None
261
+ hex_match = _HEX_RE.match(bg)
262
+ if hex_match:
263
+ return hex_match.group(1).upper()
264
+ return _BG_HEX.get(bg)
265
+
266
+
267
+ def foreground_hex(spec: Union[str, int, None]) -> Optional[str]:
268
+ """sRGB hex (no ``#``) for the first named foreground colour in a spec."""
269
+ fg_tokens, _bg = _split_spec(spec)
270
+ for token in fg_tokens:
271
+ if token in ATTRIBUTES:
272
+ continue
273
+ hex_match = _HEX_RE.match(token)
274
+ if hex_match:
275
+ return hex_match.group(1).upper()
276
+ if token in _FG_HEX:
277
+ return _FG_HEX[token]
278
+ return None
279
+
280
+
281
+ def spec_to_css(spec: Union[str, int, None]) -> str:
282
+ """Inline CSS ``color`` / ``background-color`` from a colour spec."""
283
+ parts = []
284
+ bg = background_hex(spec)
285
+ fg = foreground_hex(spec)
286
+ if bg:
287
+ parts.append(f'background-color:#{bg}')
288
+ if fg:
289
+ parts.append(f'color:#{fg}')
290
+ fg_tokens, _ = _split_spec(spec)
291
+ if 'bold' in fg_tokens:
292
+ parts.append('font-weight:600')
293
+ return ';'.join(parts)
@@ -19,6 +19,7 @@ than the span it was given is truncated, not accommodated.
19
19
  import re
20
20
  from typing import List, NamedTuple, Optional
21
21
 
22
+ from .colors import colorize
22
23
  from .fast import (
23
24
  has_ansi,
24
25
  pad_to_width,
@@ -51,6 +52,11 @@ class MergedRegion(NamedTuple):
51
52
 
52
53
  Coordinates are inclusive and zero-based, in the table's own row and
53
54
  column numbering -- the index column, when shown, is not counted.
55
+
56
+ ``color`` is an optional colour spec (same language as ``column_colors`` /
57
+ ``row_colors``). When set, the whole painted span -- text, padding and
58
+ blank continuation lines -- carries that background so a merge reads as
59
+ one solid fill rather than a dark hole.
54
60
  """
55
61
 
56
62
  first_row: int
@@ -59,6 +65,7 @@ class MergedRegion(NamedTuple):
59
65
  last_column: int
60
66
  value: Optional[str]
61
67
  align: str
68
+ color: Optional[str] = None
62
69
 
63
70
  @property
64
71
  def row_count(self) -> int:
@@ -82,7 +89,7 @@ class MergedRegion(NamedTuple):
82
89
 
83
90
 
84
91
  def normalise(first_row, first_column, last_row, last_column, value, align,
85
- row_count, column_count, existing):
92
+ row_count, column_count, existing, color=None):
86
93
  """
87
94
  Validate a merge request and turn it into a MergedRegion.
88
95
 
@@ -115,7 +122,7 @@ def normalise(first_row, first_column, last_row, last_column, value, align,
115
122
  raise ValueError(f"align must be 'l', 'r' or 'c', not {align!r}")
116
123
 
117
124
  region = MergedRegion(first_row, first_column, last_row, last_column,
118
- value, align)
125
+ value, align, color)
119
126
 
120
127
  for other in existing:
121
128
  if region.overlaps(other):
@@ -581,6 +588,13 @@ def apply(lines, row_line_map, regions, column_widths, composition,
581
588
  + pad_to_width(text, span_width, region.align, filler)
582
589
  + filler * margin)
583
590
  blank = filler * (end - start)
591
+ # Colour the entire span (text line + blank continuations) so a merge
592
+ # fill is flush across its rectangle -- same pad-then-paint contract
593
+ # as ordinary cells. Borders stay outside _repaint's range.
594
+ spec = getattr(region, 'color', None)
595
+ if spec:
596
+ painted = colorize(painted, spec)
597
+ blank = colorize(blank, spec)
584
598
 
585
599
  text_line = target_lines[len(target_lines) // 2]
586
600
  for line_index in target_lines:
@@ -130,6 +130,10 @@ Compositions = namedtuple(
130
130
 
131
131
  # Other
132
132
  'dashes',
133
+
134
+ # Fill-only (background colours, no border glyphs)
135
+ 'blocks',
136
+ 'flush',
133
137
  ]
134
138
  )
135
139
 
@@ -868,5 +872,45 @@ __style_compositions = Compositions(
868
872
  lines_with_indicator=[],
869
873
  align_indicator_margin=0,
870
874
  always_center_indicator=False
875
+ ),
876
+ # Background-colour blocks only: no outer/inner border glyphs, no junctions.
877
+ # Columns are separated by a single space (invisible spacer), not a rule.
878
+ blocks=TableComposition(
879
+ superior_header_line=None,
880
+ inferior_header_line=None,
881
+ superior_header_line_no_header=None,
882
+ table_body_line=None,
883
+ table_end_line=None,
884
+ vertical_header_lines=SeparatorLine(None, INVISIBLE_SEPARATOR, None, None),
885
+ vertical_table_body_lines=SeparatorLine(None, INVISIBLE_SEPARATOR, None, None),
886
+ margin=CELL_MARGIN,
887
+ align_sensitive=False,
888
+ align_indicator=None,
889
+ centered_indicator_on_sides=False,
890
+ left_and_right_when_centered=False,
891
+ lines_with_indicator=[],
892
+ align_indicator_margin=0,
893
+ always_center_indicator=False
894
+ ),
895
+ # Flush cell fills: full unicode grid whose cell backgrounds (pad-then-paint)
896
+ # meet the border glyphs with no interior gap and never paint over them.
897
+ # Recommended style for coloured cells and coloured merges. Same box as
898
+ # pretty_grid; the name encodes the fill contract used by demos/docs.
899
+ flush=TableComposition(
900
+ superior_header_line=SeparatorLine('╒', '═', '╤', '╕'),
901
+ inferior_header_line=SeparatorLine('╞', '═', '╪', '╡'),
902
+ superior_header_line_no_header=SeparatorLine('╒', '═', '╤', '╕'),
903
+ table_body_line=SeparatorLine('├', '─', '┼', '┤'),
904
+ table_end_line=SeparatorLine('╘', '═', '╧', '╛'),
905
+ vertical_header_lines=SeparatorLine('│', '│', None, '│'),
906
+ vertical_table_body_lines=SeparatorLine('│', '│', None, '│'),
907
+ margin=CELL_MARGIN,
908
+ align_sensitive=False,
909
+ align_indicator=None,
910
+ centered_indicator_on_sides=False,
911
+ left_and_right_when_centered=False,
912
+ lines_with_indicator=[],
913
+ align_indicator_margin=0,
914
+ always_center_indicator=False
871
915
  )
872
916
  )
@@ -1995,7 +1995,7 @@ class Table(object):
1995
1995
  return list(self.__merged_regions)
1996
1996
 
1997
1997
  def merge_cells(self, first_row, first_column, last_row=None,
1998
- last_column=None, value=None, align='c'):
1998
+ last_column=None, value=None, align='c', color=None):
1999
1999
  """
2000
2000
  Render a rectangular block of cells as a single cell.
2001
2001
 
@@ -2007,9 +2007,15 @@ class Table(object):
2007
2007
  table.merge_cells(0, 0, last_column=2) # across three columns
2008
2008
  table.merge_cells(1, 0, last_row=3) # down four rows
2009
2009
  table.merge_cells(0, 0, 2, 2, value='Total') # a 3x3 block
2010
+ table.merge_cells(0, 0, last_row=2, value='A',
2011
+ color='black on green') # coloured merge
2010
2012
 
2011
2013
  ``value`` replaces the text; left as None, the top-left cell's own
2012
2014
  content is kept. ``align`` is 'l', 'r' or 'c' within the merged span.
2015
+ ``color`` paints the whole merge span (text + padding + blank lines)
2016
+ with a colour spec; when omitted, the top-left cell's row/column/
2017
+ cell colour is inherited at render time so existing colour APIs light
2018
+ up merges without an extra argument.
2013
2019
 
2014
2020
  Raises ValueError for a merge covering a single cell, coordinates
2015
2021
  outside the table, or an overlap with a merge already in place.
@@ -2028,6 +2034,7 @@ class Table(object):
2028
2034
  region = normalise(
2029
2035
  first_row, first_column, last_row, last_column, value, align,
2030
2036
  self.row_count, self.column_count, self.__merged_regions,
2037
+ color=color,
2031
2038
  )
2032
2039
  self.__merged_regions.append(region)
2033
2040
  return region
@@ -4026,10 +4033,11 @@ class Table(object):
4026
4033
  () if self.__show_empty_columns else self.__empty_column_indexes
4027
4034
  )
4028
4035
 
4036
+ regions = self.__regions_with_colors()
4029
4037
  merged = apply_merges(
4030
4038
  table_string.split('\n'),
4031
4039
  row_line_map,
4032
- self.__merged_regions,
4040
+ regions,
4033
4041
  column_widths_list,
4034
4042
  self.__style_composition,
4035
4043
  1 if table_with_i else 0,
@@ -4037,6 +4045,36 @@ class Table(object):
4037
4045
  )
4038
4046
  return '\n'.join(merged)
4039
4047
 
4048
+ def __regions_with_colors(self):
4049
+ """
4050
+ Merged regions with an effective colour for this render.
4051
+
4052
+ Explicit ``merge_cells(..., color=...)`` wins. Otherwise, when colour
4053
+ output is on, the top-left cell's resolved colour is inherited so
4054
+ ``column_colors`` / ``row_colors`` / ``cell_color`` fill the whole
4055
+ merge span instead of leaving a dark hole.
4056
+ """
4057
+ colors_on = self.__colors_active and self.__has_any_color()
4058
+ headers = list(self.__headers)
4059
+ out = []
4060
+ for region in self.__merged_regions:
4061
+ if region.color is not None or not colors_on:
4062
+ out.append(region)
4063
+ continue
4064
+ col_name = (
4065
+ headers[region.first_column]
4066
+ if region.first_column < len(headers) else ''
4067
+ )
4068
+ try:
4069
+ raw = self.__raw_value_at(
4070
+ headers, region.first_column, region.first_row
4071
+ )
4072
+ except Exception:
4073
+ raw = None
4074
+ spec = self.__color_for_cell(raw, region.first_row, col_name)
4075
+ out.append(region if not spec else region._replace(color=spec))
4076
+ return out
4077
+
4040
4078
  def __get_processed_columns_data(self, header=False, columns_with_i=False):
4041
4079
  if columns_with_i:
4042
4080
  columns_with_headers = self.__processed_columns_with_i.values()
@@ -25,6 +25,7 @@ import json
25
25
  from typing import Any, List, Optional, Sequence
26
26
 
27
27
  from .fast import strip_ansi
28
+ from .colors import background_hex, foreground_hex, spec_to_css
28
29
  from .options import FLT_FILTER, INT_FILTER
29
30
 
30
31
 
@@ -50,6 +51,85 @@ def _table_data(table, include_index: bool):
50
51
  return headers, [[cell for cell in row] for row in rows]
51
52
 
52
53
 
54
+ def _effective_region_color(table, region):
55
+ """Explicit merge colour, else inherit from row/column colour maps."""
56
+ if getattr(region, 'color', None):
57
+ return region.color
58
+ try:
59
+ row_colors = getattr(table, 'row_colors', None) or {}
60
+ if region.first_row in row_colors:
61
+ return row_colors[region.first_row]
62
+ headers = list(getattr(table, 'headers', []) or [])
63
+ if region.first_column < len(headers):
64
+ col_colors = getattr(table, 'column_colors', None) or {}
65
+ return col_colors.get(headers[region.first_column])
66
+ except Exception:
67
+ return None
68
+ return None
69
+
70
+
71
+ def _align_style(align: str) -> str:
72
+ return {'l': 'left', 'r': 'right', 'c': 'center'}.get(align, 'center')
73
+
74
+
75
+ def _html_body_with_merges(table, include_index: bool = False) -> str:
76
+ """
77
+ Build ``<tr>…</tr>`` rows that honour ``merged_regions`` via rowspan/colspan.
78
+
79
+ Covered cells are omitted so the browser paints one merged cell. Merge
80
+ coordinates address data columns; an optional index column shifts them by 1.
81
+ """
82
+ headers, rows = _table_data(table, include_index)
83
+ col_offset = 1 if include_index else 0
84
+ regions = list(getattr(table, 'merged_regions', []) or [])
85
+
86
+ # Map every covered (row, col-in-output) cell -> owning region (or None for top-left).
87
+ covered = {}
88
+ origin = {}
89
+ for region in regions:
90
+ r0, r1 = region.first_row, region.last_row
91
+ c0, c1 = region.first_column + col_offset, region.last_column + col_offset
92
+ origin[(r0, c0)] = region
93
+ for r in range(r0, r1 + 1):
94
+ for c in range(c0, c1 + 1):
95
+ if (r, c) != (r0, c0):
96
+ covered[(r, c)] = region
97
+
98
+ parts = []
99
+ n_cols = len(headers)
100
+ for r_i, row in enumerate(rows):
101
+ parts.append('<tr>')
102
+ for c_i in range(n_cols):
103
+ if (r_i, c_i) in covered:
104
+ continue
105
+ region = origin.get((r_i, c_i))
106
+ if region is not None:
107
+ rowspan = region.last_row - region.first_row + 1
108
+ colspan = region.last_column - region.first_column + 1
109
+ text = _plain(region.value if region.value is not None else row[c_i])
110
+ attrs = []
111
+ if rowspan > 1:
112
+ attrs.append(f'rowspan="{rowspan}"')
113
+ if colspan > 1:
114
+ attrs.append(f'colspan="{colspan}"')
115
+ style_bits = [
116
+ f'text-align:{_align_style(region.align)}',
117
+ 'vertical-align:middle',
118
+ ]
119
+ color_css = spec_to_css(_effective_region_color(table, region))
120
+ if color_css:
121
+ style_bits.append(color_css)
122
+ attrs.append(f'style="{";".join(style_bits)}"')
123
+ attr_s = (' ' + ' '.join(attrs)) if attrs else ''
124
+ parts.append(f'<td{attr_s}>{_html.escape(text)}</td>')
125
+ else:
126
+ cell = row[c_i] if c_i < len(row) else ''
127
+ parts.append(f'<td>{_html.escape(_plain(cell))}</td>')
128
+ parts.append('</tr>')
129
+ return ''.join(parts)
130
+
131
+
132
+
53
133
  def to_records(table, include_index: bool = False) -> List[dict]:
54
134
  """The table as a list of dicts, one per row."""
55
135
  headers, rows = _table_data(table, include_index)
@@ -61,9 +141,10 @@ def to_simple_html(table, include_index: bool = False) -> str:
61
141
  A bare HTML ``<table>`` for notebook ``_repr_html_`` hooks.
62
142
 
63
143
  No document chrome, scripts or pagination -- just thead/tbody so Jupyter
64
- and friends can embed the table in a cell output.
144
+ and friends can embed the table in a cell output. Merged regions become
145
+ ``rowspan`` / ``colspan`` attributes.
65
146
  """
66
- headers, rows = _table_data(table, include_index)
147
+ headers, _rows = _table_data(table, include_index)
67
148
  parts = ['<table>']
68
149
  title = getattr(table, 'title', None)
69
150
  if title:
@@ -78,13 +159,7 @@ def to_simple_html(table, include_index: bool = False) -> str:
78
159
  )
79
160
  parts.append('</tr></thead>')
80
161
  parts.append('<tbody>')
81
- for row in rows:
82
- parts.append('<tr>')
83
- for cell in row:
84
- parts.append(
85
- '<td>{0}</td>'.format(_html.escape(_plain(cell)))
86
- )
87
- parts.append('</tr>')
162
+ parts.append(_html_body_with_merges(table, include_index))
88
163
  parts.append('</tbody></table>')
89
164
  return ''.join(parts)
90
165
 
@@ -388,6 +463,47 @@ _HTML_SCRIPT = """
388
463
  """
389
464
 
390
465
 
466
+
467
+ def _to_html_merged(table, target, title: str, include_index: bool,
468
+ encoding: str) -> Optional[str]:
469
+ """Static self-contained HTML page that preserves merged cells."""
470
+ headers, _rows = _table_data(table, include_index)
471
+ head_cells = ''.join(
472
+ f'<th>{_html.escape(_plain(h))}</th>' for h in headers
473
+ )
474
+ body = _html_body_with_merges(table, include_index)
475
+ markup = f"""<!DOCTYPE html>
476
+ <html lang="en">
477
+ <head>
478
+ <meta charset="utf-8">
479
+ <meta name="viewport" content="width=device-width, initial-scale=1">
480
+ <title>{_html.escape(title)}</title>
481
+ <style>{_HTML_STYLE}</style>
482
+ </head>
483
+ <body>
484
+ <div class="wrap">
485
+ <h1>{_html.escape(title)}</h1>
486
+ <p class="count">Merged cells preserved (static view).</p>
487
+ <div class="scroll">
488
+ <table>
489
+ <thead><tr>{head_cells}</tr></thead>
490
+ <tbody>{body}</tbody>
491
+ </table>
492
+ </div>
493
+ </div>
494
+ </body>
495
+ </html>
496
+ """
497
+ if target is None:
498
+ return markup
499
+ if hasattr(target, 'write'):
500
+ target.write(markup)
501
+ return None
502
+ with open(target, 'w', encoding=encoding) as handle:
503
+ handle.write(markup)
504
+ return None
505
+
506
+
391
507
  def to_html(table, target=None, title: str = 'Table', paginate: int = 25,
392
508
  include_index: bool = False, searchable: bool = True,
393
509
  encoding: str = 'utf-8') -> Optional[str]:
@@ -404,7 +520,14 @@ def to_html(table, target=None, title: str = 'Table', paginate: int = 25,
404
520
  Values are passed to the page as JSON data and written into the DOM as
405
521
  text, never as markup, so a cell containing HTML is displayed rather than
406
522
  interpreted.
523
+
524
+ When the table has merged regions, a static ``rowspan``/``colspan`` table
525
+ is written instead of the interactive grid (sort/filter would break merges).
407
526
  """
527
+ regions = list(getattr(table, 'merged_regions', []) or [])
528
+ if regions:
529
+ return _to_html_merged(table, target, title, include_index, encoding)
530
+
408
531
  headers, rows = _table_data(table, include_index)
409
532
  header_texts = [_plain(header) for header in headers]
410
533
  row_texts = [[_plain(cell) for cell in row] for row in rows]
@@ -578,5 +701,17 @@ def to_excel(table, path, sheet_name: str = 'Sheet1',
578
701
  start_row=start_row, start_column=start_col,
579
702
  end_row=end_row, end_column=end_col,
580
703
  )
704
+ spec = _effective_region_color(table, region)
705
+ if spec:
706
+ from openpyxl.styles import Font as _Font
707
+ bg = background_hex(spec)
708
+ fg = foreground_hex(spec)
709
+ if bg:
710
+ fill = PatternFill('solid', fgColor=bg)
711
+ for r in range(start_row, end_row + 1):
712
+ for c in range(start_col, end_col + 1):
713
+ worksheet.cell(row=r, column=c).fill = fill
714
+ if fg:
715
+ top_left.font = _Font(color=fg, bold='bold' in str(spec).lower())
581
716
 
582
717
  workbook.save(path)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flexablelib
3
- Version: 2.0.8
3
+ Version: 2.0.10
4
4
  Summary: Flexible console and HTML tables for Python
5
5
  Home-page: https://github.com/Opus-Perpetuus/flexablelib
6
6
  Download-URL:
@@ -355,7 +355,7 @@ flexablelib/ # GitHub repository
355
355
  ├── docs/ issue history and design notes
356
356
  ├── logos/ brand assets — see logos/README.md
357
357
  ├── ARCHITECTURE.md how it all fits together
358
- ├── style_examples.md all 42 styles rendered
358
+ ├── style_examples.md all 44 styles rendered
359
359
  ├── package.json canonical version number; drives the release
360
360
  └── setup.py reads the version from package.json
361
361
  ```
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flexablelib",
3
- "version": "2.0.8",
3
+ "version": "2.0.10",
4
4
  "description": "Flexible console and HTML tables for Python: styles, merges, colors, widths, decimal alignment.",
5
5
  "main": "__init__.py",
6
6
  "scripts": {
@@ -256,3 +256,63 @@ def test_missing_val_alias_matches_missing_value():
256
256
  table.missing_value = '?'
257
257
  assert table.missing_val == '?'
258
258
  assert '?' in str(table)
259
+
260
+
261
+ def test_html_export_preserves_merged_cells():
262
+ table = Table()
263
+ table.add_column('A', ['a0', 'a1', 'a2'])
264
+ table.add_column('B', ['b0', 'b1', 'b2'])
265
+ table.merge_cells(0, 0, last_row=1, value='VERT')
266
+ table.merge_cells(2, 0, last_column=1, value='HORZ')
267
+ html = table.to_html(title='merged')
268
+ assert 'rowspan="2"' in html
269
+ assert 'colspan="2"' in html
270
+ assert 'VERT' in html and 'HORZ' in html
271
+ bare = table._repr_html_()
272
+ assert 'rowspan="2"' in bare and 'colspan="2"' in bare
273
+
274
+
275
+ def test_merged_region_color_fills_ansi():
276
+ table = Table(style_name='flush')
277
+ table.use_colors = True
278
+ table.add_column('A', ['alpha-0', 'alpha-1', 'alpha-2'])
279
+ table.add_column('B', ['bravo-0', 'bravo-1', 'bravo-2'])
280
+ table.merge_cells(0, 0, last_row=1, value='MERGE', color='black on green')
281
+ rendered = str(table)
282
+ assert '\x1b[' in rendered
283
+ assert '42m' in rendered
284
+ assert 'MERGE' in rendered
285
+ # Background must cover more than the bare word (padding spaces painted).
286
+ assert rendered.count('42m') >= 1
287
+
288
+
289
+ def test_merged_region_inherits_column_color():
290
+ table = Table(style_name='flush')
291
+ table.use_colors = True
292
+ # Wide unmerged content so the merge span can hold the label.
293
+ table.add_column('A', ['alpha-0', 'alpha-1'])
294
+ table.add_column('B', ['b0', 'b1'])
295
+ table.column_colors = {'A': 'black on yellow'}
296
+ table.merge_cells(0, 0, last_row=1, value='INHERIT')
297
+ rendered = str(table)
298
+ assert '43m' in rendered # yellow bg
299
+ assert 'INHERIT' in rendered
300
+
301
+
302
+ def test_flush_style_is_catalogued():
303
+ assert 'flush' in Table().possible_styles
304
+
305
+
306
+ def test_html_and_excel_carry_merge_fill(tmp_path):
307
+ table = Table(style_name='flush')
308
+ table.use_colors = True
309
+ table.add_column('A', ['a0', 'a1'])
310
+ table.add_column('B', ['b0', 'b1'])
311
+ table.merge_cells(0, 0, last_column=1, value='BOX', color='black on cyan')
312
+ html = table.to_html(title='m')
313
+ assert 'background-color' in html
314
+ path = tmp_path / 'm.xlsx'
315
+ table.to_excel(path)
316
+ from openpyxl import load_workbook
317
+ ws = load_workbook(path).active
318
+ assert ws['A2'].fill.fgColor.rgb.endswith('0891B2') or '0891B2' in str(ws['A2'].fill.fgColor.rgb)
@@ -1,7 +1,7 @@
1
1
  """
2
2
  The style catalogue (``style_compositions.py``).
3
3
 
4
- Styles are data, not code: 42 ``TableComposition`` namedtuples. Nothing in the
4
+ Styles are data, not code: 43 ``TableComposition`` namedtuples. Nothing in the
5
5
  package validates them, so a malformed entry only shows up when a table is
6
6
  rendered with it. The smoke test below renders the same table in every style
7
7
  and checks the data survived.
@@ -33,10 +33,10 @@ def build_table(style_name):
33
33
  # The catalogue itself
34
34
  # +-------------------------------------------------------------------------+
35
35
 
36
- def test_the_catalogue_holds_42_styles():
36
+ def test_the_catalogue_holds_43_styles():
37
37
  # A canary: adding a style is meant to be purely additive, and the README,
38
38
  # ARCHITECTURE.md and style_examples.md all quote this number.
39
- assert len(ALL_STYLES) == 42
39
+ assert len(ALL_STYLES) == 44
40
40
 
41
41
 
42
42
  def test_style_names_are_unique():
@@ -187,3 +187,28 @@ def test_the_style_name_setter_works_from_any_directory(monkeypatch, tmp_path):
187
187
  def test_style_examples_is_present_at_the_repository_root():
188
188
  # Guards the fixture that makes the setter above usable in the suite.
189
189
  assert os.path.isfile(os.path.join(REPO_ROOT, 'style_examples.md'))
190
+
191
+
192
+ def test_blocks_style_is_in_the_catalogue():
193
+ assert 'blocks' in ALL_STYLES
194
+
195
+
196
+ def test_blocks_style_has_no_border_glyphs():
197
+ """blocks is fill-only: no box-drawing / ascii rule characters."""
198
+ table = build_table('blocks')
199
+ rendered = str(table)
200
+ for glyph in '┌┐└┘├┤┬┴┼│─═╪╧╤╞╡╒╘╛║╔╗╚╝┊┄╍+|':
201
+ assert glyph not in rendered, (glyph, rendered)
202
+
203
+
204
+ def test_blocks_style_keeps_cell_padding_for_background_fills():
205
+ import os
206
+ os.environ['FORCE_COLOR'] = '1'
207
+ os.environ.pop('NO_COLOR', None)
208
+ table = build_table('blocks')
209
+ table.use_colors = True
210
+ table.header_color = 'bold white on blue'
211
+ table.column_colors = {'Name': 'black on green'}
212
+ rendered = str(table)
213
+ assert '\x1b[' in rendered or '\033[' in rendered or '[' in rendered
214
+ assert '42m' in rendered or '44m' in rendered # green or blue bg
File without changes
File without changes
File without changes
File without changes