barnacles 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.
barnacles/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Barnacles: a static gallery for marimo notebooks."""
2
+
3
+ __version__ = "0.1.0"
barnacles/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
barnacles/build.py ADDED
@@ -0,0 +1,66 @@
1
+ """Build the static site: export every notebook with marimo and render the gallery shell around them.
2
+
3
+ <dist>/
4
+ index.html, app.js, styles.css the gallery shell, with the tree and site settings filled in
5
+ logo.*, favicon.* from site.logo / site.favicon
6
+ notebooks/<path>/ one marimo export per notebook (shown in the shell's iframe)
7
+ thumbnails/<path>[-dark].png card images
8
+
9
+ All links are relative, so the output works at a domain root or under any subpath.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import html
15
+ import json
16
+ import shutil
17
+ from typing import Callable
18
+
19
+ from . import marimo_export, thumbnails
20
+ from .config import WEB, Config
21
+ from .discovery import discover, walk
22
+
23
+
24
+ def _public(node: dict) -> dict:
25
+ """The tree as the page sees it (no local paths)."""
26
+ hidden = {"source", "thumbnails"}
27
+ return {k: [_public(c) for c in v] if k == "children" else v for k, v in node.items() if k not in hidden}
28
+
29
+
30
+ def build(cfg: Config, screenshots: bool = True, log: Callable[[str], None] = print) -> dict:
31
+ """Build the site into cfg.dist and return the gallery tree."""
32
+ tree = discover(cfg) # validate everything before touching dist
33
+ notebooks = list(walk(tree))
34
+
35
+ shutil.rmtree(cfg.dist, ignore_errors=True)
36
+ cfg.dist.mkdir(parents=True)
37
+ for name in ("app.js", "styles.css"):
38
+ shutil.copy(WEB / name, cfg.dist / name)
39
+ assets = {}
40
+ for key, src in (("logo", cfg.logo), ("favicon", cfg.favicon)):
41
+ assets[key] = f"{key}{src.suffix}"
42
+ shutil.copy(src, cfg.dist / assets[key])
43
+
44
+ log(f"Exporting {len(notebooks)} notebook(s):")
45
+ for nb in notebooks:
46
+ dest = cfg.dist / "notebooks" / nb["path"]
47
+ dest.mkdir(parents=True, exist_ok=True)
48
+ log(f" {nb['mode']:<9} {nb['source'].relative_to(cfg.root)} -> {dest.relative_to(cfg.root)}")
49
+ if nb["mode"] == "html":
50
+ marimo_export.static(nb["source"], dest / "index.html")
51
+ else:
52
+ marimo_export.wasm(nb["source"], dest)
53
+ thumbnails.add(notebooks, cfg.dist, screenshots=screenshots, log=log)
54
+
55
+ page = (WEB / "index.html").read_text()
56
+ for placeholder, value in {
57
+ "__TITLE__": html.escape(cfg.title),
58
+ "__HEADER_TITLE__": html.escape(cfg.header_title),
59
+ "__LOGO__": assets["logo"],
60
+ "__FAVICON__": assets["favicon"],
61
+ "__NOTEBOOKS__": json.dumps(_public(tree), indent=2).replace("</", "<\\/"), # safe inside <script>
62
+ }.items():
63
+ page = page.replace(placeholder, value)
64
+ (cfg.dist / "index.html").write_text(page)
65
+ log(f"Wrote {cfg.dist.relative_to(cfg.root) if cfg.dist.is_relative_to(cfg.root) else cfg.dist}/index.html")
66
+ return tree
barnacles/cli.py ADDED
@@ -0,0 +1,113 @@
1
+ """The `barnacles` command line.
2
+
3
+ barnacles init [DIR] start a project: barnacles.yaml + an example notebook
4
+ barnacles build [PROJECT] export every notebook and render the gallery
5
+ barnacles serve [PROJECT] build, then serve the gallery locally
6
+ barnacles edit [PROJECT | NOTEBOOK] open notebooks in the marimo editor
7
+
8
+ PROJECT is a folder holding barnacles.yaml (default: the current folder) or the file itself.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import shutil
15
+ import sys
16
+ from functools import partial
17
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
18
+ from pathlib import Path
19
+
20
+ from . import __version__, config
21
+ from .build import build
22
+ from .marimo_export import marimo
23
+
24
+ SCAFFOLD = Path(__file__).parent / "scaffold"
25
+
26
+
27
+ def cmd_init(args: argparse.Namespace) -> None:
28
+ target = Path(args.dir)
29
+ files = {} # scaffold file -> destination ("gitignore" is shipped without its dot)
30
+ for src in sorted(p for p in SCAFFOLD.rglob("*") if p.is_file() and "__pycache__" not in p.parts):
31
+ rel = src.relative_to(SCAFFOLD)
32
+ files[src] = target / (rel.with_name(".gitignore") if rel.name == "gitignore" else rel)
33
+ if clash := [str(d) for d in files.values() if d.exists()]:
34
+ raise config.ConfigError(f"not overwriting existing file(s): {', '.join(clash)}")
35
+ for src, dest in files.items():
36
+ dest.parent.mkdir(parents=True, exist_ok=True)
37
+ shutil.copy(src, dest)
38
+ print(f" created {dest}")
39
+ where = "" if target.resolve() == Path.cwd() else f" {args.dir}"
40
+ print(f"\nNext: barnacles serve{where}")
41
+
42
+
43
+ def cmd_build(args: argparse.Namespace) -> None:
44
+ build(config.load(args.project), screenshots=not args.no_thumbnails)
45
+
46
+
47
+ def cmd_serve(args: argparse.Namespace) -> None:
48
+ cfg = config.load(args.project)
49
+ if not args.no_build:
50
+ build(cfg, screenshots=not args.no_thumbnails)
51
+ if not (cfg.dist / "index.html").is_file():
52
+ raise config.ConfigError(f"nothing to serve in {cfg.dist}; run `barnacles build` first")
53
+
54
+ class Handler(SimpleHTTPRequestHandler):
55
+ def log_message(self, *a) -> None:
56
+ pass
57
+
58
+ server = ThreadingHTTPServer((args.host, args.port), partial(Handler, directory=str(cfg.dist)))
59
+ print(f"Serving {cfg.dist} at http://{args.host}:{server.server_port}/ (Ctrl+C to stop)")
60
+ try:
61
+ server.serve_forever()
62
+ except KeyboardInterrupt:
63
+ pass
64
+
65
+
66
+ def cmd_edit(args: argparse.Namespace) -> None:
67
+ target = Path(args.target)
68
+ if target.suffix != ".py": # a project: open its notebooks folder in marimo's file browser
69
+ target = config.load(target).notebooks
70
+ marimo("edit", str(target))
71
+
72
+
73
+ def parser() -> argparse.ArgumentParser:
74
+ p = argparse.ArgumentParser(prog="barnacles", description="A static gallery for marimo notebooks.")
75
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
76
+ sub = p.add_subparsers(dest="command", required=True, metavar="COMMAND")
77
+ project = {"nargs": "?", "default": ".", "help": "folder with barnacles.yaml, or the file (default: .)"}
78
+
79
+ s = sub.add_parser("init", help="create barnacles.yaml and an example notebook")
80
+ s.add_argument("dir", nargs="?", default=".", help="where to create the project (default: .)")
81
+ s.set_defaults(func=cmd_init)
82
+
83
+ s = sub.add_parser("build", help="export every notebook and render the gallery")
84
+ s.add_argument("project", **project)
85
+ s.add_argument("--no-thumbnails", action="store_true", help="skip notebook screenshots (faster)")
86
+ s.set_defaults(func=cmd_build)
87
+
88
+ s = sub.add_parser("serve", help="build, then serve the gallery locally")
89
+ s.add_argument("project", **project)
90
+ s.add_argument("--port", type=int, default=8000)
91
+ s.add_argument("--host", default="127.0.0.1")
92
+ s.add_argument("--no-build", action="store_true", help="serve the existing build")
93
+ s.add_argument("--no-thumbnails", action="store_true", help="skip notebook screenshots (faster)")
94
+ s.set_defaults(func=cmd_serve)
95
+
96
+ s = sub.add_parser("edit", help="open notebooks in the marimo editor")
97
+ s.add_argument("target", nargs="?", default=".", help="a project (opens its notebooks folder) or a notebook .py")
98
+ s.set_defaults(func=cmd_edit)
99
+ return p
100
+
101
+
102
+ def main(argv: list[str] | None = None) -> int:
103
+ args = parser().parse_args(argv)
104
+ try:
105
+ args.func(args)
106
+ except (config.ConfigError, RuntimeError) as e:
107
+ print(f"error: {e}", file=sys.stderr)
108
+ return 1
109
+ return 0
110
+
111
+
112
+ if __name__ == "__main__":
113
+ sys.exit(main())
barnacles/config.py ADDED
@@ -0,0 +1,109 @@
1
+ """barnacles.yaml: load, validate and fill in defaults.
2
+
3
+ Every path in the file (including the keys under `items`) is relative to the file itself.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+
11
+ import yaml
12
+
13
+ FILENAME = "barnacles.yaml"
14
+ WEB = Path(__file__).parent / "web"
15
+
16
+ SECTIONS = {"site", "paths", "defaults", "items"}
17
+ KEYS = {
18
+ "site": {"title", "header_title", "logo", "favicon"},
19
+ "paths": {"notebooks", "dist"},
20
+ "notebook": {"title", "description", "mode", "slug", "thumbnail", "thumbnail_dark"},
21
+ "folder": {"title", "description"},
22
+ }
23
+ MODES = ("html-wasm", "html")
24
+
25
+
26
+ class ConfigError(Exception):
27
+ """A problem in barnacles.yaml or the project it describes."""
28
+
29
+
30
+ @dataclass
31
+ class Config:
32
+ root: Path # the folder holding barnacles.yaml
33
+ title: str
34
+ header_title: str
35
+ logo: Path
36
+ favicon: Path
37
+ notebooks: Path
38
+ dist: Path
39
+ defaults: dict[str, dict] = field(default_factory=dict)
40
+ items: dict[str, dict] = field(default_factory=dict)
41
+
42
+ def settings(self, path: Path, kind: str) -> dict:
43
+ """defaults.<kind> overridden by the item keyed by this path."""
44
+ key = path.relative_to(self.root).as_posix()
45
+ item = self.items.get(key, {})
46
+ _check_keys(f"items.{key}", item, kind)
47
+ return {**self.defaults.get(kind, {}), **item}
48
+
49
+
50
+ def _check_keys(where: str, given: object, kind: str) -> None:
51
+ if not isinstance(given, dict):
52
+ raise ConfigError(f"{FILENAME}: {where} must be a mapping")
53
+ if bad := set(given) - KEYS[kind]:
54
+ raise ConfigError(f"{FILENAME}: {where}: unknown key(s) {sorted(bad)}; allowed: {sorted(KEYS[kind])}")
55
+
56
+
57
+ def find(project: Path) -> Path:
58
+ """The barnacles.yaml for `project`, which is either that file or the folder holding it."""
59
+ path = project if project.suffix in (".yaml", ".yml") else project / FILENAME
60
+ if not path.is_file():
61
+ raise ConfigError(f"no {FILENAME} in {project.resolve()}; create one with `barnacles init`")
62
+ return path
63
+
64
+
65
+ def load(project: Path | str = ".") -> Config:
66
+ path = find(Path(project)).resolve()
67
+ root = path.parent
68
+ try:
69
+ raw = yaml.safe_load(path.read_text()) or {}
70
+ except yaml.YAMLError as e:
71
+ raise ConfigError(f"{FILENAME}: invalid YAML: {e}") from None
72
+ if not isinstance(raw, dict):
73
+ raise ConfigError(f"{FILENAME}: expected a mapping at the top level")
74
+ if bad := set(raw) - SECTIONS:
75
+ raise ConfigError(f"{FILENAME}: unknown section(s) {sorted(bad)}; allowed: {sorted(SECTIONS)}")
76
+
77
+ site, paths, defaults = (raw.get(k) or {} for k in ("site", "paths", "defaults"))
78
+ _check_keys("site", site, "site")
79
+ _check_keys("paths", paths, "paths")
80
+ if bad := set(defaults) - {"notebook", "folder"}:
81
+ raise ConfigError(f"{FILENAME}: defaults: unknown key(s) {sorted(bad)}; allowed: ['folder', 'notebook']")
82
+ defaults = {kind: defaults.get(kind) or {} for kind in ("notebook", "folder")}
83
+ for kind, values in defaults.items():
84
+ _check_keys(f"defaults.{kind}", values, kind)
85
+
86
+ title = str(site.get("title") or "Notebooks")
87
+ logo = root / site["logo"] if site.get("logo") else WEB / "logo.svg"
88
+ favicon = root / site["favicon"] if site.get("favicon") else logo
89
+ for key, file in (("logo", logo), ("favicon", favicon)):
90
+ if not file.is_file():
91
+ raise ConfigError(f"{FILENAME}: site.{key} = {site.get(key)!r} not found")
92
+
93
+ cfg = Config(
94
+ root=root,
95
+ title=title,
96
+ header_title=str(site.get("header_title") or title),
97
+ logo=logo,
98
+ favicon=favicon,
99
+ notebooks=(root / (paths.get("notebooks") or "notebooks")).resolve(),
100
+ dist=(root / (paths.get("dist") or "dist")).resolve(),
101
+ defaults=defaults,
102
+ items={Path(k).as_posix(): v or {} for k, v in (raw.get("items") or {}).items()},
103
+ )
104
+ if not cfg.notebooks.is_dir():
105
+ raise ConfigError(f"{FILENAME}: paths.notebooks: {cfg.notebooks} is not a folder")
106
+ if cfg.dist == root or cfg.dist in root.parents or cfg.notebooks.is_relative_to(cfg.dist) \
107
+ or path.is_relative_to(cfg.dist):
108
+ raise ConfigError(f"{FILENAME}: paths.dist = {paths.get('dist')!r} would wipe your sources; pick a separate folder")
109
+ return cfg
barnacles/discovery.py ADDED
@@ -0,0 +1,112 @@
1
+ """Find the notebooks and folders under the notebooks folder and build the gallery tree.
2
+
3
+ Folders: {type, path, name, title, description, folders, notebooks, children}
4
+ Notebooks: {type, path, title, description, mode, source, thumbnails}
5
+ `path` is the URL path below the gallery root, e.g. "interactive/wasm-example".
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ from pathlib import Path
12
+ from typing import Iterator
13
+
14
+ from .config import FILENAME, MODES, Config, ConfigError
15
+
16
+
17
+ def app_title(source: Path) -> str | None:
18
+ """`marimo.App(app_title=...)` from a notebook, if set."""
19
+ for node in ast.walk(ast.parse(source.read_text())):
20
+ if isinstance(node, ast.Call) and getattr(node.func, "attr", None) == "App":
21
+ for kw in node.keywords:
22
+ if kw.arg == "app_title" and isinstance(kw.value, ast.Constant):
23
+ return kw.value.value
24
+ return None
25
+
26
+
27
+ def notebook(cfg: Config, source: Path) -> dict:
28
+ meta = cfg.settings(source, "notebook")
29
+ key = source.relative_to(cfg.root).as_posix()
30
+ mode = meta.get("mode") or MODES[0]
31
+ if mode not in MODES:
32
+ raise ConfigError(f"{FILENAME}: items.{key}: mode must be one of {list(MODES)}, got {mode!r}")
33
+ thumbnails = {}
34
+ for k in ("thumbnail", "thumbnail_dark"):
35
+ if meta.get(k):
36
+ thumbnails[k] = cfg.root / meta[k]
37
+ if not thumbnails[k].is_file():
38
+ raise ConfigError(f"{FILENAME}: items.{key}: {k} = {meta[k]!r} not found")
39
+
40
+ slug = meta.get("slug") or source.stem.replace("_", "-")
41
+ folder = source.parent.relative_to(cfg.notebooks).as_posix()
42
+ return {
43
+ "type": "notebook",
44
+ "path": slug if folder == "." else f"{folder}/{slug}",
45
+ "title": str(meta.get("title") or app_title(source) or slug),
46
+ "description": str(meta.get("description") or ""),
47
+ "mode": mode,
48
+ "source": source,
49
+ "thumbnails": thumbnails,
50
+ }
51
+
52
+
53
+ def folder(cfg: Config, path: Path) -> dict | None:
54
+ """The tree under `path`: folders first, then notebooks, each sorted by name.
55
+
56
+ Counts are recursive. Folders without notebooks (at any depth), or whose names start
57
+ with "." or "_" (like marimo's __marimo__), are left out; the root folder is always kept.
58
+ """
59
+ children, folders, notebooks = [], 0, 0
60
+ for sub in sorted(p for p in path.iterdir() if p.is_dir() and not p.name.startswith((".", "_"))):
61
+ if node := folder(cfg, sub):
62
+ children.append(node)
63
+ folders += 1 + node["folders"]
64
+ notebooks += node["notebooks"]
65
+ for source in sorted(path.glob("*.py")):
66
+ children.append(notebook(cfg, source))
67
+ notebooks += 1
68
+ is_root = path == cfg.notebooks
69
+ if not notebooks and not is_root:
70
+ return None
71
+
72
+ names = [c["path"].rsplit("/", 1)[-1] for c in children]
73
+ if dupes := sorted({n for n in names if names.count(n) > 1}):
74
+ raise ConfigError(f"{path.relative_to(cfg.root)}: folders and notebooks share a name: {dupes}")
75
+ meta = cfg.settings(path, "folder")
76
+ rel = path.relative_to(cfg.notebooks).as_posix()
77
+ return {
78
+ "type": "folder",
79
+ "path": "" if is_root else rel,
80
+ "name": path.name,
81
+ "title": str(meta.get("title") or ("Notebooks" if is_root else path.name)),
82
+ "description": str(meta.get("description") or ""),
83
+ "folders": folders,
84
+ "notebooks": notebooks,
85
+ "children": children,
86
+ }
87
+
88
+
89
+ def walk(node: dict) -> Iterator[dict]:
90
+ """Every notebook in the tree."""
91
+ for child in node["children"]:
92
+ yield from walk(child) if child["type"] == "folder" else [child]
93
+
94
+
95
+ def keys(node: dict, cfg: Config) -> Iterator[str]:
96
+ """The `items` keys that match something in the tree."""
97
+ if node["type"] == "notebook":
98
+ yield node["source"].relative_to(cfg.root).as_posix()
99
+ return
100
+ yield (cfg.notebooks / node["path"]).relative_to(cfg.root).as_posix()
101
+ for child in node["children"]:
102
+ yield from keys(child, cfg)
103
+
104
+
105
+ def discover(cfg: Config) -> dict:
106
+ """The gallery tree. Fails on `items` that match no notebook or non-empty folder."""
107
+ if not cfg.notebooks.is_relative_to(cfg.root):
108
+ raise ConfigError(f"{FILENAME}: paths.notebooks must be inside {cfg.root}")
109
+ tree = folder(cfg, cfg.notebooks)
110
+ if unmatched := sorted(set(cfg.items) - set(keys(tree, cfg))):
111
+ raise ConfigError(f"{FILENAME}: items match no notebook or non-empty folder: {unmatched}")
112
+ return tree
@@ -0,0 +1,39 @@
1
+ """Thin wrappers around `marimo export`, run with the same Python as barnacles."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ # Static (`html`) exports have no kernel, so marimo shows a "This notebook is not connected to a
10
+ # kernel" toast as soon as a UI element (e.g. mo.ui.table) reports its value. There is no export
11
+ # flag for it, so hide that one toast with a small script injected into <head>.
12
+ HIDE_KERNEL_TOAST = """<script>
13
+ new MutationObserver(() => {
14
+ for (const t of document.querySelectorAll("li[data-state]")) {
15
+ if (t.textContent.includes("not connected to a kernel")) t.style.display = "none";
16
+ }
17
+ }).observe(document.documentElement, { childList: true, subtree: true });
18
+ </script>
19
+ """
20
+
21
+
22
+ def marimo(*args: str, cwd: Path | None = None, quiet: bool = False) -> None:
23
+ cmd = [sys.executable, "-m", "marimo", *args]
24
+ result = subprocess.run(cmd, cwd=cwd, capture_output=quiet, text=True)
25
+ if result.returncode:
26
+ detail = f"\n{result.stderr.strip()}" if quiet and result.stderr else ""
27
+ raise RuntimeError(f"`marimo {' '.join(args)}` failed (exit {result.returncode}){detail}")
28
+
29
+
30
+ def static(source: Path, out: Path, quiet: bool = True) -> None:
31
+ """Run the notebook once and write its output as a single HTML page (no code, no kernel)."""
32
+ marimo("export", "html", str(source), "-o", str(out), "--no-include-code", "-f", cwd=source.parent, quiet=quiet)
33
+ out.write_text(out.read_text().replace("</head>", HIDE_KERNEL_TOAST + "</head>", 1))
34
+
35
+
36
+ def wasm(source: Path, dest: Path, quiet: bool = True) -> None:
37
+ """Export the notebook as a WASM app (Python runs in the browser via Pyodide) into `dest`."""
38
+ marimo("export", "html-wasm", str(source), "-o", str(dest), "--mode", "run", "-f", cwd=source.parent, quiet=quiet)
39
+ (dest / "CLAUDE.md").unlink(missing_ok=True) # AI-assistant prompt marimo bundles with WASM exports
@@ -0,0 +1,19 @@
1
+ # Barnacles settings. Every key is optional; paths are relative to this file.
2
+ site:
3
+ title: Notebooks # browser tab title
4
+ # header_title: My team # text next to the logo (defaults to title)
5
+ # logo: logo.svg # defaults to the barnacles logo
6
+ # favicon: favicon.svg # defaults to the logo
7
+
8
+ paths:
9
+ notebooks: notebooks
10
+ dist: dist
11
+
12
+ defaults:
13
+ notebook:
14
+ mode: html-wasm # or html: run once at build time
15
+
16
+ items: # per-path overrides; notebooks show up without an entry
17
+ "notebooks/example.py":
18
+ title: Example
19
+ description: Python running in your browser.
@@ -0,0 +1,2 @@
1
+ dist/
2
+ __marimo__/
@@ -0,0 +1,47 @@
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = ["marimo"]
4
+ # ///
5
+
6
+ import marimo
7
+
8
+ __generated_with = "0.26.0"
9
+ app = marimo.App(width="medium", app_title="Example")
10
+
11
+
12
+ @app.cell
13
+ def _():
14
+ import marimo as mo
15
+ return (mo,)
16
+
17
+
18
+ @app.cell
19
+ def _(mo):
20
+ mo.md("""
21
+ # Example
22
+
23
+ This page was exported with `marimo export html-wasm`. Python runs **in your browser**,
24
+ so the controls below are live.
25
+ """)
26
+ return
27
+
28
+
29
+ @app.cell
30
+ def _(mo):
31
+ n = mo.ui.slider(1, 20, value=8, label="Points")
32
+ amp = mo.ui.slider(1, 10, value=5, label="Amplitude")
33
+ mo.hstack([n, amp], justify="start")
34
+ return amp, n
35
+
36
+
37
+ @app.cell
38
+ def _(amp, mo, n):
39
+ import math
40
+
41
+ _rows = [{"x": i, "y": round(amp.value * math.sin(i / 2), 3)} for i in range(n.value)]
42
+ mo.ui.table(_rows, selection=None)
43
+ return
44
+
45
+
46
+ if __name__ == "__main__":
47
+ app.run()
@@ -0,0 +1,85 @@
1
+ """Card thumbnails: the images set in barnacles.yaml, or light + dark screenshots of each notebook.
2
+
3
+ Screenshots need the optional `thumbnails` extra (Playwright) and a headless Chromium:
4
+ pip install "barnacles[thumbnails]" && playwright install chromium
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import shutil
10
+ import tempfile
11
+ import threading
12
+ from functools import partial
13
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
14
+ from pathlib import Path
15
+ from typing import Callable
16
+
17
+ from . import marimo_export
18
+
19
+ SIZE = {"width": 640, "height": 360} # 16:9 like the gallery cards; small, so it shows the narrow layout
20
+ THEMES = {"light": "", "dark": "-dark"} # color scheme -> file suffix
21
+
22
+
23
+ class _QuietHandler(SimpleHTTPRequestHandler):
24
+ def log_message(self, *args) -> None:
25
+ pass
26
+
27
+
28
+ def _screenshot(pages: dict[str, Path], out: Path) -> None:
29
+ """Screenshot each page (notebook path -> rendered html) in light and dark mode into `out`.
30
+
31
+ Exported notebooks use marimo's "system" theme, so emulating prefers-color-scheme switches them.
32
+ """
33
+ from playwright.sync_api import sync_playwright
34
+
35
+ root = next(iter(pages.values())).parent
36
+ server = ThreadingHTTPServer(("127.0.0.1", 0), partial(_QuietHandler, directory=str(root)))
37
+ threading.Thread(target=server.serve_forever, daemon=True).start()
38
+ try:
39
+ with sync_playwright() as pw:
40
+ browser = pw.chromium.launch()
41
+ for scheme, suffix in THEMES.items():
42
+ page = browser.new_page(viewport=SIZE, color_scheme=scheme, reduced_motion="reduce")
43
+ for nb_path, html in pages.items():
44
+ page.goto(f"http://127.0.0.1:{server.server_port}/{html.name}", wait_until="load")
45
+ # hide marimo's chrome and watermark, like `marimo export thumbnail`
46
+ page.add_style_tag(content='.print\\:hidden,[data-testid="watermark"]{display:none !important;}')
47
+ page.wait_for_function("""() => [...document.querySelectorAll('div[id^="cell-"]')]
48
+ .some((c) => getComputedStyle(c).visibility !== "hidden")""", timeout=30_000)
49
+ page.wait_for_timeout(1500) # let fonts, tables and charts settle
50
+ target = out / f"{nb_path}{suffix}.png"
51
+ target.parent.mkdir(parents=True, exist_ok=True)
52
+ page.screenshot(path=target)
53
+ page.close()
54
+ finally:
55
+ server.shutdown()
56
+
57
+
58
+ def add(notebooks: list[dict], dist: Path, screenshots: bool, log: Callable[[str], None] = print) -> None:
59
+ """Set nb["thumbnail"] / nb["thumbnail_dark"] (paths relative to dist) on each notebook."""
60
+ out = dist / "thumbnails"
61
+ todo: dict[str, Path] = {}
62
+ with tempfile.TemporaryDirectory() as tmp:
63
+ for i, nb in enumerate(notebooks):
64
+ if nb["thumbnails"]: # configured images; a light-only one is used in both themes
65
+ for key, src in nb["thumbnails"].items():
66
+ dest = out / f"{nb['path']}{THEMES['dark'] if key == 'thumbnail_dark' else ''}{src.suffix}"
67
+ dest.parent.mkdir(parents=True, exist_ok=True)
68
+ shutil.copy(src, dest)
69
+ nb[key] = dest.relative_to(dist).as_posix()
70
+ elif screenshots:
71
+ todo[nb["path"]] = Path(tmp) / f"{i}.html"
72
+ marimo_export.static(nb["source"], todo[nb["path"]])
73
+ if not todo:
74
+ return
75
+ log(f"Screenshotting {len(todo)} notebook(s) in light + dark mode")
76
+ try:
77
+ _screenshot(todo, out)
78
+ except Exception as e: # no Playwright / Chromium: cards fall back to a letter placeholder
79
+ first = (str(e).strip().splitlines() or [type(e).__name__])[0]
80
+ log(f" warning: no thumbnails ({first}); "
81
+ 'install with `pip install "barnacles[thumbnails]" && playwright install chromium`')
82
+ for nb in notebooks:
83
+ for key, suffix in (("thumbnail", ""), ("thumbnail_dark", THEMES["dark"])):
84
+ if nb["path"] in todo and (out / f"{nb['path']}{suffix}.png").exists():
85
+ nb[key] = f"thumbnails/{nb['path']}{suffix}.png"
barnacles/web/app.js ADDED
@@ -0,0 +1,138 @@
1
+ // The tree: folders {type, path, name, title, description, folders, notebooks, children} and
2
+ // notebooks {type, path, title, description, mode, thumbnail?, thumbnail_dark?}.
3
+ // Routes: #/ (root), #/<folder path>/ (a folder), #/<folder path>/<slug> (a notebook).
4
+ const tree = JSON.parse(document.getElementById("notebooks").textContent);
5
+ const siteTitle = document.title;
6
+ const $ = (s) => document.querySelector(s);
7
+ const el = (tag, props = {}, ...kids) => {
8
+ const e = Object.assign(document.createElement(tag), props);
9
+ e.append(...kids.filter(Boolean));
10
+ return e;
11
+ };
12
+ const icon = (name) => {
13
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
14
+ svg.setAttribute("class", "icon");
15
+ svg.setAttribute("aria-hidden", "true");
16
+ const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
17
+ use.setAttribute("href", `#i-${name}`);
18
+ svg.append(use);
19
+ return svg;
20
+ };
21
+ const encode = (path) => path.split("/").map(encodeURIComponent).join("/");
22
+ const href = (node) => node.type === "folder" ? (node.path ? `#/${encode(node.path)}/` : "#/") : `#/${encode(node.path)}`;
23
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
24
+ const nameOf = (node) => node.title;
25
+
26
+ // index every node by path (folders keep a trailing "/") and remember its parents
27
+ const nodes = new Map(), parents = new Map();
28
+ (function index(folder, trail) {
29
+ nodes.set(folder.path ? folder.path + "/" : "", folder);
30
+ parents.set(folder, trail);
31
+ for (const child of folder.children) {
32
+ if (child.type === "folder") index(child, [...trail, folder]);
33
+ else { nodes.set(child.path, child); parents.set(child, [...trail, folder]); }
34
+ }
35
+ })(tree, []);
36
+
37
+ // ---- burger menu: Home + collapsible folder tree ----
38
+ const menu = $("#menu");
39
+ function menuItems(folder) {
40
+ return folder.children.map((child) => {
41
+ if (child.type === "notebook") {
42
+ return el("a", { href: href(child), className: "nb" }, icon("notebook"), el("span", { textContent: child.title }));
43
+ }
44
+ const link = el("a", { href: href(child) }, icon("folder"), el("span", { textContent: child.title }),
45
+ el("span", { className: "count", textContent: child.notebooks }));
46
+ // clicking the name opens the folder page (and expands it) instead of toggling
47
+ link.addEventListener("click", (e) => { e.preventDefault(); location.hash = link.getAttribute("href"); });
48
+ const chevron = el("span", { className: "chevron" }, icon("chevron"));
49
+ const details = el("details", {}, el("summary", {}, chevron, link),
50
+ el("div", { className: "children" }, ...menuItems(child)));
51
+ details.dataset.path = child.path;
52
+ return details;
53
+ });
54
+ }
55
+ menu.append(el("a", { href: "#/" }, icon("home"), el("span", { textContent: "Home" })), el("hr"), ...menuItems(tree));
56
+
57
+ // ---- gallery: one card per folder / notebook ----
58
+ function card(node) {
59
+ if (node.type === "folder") {
60
+ return el("a", { className: "card folder", href: href(node) },
61
+ el("div", { className: "thumb" }, icon("folder")),
62
+ el("div", { className: "body" },
63
+ el("h3", { textContent: node.title }),
64
+ node.description && el("p", { textContent: node.description }),
65
+ stats(node),
66
+ el("span", { className: "badge", textContent: "folder" })));
67
+ }
68
+ const thumb = node.thumbnail
69
+ ? el("div", { className: "thumb" }, el("picture", {},
70
+ node.thumbnail_dark && el("source", { srcset: node.thumbnail_dark, media: "(prefers-color-scheme: dark)" }),
71
+ el("img", { src: node.thumbnail, alt: "", loading: "lazy" })))
72
+ : el("div", { className: "thumb", textContent: node.title.charAt(0) });
73
+ return el("a", { className: "card", href: href(node) }, thumb,
74
+ el("div", { className: "body" },
75
+ el("h3", { textContent: node.title }),
76
+ node.description && el("p", { textContent: node.description }),
77
+ el("span", { className: "badge", textContent: node.mode })));
78
+ }
79
+ function stats(folder) {
80
+ const item = (name, n, word) => el("span", {}, icon(name), el("b", { textContent: n }), ` ${word}${n === 1 ? "" : "s"}`);
81
+ return el("div", { className: "stats" },
82
+ folder.folders > 0 && item("folder", folder.folders, "folder"),
83
+ item("notebook", folder.notebooks, "notebook"));
84
+ }
85
+ function showFolder(folder) {
86
+ $("h1").replaceChildren(folder.path ? icon("folder") : "", nameOf(folder));
87
+ const counts = folder.notebooks
88
+ ? [folder.folders && plural(folder.folders, "folder"), plural(folder.notebooks, "notebook")].filter(Boolean).join(" · ")
89
+ : "No notebooks yet. Add a marimo .py file to the notebooks folder.";
90
+ $(".lead").replaceChildren([folder.description, counts].filter(Boolean).join(" — "));
91
+ $(".grid").replaceChildren(...folder.children.map(card));
92
+ $("#gallery").scrollTop = 0;
93
+ }
94
+
95
+ // ---- drawer ----
96
+ const burger = $(".burger");
97
+ const setOpen = (open) => {
98
+ document.body.classList.toggle("open", open);
99
+ burger.setAttribute("aria-expanded", open);
100
+ };
101
+ burger.addEventListener("click", () => setOpen(!document.body.classList.contains("open")));
102
+ $(".backdrop").addEventListener("click", () => setOpen(false));
103
+ document.addEventListener("keydown", (e) => e.key === "Escape" && setOpen(false));
104
+
105
+ // ---- routing ----
106
+ const frame = $("iframe");
107
+ function route() {
108
+ const raw = location.hash.replace(/^#\/?/, "");
109
+ const key = raw.split("/").map(decodeURIComponent).join("/");
110
+ const node = nodes.get(key) ?? nodes.get(key + "/") ?? tree;
111
+ const isNotebook = node.type === "notebook";
112
+ const src = isNotebook ? `notebooks/${encode(node.path)}/` : null;
113
+
114
+ $("#gallery").hidden = isNotebook;
115
+ frame.hidden = !isNotebook;
116
+ if (isNotebook && frame.getAttribute("src") !== src) frame.src = src;
117
+ if (!isNotebook) { frame.removeAttribute("src"); showFolder(node); } // stop a running notebook
118
+
119
+ // breadcrumbs: every folder below the root, then the current page
120
+ const trail = [...parents.get(node), node].filter((n) => n !== tree);
121
+ $(".crumbs").replaceChildren(...trail.map((n, i) => el("li", {},
122
+ i === trail.length - 1 ? el("span", { textContent: nameOf(n) }) : el("a", { href: href(n), textContent: nameOf(n) }))));
123
+ $(".newtab").hidden = !isNotebook;
124
+ if (isNotebook) $(".newtab").href = src;
125
+ document.title = trail.length ? `${nameOf(node)} · ${siteTitle}` : siteTitle;
126
+
127
+ // menu: highlight the current page and expand the folders leading to it
128
+ const current = href(node);
129
+ for (const a of menu.querySelectorAll("a")) {
130
+ if (a.getAttribute("href") === current) a.setAttribute("aria-current", "page");
131
+ else a.removeAttribute("aria-current");
132
+ }
133
+ const open = new Set(trail.filter((n) => n.type === "folder").map((n) => n.path));
134
+ for (const d of menu.querySelectorAll("details")) if (open.has(d.dataset.path)) d.open = true;
135
+ setOpen(false);
136
+ }
137
+ addEventListener("hashchange", route);
138
+ route();
@@ -0,0 +1,63 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>__TITLE__</title>
7
+ <link rel="icon" href="__FAVICON__">
8
+ <link rel="stylesheet" href="styles.css">
9
+ </head>
10
+ <body>
11
+ <!-- icons: <svg class="icon"><use href="#i-folder"/></svg> -->
12
+ <svg width="0" height="0" style="position:absolute" aria-hidden="true">
13
+ <defs>
14
+ <linearGradient id="folder-front" x1="0" y1="0" x2="0" y2="1">
15
+ <stop offset="0" stop-color="var(--folder-top)"/>
16
+ <stop offset="1" stop-color="var(--folder-bottom)"/>
17
+ </linearGradient>
18
+ <symbol id="i-folder" viewBox="0 0 64 52">
19
+ <path d="M4 8a4 4 0 0 1 4-4h15.2a4 4 0 0 1 3.1 1.5L30 10h26a4 4 0 0 1 4 4v32a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4Z" fill="var(--folder-back)"/>
20
+ <rect x="9" y="13" width="44" height="22" rx="2" fill="var(--paper)" opacity="0.9" transform="rotate(-3 31 24)"/>
21
+ <rect x="11" y="16" width="44" height="22" rx="2" fill="var(--paper)"/>
22
+ <path d="M2.2 22.6A4 4 0 0 1 6.2 18H58a4 4 0 0 1 4 4.5l-2.6 23.2A4 4 0 0 1 55.4 50H8.6a4 4 0 0 1-4-3.6Z" fill="url(#folder-front)"/>
23
+ <path d="M6.2 18H58a4 4 0 0 1 3.4 1.9" stroke="#fff" stroke-opacity="0.45" stroke-width="1.2" fill="none"/>
24
+ </symbol>
25
+ <symbol id="i-notebook" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
26
+ <path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8Z"/><path d="M14 3v5h5M9 13h6M9 17h4"/>
27
+ </symbol>
28
+ <symbol id="i-home" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
29
+ <path d="M3 11.5 12 4l9 7.5M5.5 9.5V20h13V9.5"/>
30
+ </symbol>
31
+ <symbol id="i-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
32
+ <path d="m9 6 6 6-6 6"/>
33
+ </symbol>
34
+ </defs>
35
+ </svg>
36
+
37
+ <header>
38
+ <button class="burger" aria-label="Menu" aria-expanded="false" aria-controls="menu">
39
+ <svg width="20" height="20" viewBox="0 0 20 20" aria-hidden="true">
40
+ <path d="M3 5h14M3 10h14M3 15h14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
41
+ </svg>
42
+ </button>
43
+ <a class="brand" href="#/"><img src="__LOGO__" alt=""><span>__HEADER_TITLE__</span></a>
44
+ <ol class="crumbs" aria-label="Breadcrumb"></ol>
45
+ <a class="newtab" target="_blank" rel="noopener" hidden>Open in new tab ↗</a>
46
+ </header>
47
+
48
+ <nav id="menu" aria-label="Notebooks"></nav>
49
+ <div class="backdrop"></div>
50
+
51
+ <main>
52
+ <section id="gallery">
53
+ <h1></h1>
54
+ <p class="lead"></p>
55
+ <div class="grid"></div>
56
+ </section>
57
+ <iframe title="Notebook" hidden></iframe>
58
+ </main>
59
+
60
+ <script id="notebooks" type="application/json">__NOTEBOOKS__</script>
61
+ <script src="app.js"></script>
62
+ </body>
63
+ </html>
barnacles/web/logo.svg ADDED
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none">
2
+ <path d="M4 26 C4 15 10 6 16 6 S28 15 28 26 Z" fill="#0880ea"/>
3
+ <path d="M10 26 C10 19 13 13 16 13 S22 19 22 26" stroke="#fff" stroke-width="2.5" stroke-linecap="round"/>
4
+ <path d="M2 26 H30" stroke="#0880ea" stroke-width="3" stroke-linecap="round"/>
5
+ </svg>
@@ -0,0 +1,124 @@
1
+ :root {
2
+ --bg: #fff; --fg: #0f172a; --muted: #64748b; --border: #e2e8f0;
3
+ --card: #fff; --soft: #f1f5f9; --primary: #0880ea; --accent: #edf6ff;
4
+ --folder-bg: #eef6ff; --folder-back: #2f7fd6; --folder-top: #7cc0ff; --folder-bottom: #2f8ef0;
5
+ --paper: #fff;
6
+ --font: "PT Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
7
+ --heading: "Lora", Georgia, serif;
8
+ --mono: "Fira Mono", ui-monospace, monospace;
9
+ --header: 3.25rem;
10
+ color-scheme: light dark;
11
+ }
12
+ @media (prefers-color-scheme: dark) {
13
+ :root {
14
+ --bg: #181c1a; --fg: #eceeed; --muted: #aab2af; --border: #3b403e;
15
+ --card: #252927; --soft: #222; --primary: #28879f; --accent: #1d5b6a;
16
+ --folder-bg: #1d2a2e; --folder-back: #1f6a7d; --folder-top: #4fb3cc; --folder-bottom: #24879f;
17
+ --paper: #dfe7e5;
18
+ }
19
+ }
20
+ *, *::before, *::after { box-sizing: border-box; }
21
+ html, body { height: 100%; }
22
+ body {
23
+ margin: 0; display: grid; grid-template-rows: var(--header) 1fr;
24
+ font-family: var(--font); background: var(--bg); color: var(--fg); line-height: 1.5;
25
+ }
26
+ [hidden] { display: none !important; }
27
+ .icon { width: 1em; height: 1em; flex: none; }
28
+
29
+ /* top bar */
30
+ header {
31
+ display: flex; align-items: center; gap: 0.75rem; padding: 0 0.75rem; min-width: 0;
32
+ border-bottom: 1px solid var(--border); background: var(--bg); position: relative; z-index: 3;
33
+ }
34
+ .burger {
35
+ display: grid; place-items: center; width: 2.25rem; height: 2.25rem; padding: 0; flex: none;
36
+ border: 0; border-radius: 0.375rem; background: none; color: inherit; cursor: pointer;
37
+ }
38
+ .burger:hover, .burger:focus-visible { background: var(--soft); }
39
+ .brand { display: flex; align-items: center; gap: 0.5rem; color: inherit; text-decoration: none; flex: none; }
40
+ .brand img { width: 1.75rem; height: 1.75rem; }
41
+ .brand span { font-family: var(--heading); font-weight: 600; font-size: 1.15rem; }
42
+ .crumbs {
43
+ display: flex; align-items: center; min-width: 0; margin: 0; padding: 0; list-style: none;
44
+ color: var(--muted); font-size: 0.95rem; white-space: nowrap;
45
+ }
46
+ .crumbs li { display: flex; min-width: 0; }
47
+ .crumbs li::before { content: "/"; margin: 0 0.6rem; opacity: 0.5; }
48
+ .crumbs li:last-child { overflow: hidden; }
49
+ .crumbs a, .crumbs span { overflow: hidden; text-overflow: ellipsis; color: inherit; text-decoration: none; }
50
+ .crumbs a:hover { color: var(--fg); text-decoration: underline; }
51
+ .crumbs li:last-child > * { color: var(--fg); }
52
+ .newtab { margin-left: auto; color: var(--muted); font-size: 0.85rem; text-decoration: none; white-space: nowrap; }
53
+ .newtab:hover { color: var(--fg); }
54
+
55
+ /* drawer */
56
+ nav {
57
+ position: fixed; top: var(--header); bottom: 0; left: 0; z-index: 2; width: min(19rem, 85vw);
58
+ padding: 0.75rem; overflow-y: auto; background: var(--bg); border-right: 1px solid var(--border);
59
+ transform: translateX(-100%); transition: transform 0.2s ease, visibility 0.2s;
60
+ visibility: hidden;
61
+ }
62
+ body.open nav { transform: none; visibility: visible; }
63
+ .backdrop {
64
+ position: fixed; inset: var(--header) 0 0 0; z-index: 1; background: rgb(0 0 0 / 0.25);
65
+ opacity: 0; pointer-events: none; transition: opacity 0.2s;
66
+ }
67
+ body.open .backdrop { opacity: 1; pointer-events: auto; }
68
+ nav a {
69
+ display: flex; align-items: center; gap: 0.5rem; padding: 0.4rem 0.6rem; border-radius: 0.375rem;
70
+ color: inherit; text-decoration: none;
71
+ }
72
+ nav a:hover { background: var(--soft); }
73
+ nav a[aria-current="page"] { background: var(--accent); font-weight: 700; }
74
+ nav hr { border: 0; border-top: 1px solid var(--border); margin: 0.5rem 0; }
75
+ nav .icon { font-size: 1.1rem; }
76
+ nav summary { display: flex; align-items: center; list-style: none; cursor: pointer; }
77
+ nav summary::-webkit-details-marker { display: none; }
78
+ nav summary > a { flex: 1; min-width: 0; }
79
+ nav .chevron {
80
+ display: grid; place-items: center; width: 1.5rem; height: 1.5rem; flex: none;
81
+ border-radius: 0.25rem; color: var(--muted); transition: transform 0.15s;
82
+ }
83
+ nav .chevron:hover { background: var(--soft); }
84
+ nav details[open] > summary .chevron { transform: rotate(90deg); }
85
+ nav .count { margin-left: auto; font-size: 0.75rem; color: var(--muted); font-weight: 400; }
86
+ nav .children { margin-left: 0.75rem; padding-left: 0.5rem; border-left: 1px solid var(--border); }
87
+ nav .children > a, nav > a.nb { padding-left: 2.1rem; }
88
+
89
+ /* content */
90
+ main { min-height: 0; position: relative; }
91
+ iframe { display: block; width: 100%; height: 100%; border: 0; background: var(--bg); }
92
+ #gallery { height: 100%; overflow-y: auto; padding: 2rem clamp(1rem, 4vw, 3rem); }
93
+
94
+ h1 { display: flex; align-items: center; gap: 0.6rem; font-family: var(--heading); font-weight: 600; margin: 0 0 0.25rem; font-size: 2rem; }
95
+ h1 .icon { font-size: 2.25rem; }
96
+ .lead { margin: 0 0 2rem; color: var(--muted); }
97
+ .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr)); gap: 1.25rem; max-width: 80rem; }
98
+ .card {
99
+ display: flex; flex-direction: column; overflow: hidden; text-decoration: none; color: inherit;
100
+ background: var(--card); border: 1px solid var(--border); border-radius: 0.5rem;
101
+ transition: border-color 0.15s, box-shadow 0.15s, transform 0.15s;
102
+ }
103
+ .card:hover { border-color: var(--primary); box-shadow: 0 2px 8px rgb(0 0 0 / 0.08); }
104
+ .thumb {
105
+ display: grid; place-items: center; aspect-ratio: 16 / 9; background: var(--soft);
106
+ color: var(--muted); border-bottom: 1px solid var(--border);
107
+ font-family: var(--heading); font-size: 2.5rem;
108
+ }
109
+ .thumb picture { display: contents; }
110
+ .thumb img { width: 100%; height: 100%; object-fit: cover; object-position: top; }
111
+ .folder .thumb { background: var(--folder-bg); }
112
+ .folder .thumb .icon { font-size: 5.5rem; filter: drop-shadow(0 4px 6px rgb(0 0 0 / 0.12)); transition: transform 0.2s; }
113
+ .folder:hover .thumb .icon { transform: translateY(-3px) scale(1.04); }
114
+ .body { padding: 0.875rem 1rem 1rem; }
115
+ .body h3 { font-family: var(--heading); font-weight: 600; margin: 0 0 0.375rem; font-size: 1.05rem; }
116
+ .body p { margin: 0 0 0.75rem; font-size: 0.875rem; color: var(--muted); }
117
+ .stats { display: flex; gap: 1rem; margin: 0 0 0.75rem; font-size: 0.875rem; color: var(--muted); }
118
+ .stats span { display: flex; align-items: center; gap: 0.35rem; }
119
+ .stats b { color: var(--fg); }
120
+ .badge {
121
+ font-family: var(--mono); font-size: 0.7rem; padding: 0.125rem 0.5rem; border-radius: 999px;
122
+ background: var(--soft); color: var(--muted); border: 1px solid var(--border);
123
+ }
124
+ .empty { color: var(--muted); }
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.5
2
+ Name: barnacles
3
+ Version: 0.1.0
4
+ Summary: A static gallery for marimo notebooks: one YAML file, one command.
5
+ Project-URL: Homepage, https://github.com/stefanzhelev/barnacles
6
+ Project-URL: Issues, https://github.com/stefanzhelev/barnacles/issues
7
+ Author: Stefan Zhelev
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: gallery,marimo,notebooks,static-site,wasm
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Documentation
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: marimo>=0.20
15
+ Requires-Dist: pyyaml>=6
16
+ Provides-Extra: thumbnails
17
+ Requires-Dist: playwright>=1.40; extra == 'thumbnails'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # Barnacles
21
+
22
+ A static gallery for [marimo](https://marimo.io) notebooks. Point it at a folder of notebooks, describe them in one `barnacles.yaml`, and get a site you can host anywhere (GitHub Pages included). Folders become gallery folders, each notebook gets a card with a light/dark thumbnail, and notebooks run either in the browser (WASM) or once at build time (static HTML).
23
+
24
+ ## Install
25
+
26
+ ```sh
27
+ pip install barnacles # or: uv tool install barnacles
28
+ pip install "barnacles[thumbnails]" # optional: notebook screenshots for the cards
29
+ playwright install chromium # (needed once for thumbnails)
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```sh
35
+ barnacles init my-gallery # barnacles.yaml + notebooks/example.py
36
+ cd my-gallery
37
+ barnacles serve # build, then serve at http://127.0.0.1:8000
38
+ barnacles edit # open the notebooks in the marimo editor
39
+ barnacles build # build into dist/ for publishing
40
+ ```
41
+
42
+ Each command takes an optional project path (a folder with `barnacles.yaml`, or the file itself). `build` and `serve` accept `--no-thumbnails` for faster builds. Run `barnacles <command> -h` for all options.
43
+
44
+ ## barnacles.yaml
45
+
46
+ Every key is optional. All paths, including the keys under `items`, are relative to `barnacles.yaml`.
47
+
48
+ ```yaml
49
+ site:
50
+ title: Energy notebooks # browser tab title
51
+ header_title: Barnacles # text next to the logo (defaults to title)
52
+ logo: assets/logo.svg # defaults to the barnacles logo
53
+ favicon: assets/favicon.svg # defaults to the logo
54
+
55
+ paths:
56
+ notebooks: notebooks # default
57
+ dist: dist # default; wiped on every build
58
+
59
+ defaults: # applied to every notebook / folder
60
+ notebook:
61
+ mode: html-wasm
62
+ folder:
63
+ description: ""
64
+
65
+ items: # overrides per notebook or folder, keyed by path
66
+ "notebooks": # the notebooks folder itself = the home page
67
+ title: All notebooks
68
+ "notebooks/prices.py":
69
+ title: Electricity prices
70
+ description: Daily price analysis
71
+ thumbnail: thumbnails/prices.png
72
+ "notebooks/forecasts":
73
+ title: Forecasts
74
+ ```
75
+
76
+ Settings are resolved in this order: `items`, then `defaults`, then the built-in fallbacks below.
77
+
78
+ | item key | applies to | meaning (fallback) |
79
+ |---|---|---|
80
+ | `title` | both | display name (notebook: `marimo.App(app_title=...)`, then the slug; folder: its name; home page: "Notebooks") |
81
+ | `description` | both | text on the card and the folder page (none) |
82
+ | `mode` | notebook | `html-wasm` runs in the browser, `html` runs once at build time (`html-wasm`) |
83
+ | `slug` | notebook | URL segment (the file name, with `_` turned into `-`) |
84
+ | `thumbnail`, `thumbnail_dark` | notebook | card images for light and dark themes (a screenshot of the notebook; the light image is used for both if no dark one is given) |
85
+
86
+ Notes:
87
+
88
+ - A notebook appears without an `items` entry. You only add one to override something.
89
+ - Folders with no notebooks, and folders whose names start with `.` or `_`, are skipped.
90
+ - The build stops on unknown keys and on `items` that match no notebook or folder.
91
+ - All links in the output are relative, so it works at a domain root or under a subpath.
92
+
93
+ ## Development
94
+
95
+ ```sh
96
+ uv sync # installs barnacles in editable mode + dev tools
97
+ uv run playwright install chromium
98
+ uv run barnacles serve demo # the demo gallery in demo/
99
+ uv run pytest
100
+ ```
101
+
102
+ Releases: bump `__version__` in `src/barnacles/__init__.py`, push, then publish a GitHub release tagged `v<version>` (e.g. `v0.2.0`). `.github/workflows/publish.yml` checks the tag matches, runs the tests, builds the package and uploads it to PyPI.
103
+
104
+ ## License
105
+
106
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,20 @@
1
+ barnacles/__init__.py,sha256=X8Nzf0pjSEbch9xkqq_3XGo4rYboERtzE-QFVoG5O6Y,79
2
+ barnacles/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ barnacles/build.py,sha256=FLn5un3BBEChi_JwZBqEPGgOEnvE7UYt3ExTzdcDilc,2698
4
+ barnacles/cli.py,sha256=uBXSqBtMZYV0FAoD-xPLmmP76aRtb10CKJw0BCu4TYM,4572
5
+ barnacles/config.py,sha256=HiOJ2wIHmOSJovYUiNCUHchTB1jcxdDayECCw65iDrQ,4317
6
+ barnacles/discovery.py,sha256=BCd2LZMVfYxOawentRJ_9LVhXilRcJFuSzSIJoe-Dt0,4492
7
+ barnacles/marimo_export.py,sha256=lLlMyD9cq9h6b_cZWvTctTQFvWP0HV1YSsGws6GjI4s,1923
8
+ barnacles/thumbnails.py,sha256=CKIBHMpk675BxYy11O1fHcqDNAXeaC1Kjn6Rl5kKTCA,4208
9
+ barnacles/scaffold/barnacles.yaml,sha256=bIfS4uQjt_jlljxIGvTVV5OnahxABdyl2xT8ovrBOhU,655
10
+ barnacles/scaffold/gitignore,sha256=gzMCri-I9PSB7ZlWL9RHkzjICibzGrY2lPPsev_2taA,18
11
+ barnacles/scaffold/notebooks/example.py,sha256=wprsC4KPsynNX8TysKPHlop68prji3gwU_CAPyyULYo,861
12
+ barnacles/web/app.js,sha256=ZdEtQTTzif-YIxhTtrQRF5DcWKODEkE5iYkqWBU8590,6774
13
+ barnacles/web/index.html,sha256=uw6Z3xkR6TZGKrXMGj-tJb6KL7hySvTnlsHaqKcApa0,2946
14
+ barnacles/web/logo.svg,sha256=Q-fMnkgiMsBGxucjrUT2WaQyNBLeD-9S-lHK3H16aVM,336
15
+ barnacles/web/styles.css,sha256=QJ2bla2-jt36DAAtFcWKUpHXIa4-KPonAVbdtY4Rlgc,6359
16
+ barnacles-0.1.0.dist-info/METADATA,sha256=HUgwPOVfd3ynL80aHDM76qI_ZGw74_wDrJ89wP520Rs,4471
17
+ barnacles-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
18
+ barnacles-0.1.0.dist-info/entry_points.txt,sha256=URrDMw803WIVqGTSg0doTLU9lnwiVC8hnV20AQt7XOk,49
19
+ barnacles-0.1.0.dist-info/licenses/LICENSE,sha256=dWyq9Y6_yzzIB4bfwrVcOrXv00dQRHG0MHDEmd51BJ0,1070
20
+ barnacles-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ barnacles = barnacles.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stefan Zhelev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.