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,198 @@
1
+ """Build the document outline navigate from the assembled HTML body."""
2
+
3
+ import re
4
+ from html import escape, unescape
5
+ from typing import NamedTuple
6
+
7
+ _SLUG_STRIP = re.compile(r"[^\w\- ]+", re.UNICODE)
8
+ _SLUG_SEPARATOR = re.compile(r"[\s\-]+")
9
+
10
+
11
+ def _slug(text: str):
12
+ """Turn heading text into a URL fragment, keeping unicode letters.
13
+ >>> _slug("Hello, world!")
14
+ "hello-world"
15
+ """
16
+ return _SLUG_SEPARATOR.sub("-", _SLUG_STRIP.sub("", text.lower())).strip("-")
17
+
18
+
19
+ _LABEL_ANCHOR = re.compile(r'<figure class="transcript-label" id="(?P<label>[^"]+)">')
20
+ _ANCHOR = re.compile(
21
+ r'<h(?P<level>[1-6])(?: id="(?P<existing>[^"]+)")?>(?P<inner>.*?)</h(?P=level)>'
22
+ r"|" + _LABEL_ANCHOR.pattern,
23
+ re.DOTALL,
24
+ )
25
+ _TAG = re.compile(r"<[^>]+>")
26
+
27
+
28
+ def _plain_text(html: str):
29
+ """Flatten inline HTML to the text shown in the navigate."""
30
+ return unescape(_TAG.sub("", html)).strip()
31
+
32
+
33
+ def _get_label_caption(body: str, start: int):
34
+ """Return the caption of the label figure opening at *start*, if any.
35
+
36
+ The caption must belong to this figure, so captions of nested labels are
37
+ skipped while scanning for the matching ``</figure>``.
38
+ """
39
+ depth = 0
40
+ while start != -1:
41
+ if body.startswith("<figure", start):
42
+ depth += 1
43
+ start += len("<figure")
44
+ elif body.startswith("</figure>", start):
45
+ depth -= 1
46
+ start += len("</figure>")
47
+ if depth == 0:
48
+ break
49
+ elif depth == 1 and body.startswith("<figcaption>", start):
50
+ end = body.find("</figcaption>", start)
51
+ if end == -1:
52
+ break
53
+ opening = len("<figcaption>")
54
+ return _plain_text(body[start + opening : end])
55
+ else:
56
+ start = body.find("<", start + 1)
57
+
58
+
59
+ def anchors(parts: list[str]):
60
+ """Assign heading ids and collect every anchor in document order.
61
+
62
+ Headings produced by any renderer, including the Markdown renderer, share
63
+ one namespace across all parts. Each entry is
64
+ ``(kind, level, text, slug)`` with *kind* ``"heading"`` or ``"label"``;
65
+ label ids are reserved so a heading never steals their anchor, and a label
66
+ takes the level of the heading it follows so headings stay primary when
67
+ both types are shown together.
68
+ """
69
+ # record all label first, so duplicated title ids will be renamed
70
+ seen: dict[str, int] = dict.fromkeys(
71
+ (
72
+ match.group("label")
73
+ for part in parts
74
+ for match in _LABEL_ANCHOR.finditer(part)
75
+ ),
76
+ 0,
77
+ )
78
+ entries: list[Entry] = []
79
+ pieces: list[str] = []
80
+ level = 0
81
+ for part in parts:
82
+ cursor = 0
83
+ for match in _ANCHOR.finditer(part):
84
+ pieces.append(part[cursor : match.start()])
85
+ cursor = match.end()
86
+ label: str | None = match.group("label")
87
+ if label is not None:
88
+ text = _get_label_caption(part, match.start()) or label
89
+ entries.append(Entry.label(level, text, label))
90
+ pieces.append(match.group(0))
91
+ continue
92
+ level = int(match.group("level"))
93
+ inner = match.group("inner")
94
+ text = _plain_text(inner)
95
+ slug = match.group("existing") or _slug(text) or f"section-{len(entries)}"
96
+ if slug in seen:
97
+ base = slug
98
+ count = seen[slug]
99
+ while slug in seen:
100
+ count += 1
101
+ slug = f"{base}-{count}"
102
+ seen[base] = count
103
+ seen[slug] = 0
104
+ entries.append(Entry.heading(level, text, slug))
105
+ pieces.append(
106
+ f'<h{level} id="{escape(slug, quote=True)}">{inner}</h{level}>'
107
+ )
108
+ pieces.append(part[cursor:])
109
+ pieces.append("\n")
110
+ return "".join(pieces), entries
111
+
112
+
113
+ class Entry(NamedTuple):
114
+ kind: str
115
+ level: int
116
+ text: str
117
+ slug: str
118
+
119
+ @classmethod
120
+ def label(cls, level: int, text: str, slug: str):
121
+ return cls("label", min(level + 1, 6), text, slug)
122
+
123
+ @classmethod
124
+ def heading(cls, level: int, text: str, slug: str):
125
+ return cls("heading", level, text, slug)
126
+
127
+ @property
128
+ def css(self):
129
+ kind = self.kind
130
+ if kind == "heading":
131
+ return f"toc-heading toc-l{self.level}"
132
+ if kind == "label":
133
+ return "toc-label"
134
+
135
+ def render(self, shown: set[str]):
136
+ name = self._TYPES[self.kind][0]
137
+ hidden = "" if name in shown else " hidden"
138
+ # Labels are a flat type, so they share one indent instead of following
139
+ # the level of the preceding heading.
140
+ return (
141
+ f'<li class="{self.css}" data-tmd-type="{name}"{hidden}>'
142
+ f'<a href="#{escape(self.slug, quote=True)}">{escape(self.text)}</a></li>'
143
+ )
144
+
145
+ _TYPES = {"heading": ("contents", "Contents"), "label": ("labels", "Labels")}
146
+ """
147
+ Anchor kinds mapped to their navigate type and tab title, in tab order.
148
+ A new kind (for example a future "reference") only needs an entry here
149
+ and a marker in the navigate CSS; the script discovers types from the markup.
150
+ """
151
+
152
+
153
+ _EYE_PATH = (
154
+ '<path d="M1.5 8s2.4-4 6.5-4 6.5 4 6.5 4-2.4 4-6.5 4S1.5 8 1.5 8Z"/>'
155
+ '<circle cx="8" cy="8" r="2"/>'
156
+ )
157
+ _EYE = (
158
+ '<span class="navigate-eye" aria-hidden="true">'
159
+ f'<svg class="navigate-eye-open" viewBox="0 0 16 16">{_EYE_PATH}</svg>'
160
+ f'<svg class="navigate-eye-closed" viewBox="0 0 16 16">{_EYE_PATH}'
161
+ '<path d="M2.5 2.5l11 11"/></svg>'
162
+ "</span>"
163
+ )
164
+
165
+
166
+ def navigate_html(entries: list[Entry]):
167
+ """Build the navigate from the collected anchors.
168
+
169
+ One list holds every anchor in document order. Each type gets a tab whose
170
+ body isolates that type and whose toggle adds or removes it; with several
171
+ types shown, the list stays merged and headings keep their nesting. The
172
+ list may be empty, which collapses the navigate to its vertical tabs.
173
+ """
174
+ if not entries:
175
+ return "page", ""
176
+ present = {kinds.kind for kinds in entries}
177
+ types = [
178
+ (name, title) for kind, (name, title) in Entry._TYPES.items() if kind in present
179
+ ]
180
+ shown = {types[0][0]}
181
+ items = "".join(entry.render(shown) for entry in entries)
182
+ tabs = "".join(
183
+ f'<div class="navigate-tab" data-tmd-type="{name}"'
184
+ f' data-active="{str(name in shown).lower()}">'
185
+ f'<button class="navigate-tab-body" type="button">{title}</button>'
186
+ f'<button class="navigate-tab-toggle" type="button"'
187
+ f' aria-pressed="{str(name in shown).lower()}"'
188
+ f' aria-label="Add or remove {title}">'
189
+ f"{_EYE}"
190
+ "</button></div>"
191
+ for name, title in types
192
+ )
193
+ return "page page--navigate", (
194
+ '<nav class="navigate" aria-label="Document outline" data-collapsed="false">'
195
+ f'<div class="navigate-tabs">{tabs}</div>'
196
+ f'<ol class="navigate-list" data-tmd-show="{" ".join(sorted(shown))}">'
197
+ f"{items}</ol></nav>"
198
+ )
@@ -0,0 +1,100 @@
1
+ """Render statement code, recorded outputs, and hidden script blocks."""
2
+
3
+ from html import escape
4
+
5
+ from ..output import RecordedOutput, Report, split_output
6
+ from ..parse import Slot
7
+
8
+
9
+ def _ranges(numbers: set[int]):
10
+ """Encode one-based line numbers as compact comma-separated ranges.
11
+ >>> _ranges({1, 4, 5})
12
+ '1,4-5'
13
+ """
14
+ if not numbers:
15
+ return ""
16
+ values = sorted(numbers)
17
+ ranges: list[str] = []
18
+ start = previous = values[0]
19
+ for value in values[1:]:
20
+ if value == previous + 1:
21
+ previous = value
22
+ continue
23
+ ranges.append(str(start) if start == previous else f"{start}-{previous}")
24
+ start = previous = value
25
+ ranges.append(str(start) if start == previous else f"{start}-{previous}")
26
+ return ",".join(ranges)
27
+
28
+
29
+ def statement_html(span: tuple[int, int, set[int]]):
30
+ """Emit a source-backed code placeholder for one physical statement.
31
+
32
+ The browser runtime slices ``source[start:end]`` from the island and
33
+ highlights it. ``data-tmd-string-lines`` marks the continuation lines of a
34
+ multiline string, which keep their indentation and drop the ``>>>`` prompt.
35
+ """
36
+ start, end, string_lines = span
37
+ string_lines = _ranges(string_lines)
38
+ encoded = f' data-tmd-string-lines="{string_lines}"' if string_lines else ""
39
+ return f'<code class="doc-code" data-tmd-span="{start},{end}"{encoded}></code>'
40
+
41
+
42
+ def output_html(
43
+ statements: list[tuple[int, int, set[int]]],
44
+ output: Slot | None,
45
+ reports: list[Report],
46
+ report_id: str,
47
+ ):
48
+ code_block = [*map(statement_html, statements)]
49
+
50
+ def flush_text():
51
+ if parts:
52
+ code_block.append(f'<samp class="doc-out">{"".join(parts)}</samp>')
53
+ parts.clear()
54
+ elif not code_block:
55
+ return
56
+ blocks.append('<pre class="doc-text">{}</pre>'.format("".join(code_block)))
57
+ code_block.clear()
58
+
59
+ parts: list[str] = []
60
+ blocks: list[str] = []
61
+ boxed = True
62
+ if output is None:
63
+ text = ""
64
+ else:
65
+ text = output.value
66
+ chunks = split_output(output)
67
+ for ichunk, chunk in enumerate(chunks):
68
+ if isinstance(chunk, RecordedOutput):
69
+ flush_text()
70
+ report = chunk.to_report(f"{report_id}-{ichunk}", reports, output.start)
71
+ blocks.append(report.block)
72
+ boxed = ichunk != 0 or report.boxed
73
+ continue
74
+ if str(chunk):
75
+ boxed = True
76
+ for line in str(chunk).splitlines(keepends=True):
77
+ parts.append(escape(line))
78
+ flush_text()
79
+ content = "".join(blocks)
80
+ if not text:
81
+ return f'<div class="doctest-code">{content}</div>'
82
+ expanded = str(boxed).lower()
83
+ toggle = (
84
+ '<button class="output-box-toggle" type="button"'
85
+ f' aria-label="Show or hide code and frame" aria-expanded="{expanded}">'
86
+ '<span aria-hidden="true">&lt;/&gt;</span></button>'
87
+ )
88
+ return f'<div class="doctest-code" data-boxed="{expanded}">{toggle}{content}</div>'
89
+
90
+
91
+ def script_html(start: int, end: int):
92
+ """Emit a source-backed placeholder for the script region ``source[start:end]``.
93
+
94
+ The browser fills it behind a toggle. Semicolons between adjacent document
95
+ expressions are only separators, so a region that holds nothing else is
96
+ removed by the runtime instead of showing an empty toggle.
97
+ """
98
+ if start == end:
99
+ return ""
100
+ return f'<details class="script-block" data-tmd-span="{start},{end}"></details>'
@@ -0,0 +1,171 @@
1
+ """Assemble the page assets: styles, report payload, scripts, and CSP."""
2
+
3
+ import base64
4
+ import gzip
5
+ import json
6
+ from hashlib import sha256
7
+ from typing import TypedDict
8
+
9
+ from ..output import Report
10
+ from ._assets import ASSET_SCRIPTS, STYLE
11
+
12
+ _BROWSER_RENDERERS = {
13
+ "cache": "transcript-renderers-v1",
14
+ "resources": [
15
+ {
16
+ "name": "markdown-it",
17
+ "type": "script",
18
+ "global": "markdownit",
19
+ "url": "https://cdn.jsdelivr.net/npm/markdown-it@14.1.0/dist/markdown-it.min.js",
20
+ "integrity": (
21
+ "sha384-wLhprpjsmjc/XYIcF+LpMxd8yS1gss6jhevOp6F6zhiIoFK6AmHtm4bG"
22
+ "KtehTani"
23
+ ),
24
+ },
25
+ {
26
+ "name": "highlight.js",
27
+ "type": "script",
28
+ "global": "hljs",
29
+ "url": "https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.12.0/build/highlight.min.js",
30
+ "integrity": (
31
+ "sha384-wjfDDhOPPdjtva8vWBhWeVprSpmxisEu5aYT3q1JyACqXpdKpo3PWZTM"
32
+ "Vq24MBix"
33
+ ),
34
+ },
35
+ {
36
+ "name": "highlight.js-default",
37
+ "type": "style",
38
+ "url": "https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.12.0/build/styles/default.min.css",
39
+ "integrity": (
40
+ "sha384-4Y0nObtF3CbKnh+lpzmAVdAMtQXl+ganWiiv73RcGVdRdfVIya8Cao1"
41
+ "C8ZsVRRDz"
42
+ ),
43
+ },
44
+ {
45
+ "name": "jsdiff",
46
+ "type": "script",
47
+ "global": "Diff",
48
+ "url": "https://cdn.jsdelivr.net/npm/diff@9.0.0/dist/diff.min.js",
49
+ "integrity": (
50
+ "sha384-TvJwlBkfFFd9hmaVfyJyF6lIPjAUL6x01MvObCeUao5yP6QZ6owU6fqw+JQoyRD1"
51
+ ),
52
+ },
53
+ ],
54
+ }
55
+
56
+
57
+ def _digest(script: str):
58
+ """Return the CSP ``sha256-`` source that allows an inline script."""
59
+ digest = base64.b64encode(sha256(script.encode()).digest()).decode()
60
+ return f"'sha256-{digest}'"
61
+
62
+
63
+ def _renderer_config():
64
+ encoded = json.dumps(_BROWSER_RENDERERS, separators=(",", ":"))
65
+ return (
66
+ '<script id="transcript-renderers" type="application/json">'
67
+ + encoded.replace("<", "\\u003c").replace(">", "\\u003e")
68
+ + "</script>"
69
+ )
70
+
71
+
72
+ class _PackagedFile(TypedDict):
73
+ mime: str
74
+ gzip: bool
75
+ content: str
76
+
77
+
78
+ def _package_files(reports: list[Report]):
79
+ """Package files in a JSON object with:
80
+ - pool: dict[file_fingerprint, _PackagedFile]
81
+ - reports: dict[name, file_fingerprint]
82
+
83
+ Identical files (for example the shared Datavzrd bundle) are dereplicated.
84
+ Encode so they cannot terminate the surrounding script.
85
+ """
86
+
87
+ pool: dict[str, _PackagedFile] = {}
88
+ registry: dict[str, dict[str, str]] = {}
89
+ for reporter in reports:
90
+ entry: dict[str, str] = {}
91
+ for name, (mime, data) in reporter.files.items():
92
+ file_fingerprint = sha256(mime.encode() + b"\0" + data).hexdigest()
93
+ if file_fingerprint not in pool:
94
+ compressed = gzip.compress(data, compresslevel=9, mtime=0)
95
+ payload = min(compressed, data, key=len)
96
+ pool[file_fingerprint] = {
97
+ "mime": mime,
98
+ "gzip": payload is compressed,
99
+ "content": base64.b64encode(payload).decode("ascii"),
100
+ }
101
+ entry[name] = file_fingerprint
102
+ registry[reporter.id] = entry
103
+ encoded = json.dumps({"pool": pool, "reports": registry}, sort_keys=True)
104
+ return encoded.replace("<", "\\u003c").replace(">", "\\u003e")
105
+
106
+
107
+ def page_resources(reports: list[Report], origins: list[str], island: str = ""):
108
+ """Return ``(styles, csp, scripts)`` for the exported page.
109
+
110
+ styles: map(renderers, .STYLE).
111
+ csp:
112
+ Content-Security-Policy that allows the page to run in a browser
113
+ without any external resources
114
+ defaults + island + report payload + map(renderers, .sources).
115
+ scripts: the core scripts, source island, report payload,
116
+ + map(renderers, .runtime) for renderers that need it.
117
+
118
+ a renderer without a runtime never executes in the browser,
119
+ so it contributes no script or CSP source.
120
+ """
121
+
122
+ styles = [STYLE]
123
+ runtimes = []
124
+ sources = [*map(_digest, ASSET_SCRIPTS)]
125
+ for renderer in {r.name: r.chunk.renderer for r in reports}.values():
126
+ if renderer.STYLE:
127
+ styles.append(renderer.STYLE)
128
+ if renderer.runtime:
129
+ runtimes.append(renderer.runtime)
130
+ sources.extend(renderer.sources)
131
+ runtime_tags = []
132
+ for runtime in dict.fromkeys(runtimes):
133
+ sources.append(_digest(runtime))
134
+ runtime_tags.append(f"<script>{runtime}</script>")
135
+ if runtime_tags:
136
+ # No runtime means nothing reads the payload; static renderers
137
+ # already emit their final HTML into the report block.
138
+ sources.extend(["data:", "'unsafe-eval'"])
139
+ image_src = "data: blob:"
140
+ payload = (
141
+ '<script id="transcript-reports" type="application/json">'
142
+ + _package_files(reports)
143
+ + "</script>"
144
+ )
145
+ font_frame_src = " font-src data: blob:; frame-src 'self' data: blob:;"
146
+ else:
147
+ image_src = "data:"
148
+ font_frame_src = payload = ""
149
+ sources.append("blob:")
150
+ script_src = " ".join(dict.fromkeys(sources))
151
+ if origins:
152
+ image_src += " " + " ".join(origins)
153
+ csp = (
154
+ "default-src 'none'; style-src 'unsafe-inline'; "
155
+ f"img-src {image_src};{font_frame_src} "
156
+ f"script-src {script_src}; "
157
+ "connect-src https://cdn.jsdelivr.net; "
158
+ "base-uri 'none'; form-action 'none'"
159
+ )
160
+ scripts = "\n".join(
161
+ part
162
+ for part in (
163
+ island,
164
+ _renderer_config(),
165
+ *(f"<script>{script}</script>" for script in ASSET_SCRIPTS),
166
+ payload,
167
+ *runtime_tags,
168
+ )
169
+ if part
170
+ )
171
+ return "\n".join(dict.fromkeys(styles)), csp, scripts
@@ -0,0 +1,34 @@
1
+ """Embed the archive's review records into the exported page.
2
+
3
+ The source island carries the archive *without* its trailing review block; this
4
+ module adds a second island with the parsed records plus the body hash, so the
5
+ browser runtime can render annotations, rewrite the block on export, and stamp
6
+ a matching hash without parsing Python.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from typing import TYPE_CHECKING
13
+
14
+ if TYPE_CHECKING:
15
+ from ..review._block import ReviewBlock
16
+
17
+
18
+ def to_page(review: ReviewBlock | None, body_hash: str):
19
+ """Return the ``transcript-reviews`` island for *document*.
20
+
21
+ *body_hash* is the hash of the source island's archive body, reused by the
22
+ runtime when it writes the block back. An archive without a review block
23
+ still gets an island (empty records), so a review added in the browser can
24
+ carry the right hash on export.
25
+ """
26
+ records = [] if review is None else [r.to_dict() for r in review.load().records]
27
+ payload = {"records": records, "hash": body_hash}
28
+ encoded = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
29
+ encoded = encoded.replace("<", "\\u003c").replace(">", "\\u003e")
30
+ return (
31
+ '<script id="transcript-reviews" type="application/json">'
32
+ + encoded
33
+ + "</script>"
34
+ )
@@ -0,0 +1,26 @@
1
+ """Recognize online resources in Markdown rendered by the browser."""
2
+
3
+ import re
4
+ from urllib.parse import urlsplit
5
+
6
+ _MARKDOWN_IMAGE = re.compile(r"!\[[^\]]*\]\(\s*(?P<url>https?://[^)\s]+)")
7
+ _MARKDOWN_REFERENCE = re.compile(
8
+ r"^[ \t]*\[[^\]]+\]:[ \t]*(?P<url>https?://\S+)", re.MULTILINE
9
+ )
10
+
11
+
12
+ def _origin(url: str):
13
+ parsed = urlsplit(url)
14
+ return f"{parsed.scheme}://{parsed.netloc}"
15
+
16
+
17
+ def markdown_image_origins(text: str):
18
+ """Return the origins of every online image a Markdown *text* can render.
19
+
20
+ Markdown is rendered in the browser, so its images never reach the server
21
+ HTML; their hosts still have to be allowed by the page's CSP.
22
+ """
23
+ origins: set[str] = set()
24
+ for pattern in (_MARKDOWN_IMAGE, _MARKDOWN_REFERENCE):
25
+ origins.update(_origin(match.group("url")) for match in pattern.finditer(text))
26
+ return sorted(origins)
@@ -0,0 +1,107 @@
1
+ """Assemble a complete HTML page from a document's recorded blocks."""
2
+
3
+ import io
4
+ import tokenize
5
+ from html import escape
6
+ from typing import TYPE_CHECKING
7
+
8
+ from ..tmd import body_hash
9
+ from ._island import source_island
10
+ from ._navigate import anchors, navigate_html
11
+ from ._output import output_html, script_html
12
+ from ._resources import page_resources
13
+ from ._review import to_page
14
+ from .markup import markdown_image_origins
15
+
16
+ if TYPE_CHECKING:
17
+ from ..document import AstDocument
18
+ from ..output import Report
19
+
20
+
21
+ def _multiline_string_lines(source: str):
22
+ """Return physical lines inside multiline strings after their first line."""
23
+ string_interior_lines: set[int] = set()
24
+ for token in tokenize.generate_tokens(io.StringIO(source).readline):
25
+ if token.type == tokenize.STRING and token.start[0] != token.end[0]:
26
+ string_interior_lines.update(range(token.start[0] + 1, token.end[0] + 1))
27
+ return string_interior_lines
28
+
29
+
30
+ def render(self: AstDocument, *, title: str = "transcript document"):
31
+ """Render recorded content as offline HTML without executing the document."""
32
+ parts: list[str] = []
33
+ reports: list[Report] = []
34
+ origins: set[str] = set()
35
+ cursor = 0
36
+ for iblock, block in enumerate(self.blocks):
37
+ node = block.node
38
+ assert node.end_lineno is not None and node.end_col_offset is not None
39
+ start = self.position(node.lineno, node.col_offset)
40
+ end = self.position(node.end_lineno, node.end_col_offset)
41
+ parts.append(script_html(cursor, start))
42
+ cursor = end
43
+ parts.append('<section class="report-block">')
44
+ if block.markdown is not None:
45
+ markdown_start, markdown_end = block.markdown
46
+ origins.update(
47
+ markdown_image_origins(self.source[markdown_start:markdown_end])
48
+ )
49
+ parts.append(
50
+ f'<div class="doc-md"'
51
+ f' data-tmd-span="{markdown_start},{markdown_end}"></div>'
52
+ )
53
+ pending_codes: list[tuple[int, int, set[int]]] = []
54
+ last_istatement = len(block.statements) - 1
55
+ for istatement, statement in enumerate(block.statements):
56
+ # TODO: change statement.start to statement.node.lineno
57
+ # and statement.end to statement.node.end_lineno
58
+ line_start = self.source.rfind("\n", 0, statement.start) + 1
59
+ line_end = self.source.find("\n", statement.end)
60
+ if line_end == -1:
61
+ line_end = len(self.source)
62
+ stringlines = _multiline_string_lines(self.source[line_start:line_end])
63
+ pending_codes.append((line_start, line_end, stringlines))
64
+ output = statement.slot
65
+ if (output is not None and output.value) or istatement == last_istatement:
66
+ report_id = f"report-{iblock}-{istatement}"
67
+ parts.append(output_html(pending_codes, output, reports, report_id))
68
+ pending_codes = []
69
+ parts.append("</section>")
70
+
71
+ content_end = len(self.source) if self.review is None else self.review.start
72
+ parts.append(script_html(cursor, content_end))
73
+ body, entries = anchors(parts)
74
+ # The page carries the reviewed archive *without* its review block; the
75
+ # block's records live in the separate ``transcript-reviews`` island, so the
76
+ # source island is never rewritten and never contains review state.
77
+ archive = self.source_without_review.rstrip("\n") + "\n"
78
+ island = source_island(archive) + to_page(self.review, body_hash(archive))
79
+ origins.update(
80
+ image_origin
81
+ for report in reports
82
+ for image_origin in report.chunk.rendered.origins
83
+ )
84
+ style, csp, scripts = page_resources(reports, sorted(origins), island)
85
+ navigate_class, navigate = navigate_html(entries)
86
+
87
+ return f"""<!doctype html>
88
+ <html lang="en">
89
+ <head>
90
+ <meta charset="utf-8">
91
+ <meta name="viewport" content="width=device-width, initial-scale=1">
92
+ <meta http-equiv="Content-Security-Policy" content="{csp}">
93
+ <title>{escape(title)}</title>
94
+ <style>
95
+ {style}
96
+ </style>
97
+ </head>
98
+ <body>
99
+ <div class="{navigate_class}">{navigate}
100
+ <main>
101
+ {body}
102
+ </main>
103
+ </div>
104
+ {scripts}
105
+ </body>
106
+ </html>
107
+ """