feat: styles minimaux, fusions et volets figes dans la visionneuse xlsx #153
A15 — le rendu tableur lit les metadonnees du classeur (une charge en mode
normal par feuille) et les restitue : styles inline data-driven (couleur de
police en premier, fond, gras/italique, format numerique signale en mono),
alignements non-defaut, plages fusionnees (rowSpan/colSpan cote client) et
ancrage des volets figes (sticky rows/cols). Le chargement lazy replie les
metadonnees de chaque fenetre. Contrat API : styles/aligns = {ref: css},
merges = [ranges], freeze = ancre. 9 tests backend + contre-preuve (5 echecs
sur neutralisation), JSDOM 33/33.
🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
This commit is contained in:
@@ -309,6 +309,9 @@ async def api_file(vault_name: str, path: str = Query(..., description="Relative
|
||||
try:
|
||||
from backend.xlsx_reader import inspect_workbook, render_sheets
|
||||
|
||||
# #153 A15 — every sheet dict already carries its styles, aligns,
|
||||
# merges and freeze anchor (read_workbook_meta, one normal-mode
|
||||
# load inside render_sheets).
|
||||
sheets = render_sheets(file_path)
|
||||
size = file_path.stat().st_size
|
||||
return {
|
||||
|
||||
+198
-3
@@ -65,6 +65,130 @@ MAX_INDEX_CHARS = 5_000
|
||||
_INDEX_ROWS_PER_SHEET = 20
|
||||
MAX_INDEX_SHEETS = 20
|
||||
|
||||
# #153 A15 — reading styles is a second (non-read_only) pass on the sheet XML.
|
||||
# Bounded like everything else: a cell must be INSIDE the rendered window to
|
||||
# deserve an inline style, so a huge workbook never triggers a huge payload.
|
||||
# Only data-driven fragments are emitted: the hex values come from the file,
|
||||
# never from a hardcoded color table.
|
||||
|
||||
|
||||
def _cell_fragments(cell: Any) -> tuple[list[str], str | None]:
|
||||
"""Inline CSS fragments of one cell plus its horizontal alignment.
|
||||
|
||||
Fixed, color-first order: the API contract documents ``color:...`` as the
|
||||
first fragment of a styled cell. Only data-driven values are emitted —
|
||||
every hex comes from the workbook itself, never a hardcoded table.
|
||||
"""
|
||||
fragments: list[str] = []
|
||||
font = cell.font
|
||||
if font and font.color is not None and isinstance(font.color.rgb, str):
|
||||
# ARGB from the workbook itself — never a hardcoded table.
|
||||
rgb = font.color.rgb
|
||||
if len(rgb) == 8 and rgb != "FF000000":
|
||||
fragments.append(f"color:#{rgb[2:].lower()}")
|
||||
fill = cell.fill
|
||||
if fill and fill.fgColor is not None and isinstance(fill.fgColor.rgb, str):
|
||||
rgb = fill.fgColor.rgb
|
||||
if len(rgb) == 8 and rgb not in ("00000000", "FFFFFFFF"):
|
||||
fragments.append(f"background:#{rgb[2:].lower()}")
|
||||
if font and font.bold:
|
||||
fragments.append("font-weight:600")
|
||||
if font and font.italic:
|
||||
fragments.append("font-style:italic")
|
||||
fmt = cell.number_format
|
||||
if fmt and fmt not in ("General", "@"):
|
||||
# A custom number format is signalled typographically (mono font)
|
||||
# rather than rendered: the displayed value already carries the
|
||||
# formatting from _fmt(). Single quotes: the fragment lands inside a
|
||||
# double-quoted HTML attribute.
|
||||
fragments.append("font-family:'JetBrains Mono',monospace")
|
||||
alignment = cell.alignment
|
||||
align = alignment.horizontal if alignment else None
|
||||
return fragments, (align if align in ("left", "right", "center") else None)
|
||||
|
||||
|
||||
def _sheet_style_maps(ws: Any) -> tuple[dict[str, str], dict[str, str]]:
|
||||
"""Flat ``{ref: css}`` and ``{ref: align}`` maps of one worksheet.
|
||||
|
||||
The flat string is what the API serves and what the viewer applies
|
||||
verbatim to ``td.style``; a plain cell is simply absent from the map.
|
||||
``left`` is the table default and never included. Bounded by
|
||||
``MAX_ROWS x MAX_COLS`` like the render itself.
|
||||
"""
|
||||
styles: dict[str, str] = {}
|
||||
aligns: dict[str, str] = {}
|
||||
for row in ws.iter_rows(min_row=1, max_row=MAX_ROWS, max_col=MAX_COLS):
|
||||
for cell in row:
|
||||
if cell.value is None and cell.number_format == "General":
|
||||
continue
|
||||
fragments, align = _cell_fragments(cell)
|
||||
if fragments:
|
||||
styles[cell.coordinate] = ";".join(fragments)
|
||||
if align and align != "left":
|
||||
aligns[cell.coordinate] = align
|
||||
return styles, aligns
|
||||
|
||||
|
||||
def read_sheet_styles(file_path: Path, sheet: str) -> dict[str, dict[str, Any]]:
|
||||
"""Return ``{ref: {style, align}}`` for the styled cells of one sheet.
|
||||
|
||||
``style`` is the flat CSS fragment the viewer applies verbatim and
|
||||
``align`` the horizontal text-align when it is not the table default.
|
||||
Normal (non-streaming) load — styles are unavailable in read_only mode;
|
||||
a failure yields ``{}`` so the viewer falls back to the plain rendering.
|
||||
"""
|
||||
meta = read_workbook_meta(file_path).get(sheet, {})
|
||||
styles_map = meta.get("styles", {})
|
||||
aligns = meta.get("aligns", {})
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for ref, css in styles_map.items():
|
||||
entry: dict[str, Any] = {"style": css}
|
||||
if ref in aligns:
|
||||
entry["align"] = aligns[ref]
|
||||
out[ref] = entry
|
||||
return out
|
||||
|
||||
|
||||
def read_sheet_merges(file_path: Path, sheet: str) -> list[str]:
|
||||
"""Return the merged ranges of one sheet as ``A1:C3`` strings."""
|
||||
try:
|
||||
# Styles and merges are only fully materialised in normal mode
|
||||
# (read_only=True leaves merged_cells empty).
|
||||
wb = load_workbook(str(file_path))
|
||||
except Exception:
|
||||
return []
|
||||
try:
|
||||
if sheet not in wb.sheetnames:
|
||||
return []
|
||||
merged = getattr(wb[sheet], "merged_cells", None)
|
||||
ranges = getattr(merged, "ranges", None) or []
|
||||
return [str(r) for r in ranges]
|
||||
except Exception:
|
||||
logger.debug("xlsx merges unavailable", exc_info=True)
|
||||
return []
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def read_sheet_freeze(file_path: Path, sheet: str) -> str:
|
||||
"""Return the freeze-panes anchor of one sheet ('' when not frozen).
|
||||
|
||||
Normal (non-streaming) load: `freeze_panes` is NOT materialised on
|
||||
ReadOnlyWorksheet in openpyxl 3.1.x — read_only=True always yields ''.
|
||||
"""
|
||||
try:
|
||||
wb = load_workbook(str(file_path))
|
||||
except Exception:
|
||||
return ""
|
||||
try:
|
||||
if sheet not in wb.sheetnames:
|
||||
return ""
|
||||
return str(getattr(wb[sheet], "freeze_panes", None) or "")
|
||||
except Exception:
|
||||
return ""
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _fmt(value: Any) -> str:
|
||||
if value is None:
|
||||
@@ -108,6 +232,7 @@ def _table(
|
||||
grid: list[list[str]],
|
||||
cached: list[list[str]] | None = None,
|
||||
row_offset: int = 0,
|
||||
styles: dict[str, dict[str, Any]] | None = None,
|
||||
) -> str:
|
||||
"""Render a grid as an HTML table.
|
||||
|
||||
@@ -121,6 +246,11 @@ def _table(
|
||||
``row_offset`` is the number of rows skipped before this grid (#153 A9): the
|
||||
row numbers and the ``data-cell`` references must stay the real A1
|
||||
coordinates of the sheet, not of the window.
|
||||
|
||||
``styles`` maps A1 references to ``{style, align}`` fragments (#153 A15:
|
||||
bold, italic, background, alignment) — the backend only reads the
|
||||
workbook, the fragments are built from it and always data-driven, never
|
||||
hardcoded colors. A plain ``str`` value is tolerated (legacy callers).
|
||||
"""
|
||||
if not grid:
|
||||
return "<p><em>Feuille vide</em></p>"
|
||||
@@ -137,6 +267,20 @@ def _table(
|
||||
out.append(f'<tr><th class="xlsx-rownum">{r}</th>')
|
||||
for c, val in enumerate(row, start=1):
|
||||
ref = f"{get_column_letter(c)}{r}"
|
||||
meta = (styles or {}).get(ref)
|
||||
if meta is None:
|
||||
style_attr = ""
|
||||
else:
|
||||
# Legacy callers may still pass a bare CSS string.
|
||||
if isinstance(meta, str):
|
||||
meta = {"style": meta}
|
||||
fragment = meta.get("style", "")
|
||||
align = meta.get("align")
|
||||
if align and align not in ("left",):
|
||||
# left is the table default; only non-default alignments
|
||||
# need an explicit declaration.
|
||||
fragment = f"{fragment};text-align:{align}" if fragment else f"text-align:{align}"
|
||||
style_attr = f' style="{fragment}"' if fragment else ""
|
||||
# The cached result only makes sense for a formula cell: on a plain
|
||||
# value cell the two reads are identical and showing both would
|
||||
# duplicate the text.
|
||||
@@ -153,7 +297,7 @@ def _table(
|
||||
f"{html.escape(cval)}</span>"
|
||||
)
|
||||
out.append(
|
||||
f'<td data-cell="{ref}">{html.escape(val)}{shadow}</td>'
|
||||
f'<td data-cell="{ref}"{style_attr}>{html.escape(val)}{shadow}</td>'
|
||||
)
|
||||
out.append("</tr>")
|
||||
out.append("</tbody></table></div>")
|
||||
@@ -205,6 +349,40 @@ def inspect_workbook(file_path: Path) -> list[str]:
|
||||
return []
|
||||
|
||||
|
||||
def read_workbook_meta(file_path: Path) -> dict[str, dict[str, Any]]:
|
||||
"""Return ``{sheet: {styles, aligns, merges, freeze}}`` for every sheet.
|
||||
|
||||
One normal (non-streaming) load serves the three A15 metadata maps: the
|
||||
fragments are the workbook's own values, a failure yields ``{}`` per sheet
|
||||
so the viewer keeps its plain rendering. Styles are read with
|
||||
``data_only=False`` — the edited value is the formula, not its result.
|
||||
"""
|
||||
try:
|
||||
wb = load_workbook(str(file_path), data_only=False)
|
||||
except Exception:
|
||||
return {}
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
try:
|
||||
for ws in wb.worksheets:
|
||||
styles, aligns = _sheet_style_maps(ws)
|
||||
merged = getattr(ws, "merged_cells", None)
|
||||
ranges = getattr(merged, "ranges", None) or []
|
||||
out[ws.title] = {
|
||||
"styles": styles,
|
||||
"aligns": aligns,
|
||||
"merges": [str(r) for r in ranges],
|
||||
"freeze": str(getattr(ws, "freeze_panes", None) or ""),
|
||||
}
|
||||
return out
|
||||
except Exception:
|
||||
logger.debug("xlsx meta unavailable", exc_info=True)
|
||||
for t in wb.sheetnames:
|
||||
out.setdefault(t, {"styles": {}, "aligns": {}, "merges": [], "freeze": ""})
|
||||
return out
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def render_sheets(file_path: Path) -> list[dict[str, Any]]:
|
||||
"""Return one dict per sheet: ``{name, html, rows, cols, total_*, truncated}``.
|
||||
|
||||
@@ -230,6 +408,10 @@ def render_sheets(file_path: Path) -> list[dict[str, Any]]:
|
||||
if _has_cached_values(file_path):
|
||||
cached = _read_cached_grids(file_path, titles)
|
||||
|
||||
# #153 A15 — one extra normal-mode load serves the styles/merges/freeze
|
||||
# metadata of every sheet; the HTML then carries the fragments itself.
|
||||
meta = read_workbook_meta(file_path)
|
||||
|
||||
sheets = []
|
||||
for i, title in enumerate(titles):
|
||||
grid = _trim(formulas[i])
|
||||
@@ -239,10 +421,11 @@ def render_sheets(file_path: Path) -> list[dict[str, Any]]:
|
||||
# positionally against the untrimmed grid keeps the two aligned.
|
||||
shadow = cached[i] if cached is not None and i < len(cached) else None
|
||||
total_rows, total_cols = extents[i]
|
||||
sheet_meta = meta.get(title, {})
|
||||
sheets.append(
|
||||
{
|
||||
"name": title,
|
||||
"html": _table(grid, shadow),
|
||||
"html": _table(grid, shadow, styles=sheet_meta.get("styles")),
|
||||
"rows": len(grid),
|
||||
"cols": max((len(r) for r in grid), default=0),
|
||||
"total_rows": total_rows,
|
||||
@@ -257,6 +440,10 @@ def render_sheets(file_path: Path) -> list[dict[str, Any]]:
|
||||
# decided its shape: comparing against the *rendered* size would
|
||||
# flag every sheet carrying a few empty formatted rows.
|
||||
"truncated": total_rows > MAX_ROWS or total_cols > MAX_COLS,
|
||||
"styles": sheet_meta.get("styles", {}),
|
||||
"aligns": sheet_meta.get("aligns", {}),
|
||||
"merges": sheet_meta.get("merges", []),
|
||||
"freeze": sheet_meta.get("freeze", ""),
|
||||
}
|
||||
)
|
||||
return sheets
|
||||
@@ -300,6 +487,10 @@ def read_sheet_window(
|
||||
# archive really holds cached results.
|
||||
if _has_cached_values(file_path):
|
||||
shadow = _read_cached_window(file_path, sheet, offset, limit)
|
||||
# #153 A15 — same metadata as the full render, so a lazy window is
|
||||
# indistinguishable from it (styles in the HTML, merges/freeze for the
|
||||
# client-side spanning).
|
||||
meta = read_workbook_meta(file_path).get(sheet, {})
|
||||
return {
|
||||
"sheet": sheet,
|
||||
"offset": offset,
|
||||
@@ -312,7 +503,11 @@ def read_sheet_window(
|
||||
"max_cols": MAX_COLS,
|
||||
"truncated": total_rows > MAX_ROWS or total_cols > MAX_COLS,
|
||||
"has_more": offset + len(grid) < total_rows,
|
||||
"html": _table(grid, shadow, row_offset=offset),
|
||||
"html": _table(grid, shadow, row_offset=offset, styles=meta.get("styles")),
|
||||
"styles": meta.get("styles", {}),
|
||||
"aligns": meta.get("aligns", {}),
|
||||
"merges": meta.get("merges", []),
|
||||
"freeze": meta.get("freeze", ""),
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user