marimo-dev 0.3.3__tar.gz → 0.3.5__tar.gz

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.
@@ -1,19 +1,12 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: marimo-dev
3
- Version: 0.3.3
3
+ Version: 0.3.5
4
4
  Summary: Build and publish python packages from marimo notebooks
5
5
  Author: Deufel
6
6
  Author-email: Deufel <MDeufel13@gmail.com>
7
7
  License: MIT
8
8
  Classifier: Development Status :: 3 - Alpha
9
- Requires-Dist: anthropic>=0.84.0
10
- Requires-Dist: fastcore>=1.10.0
11
- Requires-Dist: ipython>=9.8.0
12
- Requires-Dist: marimo>=0.19.7
13
- Requires-Dist: mohtml>=0.1.11
14
- Requires-Dist: pydantic-ai-slim>=1.50.0
15
- Requires-Dist: pytest>=9.0.2
16
- Requires-Dist: python-fasthtml>=0.12.37
9
+ Requires-Dist: html-tags>=0.0.18
17
10
  Requires-Python: >=3.12
18
11
  Project-URL: PyPI, https://pypi.org/project/marimo-dev/
19
12
  Project-URL: Repository, https://github.com/deufel/m-dev
@@ -4,20 +4,22 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "marimo-dev"
7
- version = "0.3.3"
7
+ version = "0.3.5"
8
8
  description = "Build and publish python packages from marimo notebooks"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
11
11
  classifiers = ["Development Status :: 3 - Alpha"]
12
12
  dependencies = [
13
+ "html-tags>=0.0.18",
14
+ ]
15
+
16
+ [dependency-groups]
17
+ dev = [
13
18
  "anthropic>=0.84.0",
14
- "fastcore>=1.10.0",
15
19
  "ipython>=9.8.0",
16
20
  "marimo>=0.19.7",
17
- "mohtml>=0.1.11",
18
21
  "pydantic-ai-slim>=1.50.0",
19
22
  "pytest>=9.0.2",
20
- "python-fasthtml>=0.12.37",
21
23
  ]
22
24
 
23
25
  [project.license]
@@ -1,13 +1,12 @@
1
1
  """Build and publish python packages from marimo notebooks"""
2
- __version__ = '0.3.3'
2
+ __version__ = '0.3.5'
3
3
  __author__ = 'Deufel'
4
4
  from .core import Config, read_config, Kind, Param, Node
5
5
  from .read import inline_doc, parse_params, parse_hash_pipe, parse_class_params, parse_class_methods, parse_ret, src_with_decs, is_export, parse_import, parse_const, parse_export, parse_node, parse_file, read_meta, nb_name, scan
6
6
  from .pkg import clean, write, write_mod, rename, apply_renames, rewrite_imports, write_init
7
- from .docs import nb_path, render_node, render_module_page, build_docs, export_wasm, write_nojekyll, html_preview, render_index_page, Icon, write_highlighter
7
+ from .docs import sanitize_for_js, render_node_with_search, render_module_page_datastar, nb_path, render_index_page, html_preview, build_docs, export_wasm, write_nojekyll, Icon, write_highlighter
8
8
  from .build import build, tidy, nuke, get_pypi_name, extract_import_names, pep723_header, write_llms, bundle, bundle_notebook
9
9
  from .publish import check_credentials, check_pypi_auth, publish
10
- from .cli import main
11
10
  __all__ = [
12
11
  "Config",
13
12
  "Icon",
@@ -28,7 +27,6 @@ __all__ = [
28
27
  "html_preview",
29
28
  "inline_doc",
30
29
  "is_export",
31
- "main",
32
30
  "nb_name",
33
31
  "nb_path",
34
32
  "nuke",
@@ -48,9 +46,10 @@ __all__ = [
48
46
  "read_meta",
49
47
  "rename",
50
48
  "render_index_page",
51
- "render_module_page",
52
- "render_node",
49
+ "render_module_page_datastar",
50
+ "render_node_with_search",
53
51
  "rewrite_imports",
52
+ "sanitize_for_js",
54
53
  "scan",
55
54
  "src_with_decs",
56
55
  "tidy",
@@ -0,0 +1,383 @@
1
+ from .core import Kind, Param, Node, Config, read_config
2
+ from .read import scan, nb_name, read_meta
3
+ from .pkg import clean
4
+ from .build import bundle_notebook
5
+ import ast, re, tomllib, json
6
+ from pathlib import Path
7
+ from enum import Enum
8
+ from dataclasses import dataclass, field
9
+ import os, sys, subprocess, configparser, shutil
10
+ from functools import partial
11
+ from html_tags import mktag, setup_svg, Tag, to_html
12
+
13
+ Form = mktag('form')
14
+ Link = mktag('link', self_closing=True)
15
+ icons = {'home': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-house-icon lucide-house"><path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"/><path d="M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>', 'pypi': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-blocks-icon lucide-blocks"><path d="M10 22V7a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5a1 1 0 0 0-1-1H2"/><rect x="14" y="2" width="8" height="8" rx="1"/></svg>', 'menu': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-menu-icon lucide-menu"><path d="M4 5h16"/><path d="M4 12h16"/><path d="M4 19h16"/></svg>', 'x': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x-icon lucide-x"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>', 'github': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-github-icon lucide-github"><path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"/><path d="M9 18c-4.51 2-5-2-7-2"/></svg>', 'code': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-code-icon lucide-code"><path d="m16 18 6-6-6-6"/><path d="m8 6-6 6 6 6"/></svg>', 'info': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-info-icon lucide-info"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>', 'calendar': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-calendar1-icon lucide-calendar-1"><path d="M11 14h1v4"/><path d="M16 2v4"/><path d="M3 10h18"/><path d="M8 2v4"/><rect x="3" y="4" width="18" height="18" rx="2"/></svg>', 'circle-x': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-x-icon lucide-circle-x"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>', 'external-link': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-external-link-icon lucide-external-link"><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></svg>'}
16
+ COLORS = {'keyword': '#c792ea', 'string': '#c3e88d', 'builtin': '#82aaff', 'decorator': '#f78c6c', 'comment': '#546e7a', 'number': '#f78c6c', 'punctuation': '#89ddff', 'defname': '#82aaff', 'classname': '#ffcb6b', 'operator': '#89ddff', 'call': '#82aaff', 'fstring': '#c3e88d', 'type': '#ffcb6b'}
17
+
18
+ Div, Span, P, A, Button, Pre, Code, Li, Ul = (mktag(t) for t in
19
+ 'div span p a button pre code li ul'.split())
20
+ H1, H2, H3, Nav, Article, Header, Main, Aside = (mktag(t) for t in
21
+ 'h1 h2 h3 nav article header main aside'.split())
22
+ Html, Head, Body, Title, Input, Strong = (mktag(t) for t in
23
+ 'html head body title input strong'.split())
24
+ Script, Style, Iframe = (mktag(t, mode='raw') for t in
25
+ 'script style iframe'.split())
26
+
27
+ def sanitize_for_js(text):
28
+ """Sanitize text for safe embedding in a JS string"""
29
+ return (text
30
+ .replace('\\', ' ') # remove backslashes
31
+ .replace('\n', ' ') # remove newlines
32
+ .replace('\r', ' ') # remove carriage returns
33
+ .replace('"', ' ') # remove double quotes
34
+ .replace("'", ' ') # remove single quotes
35
+ .replace('`', ' ') # remove backticks
36
+ .replace('/', ' ') # remove forward slashes
37
+ )
38
+
39
+ def render_node_with_search(n, repo_url=None, root='.'):
40
+ t = 'class' if 'class ' in n.src else 'async' if n.src.lstrip().startswith('async ') else 'func'
41
+ signature = clean(n.src)
42
+ node_id = f"node-{n.module}-{n.name}".replace('.', '-')
43
+ signal_search = f"searchable_{node_id}".replace('-', '_')
44
+ signal_match = f"match_{node_id}".replace('-', '_')
45
+ tag_colors = {'func': '#10b981', 'async': '#f59e0b', 'class': '#8b5cf6'}
46
+
47
+ # Sanitize searchable text to be safe in JS string
48
+ raw_text = f"{n.name} {n.module} {t} {n.doc or ''} {signature}"
49
+ searchable_text = sanitize_for_js(raw_text.lower())
50
+
51
+ nb = nb_path(n.module, root)
52
+ repo_url = repo_url or ''
53
+
54
+ def ghbtn(icon, label, url):
55
+ if not url: return None
56
+ return A(href=url, target="_blank", cls="gh-link")(
57
+ Button(cls="gh-btn")(Icon(icon, size=16), label))
58
+
59
+ source_btn = ghbtn('github', 'Source', f"{repo_url}/blob/master/{nb}#L{n.lineno}" if repo_url and nb and n.lineno else None)
60
+ edit_btn = ghbtn('code', 'Edit', f"{repo_url}/edit/master/{nb}" if repo_url and nb else None)
61
+ code_lines = [Span(cls="code-line")(line) for line in signature.split('\n')]
62
+
63
+ return Div(
64
+ id=node_id,
65
+ **{
66
+ "data-signals": f'{{"{signal_search}": "{searchable_text}", "{signal_match}": 0}}',
67
+ "data-effect": f'${signal_match} = [...$tags, $search.trim()].filter(t => t.length > 0 && ${signal_search}.toLowerCase().includes(t.toLowerCase())).length',
68
+ "data-show": f'($tags.length === 0 && $search.trim().length === 0) || ${signal_match} > 0',
69
+ "data-style:order": f'($tags.length === 0 && $search.trim().length === 0) ? 0 : -${signal_match}',
70
+ }
71
+ )(
72
+ Style()("""
73
+ me { margin-bottom:0.75rem; border-radius:8px; overflow:hidden; background:#1e1e1e; position:relative; }
74
+ me .match-badge { position:absolute; top:1rem; right:1rem; background:#3b82f6; color:white; padding:0.25rem 0.75rem; border-radius:9999px; font-size:0.8rem; font-weight:600; }
75
+ me .header { display:flex; align-items:center; justify-content:space-between; padding:0.75rem 1rem; }
76
+ me .header-left { display:flex; align-items:center; gap:0.75rem; }
77
+ me .header-right { display:flex; align-items:center; gap:0.5rem; }
78
+ me .tag { padding:0.25rem 0.6rem; border-radius:4px; font-size:0.75rem; font-weight:600; color:white; }
79
+ me .full-name { font-size:1rem; font-weight:500; }
80
+ me .mod { color:#666; }
81
+ me .name { color:#e5e5e5; }
82
+ me .doc { margin:0; padding:0 1rem 0.5rem; color:#888; font-size:0.85rem; }
83
+ me .gh-btn { display:flex; align-items:center; gap:0.25rem; background:#333; border:1px solid #444; color:#ccc; padding:0.25rem 0.5rem; border-radius:4px; cursor:pointer; font-size:0.75rem; }
84
+ me .gh-link { text-decoration:none; }
85
+ me pre { background:#1a1a1a; border-top:1px solid #2a2a2a; margin:0; padding:0.5rem 0; }
86
+ me code { font-size:0.8rem; line-height:1.6; color:#ccc; counter-reset:line; }
87
+ me .code-line { display:block; padding-left:3.5em; white-space:pre-wrap; word-break:break-all; position:relative; }
88
+ me .code-line::before { content:counter(line); counter-increment:line; position:absolute; left:0; width:2.5em; text-align:right; color:#555; user-select:none; }
89
+ """),
90
+ Span(cls="match-badge", **{
91
+ "data-show": f'$tags.length > 0 || $search.trim().length > 0',
92
+ "data-text": f'${signal_match}'
93
+ })(),
94
+ Div(cls="header")(
95
+ Div(cls="header-left")(
96
+ Span(cls="tag", style=f"background:{tag_colors.get(t,'#666')};")(t),
97
+ Span(cls="full-name")(
98
+ Span(cls="mod")(f"{n.module}."),
99
+ Span(cls="name")(n.name)
100
+ ) if n.module else Span(cls="full-name name")(n.name)
101
+ ),
102
+ Div(cls="header-right")(source_btn, edit_btn)
103
+ ),
104
+ P(cls="doc")(n.doc) if n.doc else None,
105
+ Pre()(Code(cls="language-python", id=f"code-{node_id}")(*code_lines))
106
+ )
107
+
108
+ def render_module_page_datastar(mod_name, mod_nodes, all_mod_names, meta, root='.'):
109
+ """Builds a Module Page with Datastar search"""
110
+ repo_url = meta.get('urls', {}).get('Repository')
111
+ exp_nodes = [n for n in mod_nodes if n.kind == Kind.EXP]
112
+
113
+ head_elements = [
114
+ Script(type="module", src="https://cdn.jsdelivr.net/gh/starfederation/datastar@1.0.0-RC.8/bundles/datastar.js")(),
115
+ mktag('script', mode='raw')(src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js")(),
116
+ Script(src="js/highlight.js", type="module")(),
117
+ Title()(f"{mod_name} - {meta['name']}"),
118
+ Style()("""
119
+ * { scrollbar-gutter:stable; box-sizing:border-box; }
120
+ body { font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; margin:0; background:#121212; }
121
+ code { font-family:'SF Mono',Consolas,monospace; }
122
+ .layout { display:flex; height:100vh; }
123
+ .sidenav { width:220px; background:#1a1a1a; padding:1rem; overflow-y:auto; display:flex; flex-direction:column; gap:0.25rem; flex-shrink:0; }
124
+ .sidenav h3 { margin:0 0 0.75rem 0; color:#fff; font-size:0.9rem; text-transform:uppercase; }
125
+ .nav-item { display:flex; align-items:center; justify-content:space-between; padding:0.4rem 0.5rem; border-radius:4px; color:#aaa; text-decoration:none; font-size:0.85rem; }
126
+ .nav-item:hover { background:#252525; color:#fff; }
127
+ .nav-item.active { color:#fff; background:#252525; }
128
+ .nav-badge { background:#3b82f6; color:white; padding:0.1rem 0.4rem; border-radius:9999px; font-size:0.7rem; font-weight:600; }
129
+ .nav-item.disabled { opacity:0.3; pointer-events:none; }
130
+ .main { flex:1; display:flex; flex-direction:column; overflow:hidden; }
131
+ .topbar { display:flex; align-items:center; justify-content:space-between; padding:0.75rem 1rem; background:#1e1e1e; border-bottom:1px solid #2a2a2a; gap:1rem; flex-shrink:0; }
132
+ .topbar h1 { margin:0; font-size:1.25rem; color:#fff; }
133
+ .search-bar { display:flex; gap:0.5rem; align-items:center; }
134
+ .search-bar input { padding:0.5rem 0.75rem; border:1px solid #333; border-radius:4px; background:#252525; color:#fff; font-size:0.9rem; min-width:220px; }
135
+ .search-bar input:focus { outline:2px solid #3b82f6; }
136
+ .btn { padding:0.5rem 0.9rem; background:#3b82f6; color:white; border:none; border-radius:4px; cursor:pointer; font-size:0.85rem; }
137
+ .btn:hover { background:#2563eb; }
138
+ .btn.clear { background:#dc2626; }
139
+ .btn.clear:hover { background:#b91c1c; }
140
+ .content { flex:1; overflow-y:auto; padding:1rem; display:flex; flex-direction:column; }
141
+ .tags-bar { display:flex; gap:0.5rem; flex-wrap:wrap; margin-bottom:0.5rem; min-height:1.5rem; }
142
+ .tag-pill { background:#3b82f6; color:white; padding:0.2rem 0.6rem; border-radius:9999px; font-size:0.8rem; }
143
+ """)
144
+ ]
145
+
146
+ nav_links = [
147
+ Li()(A(href="index.html", cls="nav-item")("← Index")),
148
+ *[
149
+ Li()(A(
150
+ href=f"{m}.html",
151
+ cls=f"nav-item {'active' if m == mod_name else ''}",
152
+ )(
153
+ Span()(m),
154
+ Span(cls="nav-badge", **{
155
+ "data-show": "$tags.length > 0 || $search.trim().length > 0",
156
+ "data-text": "0"
157
+ })()
158
+ ))
159
+ for m in all_mod_names
160
+ ]
161
+ ]
162
+
163
+ body = Body(
164
+ **{"data-signals": '{"search": "", "tags": []}', "style": "margin:0;"}
165
+ )(
166
+ Div(cls="layout")(
167
+ Nav(cls="sidenav")(
168
+ H3()(meta['name']),
169
+ *nav_links
170
+ ),
171
+ Div(cls="main")(
172
+ Div(cls="topbar")(
173
+ H1()(mod_name),
174
+ Form(
175
+ cls="search-bar",
176
+ **{"data-on:submit__prevent": "$search.trim() ? ($tags = [...$tags, $search.trim()], $search = '') : null"}
177
+ )(
178
+ Input(type="text", placeholder="Search... (Enter to add tag)", **{"data-bind": "search"})(),
179
+ Button(cls="btn", type="submit")("Add Tag"),
180
+ Button(cls="btn clear", type="button", **{"data-on:click": "$tags = [], $search = ''"})("Clear")
181
+ )
182
+ ),
183
+ Div(cls="content")(
184
+ Div(cls="tags-bar", **{"data-show": "$tags.length > 0"})(),
185
+ Div(style="display:flex; flex-direction:column;")(
186
+ *[render_node_with_search(n, repo_url, root) for n in exp_nodes]
187
+ )
188
+ )
189
+ )
190
+ )
191
+ )
192
+
193
+ return Html()(Head()(*head_elements), body)
194
+
195
+ def nb_path(
196
+ mod_name,
197
+ root='.'
198
+ ):
199
+ '''[TODO] '''
200
+ cfg = read_config(root)
201
+ for f in (Path(root) / cfg.nbs).glob('*.py'):
202
+ if nb_name(f, root) == mod_name: return f.relative_to(root)
203
+ return None
204
+
205
+ def render_index_page(meta, mods, repo_url=None):
206
+ mod_names = [name for name, _ in mods]
207
+ head_elements = [
208
+ Script(type="module", src="https://cdn.jsdelivr.net/gh/starfederation/datastar@1.0.0-RC.7/bundles/datastar.js")(),
209
+ mktag('script', mode='raw')(src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js")(),
210
+ Script(src="js/highlight.js", type="module")(),
211
+ Style()("body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; } code { font-family: 'SF Mono', Consolas, monospace; }"),
212
+ Title()(meta['name'])]
213
+
214
+ nav_links = [Li()(A(href=f"{m}.html", cls="nav-link")(m)) for m in mod_names]
215
+
216
+ nav = Nav()(
217
+ Style()("""
218
+ me { padding: 1rem; background: #1a1a1a; min-width: 180px; }
219
+ me h3 { margin: 0 0 1rem 0; color: #fff; }
220
+ me ul { list-style: none; padding: 0; margin: 0; }
221
+ me .nav-link { color: #aaa; text-decoration: none; }
222
+ me .nav-link:hover { color: #fff; }
223
+ """),
224
+ H3()(meta['name']),
225
+ Ul()(*nav_links))
226
+
227
+ module_cards = [A(href=f"{name}.html", cls="card-link")(
228
+ Div(cls="card")(
229
+ H3(cls="card-title")(name),
230
+ P(cls="card-count")(f"{len([n for n in nodes if n.kind == Kind.EXP])} exports")))
231
+ for name, nodes in mods]
232
+
233
+ content = Div()(
234
+ Style()("""
235
+ me { padding: 2rem; flex: 1; }
236
+ me h1 { margin: 0 0 0.5rem 0; color: #fff; }
237
+ me .desc { color: #888; margin: 0 0 2rem 0; }
238
+ me .version { color: #666; margin: 0 0 2rem 0; font-size: 0.9rem; }
239
+ me h2 { color: #fff; margin: 0 0 1rem 0; font-size: 1.2rem; }
240
+ me .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 1rem; }
241
+ me .card-link { text-decoration: none; }
242
+ me .card { padding: 1rem; background: #1e1e1e; border-radius: 8px; }
243
+ me .card:hover { background: #252525; }
244
+ me .card-title { margin: 0 0 0.5rem 0; color: #fff; }
245
+ me .card-count { margin: 0; color: #888; }
246
+ """),
247
+ H1()(meta['name']),
248
+ P(cls="desc")(meta['desc']),
249
+ P(cls="version")(f"Version {meta['version']}"),
250
+ H2()("Modules"),
251
+ Div(cls="grid")(*module_cards))
252
+
253
+ body = Body(style="display: flex; min-height: 100vh; margin: 0; background: #121212;")(nav, content)
254
+ return Html()(Head()(*head_elements), body)
255
+
256
+ def html_preview(width='100%', height='300px'):
257
+ "Display FT components in an IFrame"
258
+ from IPython.display import display, HTML
259
+ def _preview(*components):
260
+ html = str(components[0]) if len(components) == 1 else str(Div()(*components))
261
+ display(HTML(f'<iframe srcdoc="{html}" width="{width}" height="{height}"></iframe>'))
262
+ return _preview
263
+
264
+ def build_docs(root='.'):
265
+ cfg = read_config(root)
266
+ meta = read_meta(root)
267
+ _, mods = scan(root)
268
+ mod_names = [name for name, _ in mods]
269
+ docs_path = Path(root) / cfg.docs
270
+ docs_path.mkdir(exist_ok=True)
271
+
272
+ (docs_path / "index.html").write_text(to_html(render_index_page(meta, mods)))
273
+
274
+ for mod_name, mod_nodes in mods:
275
+ (docs_path / f"{mod_name}.html").write_text(
276
+ to_html(render_module_page_datastar(mod_name, mod_nodes, mod_names, meta, root))
277
+ )
278
+
279
+ export_wasm(root)
280
+ return f"Generated index + {len(mods)} module pages with Datastar search in {docs_path}"
281
+
282
+ def export_wasm(
283
+ root='.' # Project Root
284
+ ):
285
+ """Uses the bundeled notebook to make a WASM marimo notebook"""
286
+ cfg = read_config(root)
287
+ wasm_dir = Path(root) / cfg.docs / 'wasm'
288
+ wasm_dir.mkdir(parents=True, exist_ok=True)
289
+ bundled = Path(root) / cfg.nbs / '_bundled.py'
290
+ bundle_notebook(root, name=str(bundled))
291
+ os.system(f"marimo export html-wasm {bundled} -o {wasm_dir} --mode edit")
292
+ bundled.unlink()
293
+
294
+ def write_nojekyll(root='.'):
295
+ cfg = read_config(root)
296
+ Path(root, cfg.docs, '.nojekyll').touch()
297
+
298
+ def Icon(name: str, # name of the icon MUST be in icon_dict
299
+ size=24, # value to be passed to height and width of the icon
300
+ stroke=1.5, # stroke width
301
+ cls=None, # css class
302
+ icon_dict:dict=icons, # Dict of icons {"name":"<svg...>"}
303
+ **kwargs # passed through to tag
304
+ ):
305
+ '''Creates a custom html compliant <icon-{name}>...'''
306
+ if name not in icon_dict: raise ValueError(f"Icon '{name}' not found")
307
+
308
+ svg_string = icon_dict[name]
309
+ svg_string = re.sub(r'width="\d+"', f'width="{size}"', svg_string, count=1)
310
+ svg_string = re.sub(r'height="\d+"', f'height="{size}"', svg_string, count=1)
311
+ svg_string = re.sub(r'stroke-width="\d+"', f'stroke-width="{stroke}"', svg_string)
312
+
313
+ return mktag(f'icon-{name}', mode='raw')(cls=cls, **kwargs)(svg_string)
314
+
315
+ def write_highlighter(root='.'):
316
+ "Write Python syntax highlighter JS to docs folder."
317
+ cfg = read_config(root)
318
+ js_dir = Path(root) / cfg.docs / 'js'
319
+ js_dir.mkdir(parents=True, exist_ok=True)
320
+
321
+ tokens = [
322
+ ('py-decorator', r'@[\w.]+'),
323
+ ('py-defname', r'(?<=def )\w+'),
324
+ ('py-classname', r'(?<=class )\w+'),
325
+ ('py-keyword', r'\b(?:def|class|return|if|elif|else|for|while|import|from|as|with|try|except|finally|raise|yield|async|await|pass|break|continue|in|is|not|and|or|lambda|None|True|False|self)\b'),
326
+ ('py-builtin', r'\b(?:print|len|range|list|dict|set|tuple|int|str|float|bool|isinstance|hasattr|getattr|setattr|enumerate|zip|map|filter|any|all|sorted|reversed|super|type|open|next)\b'),
327
+ ('py-call', r'\b\w+(?=\()'),
328
+ ('py-number', r'\b\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?\b'),
329
+ ('py-operator', r'->|==|!=|<=|>=|\*\*|\/\/|[+\-*/%=<>&|^~]'),
330
+ ('py-punctuation', r'[{}\(\)\[\]:,;]'),
331
+ ('py-fstring', r"f(?='|\")"),
332
+ ('py-type', r'(?<=: )\w+'),
333
+ ('py-string', r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'|"[^"\n]*"|\'[^\'\n]*\''),
334
+ ('py-comment', r'#.*'),
335
+ ]
336
+
337
+
338
+ token_js = ',\n '.join(f"['{name}', /{pattern}/g]" for name, pattern in tokens)
339
+ color_css = '\n'.join(f'::highlight({name}) {{ color: {COLORS[name.replace("py-", "")]}; }}' for name, _ in tokens)
340
+
341
+ js = f"""const PY_TOKENS = [
342
+ {token_js}
343
+ ];
344
+
345
+ function highlightAll(root = document) {{
346
+ if (!CSS?.highlights) return;
347
+ for (const [name] of PY_TOKENS) CSS.highlights.delete(name);
348
+ root.querySelectorAll('pre code').forEach(code => {{
349
+ const textNodes = [];
350
+ code.querySelectorAll('.code-line').forEach(line => {{
351
+ if (line.firstChild?.nodeType === Node.TEXT_NODE) textNodes.push(line.firstChild);
352
+ }});
353
+ if (!textNodes.length) return;
354
+
355
+ for (const [name, pattern] of PY_TOKENS) {{
356
+ const highlight = CSS.highlights.get(name) ?? new Highlight();
357
+ for (const node of textNodes) {{
358
+ const src = node.textContent;
359
+ const re = new RegExp(pattern.source, pattern.flags);
360
+ for (const match of src.matchAll(re)) {{
361
+ const range = new Range();
362
+ range.setStart(node, match.index);
363
+ range.setEnd(node, match.index + match[0].length);
364
+ highlight.add(range);
365
+ }}
366
+ }}
367
+ if (highlight.size > 0) CSS.highlights.set(name, highlight);
368
+ }}
369
+ }});
370
+ }}
371
+
372
+ // Inject highlight styles
373
+ const style = document.createElement('style');
374
+ style.textContent = `{color_css}`;
375
+ document.head.appendChild(style);
376
+
377
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => highlightAll());
378
+ else highlightAll();
379
+ """
380
+
381
+
382
+ (js_dir / 'highlight.js').write_text(js)
383
+ return f"Wrote {js_dir}/highlight.js"
@@ -25,6 +25,12 @@ def write_mod(
25
25
  g = {k: [n for n in nodes if n.kind == k] for k in Kind}
26
26
  imports = '\n'.join(rewrite_imports(n.src, mod_names) for n in g[Kind.IMP])
27
27
  exp_src = '\n\n'.join(apply_renames(clean(n.src), n.name, renames) for n in g[Kind.EXP])
28
+
29
+ # Second pass: fix cross-references to renamed symbols
30
+ rename_map = {n.name: rename(n.name, renames) for n in g[Kind.EXP] if rename(n.name, renames) != n.name}
31
+ for old, new in rename_map.items():
32
+ exp_src = re.sub(rf'\b{re.escape(old)}\b', new, exp_src)
33
+
28
34
  parts = [imports, '\n'.join(n.src for n in g[Kind.CONST]), '\n'.join(n.src for n in g[Kind.SETUP]), exp_src, '\n\n'.join(n.src for n in g[Kind.RAW])]
29
35
  write(path, *parts)
30
36
 
@@ -1,25 +0,0 @@
1
- from .build import build, tidy, nuke, bundle
2
- from .publish import publish
3
- from .docs import build_docs
4
- import sys, subprocess
5
- from pathlib import Path
6
-
7
- def main():
8
- if len(sys.argv) < 2: print("Usage: md [build|publish|docs|tidy|nuke]"); sys.exit(1)
9
- cmd = sys.argv[1]
10
- if cmd == 'build':
11
- print(f"Built package at: {build()}")
12
- print(build_docs())
13
- elif cmd == 'publish':
14
- test = '--test' in sys.argv or '-t' in sys.argv
15
- target = "TestPyPI" if test else "PyPI"
16
- if input(f"Publish to {target}? [y/N] ").lower() != 'y': print("Aborted"); sys.exit(0)
17
- publish(test=test)
18
- elif cmd == 'docs': build_docs()
19
- elif cmd == 'tidy': tidy()
20
- elif cmd == 'nuke': nuke()
21
- elif cmd == 'bundle':
22
- name = sys.argv[2] if len(sys.argv) > 2 else None
23
- print(bundle(name=name))
24
-
25
- else: print(f"Unknown command: {cmd}"); sys.exit(1)
@@ -1,310 +0,0 @@
1
- from .core import Kind, Param, Node, Config, read_config
2
- from .read import scan, nb_name, read_meta
3
- from .pkg import clean
4
- from .build import bundle_notebook
5
- from pathlib import Path
6
- import ast, re, os
7
- import marimo as mo
8
- from functools import partial
9
- from fastcore.xml import Span, Code, Li, Article, Div, Ul, P, FT, to_xml, Pre, Link, A, Iframe, Button, H1, H2, H3, Nav, Aside, Header, Input, NotStr, Strong, Main
10
- from fasthtml.components import ft, Html, Head, Script, Body, show, Style, Title
11
-
12
- icons = {'home': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-house-icon lucide-house"><path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"/><path d="M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>', 'pypi': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-blocks-icon lucide-blocks"><path d="M10 22V7a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5a1 1 0 0 0-1-1H2"/><rect x="14" y="2" width="8" height="8" rx="1"/></svg>', 'menu': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-menu-icon lucide-menu"><path d="M4 5h16"/><path d="M4 12h16"/><path d="M4 19h16"/></svg>', 'x': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x-icon lucide-x"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>', 'github': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-github-icon lucide-github"><path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"/><path d="M9 18c-4.51 2-5-2-7-2"/></svg>', 'code': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-code-icon lucide-code"><path d="m16 18 6-6-6-6"/><path d="m8 6-6 6 6 6"/></svg>', 'info': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-info-icon lucide-info"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>', 'calendar': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-calendar1-icon lucide-calendar-1"><path d="M11 14h1v4"/><path d="M16 2v4"/><path d="M3 10h18"/><path d="M8 2v4"/><rect x="3" y="4" width="18" height="18" rx="2"/></svg>', 'circle-x': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-x-icon lucide-circle-x"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>', 'external-link': '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-external-link-icon lucide-external-link"><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></svg>'}
13
- COLORS = {'keyword': '#c792ea', 'string': '#c3e88d', 'builtin': '#82aaff', 'decorator': '#f78c6c', 'comment': '#546e7a', 'number': '#f78c6c', 'punctuation': '#89ddff', 'defname': '#82aaff', 'classname': '#ffcb6b', 'operator': '#89ddff', 'call': '#82aaff', 'fstring': '#c3e88d', 'type': '#ffcb6b'}
14
-
15
- def nb_path(
16
- mod_name,
17
- root='.'
18
- ):
19
- '''[TODO] '''
20
- cfg = read_config(root)
21
- for f in (Path(root) / cfg.nbs).glob('*.py'):
22
- if nb_name(f, root) == mod_name: return f.relative_to(root)
23
- return None
24
-
25
- def render_node(n, repo_url=None, root='.'):
26
- '''Builds a `node` for docs'''
27
- t = 'class' if 'class ' in n.src else 'async' if n.src.lstrip().startswith('async ') else 'func'
28
- signature = clean(n.src)
29
- node_id = f"code-{n.module}-{n.name}"
30
- nb = nb_path(n.module, root)
31
- tag_colors = {'func': '#10b981', 'async': '#f59e0b', 'class': '#8b5cf6'}
32
-
33
- code_lines = [Span(line, cls="code-line") for line in signature.split('\n')]
34
-
35
- def ghbtn(icon, label, url):
36
- if not url: return None
37
- return A(Button(Icon(icon, size=16), label, cls="gh-btn"), href=url, target="_blank", cls="gh-link")
38
-
39
- tag = Span(t, cls="tag", style=f"background:{tag_colors.get(t, '#666')};")
40
- mod_name = Span(Span(f"{n.module}.", cls="mod"), Span(n.name, cls="name"), cls="full-name") if n.module else Span(n.name, cls="full-name name")
41
-
42
- copy_btn = Button("📋", cls="copy-btn", onclick=f"navigator.clipboard.writeText(document.getElementById('{node_id}').textContent).then(() => this.textContent = '✓').then(() => setTimeout(() => this.textContent = '📋', 1500))")
43
- source_btn = ghbtn('github', 'Source', f"{repo_url}/blob/master/{nb}#L{n.lineno}" if repo_url and nb and n.lineno else None)
44
- edit_btn = ghbtn('code', 'Edit', f"{repo_url}/edit/master/{nb}" if repo_url and nb else None)
45
- blame_btn = ghbtn('info', 'Blame', f"{repo_url}/blame/master/{nb}#L{n.lineno}" if repo_url and nb and n.lineno else None)
46
- history_btn = ghbtn('calendar', 'History', f"{repo_url}/commits/master/{nb}" if repo_url and nb else None)
47
- issue_btn = ghbtn('circle-x', 'Issue', f"{repo_url}/issues/new?title=Issue%20with%20{n.name}&body={repo_url}/blob/master/{nb}%23L{n.lineno}" if repo_url and nb and n.lineno else None)
48
-
49
- return Article(
50
- Style("""
51
- me { margin-bottom: 0.75rem; border-radius: 8px; overflow: hidden; background: #1e1e1e; max-width: 100%; }
52
- me .header { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 1rem; }
53
- me .header-left { display: flex; align-items: center; }
54
- me .header-right { display: flex; align-items: center; gap: 0.5rem; }
55
- me .tag { padding: 0.25rem 0.6rem; border-radius: 4px; font-size: 0.75rem; font-weight: 600; color: white; }
56
- me .full-name { font-weight: 500; font-size: 1rem; margin-left: 0.75rem; }
57
- me .mod { color: #666; }
58
- me .name { color: #e5e5e5; }
59
- me .doc { margin: 0; padding: 0 1rem 0.5rem 1rem; color: #888; font-size: 0.85rem; }
60
- me .gh-btn { display: flex; align-items: center; gap: 0.25rem; background: #333; border: 1px solid #444; color: #ccc; padding: 0.25rem 0.5rem; border-radius: 4px; cursor: pointer; font-size: 0.75rem; }
61
- me .gh-link { text-decoration: none; }
62
- me .copy-btn { background: transparent; border: none; cursor: pointer; font-size: 0.9rem; padding: 0.25rem; }
63
- me pre { background: #1a1a1a; border-top: 1px solid #2a2a2a; margin: 0; padding: 0.5rem 0; }
64
- me code { counter-reset: line; font-size: 0.8rem; line-height: 1.6; color: #ccc; }
65
- me .code-line { display: block; padding-left: 3.5em; white-space: pre-wrap; word-break: break-all; position: relative; }
66
- me .code-line::before { content: counter(line); counter-increment: line; position: absolute; left: 0; width: 2.5em; text-align: right; color: #555; user-select: none; }
67
- """),
68
- Div(Div(tag, mod_name, cls="header-left"),
69
- Div(copy_btn, source_btn, edit_btn, blame_btn, history_btn, issue_btn, cls="header-right"),
70
- cls="header"),
71
- P(n.doc, cls="doc") if n.doc else None,
72
- Pre(Code(*code_lines, cls="language-python", id=node_id)))
73
-
74
- def render_module_page(mod_name, mod_nodes, all_mod_names, meta, root='.'):
75
- '''Builds a Module Page'''
76
- repo_url = meta.get('urls', {}).get('Repository')
77
- exp_nodes = [n for n in mod_nodes if n.kind == Kind.EXP]
78
-
79
- head_elements = [
80
- Script(type="module", src="https://cdn.jsdelivr.net/gh/starfederation/datastar@1.0.0-RC.8/bundles/datastar.js"),
81
- Script(src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js"),
82
- Script(src="js/highlight.js", type="module"),
83
- Style("body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; } code { font-family: 'SF Mono', Consolas, monospace; }"),
84
- Title(f"{mod_name} - {meta['name']}")]
85
-
86
- nav_links = [Li(A("← Index", href="index.html", cls="back-link"))] + [
87
- Li(A(m, href=f"{m}.html", cls=f"nav-link {'active' if m == mod_name else ''}")) for m in all_mod_names]
88
-
89
- nav = Nav(
90
- Style("""
91
- me { padding: 1rem; background: #1a1a1a; min-width: 180px; }
92
- me h3 { margin: 0 0 1rem 0; color: #fff; }
93
- me ul { list-style: none; padding: 0; margin: 0; }
94
- me .back-link { color: #888; text-decoration: none; font-size: 0.85rem; }
95
- me .back-link:hover { color: #fff; }
96
- me .nav-link { color: #aaa; text-decoration: none; }
97
- me .nav-link:hover { color: #fff; }
98
- me .nav-link.active { color: #fff; }
99
- me input { width: 100%; padding: 0.5rem; border: 1px solid #333; border-radius: 4px; background: #252525; color: #fff; margin-bottom: 1rem; box-sizing: border-box; }
100
- """),
101
- H3(meta['name']),
102
- Input(type="text", placeholder="Search...", **{"data-bind": "search"}),
103
- Ul(*nav_links))
104
-
105
- header = Header(
106
- Style("""
107
- me { padding: 1rem; background: #1e1e1e; border-bottom: 1px solid #333; }
108
- me .header-row { display: flex; align-items: center; justify-content: space-between; }
109
- me h1 { margin: 0; font-size: 1.5rem; color: #fff; }
110
- me .wasm-btn { display: flex; align-items: center; gap: 0.25rem; background: #333; border: 1px solid #444; color: #ccc; padding: 0.5rem 0.75rem; border-radius: 4px; cursor: pointer; font-size: 0.85rem; }
111
- me .wasm-link { text-decoration: none; }
112
- """),
113
- Div(H1(mod_name),
114
- A(Button(Icon('external-link', size=16), "Run in Browser", cls="wasm-btn"),
115
- href=f"wasm/{mod_name}/index.html", target="_blank", cls="wasm-link"),
116
- cls="header-row"))
117
-
118
- content = Div(
119
- Style("""
120
- me { padding: 1rem; background: #121212; overflow-y: auto; flex: 1; }
121
- """),
122
- *[render_node(n, repo_url, root) for n in exp_nodes])
123
-
124
- body = Body(nav,
125
- Div(header, content, style="flex: 1; display: flex; flex-direction: column;"),
126
- style="display: flex; height: 100vh; margin: 0; background: #121212;",
127
- **{"data-signals": "{search: ''}"})
128
-
129
- return Html(Head(*head_elements), body)
130
-
131
- def build_docs(
132
- root='.' # the project root (this should never really change)
133
- ):
134
- '''Builds the static documentation website'''
135
- cfg = read_config(root)
136
- meta = read_meta(root)
137
- _, mods = scan(root)
138
- mod_names = [name for name, _ in mods]
139
- docs_path = Path(root) / cfg.docs
140
- docs_path.mkdir(exist_ok=True)
141
- (docs_path / "index.html").write_text(to_xml(render_index_page(meta, mods)))
142
- for mod_name, mod_nodes in mods:
143
- (docs_path / f"{mod_name}.html").write_text(to_xml(render_module_page(mod_name, mod_nodes, mod_names, meta, root)))
144
- export_wasm(root)
145
- return f"Generated index + {len(mods)} module pages in {docs_path}"
146
-
147
- def export_wasm(
148
- root='.' # Project Root
149
- ):
150
- """Uses the bundeled notebook to make a WASM marimo notebook"""
151
- cfg = read_config(root)
152
- wasm_dir = Path(root) / cfg.docs / 'wasm'
153
- wasm_dir.mkdir(parents=True, exist_ok=True)
154
- bundled = Path(root) / cfg.nbs / '_bundled.py'
155
- bundle_notebook(root, name=str(bundled))
156
- os.system(f"marimo export html-wasm {bundled} -o {wasm_dir} --mode edit")
157
- bundled.unlink()
158
-
159
- def write_nojekyll(root='.'):
160
- cfg = read_config(root)
161
- Path(root, cfg.docs, '.nojekyll').touch()
162
-
163
- def html_preview(width='100%', height='300px'):
164
- "Display FT components in an IFrame"
165
- def _preview(*components): show(Iframe(srcdoc=to_xml(components[0] if len(components) == 1 else Div(*components)), width=width, height=height))
166
- return _preview
167
-
168
- def render_index_page(meta, mods, repo_url=None):
169
- mod_names = [name for name, _ in mods]
170
- head_elements = [
171
- Script(type="module", src="https://cdn.jsdelivr.net/gh/starfederation/datastar@1.0.0-RC.7/bundles/datastar.js"),
172
- Script(src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js"),
173
- Script(src="js/highlight.js", type="module"),
174
- Style("body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; } code { font-family: 'SF Mono', Consolas, monospace; }"),
175
- Title(meta['name'])]
176
-
177
- nav_links = [Li(A(m, href=f"{m}.html", cls="nav-link")) for m in mod_names]
178
-
179
- nav = Nav(
180
- Style("""
181
- me { padding: 1rem; background: #1a1a1a; min-width: 180px; }
182
- me h3 { margin: 0 0 1rem 0; color: #fff; }
183
- me ul { list-style: none; padding: 0; margin: 0; }
184
- me .nav-link { color: #aaa; text-decoration: none; }
185
- me .nav-link:hover { color: #fff; }
186
- """),
187
- H3(meta['name']),
188
- Ul(*nav_links))
189
-
190
- module_cards = [A(
191
- Div(H3(name, cls="card-title"),
192
- P(f"{len([n for n in nodes if n.kind == Kind.EXP])} exports", cls="card-count"),
193
- cls="card"),
194
- href=f"{name}.html", cls="card-link")
195
- for name, nodes in mods]
196
-
197
- content = Div(
198
- Style("""
199
- me { padding: 2rem; flex: 1; }
200
- me h1 { margin: 0 0 0.5rem 0; color: #fff; }
201
- me .desc { color: #888; margin: 0 0 2rem 0; }
202
- me .version { color: #666; margin: 0 0 2rem 0; font-size: 0.9rem; }
203
- me h2 { color: #fff; margin: 0 0 1rem 0; font-size: 1.2rem; }
204
- me .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 1rem; }
205
- me .card-link { text-decoration: none; }
206
- me .card { padding: 1rem; background: #1e1e1e; border-radius: 8px; }
207
- me .card:hover { background: #252525; }
208
- me .card-title { margin: 0 0 0.5rem 0; color: #fff; }
209
- me .card-count { margin: 0; color: #888; }
210
- """),
211
- H1(meta['name']),
212
- P(meta['desc'], cls="desc"),
213
- P(f"Version {meta['version']}", cls="version"),
214
- H2("Modules"),
215
- Div(*module_cards, cls="grid"))
216
-
217
- body = Body(nav, content, style="display: flex; min-height: 100vh; margin: 0; background: #121212;")
218
- return Html(Head(*head_elements), body)
219
-
220
- def Icon(name: str, # name of the icon MUST be in icon_dict
221
- size=24, # value to be passed to height and width of the icon
222
- stroke=1.5, # stroke width
223
- cls=None, # css class
224
- icon_dict:dict=icons, # Dict of icons {"name":"<svg...>"}
225
- **kwargs # passed to through to FT
226
- ) -> 'Any': # Follow recomendation from fastHTML docs
227
- '''
228
- Creates a custom html compliant <icon-{name}>...
229
- Intended to be used with a Global Dict of icons {"home": "<svg...", "info": "<svg..."}
230
- Icon('home') -> <icon-home> .... </icon-home>
231
- '''
232
- if name not in icon_dict: raise ValueError(f"Icon '{name}' not found")
233
-
234
- # count=1 Replace only the first occurrence of width & height 99% of time this is what you want
235
- svg_string = icon_dict[name]
236
- svg_string = re.sub(r'width="\d+"', f'width="{size}"', svg_string, count=1)
237
- svg_string = re.sub(r'height="\d+"', f'height="{size}"', svg_string, count=1)
238
- svg_string = re.sub(r'stroke-width="\d+"', f'stroke-width="{stroke}"', svg_string)
239
-
240
- return ft(f'icon-{name}', NotStr(svg_string), cls=cls, **kwargs)
241
-
242
- def write_highlighter(root='.'):
243
- "Write Python syntax highlighter JS to docs folder."
244
- cfg = read_config(root)
245
- js_dir = Path(root) / cfg.docs / 'js'
246
- js_dir.mkdir(parents=True, exist_ok=True)
247
-
248
- tokens = [
249
- ('py-decorator', r'@[\w.]+'),
250
- ('py-defname', r'(?<=def )\w+'),
251
- ('py-classname', r'(?<=class )\w+'),
252
- ('py-keyword', r'\b(?:def|class|return|if|elif|else|for|while|import|from|as|with|try|except|finally|raise|yield|async|await|pass|break|continue|in|is|not|and|or|lambda|None|True|False|self)\b'),
253
- ('py-builtin', r'\b(?:print|len|range|list|dict|set|tuple|int|str|float|bool|isinstance|hasattr|getattr|setattr|enumerate|zip|map|filter|any|all|sorted|reversed|super|type|open|next)\b'),
254
- ('py-call', r'\b\w+(?=\()'),
255
- ('py-number', r'\b\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?\b'),
256
- ('py-operator', r'->|==|!=|<=|>=|\*\*|\/\/|[+\-*/%=<>&|^~]'),
257
- ('py-punctuation', r'[{}\(\)\[\]:,;]'),
258
- ('py-fstring', r"f(?='|\")"),
259
- ('py-type', r'(?<=: )\w+'),
260
- ('py-string', r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'|"[^"\n]*"|\'[^\'\n]*\''),
261
- ('py-comment', r'#.*'),
262
- ]
263
-
264
-
265
- token_js = ',\n '.join(f"['{name}', /{pattern}/g]" for name, pattern in tokens)
266
- color_css = '\n'.join(f'::highlight({name}) {{ color: {COLORS[name.replace("py-", "")]}; }}' for name, _ in tokens)
267
-
268
- js = f"""const PY_TOKENS = [
269
- {token_js}
270
- ];
271
-
272
- function highlightAll(root = document) {{
273
- if (!CSS?.highlights) return;
274
- for (const [name] of PY_TOKENS) CSS.highlights.delete(name);
275
- root.querySelectorAll('pre code').forEach(code => {{
276
- const textNodes = [];
277
- code.querySelectorAll('.code-line').forEach(line => {{
278
- if (line.firstChild?.nodeType === Node.TEXT_NODE) textNodes.push(line.firstChild);
279
- }});
280
- if (!textNodes.length) return;
281
-
282
- for (const [name, pattern] of PY_TOKENS) {{
283
- const highlight = CSS.highlights.get(name) ?? new Highlight();
284
- for (const node of textNodes) {{
285
- const src = node.textContent;
286
- const re = new RegExp(pattern.source, pattern.flags);
287
- for (const match of src.matchAll(re)) {{
288
- const range = new Range();
289
- range.setStart(node, match.index);
290
- range.setEnd(node, match.index + match[0].length);
291
- highlight.add(range);
292
- }}
293
- }}
294
- if (highlight.size > 0) CSS.highlights.set(name, highlight);
295
- }}
296
- }});
297
- }}
298
-
299
- // Inject highlight styles
300
- const style = document.createElement('style');
301
- style.textContent = `{color_css}`;
302
- document.head.appendChild(style);
303
-
304
- if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => highlightAll());
305
- else highlightAll();
306
- """
307
-
308
-
309
- (js_dir / 'highlight.js').write_text(js)
310
- return f"Wrote {js_dir}/highlight.js"
File without changes