transcript.md 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 (49) hide show
  1. transcript/__init__.py +35 -0
  2. transcript/_rule/__init__.py +0 -0
  3. transcript/_rule/archive.py +128 -0
  4. transcript/_rule/conda.py +52 -0
  5. transcript/_rule/container.py +290 -0
  6. transcript/_rule/core.py +524 -0
  7. transcript/_rule/lambdas.py +120 -0
  8. transcript/_rule/registry.py +54 -0
  9. transcript/_rule/serialize.py +26 -0
  10. transcript/_rule/snakefile.py +81 -0
  11. transcript/_rule/wildcards.py +110 -0
  12. transcript/cli.py +363 -0
  13. transcript/document.py +56 -0
  14. transcript/execute.py +240 -0
  15. transcript/html/__init__.py +17 -0
  16. transcript/html/_assets/.frontend.sha256 +1 -0
  17. transcript/html/_assets/__init__.py +21 -0
  18. transcript/html/_assets/style.min.css +1 -0
  19. transcript/html/_assets/transcript.min.js +21 -0
  20. transcript/html/_island.py +72 -0
  21. transcript/html/_navigate.py +198 -0
  22. transcript/html/_output.py +100 -0
  23. transcript/html/_resources.py +171 -0
  24. transcript/html/_review.py +34 -0
  25. transcript/html/markup.py +26 -0
  26. transcript/html/page.py +107 -0
  27. transcript/output.py +308 -0
  28. transcript/parse.py +256 -0
  29. transcript/renderers/__init__.py +126 -0
  30. transcript/renderers/bitmap.py +166 -0
  31. transcript/renderers/compose.py +174 -0
  32. transcript/renderers/compose_runtime.js +233 -0
  33. transcript/renderers/datavzrd.py +321 -0
  34. transcript/renderers/datavzrd_runtime.js +362 -0
  35. transcript/renderers/label.py +211 -0
  36. transcript/renderers/markdown.py +45 -0
  37. transcript/renderers/table.py +32 -0
  38. transcript/renderers/vegalite.py +250 -0
  39. transcript/review/__init__.py +13 -0
  40. transcript/review/_block.py +167 -0
  41. transcript/review/_migrate.py +212 -0
  42. transcript/review/_records.py +238 -0
  43. transcript/review/_span.py +287 -0
  44. transcript/review/load.py +64 -0
  45. transcript/tmd.py +159 -0
  46. transcript_md-0.1.0.dist-info/METADATA +17 -0
  47. transcript_md-0.1.0.dist-info/RECORD +49 -0
  48. transcript_md-0.1.0.dist-info/WHEEL +4 -0
  49. transcript_md-0.1.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,166 @@
1
+ """Renderer for static bitmaps and Matplotlib plot snapshots."""
2
+
3
+ import base64
4
+ import json
5
+ import struct
6
+ from html import escape
7
+ from io import BytesIO
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from ..output import Renderer
12
+ from . import register
13
+
14
+ _STYLE = """
15
+ /* portable bitmap snapshots */
16
+ .transcript-bitmap {
17
+ display: block; max-width: 100%; height: auto; margin: .5rem auto;
18
+ }
19
+ .transcript-bitmap[style] {
20
+ width: min(100%, calc(50vh * var(--image-ratio)));
21
+ }
22
+ """
23
+
24
+
25
+ def _image_type(data: bytes):
26
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
27
+ return "image/png"
28
+ if data.startswith(b"\xff\xd8\xff"):
29
+ return "image/jpeg"
30
+ if data.startswith((b"GIF87a", b"GIF89a")):
31
+ return "image/gif"
32
+ if data.startswith(b"RIFF") and data[8:12] == b"WEBP":
33
+ return "image/webp"
34
+ return None
35
+
36
+
37
+ def _png_dimensions(data: bytes) -> tuple[int, int] | None:
38
+ if (
39
+ len(data) >= 24
40
+ and data.startswith(b"\x89PNG\r\n\x1a\n")
41
+ and data[12:16] == b"IHDR"
42
+ ):
43
+ width, height = struct.unpack(">II", data[16:24])
44
+ if width and height:
45
+ return width, height
46
+ return None
47
+
48
+
49
+ def _matplotlib_figure(value) -> Any:
50
+ """Return the Figure behind a Figure, Axes, Artist, or artist sequence."""
51
+ if callable(getattr(value, "savefig", None)):
52
+ return value
53
+ if isinstance(value, (list, tuple)) and value:
54
+ figures = [_matplotlib_figure(item) for item in value]
55
+ if any(figure is None for figure in figures):
56
+ return None
57
+ if any(figure is not figures[0] for figure in figures[1:]):
58
+ raise ValueError("bitmap plot objects must belong to one figure")
59
+ return figures[0]
60
+ get_figure = getattr(value, "get_figure", None)
61
+ return get_figure() if callable(get_figure) else None
62
+
63
+
64
+ def bitmap(source, *, alt: str = ""):
65
+ """Snapshot a bitmap file or IO for portable HTML output.
66
+
67
+ ``source`` may be a PNG, JPEG, GIF, or WebP path, bytes-like, or binary IO.
68
+ """
69
+ return Bitmap(source, alt=alt)
70
+
71
+
72
+ def image(source, *, alt: str = ""):
73
+ """Snapshot a static bitmap source or render a Matplotlib plot.
74
+
75
+ In addition to every source accepted by :func:`bitmap`, ``source`` may be
76
+ a Matplotlib ``Figure``, ``Axes``, artist, or the artist sequence returned
77
+ by ``plt.plot``.
78
+ """
79
+ figure = _matplotlib_figure(source)
80
+ if figure is not None:
81
+ stream = BytesIO()
82
+ figure.savefig(stream, format="png", bbox_inches="tight")
83
+ source = stream.getvalue()
84
+ alt = alt or "Matplotlib plot"
85
+ return Bitmap(source, alt=alt)
86
+
87
+
88
+ @register
89
+ class Bitmap(Renderer):
90
+ """Registered renderer for :func:`transcript.bitmap` snapshots."""
91
+
92
+ name = "bitmap"
93
+ version = (1,)
94
+ STYLE = _STYLE
95
+
96
+ def __init__(self, source, *, alt: str = ""):
97
+ if not isinstance(alt, str):
98
+ raise TypeError("bitmap alt text must be a string")
99
+ if isinstance(source, (str, Path)):
100
+ path = Path(source)
101
+ data = path.read_bytes()
102
+ default_alt = path.name
103
+ elif isinstance(source, (bytes, bytearray, memoryview)):
104
+ data = bytes(source)
105
+ default_alt = ""
106
+ else:
107
+ read = getattr(source, "read", None)
108
+ if not callable(read):
109
+ raise TypeError("bitmap requires a path, bytes, or binary IO")
110
+ data = read()
111
+ if not isinstance(data, bytes):
112
+ raise TypeError("bitmap IO must return bytes")
113
+ name = getattr(source, "name", "")
114
+ default_alt = Path(name).name if isinstance(name, (str, Path)) else ""
115
+ mime = _image_type(data)
116
+ if mime is None:
117
+ raise ValueError("bitmap supports PNG, JPEG, GIF, and WebP images")
118
+ self.mime = mime
119
+ self.data = data
120
+ self.alt = alt or default_alt
121
+
122
+ def serialize(self):
123
+ return json.dumps(
124
+ {
125
+ "mime": self.mime,
126
+ "data": base64.b64encode(self.data).decode("ascii"),
127
+ "alt": self.alt,
128
+ },
129
+ sort_keys=True,
130
+ separators=(",", ":"), # eliminate whitespace
131
+ )
132
+
133
+ @classmethod
134
+ def to_html(cls, slot):
135
+ try:
136
+ snapshot = json.loads(slot.value)
137
+ mime = snapshot["mime"]
138
+ encoded = snapshot["data"]
139
+ alt = snapshot["alt"]
140
+ except (json.JSONDecodeError, KeyError, TypeError) as error:
141
+ raise ValueError("bitmap data must be a valid snapshot") from error
142
+ if not isinstance(mime, str) or not isinstance(encoded, str):
143
+ raise ValueError("bitmap snapshot must contain string image data")
144
+ if not isinstance(alt, str):
145
+ raise ValueError("bitmap snapshot alt text must be a string")
146
+ try:
147
+ raw = base64.b64decode(encoded, validate=True)
148
+ except ValueError as error:
149
+ raise ValueError("bitmap snapshot contains invalid base64") from error
150
+ if _image_type(raw) != mime:
151
+ raise ValueError("bitmap snapshot MIME type does not match its data")
152
+ uri = f"data:{mime};base64,{encoded}"
153
+ dimensions = _png_dimensions(raw)
154
+ size = ""
155
+ if dimensions is not None:
156
+ width, height = dimensions
157
+ size = (
158
+ f' width="{width}" height="{height}"'
159
+ f' style="--image-ratio:{width / height}"'
160
+ )
161
+ image = (
162
+ f'<img class="transcript-bitmap" src="{uri}"'
163
+ + size
164
+ + f' alt="{escape(alt, quote=True)}">'
165
+ )
166
+ return cls._htmlout(image, boxed=False)
@@ -0,0 +1,174 @@
1
+ """Renderer that arranges several outputs in a panel grid."""
2
+
3
+ import json
4
+ from collections.abc import Mapping, Sequence
5
+ from pathlib import Path
6
+
7
+ from ..output import RecordedOutput, Renderer, split_output
8
+ from ..parse import Slot
9
+ from . import register
10
+ from .label import CodeRenderer
11
+
12
+ _DEFAULT_NCOL = 2
13
+
14
+ _STYLE = """
15
+ /* composed panel grids */
16
+ .transcript-compose { display: grid; margin: .5rem 0 1rem; gap: .75rem;
17
+ align-items: start;
18
+ grid-template-columns: repeat(var(--transcript-cols, 2),
19
+ minmax(0, 1fr)); }
20
+ .transcript-compose > .transcript-panel { position: relative; margin: 0;
21
+ min-width: 0; }
22
+ .transcript-compose .transcript-chart { margin: 0; }
23
+ .transcript-compose .transcript-label { margin: 0; }
24
+ .transcript-compose .transcript-label-caption-header {
25
+ display: flex; flex-direction: column;
26
+ }
27
+ .transcript-compose .transcript-label-caption-header > figcaption {
28
+ order: -1; margin: 0 0 .25rem;
29
+ }
30
+ .transcript-panel-label { position: absolute; top: 0; left: 0; z-index: 1;
31
+ padding: 0; border-radius: .125rem;
32
+ background: Canvas;
33
+ background: color-mix(in srgb, Canvas 65%, transparent);
34
+ color: CanvasText;
35
+ font-weight: 700; line-height: 1;
36
+ pointer-events: none; }
37
+ .transcript-panel-label-inline { position: static; margin-right: .35em;
38
+ background: none; color: CanvasText;
39
+ line-height: inherit; }
40
+ .transcript-panel-label-header { position: static; display: block;
41
+ width: max-content; margin-bottom: .25rem;
42
+ background: none; color: CanvasText;
43
+ font-size: .9em; line-height: 1.65; }
44
+ @media (max-width: 640px) {
45
+ .transcript-compose { grid-template-columns: minmax(0, 1fr); }
46
+ }
47
+ """
48
+
49
+
50
+ def _panel_letter(index: int):
51
+ """Return spreadsheet-style letters: 0 -> A, 25 -> Z, 26 -> AA."""
52
+ name = ""
53
+ index += 1
54
+ while index:
55
+ index, remainder = divmod(index - 1, 26)
56
+ name = chr(ord("A") + remainder) + name
57
+ return name
58
+
59
+
60
+ def _validate_config(config: Mapping):
61
+ """Return a normalized grid configuration or raise ``ValueError``."""
62
+ if set(config) - {"ncol", "labels"}:
63
+ raise ValueError("compose header has unknown fields")
64
+ ncol = config.get("ncol", _DEFAULT_NCOL)
65
+ if isinstance(ncol, bool) or not isinstance(ncol, int) or ncol < 1:
66
+ raise ValueError("compose ncol must be a positive integer")
67
+ labels = config.get("labels", True)
68
+ if not isinstance(labels, bool):
69
+ raise ValueError("compose labels must be a boolean")
70
+ return {"ncol": ncol, "labels": labels}
71
+
72
+
73
+ def compose(*panels, ncol=_DEFAULT_NCOL, labels=True):
74
+ """Arrange several outputs in a panel grid during HTML export.
75
+
76
+ Each *panel* is a renderer output, usually a chart wrapped by
77
+ :func:`~transcript.vegalite` or :func:`~transcript.label`; ordinary values
78
+ fall back to the ``code`` renderer. ``ncol`` sets the number of grid
79
+ columns. Panels fill row by row and share the same column widths, and the
80
+ grid collapses to one column on narrow screens.
81
+
82
+ Each panel is tagged ``(A)``, ``(B)``, ... in reading order unless
83
+ ``labels=False``.
84
+
85
+ Composed panels keep their own rendering, runtime, and report files, so a
86
+ compose can nest inside another compose or a label. This first version only
87
+ lays panels out; it does not align axes or merge their scales.
88
+ """
89
+ if not panels:
90
+ raise ValueError("compose needs at least one panel")
91
+ return Compose(list(panels), {"ncol": ncol, "labels": labels})
92
+
93
+
94
+ @register
95
+ class Compose(Renderer):
96
+ """Registered renderer for :func:`transcript.compose` snapshots."""
97
+
98
+ name = "compose"
99
+ version = (1,)
100
+ STYLE = _STYLE
101
+
102
+ def __init__(self, panels: Sequence, config: Mapping):
103
+ config_ = _validate_config(config)
104
+ self.panels = [
105
+ panel if isinstance(panel, Renderer) else CodeRenderer(panel)
106
+ for panel in panels
107
+ ]
108
+ if not self.panels:
109
+ raise ValueError("compose needs at least one panel")
110
+ self.config = config_
111
+
112
+ def serialize(self):
113
+ """Return the JSON header followed by one nested fence per panel."""
114
+ config = self.config
115
+ if config["labels"]:
116
+ # ``labels`` defaults to true, so leave it out of the archive.
117
+ config = {key: value for key, value in config.items() if key != "labels"}
118
+ header = json.dumps(config, sort_keys=True, separators=(",", ":"))
119
+ parts = [header, *(panel.to_tmd() for panel in self.panels)]
120
+ return "\n".join(part.rstrip("\n") for part in parts) + "\n"
121
+
122
+ @classmethod
123
+ def from_tmd(cls, slot: Slot):
124
+ """Split stored *slot* into its grid configuration and panel outputs."""
125
+ content = [
126
+ chunk
127
+ for chunk in split_output(slot)
128
+ if not (isinstance(chunk, str) and not chunk.strip())
129
+ ]
130
+ if len(content) < 2:
131
+ raise ValueError("composed output needs a header and at least one panel")
132
+ header, *panels = content
133
+ if not isinstance(header, str):
134
+ raise ValueError("composed output must start with a configuration header")
135
+ if not all(isinstance(panel, RecordedOutput) for panel in panels):
136
+ raise ValueError("composed output panels must be renderer outputs")
137
+ try:
138
+ config = json.loads(header)
139
+ except json.JSONDecodeError as error:
140
+ raise ValueError("composed output header must be JSON") from error
141
+ if not isinstance(config, dict):
142
+ raise ValueError("composed output header must be a JSON object")
143
+ return _validate_config(config), panels
144
+
145
+ @classmethod
146
+ def to_html(cls, slot):
147
+ """Render a CSS grid whose cells are the composed panel reports."""
148
+ config, panels = cls.from_tmd(slot)
149
+ cells = "".join(
150
+ '<figure class="transcript-panel">'
151
+ + (
152
+ f'<span class="transcript-panel-label">({_panel_letter(index)})</span>'
153
+ if config["labels"]
154
+ else ""
155
+ )
156
+ + "{{"
157
+ + str(index)
158
+ + "}}</figure>"
159
+ for index in range(len(panels))
160
+ )
161
+ style = f' style="--transcript-cols:{config["ncol"]}"'
162
+ return cls._htmlout(
163
+ f'<div class="transcript-compose"{style}>{cells}</div>', {}, tuple(panels)
164
+ )
165
+
166
+ @classmethod
167
+ def render_node(cls, output, child_blocks):
168
+ """Render the grid after substituting each rendered panel."""
169
+ text = output.rendered.text
170
+ for index, block in enumerate(child_blocks):
171
+ text = text.replace("{{" + str(index) + "}}", block)
172
+ return text
173
+
174
+ runtime = Path(__file__).with_name("compose_runtime.js").read_text(encoding="utf-8")
@@ -0,0 +1,233 @@
1
+ /* Make each composed panel's label readable over whatever the chart draws
2
+ behind it: sample the covered region, pick black or white text from its
3
+ average brightness, compress the colours nearest that text into the middle
4
+ luminance band, and use the adjusted patch as background.
5
+ The CSS chip stays as a fallback when sampling is impossible (no chart,
6
+ cross-origin image, disabled JavaScript). */
7
+ (() => {
8
+ "use strict";
9
+ if (!document.querySelector(".transcript-panel-label")) return;
10
+
11
+ function captionOf(panel) {
12
+ const report = panel?.querySelector(
13
+ ':scope > .transcript-report[data-tmd-renderer="label"]',
14
+ );
15
+ const figure = report?.querySelector(":scope > .transcript-label");
16
+ return figure?.querySelector(":scope > figcaption") || null;
17
+ }
18
+
19
+ function arrangeLabels() {
20
+ const overlays = [];
21
+ for (const compose of document.querySelectorAll(".transcript-compose")) {
22
+ const panels = [...compose.querySelectorAll(":scope > .transcript-panel")];
23
+ const entries = panels.map((panel) => {
24
+ const caption = captionOf(panel);
25
+ caption?.parentElement?.classList.remove(
26
+ "transcript-label-caption-header",
27
+ );
28
+ const label = panel.querySelector(
29
+ ":scope > .transcript-panel-label, " +
30
+ ':scope > .transcript-report[data-tmd-renderer="label"] > ' +
31
+ ".transcript-label > figcaption > .transcript-panel-label",
32
+ );
33
+ if (label) {
34
+ for (const property of [
35
+ "color",
36
+ "background-image",
37
+ "background-size",
38
+ "background-repeat",
39
+ ]) {
40
+ label.style.removeProperty(property);
41
+ }
42
+ label.classList.remove(
43
+ "transcript-panel-label-inline",
44
+ "transcript-panel-label-header",
45
+ );
46
+ panel.prepend(label);
47
+ }
48
+ return {panel, label, caption};
49
+ });
50
+ const rows = new Map();
51
+ for (const entry of entries) {
52
+ const top = Math.round(entry.panel.getBoundingClientRect().top);
53
+ const row = rows.get(top) || [];
54
+ row.push(entry);
55
+ rows.set(top, row);
56
+ }
57
+ for (const row of rows.values()) {
58
+ const hasCaption = row.some((entry) => entry.label && entry.caption);
59
+ for (const {label, caption} of row) {
60
+ if (!label) continue;
61
+ if (caption) {
62
+ caption.parentElement.classList.add(
63
+ "transcript-label-caption-header",
64
+ );
65
+ label.classList.add("transcript-panel-label-inline");
66
+ caption.prepend(label);
67
+ } else if (hasCaption) {
68
+ label.classList.add("transcript-panel-label-header");
69
+ } else {
70
+ overlays.push(label);
71
+ }
72
+ }
73
+ }
74
+ }
75
+ return overlays;
76
+ }
77
+
78
+ let overlayLabels = arrangeLabels();
79
+
80
+ const darkEdge = 0.35;
81
+ const lightEdge = 0.58;
82
+ function brightness(red, green, blue) {
83
+ return (0.2126 * red + 0.7152 * green + 0.0722 * blue) / 255;
84
+ }
85
+
86
+ function pageBackground() {
87
+ for (const element of [document.body, document.documentElement]) {
88
+ if (!element) continue;
89
+ const color = getComputedStyle(element).backgroundColor;
90
+ if (color && color !== "transparent" && color !== "rgba(0, 0, 0, 0)") {
91
+ return color;
92
+ }
93
+ }
94
+ return matchMedia("(prefers-color-scheme: dark)").matches
95
+ ? "rgb(18, 18, 18)"
96
+ : "rgb(255, 255, 255)";
97
+ }
98
+
99
+ function loadImage(target) {
100
+ if (target instanceof HTMLImageElement) return Promise.resolve(target);
101
+ if (!(target instanceof SVGSVGElement)) return Promise.resolve(null);
102
+ const rect = target.getBoundingClientRect();
103
+ const clone = target.cloneNode(true);
104
+ clone.setAttribute("width", String(rect.width));
105
+ clone.setAttribute("height", String(rect.height));
106
+ const xml = new XMLSerializer().serializeToString(clone);
107
+ const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(xml);
108
+ const image = new Image();
109
+ return new Promise((resolve, reject) => {
110
+ image.onload = () => resolve(image);
111
+ image.onerror = reject;
112
+ image.src = url;
113
+ });
114
+ }
115
+
116
+ function makeCanvas(width, height) {
117
+ const canvas = document.createElement("canvas");
118
+ canvas.width = Math.max(1, Math.round(width));
119
+ canvas.height = Math.max(1, Math.round(height));
120
+ return canvas;
121
+ }
122
+
123
+ function tonePatch(context, width, height, useBlackText) {
124
+ const image = context.getImageData(0, 0, width, height);
125
+ const pixels = image.data;
126
+ for (let index = 0; index < pixels.length; index += 4) {
127
+ const luminance = brightness(
128
+ pixels[index],
129
+ pixels[index + 1],
130
+ pixels[index + 2],
131
+ );
132
+ let scale;
133
+ let offset;
134
+ if (useBlackText && luminance < lightEdge) {
135
+ // Keep the light band unchanged. Lift the middle and dark bands
136
+ // into the middle band; even black stays visibly separated from text.
137
+ const target =
138
+ darkEdge + (luminance * (lightEdge - darkEdge)) / lightEdge;
139
+ scale = (1 - target) / (1 - luminance);
140
+ offset = 255 * (1 - scale);
141
+ } else if (!useBlackText && luminance > darkEdge) {
142
+ // Keep the dark band unchanged and mirror the operation for white text.
143
+ const target =
144
+ darkEdge +
145
+ ((luminance - darkEdge) * (lightEdge - darkEdge)) / (1 - darkEdge);
146
+ scale = target / luminance;
147
+ offset = 0;
148
+ } else {
149
+ continue;
150
+ }
151
+ pixels[index] = pixels[index] * scale + offset;
152
+ pixels[index + 1] = pixels[index + 1] * scale + offset;
153
+ pixels[index + 2] = pixels[index + 2] * scale + offset;
154
+ }
155
+ context.putImageData(image, 0, 0);
156
+ }
157
+
158
+ async function adapt(label) {
159
+ const panel = label.closest(".transcript-panel");
160
+ const target = panel && panel.querySelector("svg, img");
161
+ if (!target) return;
162
+ const labelRect = label.getBoundingClientRect();
163
+ const targetRect = target.getBoundingClientRect();
164
+ if (!labelRect.width || !labelRect.height || !targetRect.width) return;
165
+ const image = await loadImage(target);
166
+ if (!image) return;
167
+
168
+ const chart = makeCanvas(targetRect.width, targetRect.height);
169
+ chart.getContext("2d").drawImage(image, 0, 0, chart.width, chart.height);
170
+
171
+ // Compose the chart (offset by its position under the label) over the page
172
+ // background, so transparent charts and margins sample correctly.
173
+ const patch = makeCanvas(labelRect.width, labelRect.height);
174
+ const context = patch.getContext("2d", { willReadFrequently: true });
175
+ context.fillStyle = pageBackground();
176
+ context.fillRect(0, 0, patch.width, patch.height);
177
+ context.drawImage(
178
+ chart,
179
+ targetRect.left - labelRect.left,
180
+ targetRect.top - labelRect.top,
181
+ targetRect.width,
182
+ targetRect.height,
183
+ );
184
+
185
+ const sample = makeCanvas(1, 1);
186
+ const sampleContext = sample.getContext("2d", { willReadFrequently: true });
187
+ sampleContext.drawImage(patch, 0, 0, 1, 1);
188
+ const [red, green, blue] = sampleContext.getImageData(0, 0, 1, 1).data;
189
+ const useBlackText = brightness(red, green, blue) > 0.5;
190
+ tonePatch(context, patch.width, patch.height, useBlackText);
191
+ label.style.color = useBlackText ? "#000" : "#fff";
192
+ label.style.backgroundImage = `url("${patch.toDataURL()}")`;
193
+ label.style.backgroundSize = "100% 100%";
194
+ label.style.backgroundRepeat = "no-repeat";
195
+ }
196
+
197
+ function refresh() {
198
+ for (const label of overlayLabels) {
199
+ try {
200
+ adapt(label).catch(() => { });
201
+ } catch (error) {
202
+ /* keep the CSS fallback */
203
+ }
204
+ }
205
+ }
206
+
207
+ // Charts upgrade asynchronously (Vega-Lite embeds after its CDN loads), so
208
+ // re-sample whenever a panel's contents change.
209
+ let pending;
210
+ const observer = new MutationObserver(() => {
211
+ clearTimeout(pending);
212
+ pending = setTimeout(refresh, 150);
213
+ });
214
+ for (const panel of document.querySelectorAll(".transcript-panel")) {
215
+ observer.observe(panel, { childList: true, subtree: true });
216
+ }
217
+
218
+ if (document.readyState === "loading") {
219
+ document.addEventListener("DOMContentLoaded", refresh);
220
+ } else {
221
+ refresh();
222
+ }
223
+ window.addEventListener("load", refresh);
224
+ let resizePending;
225
+ window.addEventListener("resize", () => {
226
+ clearTimeout(resizePending);
227
+ resizePending = setTimeout(() => {
228
+ overlayLabels = arrangeLabels();
229
+ refresh();
230
+ }, 150);
231
+ });
232
+ document.addEventListener("transcript-rendered", refresh);
233
+ })();