sheetmap 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.
sheetmap/page.py ADDED
@@ -0,0 +1,268 @@
1
+ """The standalone page: sheet images laid out in sections and grids, with optional review tools."""
2
+
3
+ import base64
4
+ from html import escape
5
+ import json
6
+
7
+ from sheetmap.layout import Grid, Slot, join
8
+
9
+
10
+ GENERATOR = '<meta name="generator" content="sheetmap">'
11
+
12
+ REVIEW_UI = """
13
+ <button id="open-summary" type="button" class="primary">Review summary (0)</button>
14
+ <dialog id="edit-dialog" aria-labelledby="edit-title">
15
+ <h2 id="edit-title">Review range</h2><div id="edit-context"></div>
16
+ <label for="new-range">Replacement cell or range, optional</label>
17
+ <input id="new-range" type="text" placeholder="For example: Analysis!F34:P36">
18
+ <label for="review-note">What should change?</label>
19
+ <textarea id="review-note" rows="3" placeholder="Describe the change, or add a reason for removal."></textarea>
20
+ <label class="scope" id="scope-option"><input id="wider-scope" type="checkbox"> <span id="scope-text"></span></label>
21
+ <p id="edit-error" role="alert"></p>
22
+ <div class="actions"><button id="save-remove" type="button" class="danger">Mark for removal</button>
23
+ <button id="save-change" type="button" class="primary">Save change</button>
24
+ <button id="clear-request" type="button">Undo request</button>
25
+ <button id="cancel-edit" type="button">Cancel</button></div>
26
+ </dialog>
27
+ <dialog id="summary-dialog" aria-labelledby="summary-title">
28
+ <h2 id="summary-title">Review summary</h2>
29
+ <p>Copy this text to pass the requests on. Nothing in the workbooks or their mappings has been changed.</p>
30
+ <textarea id="summary-text" readonly aria-label="Requested mapping changes"></textarea>
31
+ <p id="copy-status" role="status"></p>
32
+ <div class="actions"><button id="copy-summary" type="button" class="primary">Copy summary</button>
33
+ <button id="close-summary" type="button">Close</button></div>
34
+ </dialog>
35
+ """
36
+
37
+ SCRIPT = r"""
38
+ const storageKey=__STORAGE_KEY__;
39
+ const $=id=>document.getElementById(id);
40
+ const buttons=[...document.querySelectorAll('.range-review')];
41
+ const fields=new Map(buttons.map(button=>{const field=JSON.parse(button.dataset.field);return[field.id,field]}));
42
+ const requests=new Map();
43
+ let storageAvailable=true;
44
+ try{
45
+ const saved=JSON.parse(localStorage.getItem(storageKey)||'[]');
46
+ if(Array.isArray(saved))for(const request of saved){
47
+ const field=fields.get(request?.id);
48
+ if(field&&request.current===field.current&&['remove','change'].includes(request.action)
49
+ &&typeof request.note==='string'&&typeof request.replacement==='string'&&typeof request.widerScope==='boolean'){
50
+ requests.set(field.id,{...field,action:request.action,note:request.note,replacement:request.replacement,
51
+ widerScope:request.widerScope&&Boolean(field.scope)});
52
+ }
53
+ }
54
+ }catch{storageAvailable=false}
55
+ const edit=$('edit-dialog'), summaryDialog=$('summary-dialog'), replacement=$('new-range'), note=$('review-note');
56
+ const widerScope=$('wider-scope'), summary=$('summary-text');
57
+ let selected=null;
58
+ function context(field){
59
+ return ['Map: '+field.map,...Object.entries(field.details).map(([name,value])=>name+': '+value),
60
+ 'Workbook: '+field.workbook,'Sheet: '+field.sheet,'Label: '+field.label,
61
+ 'Current: '+field.current+' ('+field.kind+')'];
62
+ }
63
+ function summaryText(){
64
+ if(!requests.size)return 'No changes marked yet. Click a coloured label to add a request.';
65
+ const blocks=[...requests.values()].map(request=>[
66
+ ...context(request),
67
+ ...(request.scope?['Scope: '+(request.widerScope?request.scope:'Only this map')]:[]),
68
+ 'Action: '+request.action.toUpperCase(),
69
+ ...(request.action==='change'&&request.replacement?['Replacement: '+request.replacement]:[]),
70
+ ...(request.note?['Note: '+request.note]:[])
71
+ ].join('\n'));
72
+ return 'Requested mapping changes ('+requests.size+')\n\n'+blocks.join('\n\n');
73
+ }
74
+ function update(){
75
+ for(const button of buttons){
76
+ const request=requests.get(JSON.parse(button.dataset.field).id);
77
+ if(request)button.dataset.action=request.action;else delete button.dataset.action;
78
+ }
79
+ $('open-summary').textContent='Review summary ('+requests.size+')';
80
+ summary.value=summaryText();
81
+ $('copy-summary').disabled=!requests.size;
82
+ try{localStorage.setItem(storageKey,JSON.stringify([...requests.values()]))}catch{storageAvailable=false}
83
+ $('copy-status').textContent=storageAvailable?'Requests are saved in this browser.'
84
+ :'Browser storage is unavailable. Copy the summary before refreshing or closing this page.';
85
+ }
86
+ for(const button of buttons)button.addEventListener('click',()=>{
87
+ selected=JSON.parse(button.dataset.field);
88
+ const request=requests.get(selected.id);
89
+ $('edit-title').textContent=selected.label;
90
+ $('edit-context').textContent=context(selected).join('\n');
91
+ replacement.value=request?.replacement||'';note.value=request?.note||'';
92
+ $('scope-option').hidden=!selected.scope;$('scope-text').textContent=selected.scope||'';
93
+ widerScope.checked=request?.widerScope||false;
94
+ $('clear-request').disabled=!request;
95
+ $('edit-error').textContent='';edit.showModal();
96
+ });
97
+ function save(action){
98
+ const value=replacement.value.trim(), explanation=note.value.trim();
99
+ if(action==='change'&&!value&&!explanation){
100
+ $('edit-error').textContent='Enter a replacement cell or range, or describe the change.';return;
101
+ }
102
+ requests.set(selected.id,{...selected,action,replacement:action==='change'?value:'',note:explanation,
103
+ widerScope:Boolean(selected.scope)&&widerScope.checked});
104
+ update();edit.close();
105
+ }
106
+ $('save-remove').addEventListener('click',()=>save('remove'));
107
+ $('save-change').addEventListener('click',()=>save('change'));
108
+ $('clear-request').addEventListener('click',()=>{requests.delete(selected.id);update();edit.close()});
109
+ $('cancel-edit').addEventListener('click',()=>edit.close());
110
+ $('open-summary').addEventListener('click',()=>{update();summaryDialog.showModal()});
111
+ $('close-summary').addEventListener('click',()=>summaryDialog.close());
112
+ $('copy-summary').addEventListener('click',async()=>{
113
+ try{await navigator.clipboard.writeText(summary.value);$('copy-status').textContent='Copied to the clipboard.'}
114
+ catch{
115
+ summary.focus();summary.select();
116
+ $('copy-status').textContent='Summary selected. Press Ctrl+C or Cmd+C to copy it.';
117
+ }
118
+ });
119
+ update();
120
+ """
121
+
122
+
123
+ STYLES = """
124
+ :root{--ink:#172033;--muted:#64748b;--line:#e2e8f0;--page:#f8fafc}
125
+ *{box-sizing:border-box}
126
+ body{margin:0;background:var(--page);color:var(--ink);font:15px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
127
+ main{padding:28px 32px 64px}
128
+ header{margin-bottom:28px}
129
+ h1{font-size:24px;line-height:1.25;margin:0}
130
+ h2{font-size:17px;line-height:1.3;margin:0}
131
+ .meta{color:var(--muted);margin:4px 0 0;font-size:14px}
132
+ .legend{display:flex;flex-wrap:wrap;gap:6px 16px;margin:12px 0 0;padding:0;list-style:none;font-size:13px;
133
+ color:var(--muted)}
134
+ .legend li{display:flex;align-items:center;gap:6px}
135
+ .swatch{width:12px;height:12px;border-radius:3px;border:2px solid;display:inline-block}
136
+ section{margin:0 0 40px}
137
+ section>h2{margin-bottom:14px}
138
+ .scroll{overflow-x:auto;padding-bottom:4px}
139
+ .gallery{display:flex;flex-wrap:wrap;gap:24px;align-items:flex-start}
140
+ .grid{display:grid;gap:24px;align-items:start}
141
+ .grid>*{min-width:0}
142
+ .column-head,.row-head{font-weight:600;font-size:14px;color:var(--ink)}
143
+ .column-head{align-self:end;padding:0 2px}
144
+ .row-head{padding:12px 2px 0;position:sticky;left:0}
145
+ .gap{border:1px dashed var(--line);border-radius:8px;padding:16px;color:var(--muted);font-size:13px;
146
+ text-align:center}
147
+ figure{margin:0;max-width:100%;justify-self:start;background:white;border:1px solid var(--line);border-radius:8px;
148
+ box-shadow:0 1px 2px #0f172a0d;overflow:hidden}
149
+ figcaption{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 10px;padding:10px 14px;
150
+ border-bottom:1px solid var(--line)}
151
+ figcaption strong{font-size:15px}figcaption span{color:var(--muted);font-size:13px}
152
+ .frame{overflow-x:auto}
153
+ .sheet-image{position:relative}
154
+ img{display:block;max-width:none}
155
+ .fit img{width:100%;height:auto}
156
+ .grid>.column-head{margin-bottom:-12px}
157
+ @media print{body{background:white}main{padding:0}figure{break-inside:avoid;box-shadow:none}.scroll{overflow:visible}}
158
+ """
159
+
160
+ REVIEW_STYLES = """
161
+ .range-review{position:absolute;border:0;padding:0;background:transparent;cursor:pointer}
162
+ .range-review:hover,.range-review:focus-visible{outline:2px solid #172033;background:#ffffff33}
163
+ .range-review[data-action="remove"]{outline:2px solid #dc2626;background:#ef444433}
164
+ .range-review[data-action="remove"]:after{content:'';position:absolute;left:0;right:0;top:50%;
165
+ border-top:2px solid #b91c1c}
166
+ .range-review[data-action="change"]{outline:2px solid #d97706;background:#f59e0b33}
167
+ button{font:inherit;cursor:pointer;border:1px solid #cbd5e1;border-radius:5px;background:white;padding:8px 12px}
168
+ button.primary{background:#172033;color:white;border-color:#172033}
169
+ button.danger{color:#b91c1c;border-color:#fca5a5}
170
+ button:disabled{opacity:.45;cursor:default}
171
+ #open-summary{position:fixed;right:20px;bottom:20px;z-index:5;box-shadow:0 2px 12px #0002}
172
+ dialog{border:1px solid #cbd5e1;border-radius:9px;max-width:min(680px,90vw);width:640px;padding:24px;color:#172033}
173
+ dialog::backdrop{background:#17203366}dialog h2{margin:0 0 10px}dialog p{color:var(--muted)}
174
+ label{display:block;margin:16px 0 5px;font-size:13px}
175
+ input[type=text],textarea{width:100%;padding:9px;border:1px solid #cbd5e1;border-radius:4px;
176
+ font:13px ui-monospace,monospace}
177
+ textarea{resize:vertical}#summary-text{min-height:300px}
178
+ #edit-context{white-space:pre-wrap;font:12px ui-monospace,monospace;line-height:1.6;color:#475569;background:#f8fafc;
179
+ padding:12px}
180
+ .scope{display:flex;gap:8px;align-items:center}.scope[hidden]{display:none}
181
+ .actions{display:flex;flex-wrap:wrap;gap:9px;margin-top:18px}#edit-error,#copy-status{font-size:13px}
182
+ @media print{#open-summary,.range-review,dialog{display:none}}
183
+ """
184
+
185
+
186
+ def render_page(title: str, grids: list[Grid], *, fit: bool, legend: dict[str, str], storage_key: str | None) -> str:
187
+ """Build the page. ``storage_key`` turns on the review tools; ``None`` leaves the page without script."""
188
+ figures = [slot.figure for grid in grids for row in grid.rows for slot in row if slot]
189
+ maps = list(dict.fromkeys(figure.map_key for figure in figures))
190
+ workbooks = list(dict.fromkeys(figure.workbook for figure in figures))
191
+ if len(maps) == 1:
192
+ meta = join(figures[0].subtitle, figures[0].workbook)
193
+ else:
194
+ meta = join(f"{len(maps)} maps", ", ".join(workbooks))
195
+ # A single section named like the page needs no heading of its own.
196
+ if len(grids) == 1 and grids[0].heading in (title, figures[0].map_name if len(maps) == 1 else None):
197
+ grids[0].heading = None
198
+ swatches = "".join(
199
+ f'<li><span class="swatch" style="border-color:{colour};background:{colour}29"></span>{escape(kind)}</li>'
200
+ for kind, colour in legend.items()
201
+ )
202
+ review = storage_key is not None
203
+ script = f"<script>{SCRIPT.replace('__STORAGE_KEY__', json.dumps(storage_key))}</script>" if review else ""
204
+ return (
205
+ f'<!doctype html><html lang="en"><meta charset="utf-8">{GENERATOR}'
206
+ '<meta name="viewport" content="width=device-width,initial-scale=1">'
207
+ f"<title>{escape(title)}</title><style>{STYLES}{REVIEW_STYLES if review else ''}</style>"
208
+ f'<main{' class="fit"' if fit else ""}><header><h1>{escape(title)}</h1><p class="meta">{escape(meta)}</p>'
209
+ f'<ul class="legend" aria-label="Region kinds">{swatches}</ul></header>'
210
+ f"{''.join(_section(grid, fit) for grid in grids)}</main>{REVIEW_UI if review else ''}{script}</html>\n"
211
+ )
212
+
213
+
214
+ def _section(grid: Grid, fit: bool) -> str:
215
+ heading = f"<h2>{escape(grid.heading)}</h2>" if grid.heading else ""
216
+ if grid.flow:
217
+ # Flowing images keep their full size; fit applies to grids, where columns set the width.
218
+ body = '<div class="gallery">' + "".join(_figure(slot, False) for slot in grid.rows[0] if slot) + "</div>"
219
+ return f"<section>{heading}{body}</section>"
220
+ widths = grid.column_widths
221
+ # Fitted columns share the window in proportion to their full widths, so every image scales alike.
222
+ tracks = [f"minmax(0,{width}fr)" if fit else f"minmax({width}px,max-content)" for width in widths]
223
+ if grid.row_headers is not None:
224
+ tracks.insert(0, "max-content")
225
+ cells = []
226
+ if grid.column_headers is not None:
227
+ if grid.row_headers is not None:
228
+ cells.append("<div></div>")
229
+ cells.extend(f'<div class="column-head">{escape(name)}</div>' for name in grid.column_headers)
230
+ for index, row in enumerate(grid.rows):
231
+ if grid.row_headers is not None:
232
+ cells.append(f'<div class="row-head">{escape(grid.row_headers[index])}</div>')
233
+ for column, slot in enumerate(row):
234
+ if slot:
235
+ cells.append(_figure(slot, fit, widths[column]))
236
+ elif grid.gaps_say:
237
+ cells.append(f'<div class="gap">{escape(grid.gaps_say)}</div>')
238
+ else:
239
+ cells.append("<div></div>")
240
+ grid_html = f'<div class="grid" style="grid-template-columns:{" ".join(tracks)}">{"".join(cells)}</div>'
241
+ return f'<section>{heading}<div class="scroll">{grid_html}</div></section>'
242
+
243
+
244
+ def _figure(slot: Slot, fit: bool, column_width: int = 0) -> str:
245
+ figure = slot.figure
246
+ notes = [_count(figure.regions, "region")]
247
+ cut = [_count(figure.rows, "row")] * figure.rows_cut + [_count(figure.cols, "column")] * figure.cols_cut
248
+ if cut:
249
+ notes.append("preview of the first " + " and ".join(cut))
250
+ caption = f"<strong>{escape(slot.caption)}</strong>" if slot.caption else ""
251
+ encoded = base64.b64encode(figure.png).decode("ascii")
252
+ alt = escape(f"{figure.sheet} with highlighted and labelled ranges", quote=True)
253
+ # Review buttons are placed in percentages, so they stay on their labels when an image is scaled.
254
+ if fit:
255
+ figure_style = f' style="width:{figure.width / column_width * 100:.4f}%;max-width:{figure.width + 2}px"'
256
+ size = "width:100%"
257
+ else:
258
+ figure_style, size = "", f"width:{figure.width}px"
259
+ return (
260
+ f"<figure{figure_style}><figcaption>{caption}<span>{escape(join(*notes))}</span></figcaption>"
261
+ f'<div class="frame"><div class="sheet-image" style="{size}">'
262
+ f'<img src="data:image/png;base64,{encoded}" width="{figure.width}" height="{figure.height}" alt="{alt}">'
263
+ f"{''.join(figure.buttons)}</div></div></figure>"
264
+ )
265
+
266
+
267
+ def _count(number: int, noun: str) -> str:
268
+ return f"{number} {noun}" + ("" if number == 1 else "s")
sheetmap/py.typed ADDED
File without changes
sheetmap/render.py ADDED
@@ -0,0 +1,193 @@
1
+ """Render maps to PNGs, a manifest and a standalone HTML page."""
2
+
3
+ from collections.abc import Iterable, Iterator
4
+ from contextlib import contextmanager
5
+ import hashlib
6
+ from html import escape
7
+ import json
8
+ from pathlib import Path
9
+ import re
10
+ import warnings
11
+ from zipfile import BadZipFile
12
+
13
+ from openpyxl import load_workbook
14
+ from openpyxl.utils.exceptions import InvalidFileException
15
+ from openpyxl.workbook import Workbook
16
+
17
+ from sheetmap.addressing import area_text
18
+ from sheetmap.draw import COLOURS, SheetImage, load_fonts, place, render_sheet
19
+ from sheetmap.errors import SheetmapError
20
+ from sheetmap.layout import Figure, Layout, arrange, check_layout
21
+ from sheetmap.model import SheetMap, validate
22
+ from sheetmap.page import GENERATOR, render_page
23
+
24
+
25
+ def render(
26
+ maps: Iterable[SheetMap],
27
+ output: str | Path,
28
+ title: str | None = None,
29
+ *,
30
+ layout: Layout | None = None,
31
+ review: bool = False,
32
+ ) -> Path:
33
+ """Write ``output`` (an .html file) and ``<stem>_assets/`` holding a PNG per sheet and ``manifest.json``.
34
+
35
+ ``layout`` arranges the images; by default each map gets a section with its sheets side by side.
36
+ See ``sheetmap.Layout``. ``review`` adds clickable labels and a summary of requested changes.
37
+
38
+ Only sheets with regions are drawn. Formula cells show their saved values. Workbooks are opened for
39
+ reading and never saved. An existing HTML file is replaced only if sheetmap wrote it.
40
+ """
41
+ layout = layout or Layout()
42
+ check_layout(layout)
43
+ output = Path(output)
44
+ if output.suffix.lower() != ".html":
45
+ raise SheetmapError("Output must be an .html file")
46
+ maps = _checked(maps)
47
+ if output.exists() and GENERATOR not in output.read_text(encoding="utf-8", errors="replace")[:2048]:
48
+ raise SheetmapError(f"{output} exists and was not written by sheetmap; choose another output")
49
+ assets = output.parent / (output.stem + "_assets")
50
+ assets.mkdir(parents=True, exist_ok=True)
51
+ fonts = load_fonts()
52
+ figures, manifest, kinds = [], [], set()
53
+ for sheet_map in maps:
54
+ with _open(sheet_map) as book:
55
+ for sheet_name, regions in place(book, sheet_map).items():
56
+ drawn = render_sheet(book[sheet_name], regions, sheet_map, fonts)
57
+ png = _slug(sheet_map.resolved_key, sheet_name) + ".png"
58
+ drawn.image.save(assets / png)
59
+ figures.append(_figure(sheet_map, sheet_name, drawn, (assets / png).read_bytes(), review))
60
+ kinds.update(placed.kind for placed in regions if not placed.region.colour)
61
+ manifest.append(_manifest_entry(sheet_map, sheet_name, drawn, png))
62
+ if not manifest:
63
+ raise SheetmapError("No regions to draw")
64
+ page_title = title or (maps[0].resolved_title if len(maps) == 1 else "Sheet maps")
65
+ storage_key = None
66
+ if review:
67
+ storage_key = "sheetmap-review-" + hashlib.sha256(str(output.resolve()).encode()).hexdigest()[:16]
68
+ legend = {kind: colour for kind, colour in COLOURS.items() if kind in kinds}
69
+ grids = arrange(figures, layout)
70
+ page = render_page(page_title, grids, fit=layout.fit, legend=legend, storage_key=storage_key)
71
+ output.write_text(page, encoding="utf-8")
72
+ (assets / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
73
+ return output
74
+
75
+
76
+ def check(maps: Iterable[SheetMap]) -> dict[str, int]:
77
+ """Check every map against its workbook without drawing or writing anything."""
78
+ maps = _checked(maps)
79
+ sheets = regions = 0
80
+ for sheet_map in maps:
81
+ with _open(sheet_map) as book:
82
+ placed = place(book, sheet_map)
83
+ sheets += len(placed)
84
+ regions += sum(len(items) for items in placed.values())
85
+ return {"maps": len(maps), "sheets": sheets, "regions": regions}
86
+
87
+
88
+ def _checked(maps: Iterable[SheetMap]) -> list[SheetMap]:
89
+ maps = list(maps)
90
+ if not maps:
91
+ raise SheetmapError("Provide at least one map")
92
+ keys = set()
93
+ for sheet_map in maps:
94
+ validate(sheet_map)
95
+ if sheet_map.resolved_key in keys:
96
+ raise SheetmapError(f"Duplicate map key {sheet_map.resolved_key!r}; give each map its own key")
97
+ keys.add(sheet_map.resolved_key)
98
+ return maps
99
+
100
+
101
+ @contextmanager
102
+ def _open(sheet_map: SheetMap) -> Iterator[Workbook]:
103
+ # Full mode, not read-only: merged ranges, fills and borders are only available there.
104
+ with warnings.catch_warnings():
105
+ warnings.simplefilter("ignore", UserWarning)
106
+ try:
107
+ book = load_workbook(sheet_map.workbook, data_only=True)
108
+ except (OSError, BadZipFile, InvalidFileException, KeyError) as error:
109
+ raise SheetmapError(f"Cannot open {sheet_map.workbook}: {error}") from error
110
+ try:
111
+ yield book
112
+ finally:
113
+ book.close()
114
+
115
+
116
+ def _slug(key: str, sheet: str) -> str:
117
+ readable = re.sub(r"[^a-z0-9]+", "_", (key + "__" + sheet).lower()).strip("_")
118
+ return readable + "_" + hashlib.sha256((key + "\0" + sheet).encode()).hexdigest()[:8]
119
+
120
+
121
+ def _figure(sheet_map: SheetMap, sheet_name: str, drawn: SheetImage, png: bytes, review: bool) -> Figure:
122
+ width, height = drawn.image.size
123
+ return Figure(
124
+ map_key=sheet_map.resolved_key,
125
+ map_title=sheet_map.resolved_title,
126
+ subtitle=sheet_map.subtitle,
127
+ workbook=Path(sheet_map.workbook).name,
128
+ sheet=sheet_name,
129
+ png=png,
130
+ width=width,
131
+ height=height,
132
+ regions=len(drawn.tags),
133
+ rows=drawn.rows,
134
+ cols=drawn.cols,
135
+ rows_cut=drawn.rows_cut,
136
+ cols_cut=drawn.cols_cut,
137
+ buttons=_review_buttons(sheet_map, sheet_name, drawn) if review else [],
138
+ )
139
+
140
+
141
+ def _review_buttons(sheet_map: SheetMap, sheet_name: str, drawn: SheetImage) -> list[str]:
142
+ width, height = drawn.image.size
143
+ buttons = []
144
+ for tag in drawn.tags:
145
+ region = tag.placed.region
146
+ field = {
147
+ "id": json.dumps([sheet_map.resolved_key, region.label], separators=(",", ":")),
148
+ "map": sheet_map.resolved_title,
149
+ "details": dict(sheet_map.details),
150
+ "workbook": Path(sheet_map.workbook).name,
151
+ "sheet": sheet_name,
152
+ "label": region.label,
153
+ "current": region.ref,
154
+ "kind": tag.placed.kind,
155
+ "scope": sheet_map.scope,
156
+ }
157
+ style = (
158
+ f"left:{tag.left / width * 100:.8f}%;top:{tag.top / height * 100:.8f}%;"
159
+ f"width:{(tag.right - tag.left) / width * 100:.8f}%;height:{19 / height * 100:.8f}%"
160
+ )
161
+ buttons.append(
162
+ f'<button type="button" class="range-review" data-field="{escape(json.dumps(field), quote=True)}" '
163
+ f'style="{style}" '
164
+ f'aria-label="Review {escape(region.label, quote=True)} on {escape(sheet_name, quote=True)}" '
165
+ f'title="Review {escape(region.label, quote=True)}: {escape(region.ref, quote=True)}"></button>'
166
+ )
167
+ return buttons
168
+
169
+
170
+ def _manifest_entry(sheet_map: SheetMap, sheet_name: str, drawn: SheetImage, png: str) -> dict:
171
+ width, height = drawn.image.size
172
+ return {
173
+ "key": sheet_map.resolved_key,
174
+ "title": sheet_map.resolved_title,
175
+ "subtitle": sheet_map.subtitle,
176
+ "workbook": Path(sheet_map.workbook).name,
177
+ "sheet": sheet_name,
178
+ "png": png,
179
+ "width": width,
180
+ "height": height,
181
+ "values_drawn": drawn.values_drawn,
182
+ "truncated": drawn.truncated,
183
+ "regions": [
184
+ {
185
+ "label": tag.placed.region.label,
186
+ "ref": tag.placed.region.ref,
187
+ "kind": tag.placed.kind,
188
+ "area": area_text(*tag.placed.area),
189
+ "axis_labels": [label.text for label in tag.placed.axis_labels],
190
+ }
191
+ for tag in drawn.tags
192
+ ],
193
+ }