Coverage for src/python/ensembl/vep/render/table.py: 100%
61 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Rendering a table in the formats this project publishes to."""
16from __future__ import annotations
18from collections.abc import Sequence
19from enum import Enum
20from xml.sax.saxutils import escape
22from ensembl.vep.render.theme import Colour, Metric
24__all__ = ["TableFormat", "render_table"]
26EMPTY_CELL = "--"
27"""What an absent value is shown as, matching the retired scripts' convention."""
30class TableFormat(Enum):
31 """The formats a table can be rendered in."""
33 MARKDOWN = "markdown"
34 CONFLUENCE = "confluence"
35 TEXT = "text"
36 HTML = "html"
39def _cells(row: Sequence[object]) -> list[str]:
40 """Return one row's values as display strings."""
41 rendered = []
42 for value in row:
43 text = "" if value is None else str(value)
44 rendered.append(text or EMPTY_CELL)
45 return rendered
48def _column_widths(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> list[int]:
49 """Return the width each column needs to fit its widest value."""
50 widths = [len(header) for header in headers]
51 for row in rows:
52 for index, text in enumerate(_cells(row)):
53 widths[index] = max(widths[index], len(text))
54 return widths
57def _render_markdown(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> str:
58 """Return a GitHub-flavoured pipe table."""
59 lines = ["| " + " | ".join(headers) + " |"]
60 lines.append("|" + "|".join("---" for _ in headers) + "|")
61 for row in rows:
62 lines.append("| " + " | ".join(_cells(row)) + " |")
63 return "\n".join(lines)
66def _render_confluence(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> str:
67 """Return classic Confluence wiki markup, for pasting into the source view."""
68 lines = ["||" + "||".join(headers) + "||"]
69 for row in rows:
70 lines.append("|" + "|".join(_cells(row)) + "|")
71 return "\n".join(lines)
74def _render_text(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> str:
75 """Return a fixed-width table, as the retired scripts printed."""
76 widths = _column_widths(headers, rows)
77 header_line = " ".join(header.ljust(widths[index]) for index, header in enumerate(headers))
78 lines = [header_line.rstrip(), " ".join("-" * width for width in widths)]
79 for row in rows:
80 cells = _cells(row)
81 line = " ".join(cell.ljust(widths[index]) for index, cell in enumerate(cells))
82 lines.append(line.rstrip())
83 return "\n".join(lines)
86def _render_html(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> str:
87 """Return an HTML table styled as ``ensembl-client``'s table component.
89 Follows the site rather than the old VEP summary page, which striped alternate rows.
90 """
91 head = "".join(f"<th>{escape(header)}</th>" for header in headers)
92 body_rows = []
93 for row in rows:
94 cells = "".join(f"<td>{escape(cell)}</td>" for cell in _cells(row))
95 body_rows.append(f"<tr>{cells}</tr>")
96 body = "\n ".join(body_rows)
97 return (
98 f'<table class="vep-table">\n <thead><tr>{head}</tr></thead>\n'
99 f" <tbody>\n {body}\n </tbody>\n</table>"
100 )
103TABLE_STYLES = f"""
104.vep-table {{
105 border-collapse: collapse;
106 background-color: {Colour.WHITE.var};
107}}
109.vep-table th {{
110 font-size: 11px;
111 font-weight: {Metric.FONT_WEIGHT_LIGHT.value};
112 text-align: left;
113 padding: 0 32px 4px 24px;
114 box-shadow: inset 0 -1.5px 0 {Colour.BLUE.var};
115}}
117.vep-table td {{
118 padding: 9px 32px 9px 24px;
119 vertical-align: middle;
120}}
122.vep-table tr + tr {{
123 border-top: 1px solid {Colour.GREY.var};
124}}
125"""
126"""CSS the HTML format depends on, for a page that embeds a table."""
128_RENDERERS = {
129 TableFormat.MARKDOWN: _render_markdown,
130 TableFormat.CONFLUENCE: _render_confluence,
131 TableFormat.TEXT: _render_text,
132 TableFormat.HTML: _render_html,
133}
136def render_table(
137 headers: Sequence[str],
138 rows: Sequence[Sequence[object]],
139 table_format: TableFormat = TableFormat.MARKDOWN,
140) -> str:
141 """Return a table in one of the published formats.
143 Args:
144 headers (Sequence[str]): The column headings.
145 rows (Sequence[Sequence[object]]): One sequence of values per row, each the same length as
146 ``headers``.
147 table_format (TableFormat): Which format to render.
149 Returns:
150 str: The rendered table.
152 Raises:
153 ValueError: If a row has a different number of values than there are headers.
154 """
155 for index, row in enumerate(rows):
156 if len(row) != len(headers):
157 raise ValueError(f"Row {index} has {len(row)} values, expected {len(headers)}")
158 return _RENDERERS[table_format](headers, rows)