mintchip 0.2.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.
mintchip/prose.py ADDED
@@ -0,0 +1,225 @@
1
+ """Prose with chips in it: ``format_prose`` fills ``{name}`` placeholders, ``lint`` checks
2
+ density (one chip per sentence is normal, two is the ceiling, three comparable values make a
3
+ table) and collects the chips' own warnings."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import html
8
+ import re
9
+ from collections.abc import Iterable, Mapping
10
+ from typing import Any
11
+
12
+ from .spec import Chip, ChipError, sibling_domain
13
+
14
+ __all__ = ["FORMATS", "format_prose", "lint", "shared_domains"]
15
+
16
+ FORMATS = ("text", "markdown", "ansi", "html")
17
+ _SLOT = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}")
18
+ _SENTENCE_END = re.compile(r"(?<=[.!?])\s+|(?<=[.!?][\"')\]”’])\s+")
19
+ _PARAGRAPH = re.compile(r"\n[ \t]*\n")
20
+ _NUM = re.compile(r"[-+−]?\d[\d,]*(?:\.\d+)?%?")
21
+ Domain = tuple[float, float]
22
+
23
+
24
+ def format_prose(
25
+ template: str,
26
+ *,
27
+ format: str = "text",
28
+ ascii: bool = False,
29
+ compact: bool = True,
30
+ color: bool = False,
31
+ share: Any = "auto",
32
+ theme: Any = "auto",
33
+ **chips: Chip,
34
+ ) -> str:
35
+ """Replace each ``{name}`` in ``template`` with the chip passed as ``name=``.
36
+
37
+ ``format`` is "text", "ansi" (text with colour), "markdown" (chips in code spans) or
38
+ "html" (prose escaped, chips from ``Chip.html``). ``ascii`` and ``color`` apply to the
39
+ text forms, ``theme`` to html. ``compact`` gives the short mid-sentence value.
40
+
41
+ ``share="auto"`` puts chips of one kind with the same non-empty unit on one scale;
42
+ ``share=[("a", "b"), ...]`` names the groups; ``share=False`` leaves each chip its own.
43
+ """
44
+ if format not in FORMATS:
45
+ raise ChipError(
46
+ f"mintchip.format_prose: unknown format {format!r}.",
47
+ fix_hint=f"Use one of: {', '.join(FORMATS)}.",
48
+ )
49
+ _check_chips("format_prose", chips)
50
+ used = list(dict.fromkeys(_SLOT.findall(template)))
51
+ missing = [n for n in used if n not in chips]
52
+ if missing:
53
+ raise ChipError(
54
+ f"mintchip.format_prose: no chip for {{{missing[0]}}}.",
55
+ fix_hint=f"Pass {missing[0]}=mintchip.<kind>(...), or reword the placeholder.",
56
+ )
57
+ domains = shared_domains(chips, share, used=used)
58
+ out = []
59
+ for i, piece in enumerate(_SLOT.split(template)):
60
+ if i % 2:
61
+ out.append(_render(chips[piece], domains.get(piece), format, ascii, compact, color,
62
+ theme)) # fmt: skip
63
+ else:
64
+ out.append(html.escape(piece, quote=False) if format == "html" else piece)
65
+ return "".join(out)
66
+
67
+
68
+ def _render(c: Chip, domain, format: str, ascii: bool, compact: bool, color: bool, theme) -> str:
69
+ if format == "html":
70
+ return c.html(theme=theme, compact=compact, domain=domain)
71
+ if format == "markdown":
72
+ t = c.text(ascii=ascii, compact=compact, domain=domain)
73
+ return f"`` {t} ``" if "`" in t else f"`{t}`"
74
+ return c.text(ascii=ascii, compact=compact, color=color or format == "ansi", domain=domain)
75
+
76
+
77
+ def _check_chips(fn: str, chips: Mapping[str, Any]) -> None:
78
+ for name, c in chips.items():
79
+ if not isinstance(c, Chip):
80
+ raise ChipError(
81
+ f"mintchip.{fn}: {name} is a {type(c).__name__}, not a chip.",
82
+ fix_hint=f"Pass {name}=mintchip.<kind>(...); type plain values into the prose.",
83
+ )
84
+
85
+
86
+ def shared_domains(
87
+ chips: Mapping[str, Chip], share: Any = "auto", *, used: Iterable[str] | None = None
88
+ ) -> dict[str, Domain]:
89
+ """The share rule: the scale each grouped chip is drawn on, by name; a chip in no group is
90
+ left out and keeps its own. ``share="auto"`` groups the chips of one kind with the same
91
+ non-empty unit; ``share=[("a", "b"), ...]`` names the groups; ``share=False`` makes none.
92
+ A group's scale is the union of its chips' own. ``used`` limits ``"auto"`` to the chips
93
+ a template actually places (default: all of them)."""
94
+ if share is False or share is None:
95
+ return {}
96
+ if share == "auto" or share is True:
97
+ by_key: dict[tuple[str, str], list[str]] = {}
98
+ for n in chips if used is None else used:
99
+ c = chips[n]
100
+ if c.unit and c._domain(None) is not None:
101
+ by_key.setdefault((c.kind, c.unit), []).append(n)
102
+ groups = list(by_key.values())
103
+ else:
104
+ groups = _explicit_groups(share, chips)
105
+ out: dict[str, Domain] = {}
106
+ for group in groups:
107
+ if len(group) > 1:
108
+ d = sibling_domain(chips[group[0]].kind, (chips[n]._domain(None) for n in group))
109
+ if d is not None:
110
+ out.update(dict.fromkeys(group, d))
111
+ return out
112
+
113
+
114
+ def _explicit_groups(share: Any, chips: Mapping[str, Chip]) -> list[list[str]]:
115
+ hint = 'Pass share="auto", share=False, or groups of chip names: share=[("a", "b")].'
116
+ if isinstance(share, (str, bytes)) or not isinstance(share, Iterable):
117
+ raise ChipError(f"mintchip.format_prose: share must be groups; got {share!r}.",
118
+ fix_hint=hint) # fmt: skip
119
+ groups, seen = [], set()
120
+ for g in share:
121
+ if isinstance(g, (str, bytes)) or not isinstance(g, Iterable):
122
+ raise ChipError(f"mintchip.format_prose: share group {g!r} is not a list of names.",
123
+ fix_hint=hint) # fmt: skip
124
+ g = list(g)
125
+ for n in g:
126
+ if n not in chips:
127
+ raise ChipError(f"mintchip.format_prose: share names {n!r}, which is not a chip.",
128
+ fix_hint=f"Name chips passed as keywords: {', '.join(chips)}.") # fmt: skip
129
+ if n in seen:
130
+ raise ChipError(f"mintchip.format_prose: {n!r} is in two share groups.",
131
+ fix_hint="Put each chip in at most one group.") # fmt: skip
132
+ seen.add(n)
133
+ kinds = {chips[n].kind for n in g}
134
+ if len(kinds) > 1:
135
+ raise ChipError(
136
+ f"mintchip.format_prose: share group {g} mixes kinds ({', '.join(sorted(kinds))}).",
137
+ fix_hint="Share a scale only among chips of one kind.",
138
+ )
139
+ if any(chips[n]._domain(None) is None for n in g):
140
+ raise ChipError(
141
+ f"mintchip.format_prose: {chips[g[0]].kind} chips have no scale to share.",
142
+ fix_hint="Leave them out of share=; only position and series chips share a scale.",
143
+ )
144
+ groups.append(g)
145
+ return groups
146
+
147
+
148
+ # --- lint -----------------------------------------------------------------------------------
149
+ def lint(
150
+ template: str,
151
+ chips: Mapping[str, Chip],
152
+ *,
153
+ share: Any = "auto",
154
+ written: Mapping[str, tuple[str, str]] | None = None,
155
+ ) -> list[str]:
156
+ """Density problems in ``template``, then each placed chip's own warnings, one message
157
+ per line, each saying what to do instead. An empty list means nothing to fix. ``share``
158
+ is ``format_prose``'s: the warnings are those that hold on the scale each chip is drawn
159
+ on there. ``written`` maps a placeholder name to the text it stands for and where that
160
+ is (``mintchip render --check`` passes each directive and its line:column), so a crowded
161
+ sentence is quoted as its writer wrote it, with the locations after the quote."""
162
+ _check_chips("lint", chips)
163
+ used = list(dict.fromkeys(n for n in _SLOT.findall(template) if n in chips))
164
+ domains = shared_domains(chips, share, used=used)
165
+ msgs: list[str] = []
166
+ for p, para in enumerate(_PARAGRAPH.split(template), 1):
167
+ for sentence in _SENTENCE_END.split(para):
168
+ slots = [n for n in _SLOT.findall(sentence) if n in chips]
169
+ if len(slots) > 2:
170
+ shown, at = sentence, ""
171
+ if written:
172
+ shown = _SLOT.sub(lambda m: written.get(m[1], (m[0],))[0], sentence)
173
+ places = [written[n][1] for n in slots if n in written]
174
+ at = f" (at {', '.join(places)})" if places else ""
175
+ msgs.append(
176
+ f"{_quote(shown)} has {len(slots)} chips{at}; keep one or two per "
177
+ "sentence, or use a table."
178
+ )
179
+ msgs += _typed_copies(sentence, slots, chips)
180
+ by_kind: dict[str, list[str]] = {}
181
+ for n in dict.fromkeys(_SLOT.findall(para)):
182
+ if n in chips:
183
+ by_kind.setdefault(chips[n].kind, []).append(n)
184
+ for kind, names in by_kind.items():
185
+ if len(names) >= 3:
186
+ listed = ", ".join(f"{{{n}}}" for n in names)
187
+ msgs.append(
188
+ f"Paragraph {p} has {len(names)} {kind} chips ({listed}); put comparable "
189
+ "values in a table."
190
+ )
191
+ for n in used:
192
+ msgs += [f"{{{n}}}: {w}" for w in chips[n].warnings_for(domains.get(n))]
193
+ return msgs
194
+
195
+
196
+ def _typed_copies(sentence: str, slots: list[str], chips: Mapping[str, Chip]) -> list[str]:
197
+ """A num chip next to the same number typed by hand says it twice."""
198
+ typed = _NUM.findall(_SLOT.sub(" ", sentence))
199
+ out = []
200
+ for n in dict.fromkeys(slots):
201
+ c = chips[n]
202
+ if c.kind != "num":
203
+ continue
204
+ shown = _NUM.findall(c.text(compact=True))
205
+ if not shown:
206
+ continue
207
+ copy = next((t for t in typed if _same(t, shown[0])), None)
208
+ if copy is not None:
209
+ out.append(f"{{{n}}} repeats the typed {copy} beside it; delete the typed number.")
210
+ return out
211
+
212
+
213
+ def _same(a: str, b: str) -> bool:
214
+ if a.endswith("%") != b.endswith("%"):
215
+ return False
216
+
217
+ def val(s: str) -> float:
218
+ return float(s.rstrip("%").replace(",", "").replace("−", "-").lstrip("+"))
219
+
220
+ return val(a) == val(b)
221
+
222
+
223
+ def _quote(sentence: str) -> str:
224
+ s = " ".join(sentence.split())
225
+ return f'"{s[:40]}…"' if len(s) > 41 else f'"{s}"'
@@ -0,0 +1 @@
1
+ """Renderers: text_base (Unicode, ASCII, ANSI), svg_base (Canvas), html (inline chip)."""
@@ -0,0 +1,295 @@
1
+ """HTML tier: a chip inline in prose, its details on demand, the stylesheet and a reading page.
2
+
3
+ A chip is a bare ``<span class="mc">``: the value in the surrounding text's own type, a space,
4
+ then the inline SVG. Details on demand use the HTML popover API (a ``<button popovertarget>``
5
+ and a ``<span popover>``), which needs no JavaScript and, unlike ``<details>``, is phrasing
6
+ content, so it does not end the enclosing ``<p>``. The popover reads like a footnote: it holds
7
+ only what the sentence does not already say.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import html
13
+ import itertools
14
+ import re
15
+ import zlib
16
+ from collections.abc import Sequence
17
+ from typing import Any
18
+
19
+ __all__ = ["chip_html", "css", "document", "page"]
20
+
21
+ # Every popover id on a page must be unique, even for one chip rendered twice.
22
+ _SEQ = itertools.count(1)
23
+ # Inline, so a chip in a page without mintchip.css() still reads as text, not as a button.
24
+ _RESET = (
25
+ "font:inherit;color:inherit;background:none;border:0;padding:0;margin:0;"
26
+ "cursor:pointer;white-space:nowrap"
27
+ )
28
+ _NUM = re.compile(r"\d[\d,]*(?:\.\d+)?%?")
29
+ _WORD = re.compile(r"[^\W\d_]+")
30
+ _FILLER = frozenset(
31
+ ["a", "an", "and", "at", "exact", "is", "median", "of", "out", "the", "to", "value", "whole"]
32
+ )
33
+ _BLOCK = re.compile(
34
+ r"<(?:address|article|aside|blockquote|details|div|dl|figure|footer|form|h[1-6]|header|hr|"
35
+ r"nav|ol|p|pre|section|table|ul)\b",
36
+ re.IGNORECASE,
37
+ )
38
+
39
+
40
+ # --- one chip -------------------------------------------------------------------------------
41
+ def chip_html(
42
+ chip: Any,
43
+ *,
44
+ svg: str,
45
+ value: str | None,
46
+ full: str | None = None,
47
+ label: str | None = None,
48
+ details: bool = True,
49
+ detail: str | None = None,
50
+ warnings: Sequence[str] | None = None,
51
+ ) -> str:
52
+ """Inline HTML for one chip. ``value`` is the value shown in the sentence, ``full`` the
53
+ uncompacted value offered in the popover, ``detail`` caller-supplied (trusted) HTML,
54
+ ``warnings`` the lines that hold at the rendered scale (default ``chip.warnings``)."""
55
+ parts = []
56
+ if label:
57
+ parts.append(f'<span class="mc-label">{html.escape(label)}</span> ')
58
+ if value:
59
+ parts.append(f'<span class="mc-v">{html.escape(value)}</span>')
60
+ if svg:
61
+ parts.append((" " if value else "") + svg)
62
+ inner = "".join(parts)
63
+ cls = f"mc mc-{chip.kind}"
64
+ notes = chip.warnings if warnings is None else warnings
65
+ body = _popover(chip, value, full, bool(label), detail, notes) if details else ""
66
+ if not body:
67
+ return f'<span class="{cls}" style="white-space:nowrap">{inner}</span>'
68
+ pid = f"mc-{zlib.crc32(repr((chip.kind, chip.args, detail)).encode()):08x}-{next(_SEQ)}"
69
+ return (
70
+ f'<span class="{cls}"><button type="button" class="mc-open" popovertarget="{pid}" '
71
+ f'style="{_RESET};anchor-name:--{pid}" aria-label="{html.escape(chip.alt, quote=True)}">'
72
+ f'{inner}</button><span id="{pid}" class="mc-pop" popover '
73
+ f'style="position-anchor:--{pid}">{body}</span></span>'
74
+ )
75
+
76
+
77
+ def _popover(
78
+ chip: Any, value: str | None, full: str | None, label_shown: bool, detail, warnings
79
+ ) -> str:
80
+ """Label, full value, the facts that add to what is visible, warnings, then ``detail``."""
81
+ lines = []
82
+ if chip.label and not label_shown:
83
+ lines.append(f'<span class="mc-pop-l">{html.escape(chip.label)}</span>')
84
+ shown = value or ""
85
+ if full and full != value:
86
+ lines.append(html.escape(full))
87
+ shown = f"{shown} {full}"
88
+ lines += [html.escape(f) for f in chip.facts if not restates(f, shown)]
89
+ lines += [f'<span class="mc-pop-w">Note: {html.escape(w)}</span>' for w in warnings]
90
+ if detail:
91
+ lines.append(detail)
92
+ return "<br>".join(lines)
93
+
94
+
95
+ def restates(fact: str, shown: str) -> bool:
96
+ """Whether ``fact`` only repeats ``shown``: every number in it is visible already and its
97
+ other words are visible or filler ("exact value 0.82" next to "0.82"). A fact with no
98
+ number is never a restatement."""
99
+ nums = {n.replace(",", "") for n in _NUM.findall(fact)}
100
+ if not nums or not nums <= {n.replace(",", "") for n in _NUM.findall(shown)}:
101
+ return False
102
+ words = {w.lower() for w in _WORD.findall(fact)} - _FILLER
103
+ return words <= {w.lower() for w in _WORD.findall(shown)}
104
+
105
+
106
+ # --- the stylesheet -------------------------------------------------------------------------
107
+ _LIGHT = "--mc-accent:#3B7DDD;--mc-good:#2A9152;--mc-bad:#DC4535;--mc-warn:#B87A00"
108
+ _DARK = "--mc-accent:#5590E8;--mc-good:#31A05C;--mc-bad:#E85A48;--mc-warn:#C08000"
109
+ _PAPER = {
110
+ "light": "--mc-paper:#FFFFFF;--mc-ink:#1A1D21",
111
+ "dark": "--mc-paper:#14181F;--mc-ink:#E6E9EE",
112
+ }
113
+ _RULE = "1px solid color-mix(in srgb,currentColor 40%,transparent)"
114
+ _MUTED = "color-mix(in srgb,currentColor 66%,transparent)"
115
+
116
+ # Role colours meet 3:1 on #FFFFFF and on #14181F in both sets, so a host page whose colour
117
+ # scheme disagrees with the reader's system setting still reads.
118
+ _CSS = f"""
119
+ :root{{{_LIGHT}}}
120
+ @media (prefers-color-scheme:dark){{:root{{{_DARK}}}}}
121
+ .mc{{white-space:nowrap;font-variant-numeric:tabular-nums}}
122
+ .mc-open{{text-decoration:none}}
123
+ .mc-open:hover,.mc-open:focus-visible,.mc:has(>.mc-pop:popover-open)>.mc-open{{
124
+ text-decoration:underline dotted 1px;text-decoration-color:{_MUTED};
125
+ text-underline-offset:.22em;outline:none}}
126
+ .mc-open:focus-visible:not(:has(.mc-v)){{outline:1px dotted;outline-offset:2px}}
127
+ .mc-pop{{margin:auto;padding:.35em .6em .4em;max-width:min(22em,calc(100vw - 2em));
128
+ border:1px solid color-mix(in srgb,currentColor 22%,transparent);border-radius:3px;
129
+ background:var(--mc-paper,Canvas);color:var(--mc-ink,CanvasText);font-size:.84em;
130
+ line-height:1.45;font-weight:400;font-style:normal;text-align:left;white-space:normal;
131
+ overflow-wrap:break-word}}
132
+ .mc-pop-l{{font-weight:600}}
133
+ .mc-pop-w{{color:{_MUTED}}}
134
+ @supports (position-area:bottom) or (inset-area:bottom){{.mc-pop{{inset:auto;margin:.3em 0;
135
+ inset-area:bottom span-right;position-area:bottom span-right;
136
+ position-try-options:flip-block,flip-inline;position-try-fallbacks:flip-block,flip-inline}}}}
137
+ .mc-table{{border-collapse:collapse;font-variant-numeric:tabular-nums;line-height:1.4}}
138
+ .mc-table caption{{caption-side:top;text-align:left;font-weight:600;padding:0 0 .4em}}
139
+ .mc-table th,.mc-table td{{padding:.3em 0 .3em 1.25em;border:0;text-align:left;
140
+ vertical-align:baseline}}
141
+ .mc-table :is(th,td):first-child{{padding-left:0}}
142
+ .mc-table .mc-graph{{padding-left:.45em}}
143
+ .mc-table thead th{{font-weight:600;vertical-align:bottom}}
144
+ .mc-table thead tr:last-child>th{{border-bottom:{_RULE}}}
145
+ .mc-table .mc-scale>th{{font-weight:400;font-size:.75em;color:{_MUTED};padding-top:0}}
146
+ .mc-table tbody th{{font-weight:inherit}}
147
+ .mc-table tbody tr:first-child>*{{padding-top:.5em}}
148
+ .mc-table tbody tr:last-child>*{{padding-bottom:.5em;border-bottom:{_RULE}}}
149
+ .mc-table .mc-num{{text-align:right}}
150
+ .mc-table .mc-empty{{color:{_MUTED}}}
151
+ .mc-table tr.mc-highlight>*{{font-weight:600;background:color-mix(in srgb,var(--mc-accent) 9%,transparent)}}
152
+ .mc-table tr.mc-baseline>*{{color:{_MUTED}}}
153
+ .mc-table tr.mc-baseline:not(:first-child)>*{{border-top:1px dashed color-mix(in srgb,currentColor 28%,transparent)}}
154
+ .mc-page{{color-scheme:light dark;{_PAPER["light"]};background:var(--mc-paper);
155
+ color:var(--mc-ink)}}
156
+ @media (prefers-color-scheme:dark){{.mc-page{{{_PAPER["dark"]}}}}}
157
+ [data-mc-scheme="light"],[data-mc-scheme="light"] .mc,.mc[data-mc-scheme="light"],.mc-page[data-mc-scheme="light"]{{color-scheme:light;{_PAPER["light"]};{_LIGHT}}}
158
+ [data-mc-scheme="dark"],[data-mc-scheme="dark"] .mc,.mc[data-mc-scheme="dark"],.mc-page[data-mc-scheme="dark"]{{color-scheme:dark;{_PAPER["dark"]};{_DARK}}}
159
+ .mc-page body{{margin:0}}
160
+ .mc-doc{{display:grid;grid-template-columns:1fr min(34em,100%) 1fr;
161
+ padding:clamp(2em,8vh,4.5em) 1.25em 4em;font:1.0625rem/1.55 system-ui,-apple-system,
162
+ "Segoe UI",Roboto,sans-serif;-webkit-text-size-adjust:100%}}
163
+ .mc-doc>*{{grid-column:2;margin:0 0 1em}}
164
+ .mc-doc p{{text-wrap:pretty}}
165
+ .mc-doc>h1{{font-size:1.55em;line-height:1.2;font-weight:650;letter-spacing:-.01em;
166
+ margin-bottom:.3em;text-wrap:balance}}
167
+ .mc-doc>.mc-sub{{color:{_MUTED};margin-bottom:1.75em}}
168
+ .mc-doc>h2{{font-size:1.1em;font-weight:600;margin:.8em 0 .4em}}
169
+ .mc-doc>.mc-wide{{grid-column:1/-1;justify-self:center;width:max-content;
170
+ min-width:min(34em,100%);max-width:100%;overflow-x:auto;margin:.25em 0 1.25em}}
171
+ .mc-doc .mc-table{{font-size:.94em}}
172
+ .mc-doc>.mc-src{{margin-top:1.5em;font-size:.85em;color:{_MUTED}}}
173
+ """
174
+ _CSS = "".join(line.strip() for line in _CSS.strip().splitlines())
175
+ _COMPACT_CSS = (
176
+ ".mc-compact,.mc-compact body{background:transparent}"
177
+ ".mc-compact .mc-doc{display:block;padding:4px 0}"
178
+ ".mc-compact .mc-doc>.mc-wide{width:auto;min-width:0}"
179
+ )
180
+ _THEME_SYNC_JS = (
181
+ "(function(){var H=document.documentElement;"
182
+ "function sync(){"
183
+ "var c=H.classList,t=H.getAttribute('data-theme');"
184
+ "if(c.contains('light')||t==='light'){H.setAttribute('data-mc-scheme','light');}"
185
+ "else if(c.contains('dark')||t==='dark'){H.setAttribute('data-mc-scheme','dark');}"
186
+ "else if(window.matchMedia){"
187
+ "H.setAttribute('data-mc-scheme',"
188
+ "window.matchMedia('(prefers-color-scheme:dark)').matches?'dark':'light');}"
189
+ "}"
190
+ "sync();"
191
+ "window.addEventListener('themechange',sync);"
192
+ "if(window.matchMedia){"
193
+ "var mq=window.matchMedia('(prefers-color-scheme:dark)');"
194
+ "if(mq.addEventListener)mq.addEventListener('change',sync);}"
195
+ "})();"
196
+ )
197
+
198
+
199
+ def css(accent: str | None = None) -> str:
200
+ """The one stylesheet for chips, popovers, ``mintchip.table`` and ``document()``. It
201
+ sets ``--mc-accent``, ``--mc-good``, ``--mc-bad`` and ``--mc-warn`` (with dark values under
202
+ ``prefers-color-scheme: dark``); override them on any ancestor or pass ``accent="#HEX"``
203
+ to restyle."""
204
+ if accent is None:
205
+ return _CSS
206
+ from ..spec import ChipError
207
+ from ..themes import resolve_theme
208
+
209
+ try:
210
+ colour = resolve_theme("auto", accent).accent
211
+ except (TypeError, ValueError) as e:
212
+ raise ChipError(
213
+ f"mintchip.css: {e}.", fix_hint="Pass a hex colour like '#2563EB'."
214
+ ) from None
215
+ return _CSS.replace("--mc-accent:#3B7DDD", f"--mc-accent:{colour}").replace(
216
+ "--mc-accent:#5590E8", f"--mc-accent:{colour}"
217
+ )
218
+
219
+
220
+ # --- pages ----------------------------------------------------------------------------------
221
+ def document(
222
+ title: str,
223
+ blocks: Any,
224
+ *,
225
+ subtitle: str | None = None,
226
+ source: str | None = None,
227
+ theme: Any = "auto",
228
+ accent: str | None = None,
229
+ compact: bool = False,
230
+ ) -> str:
231
+ """A self-contained reading page with no JavaScript (or a transparent flush embed with
232
+ lightweight host theme sync when ``compact=True``): a title, then ``blocks`` on a measure
233
+ of about 34em in the reader's system text face, adapting to light and dark (``theme``
234
+ "light" or "dark" fixes one). A block is an HTML string (block-level markup is kept as is;
235
+ anything else, such as ``format_prose(..., format="html")`` output, becomes a ``<p>``), a
236
+ ``Chip``, or a ``Table``. Strings are HTML: escape untrusted text before passing it.
237
+ ``title``, ``subtitle`` and ``source`` are plain text."""
238
+ from ..spec import Chip, ChipError
239
+ from ..themes import resolve_theme
240
+
241
+ try:
242
+ name = resolve_theme(theme, accent).name
243
+ except (TypeError, ValueError) as e:
244
+ raise ChipError(f"mintchip.document: {e}.", fix_hint="Use theme='auto'.") from None
245
+ if isinstance(blocks, str) or not hasattr(blocks, "__iter__"):
246
+ blocks = [blocks]
247
+ parts = [f"<h1>{html.escape(title)}</h1>"] if title else []
248
+ if subtitle:
249
+ parts.append(f'<p class="mc-sub">{html.escape(subtitle)}</p>')
250
+ for i, b in enumerate(blocks):
251
+ if isinstance(b, str):
252
+ if b.lstrip().lower().startswith("<table"):
253
+ parts.append(f'<div class="mc-wide">{b}</div>')
254
+ else:
255
+ parts.append(b if _BLOCK.match(b.lstrip()) else f"<p>{b}</p>")
256
+ elif isinstance(b, Chip):
257
+ parts.append(f"<p>{b.html(theme=theme, accent=accent)}</p>")
258
+ elif callable(getattr(b, "html", None)):
259
+ kw = {"theme": theme, **({"accent": accent} if accent is not None else {})}
260
+ parts.append(f'<div class="mc-wide">{b.html(**kw)}</div>')
261
+ else:
262
+ raise ChipError(
263
+ f"mintchip.document: block {i} is a {type(b).__name__}.",
264
+ fix_hint="Pass HTML strings, plain strings, chips or mintchip.table(...) objects.",
265
+ )
266
+ if source:
267
+ parts.append(f'<footer class="mc-src">Source: {html.escape(source)}</footer>')
268
+ scheme = {"dark": "dark", "light": "light", "mono": "light"}.get(name)
269
+ return _shell(title or "mintchip", "\n".join(parts), scheme, accent=accent, compact=compact)
270
+
271
+
272
+ def page(body: str, *, title: str = "mintchip") -> str:
273
+ """A standalone page around one inline fragment (used by ``Chip.save(".html")``)."""
274
+ return _shell(title, f"<p>{body}</p>", None)
275
+
276
+
277
+ def _shell(
278
+ title: str,
279
+ body: str,
280
+ scheme: str | None,
281
+ *,
282
+ accent: str | None = None,
283
+ compact: bool = False,
284
+ ) -> str:
285
+ cls = "mc-page mc-compact" if compact else "mc-page"
286
+ attr = f' data-mc-scheme="{scheme}"' if scheme else ""
287
+ style = css(accent) + (_COMPACT_CSS if compact else "")
288
+ sync = f"\n<script>{_THEME_SYNC_JS}</script>" if compact and scheme is None else ""
289
+ return (
290
+ f'<!doctype html>\n<html lang="en" class="{cls}"{attr}>\n<head>\n<meta charset="utf-8">\n'
291
+ '<meta name="viewport" content="width=device-width,initial-scale=1">\n'
292
+ f'<meta name="color-scheme" content="{scheme or "light dark"}">\n'
293
+ f"<title>{html.escape(title)}</title>\n<style>{style}</style>\n</head>\n"
294
+ f'<body>\n<main class="mc-doc">\n{body}\n</main>{sync}\n</body>\n</html>\n'
295
+ )