marimo-banners 0.1.4__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.
- banners/__init__.py +38 -0
- banners/background.py +157 -0
- banners/config.py +74 -0
- banners/content/__init__.py +21 -0
- banners/content/animated_graph.py +246 -0
- banners/content/flow_animation.py +404 -0
- banners/content/graph.py +37 -0
- banners/content/image.py +41 -0
- banners/content/manim.py +306 -0
- banners/content/plot.py +44 -0
- banners/content/table.py +31 -0
- banners/content/text.py +43 -0
- banners/palette.py +115 -0
- banners/scenes/__init__.py +5 -0
- banners/scenes/pipeline.py +123 -0
- banners/slide.py +273 -0
- banners/slides/__init__.py +6 -0
- banners/slides/closing.py +108 -0
- banners/slides/cover.py +90 -0
- banners/slides/intro.py +109 -0
- banners/slides/section.py +110 -0
- banners/static/mermaid.min.js +2029 -0
- marimo_banners-0.1.4.dist-info/METADATA +15 -0
- marimo_banners-0.1.4.dist-info/RECORD +26 -0
- marimo_banners-0.1.4.dist-info/WHEEL +4 -0
- marimo_banners-0.1.4.dist-info/licenses/LICENSE +339 -0
banners/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Composable slides for marimo presentations.
|
|
2
|
+
|
|
3
|
+
Build a presentation by combining slide classes with content elements:
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from banners.slides import Cover, Intro, Section, Closing
|
|
7
|
+
from banners.content import Text, Image, Graph
|
|
8
|
+
from banners.palette import Palette, BLUE, GREEN
|
|
9
|
+
|
|
10
|
+
Cover(
|
|
11
|
+
title="My Project",
|
|
12
|
+
subtitle="Context in one line.",
|
|
13
|
+
date="April 2026",
|
|
14
|
+
content=[
|
|
15
|
+
Text("**Point 1** — Something relevant."),
|
|
16
|
+
Text("**Point 2** — Concrete result."),
|
|
17
|
+
Text("**Point 3** — Team impact."),
|
|
18
|
+
],
|
|
19
|
+
content_kind="neutral",
|
|
20
|
+
).render()
|
|
21
|
+
```
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from .slide import Slide
|
|
25
|
+
from .slides import Cover, Intro, Section, Closing
|
|
26
|
+
from .content import Text, Image, Graph, AnimatedGraph, Table, Plot, Manim, FlowAnimation
|
|
27
|
+
from .palette import Palette, SectionPalette, ORANGE, BLUE, GREEN, PURPLE, GRAY
|
|
28
|
+
from .background import Background
|
|
29
|
+
from .config import configure
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"configure",
|
|
33
|
+
"Slide",
|
|
34
|
+
"Cover", "Intro", "Section", "Closing",
|
|
35
|
+
"Text", "Image", "Graph", "AnimatedGraph", "Table", "Plot", "Manim", "FlowAnimation",
|
|
36
|
+
"Palette", "SectionPalette", "ORANGE", "BLUE", "GREEN", "PURPLE", "GRAY",
|
|
37
|
+
"Background",
|
|
38
|
+
]
|
banners/background.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Background — per-slide background for banners presentations."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
_NAMED_COLORS = {
|
|
8
|
+
"white": (255, 255, 255), "black": (0, 0, 0),
|
|
9
|
+
"red": (255, 0, 0), "green": (0, 128, 0), "blue": (0, 0, 255),
|
|
10
|
+
"yellow": (255, 255, 0), "cyan": (0, 255, 255), "magenta": (255, 0, 255),
|
|
11
|
+
"gray": (128, 128, 128), "grey": (128, 128, 128),
|
|
12
|
+
"silver": (192, 192, 192), "navy": (0, 0, 128), "teal": (0, 128, 128),
|
|
13
|
+
"maroon": (128, 0, 0), "purple": (128, 0, 128), "orange": (255, 165, 0),
|
|
14
|
+
"pink": (255, 192, 203), "transparent": (0, 0, 0),
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _parse_first_color(css: str):
|
|
19
|
+
# Named color (e.g. "white", "black")
|
|
20
|
+
key = css.strip().lower()
|
|
21
|
+
if key in _NAMED_COLORS:
|
|
22
|
+
return _NAMED_COLORS[key]
|
|
23
|
+
|
|
24
|
+
# 8-digit hex #rrggbbaa (take RGB, ignore alpha)
|
|
25
|
+
m = re.search(r'#([0-9a-fA-F]{8})', css)
|
|
26
|
+
if m:
|
|
27
|
+
h = m.group(1)
|
|
28
|
+
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
|
29
|
+
|
|
30
|
+
# 6-digit hex #rrggbb
|
|
31
|
+
m = re.search(r'#([0-9a-fA-F]{6})', css)
|
|
32
|
+
if m:
|
|
33
|
+
h = m.group(1)
|
|
34
|
+
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
|
35
|
+
|
|
36
|
+
# 4-digit hex #rgba → expand RGB channels
|
|
37
|
+
m = re.search(r'#([0-9a-fA-F]{4})(?![0-9a-fA-F])', css)
|
|
38
|
+
if m:
|
|
39
|
+
h = m.group(1)
|
|
40
|
+
return int(h[0] * 2, 16), int(h[1] * 2, 16), int(h[2] * 2, 16)
|
|
41
|
+
|
|
42
|
+
# 3-digit hex #rgb → expand to #rrggbb
|
|
43
|
+
m = re.search(r'#([0-9a-fA-F]{3})(?![0-9a-fA-F])', css)
|
|
44
|
+
if m:
|
|
45
|
+
h = m.group(1)
|
|
46
|
+
return int(h[0] * 2, 16), int(h[1] * 2, 16), int(h[2] * 2, 16)
|
|
47
|
+
|
|
48
|
+
# rgb() / rgba() — handles integers (0-255) and floats (0.0-1.0 / 0-255)
|
|
49
|
+
m = re.search(r'rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)', css)
|
|
50
|
+
if m:
|
|
51
|
+
vals = [float(m.group(i)) for i in (1, 2, 3)]
|
|
52
|
+
if all(v <= 1.0 for v in vals): # 0-1 range → scale to 0-255
|
|
53
|
+
vals = [v * 255 for v in vals]
|
|
54
|
+
return int(vals[0]), int(vals[1]), int(vals[2])
|
|
55
|
+
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _relative_luminance(r, g, b) -> float:
|
|
60
|
+
def lin(c):
|
|
61
|
+
c /= 255
|
|
62
|
+
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
|
|
63
|
+
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class Background:
|
|
68
|
+
"""Encapsulates a CSS background value for use as a slide backdrop.
|
|
69
|
+
|
|
70
|
+
Do not instantiate directly — use the factory methods:
|
|
71
|
+
|
|
72
|
+
- :meth:`color` — solid color
|
|
73
|
+
- :meth:`gradient` — linear gradient
|
|
74
|
+
- :meth:`image` — image with optional dark overlay
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
css: Ready-to-use CSS value for the ``background`` property.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
css: str
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def color(c: str) -> "Background":
|
|
84
|
+
"""Solid background color.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
c: Any CSS color value (hex, rgb, named).
|
|
88
|
+
|
|
89
|
+
Example::
|
|
90
|
+
|
|
91
|
+
Background.color("#0f172a")
|
|
92
|
+
"""
|
|
93
|
+
return Background(css=c)
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def gradient(
|
|
97
|
+
start: str,
|
|
98
|
+
end: str,
|
|
99
|
+
*,
|
|
100
|
+
mid: str = None,
|
|
101
|
+
angle: int = 135,
|
|
102
|
+
) -> "Background":
|
|
103
|
+
"""Linear gradient background.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
start: Start color (0%).
|
|
107
|
+
end: End color (100%).
|
|
108
|
+
mid: Optional mid-stop color (50%).
|
|
109
|
+
angle: Gradient angle in degrees. Defaults to 135.
|
|
110
|
+
|
|
111
|
+
Example::
|
|
112
|
+
|
|
113
|
+
Background.gradient("#0d1b2a", "#4a1a6e")
|
|
114
|
+
Background.gradient("#0d1b2a", "#4a1a6e", mid="#1a2a5e", angle=45)
|
|
115
|
+
"""
|
|
116
|
+
if mid:
|
|
117
|
+
return Background(
|
|
118
|
+
css=f"linear-gradient({angle}deg,{start} 0%,{mid} 50%,{end} 100%)"
|
|
119
|
+
)
|
|
120
|
+
return Background(css=f"linear-gradient({angle}deg,{start} 0%,{end} 100%)")
|
|
121
|
+
|
|
122
|
+
@staticmethod
|
|
123
|
+
def image(src, *, overlay: str = "rgba(0,0,0,0.55)") -> "Background":
|
|
124
|
+
"""Image background, with an optional dark overlay for text legibility.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
src: File path (``str`` / ``Path``), URL, or raw ``bytes``.
|
|
128
|
+
overlay: CSS color applied as a semi-transparent layer on top of
|
|
129
|
+
the image. Defaults to ``"rgba(0,0,0,0.55)"``. Pass ``None``
|
|
130
|
+
to disable the overlay entirely.
|
|
131
|
+
|
|
132
|
+
Example::
|
|
133
|
+
|
|
134
|
+
Background.image("assets/photo.jpg")
|
|
135
|
+
Background.image("https://example.com/bg.jpg", overlay="rgba(0,0,0,0.7)")
|
|
136
|
+
Background.image(raw_bytes, overlay=None)
|
|
137
|
+
"""
|
|
138
|
+
from banners.slide import Slide
|
|
139
|
+
data_uri = Slide._icon_src(src)
|
|
140
|
+
img_css = f"url({data_uri}) center/cover no-repeat"
|
|
141
|
+
if overlay:
|
|
142
|
+
return Background(css=f"linear-gradient({overlay},{overlay}),{img_css}")
|
|
143
|
+
return Background(css=img_css)
|
|
144
|
+
|
|
145
|
+
def text_color(self) -> "str | None":
|
|
146
|
+
"""Return a contrasting text color based on the background luminance.
|
|
147
|
+
|
|
148
|
+
Returns ``"#ffffff"`` for dark backgrounds, ``"#1f2937"`` for light
|
|
149
|
+
ones, using the WCAG relative luminance formula. Returns ``None`` when
|
|
150
|
+
the color cannot be parsed (unrecognized format) — in that case no
|
|
151
|
+
automatic color is applied.
|
|
152
|
+
"""
|
|
153
|
+
rgb = _parse_first_color(self.css)
|
|
154
|
+
if rgb is None:
|
|
155
|
+
return None
|
|
156
|
+
lum = _relative_luminance(*rgb)
|
|
157
|
+
return "#ffffff" if lum < 0.2 else "#1f2937"
|
banners/config.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Global presentation configuration."""
|
|
2
|
+
|
|
3
|
+
_state: dict = {
|
|
4
|
+
"team": "",
|
|
5
|
+
"date": "",
|
|
6
|
+
"icon": None,
|
|
7
|
+
"palette": None,
|
|
8
|
+
"background": None,
|
|
9
|
+
"_section_counter": 0,
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
_UNSET = object()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def configure(
|
|
16
|
+
team: str = _UNSET,
|
|
17
|
+
date: str = _UNSET,
|
|
18
|
+
icon=_UNSET,
|
|
19
|
+
palette=_UNSET,
|
|
20
|
+
background=_UNSET,
|
|
21
|
+
) -> None:
|
|
22
|
+
"""Set global defaults shared by all slides and reset the section counter.
|
|
23
|
+
|
|
24
|
+
Call this once at the top of the notebook. Any slide parameter left at its
|
|
25
|
+
default will inherit the value set here. Calling `configure()` without
|
|
26
|
+
arguments only resets the section counter.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
team: Team line shown in `Cover`, `Intro`, and `Closing` banners.
|
|
30
|
+
date: Date string shown in `Cover` (e.g. `"April 2026"`).
|
|
31
|
+
icon: Icon applied to all slides. Pass a dict with keys `"src"`
|
|
32
|
+
(path, URL, or bytes) and optionally `"size"` (CSS height).
|
|
33
|
+
palette: Color palette applied to `Cover`, `Intro`, and `Closing`.
|
|
34
|
+
Pass any `Palette` instance or predefined constant
|
|
35
|
+
(`BLUE`, `GREEN`, `PURPLE`, `GRAY`).
|
|
36
|
+
background: Background applied to all slides. Pass a `Background`
|
|
37
|
+
instance (`Background.color()`, `Background.gradient()`, or
|
|
38
|
+
`Background.image()`). Individual slides can override this with
|
|
39
|
+
their own `background` argument.
|
|
40
|
+
|
|
41
|
+
Example:
|
|
42
|
+
```python
|
|
43
|
+
from banners import configure, Background
|
|
44
|
+
from banners.palette import BLUE
|
|
45
|
+
|
|
46
|
+
configure(
|
|
47
|
+
team="Analytics Team",
|
|
48
|
+
date="April 2026",
|
|
49
|
+
palette=BLUE,
|
|
50
|
+
icon={"src": "img/logo.png"},
|
|
51
|
+
background=Background.gradient("#0f172a", "#1e3a5f"),
|
|
52
|
+
)
|
|
53
|
+
```
|
|
54
|
+
"""
|
|
55
|
+
if team is not _UNSET:
|
|
56
|
+
_state["team"] = team
|
|
57
|
+
if date is not _UNSET:
|
|
58
|
+
_state["date"] = date
|
|
59
|
+
if icon is not _UNSET:
|
|
60
|
+
_state["icon"] = icon
|
|
61
|
+
if palette is not _UNSET:
|
|
62
|
+
_state["palette"] = palette
|
|
63
|
+
if background is not _UNSET:
|
|
64
|
+
_state["background"] = background
|
|
65
|
+
_state["_section_counter"] = 0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def get(key: str, default=None):
|
|
69
|
+
return _state.get(key, default)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _next_section_number() -> str:
|
|
73
|
+
_state["_section_counter"] += 1
|
|
74
|
+
return f"{_state['_section_counter']:02d}"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Módulo de contenido para slides.
|
|
2
|
+
|
|
3
|
+
Clases disponibles:
|
|
4
|
+
Text — Texto en Markdown.
|
|
5
|
+
Image — Imagen desde path, bytes o URL.
|
|
6
|
+
Graph — Diagrama Mermaid.
|
|
7
|
+
Table — Tabla desde un pandas DataFrame.
|
|
8
|
+
Plot — Figura de matplotlib o plotly.
|
|
9
|
+
Manim — Animación renderizada con Manim (requiere `banners[manim]`).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from .text import Text
|
|
13
|
+
from .image import Image
|
|
14
|
+
from .graph import Graph
|
|
15
|
+
from .animated_graph import AnimatedGraph
|
|
16
|
+
from .table import Table
|
|
17
|
+
from .plot import Plot
|
|
18
|
+
from .manim import Manim
|
|
19
|
+
from .flow_animation import FlowAnimation
|
|
20
|
+
|
|
21
|
+
__all__ = ["Text", "Image", "Graph", "AnimatedGraph", "Table", "Plot", "Manim", "FlowAnimation"]
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""AnimatedGraph — interactive graph rendered as an anywidget."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
import uuid
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
|
|
8
|
+
import anywidget
|
|
9
|
+
import traitlets
|
|
10
|
+
import marimo as mo
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# ---------------------------------------------------------------------------
|
|
14
|
+
# Parser
|
|
15
|
+
# ---------------------------------------------------------------------------
|
|
16
|
+
|
|
17
|
+
def _parse(diagram: str):
|
|
18
|
+
direction = "LR"
|
|
19
|
+
nodes: dict[str, str] = {}
|
|
20
|
+
edges: list[tuple[str, str, str]] = []
|
|
21
|
+
|
|
22
|
+
_ns = (
|
|
23
|
+
r'(?:\[\[?([^\]\)]*?)\]?\]?'
|
|
24
|
+
r'|\(\(?([^\)\]]*?)\)?\)?'
|
|
25
|
+
r'|\{([^\}]*?)\}'
|
|
26
|
+
r'|>([^\]]*?)\]'
|
|
27
|
+
r')?'
|
|
28
|
+
)
|
|
29
|
+
_nid = r'([A-Za-z0-9_]+)'
|
|
30
|
+
_edge_re = re.compile(_nid + _ns + r'\s*-[-\.]+>+(?:\|([^|]*)\|)?\s*' + _nid + _ns)
|
|
31
|
+
_solo_re = re.compile(_nid + _ns + r'\s*$')
|
|
32
|
+
|
|
33
|
+
def _label(groups, fallback):
|
|
34
|
+
return next((g for g in groups if g), fallback)
|
|
35
|
+
|
|
36
|
+
for raw in diagram.strip().splitlines():
|
|
37
|
+
line = raw.strip()
|
|
38
|
+
if not line or line.startswith("%%"):
|
|
39
|
+
continue
|
|
40
|
+
if line.lower().startswith("graph"):
|
|
41
|
+
parts = line.split()
|
|
42
|
+
if len(parts) > 1:
|
|
43
|
+
direction = parts[1].upper()
|
|
44
|
+
continue
|
|
45
|
+
m = _edge_re.match(line)
|
|
46
|
+
if m:
|
|
47
|
+
src = m.group(1)
|
|
48
|
+
sl = _label(m.groups()[1:5], src)
|
|
49
|
+
el = m.group(6) or ""
|
|
50
|
+
dst = m.group(7)
|
|
51
|
+
dl = _label(m.groups()[7:11], dst)
|
|
52
|
+
if src not in nodes:
|
|
53
|
+
nodes[src] = sl
|
|
54
|
+
if dst not in nodes:
|
|
55
|
+
nodes[dst] = dl
|
|
56
|
+
edges.append((src, dst, el.strip()))
|
|
57
|
+
continue
|
|
58
|
+
m = _solo_re.match(line)
|
|
59
|
+
if m:
|
|
60
|
+
nid = m.group(1)
|
|
61
|
+
label = _label(m.groups()[1:5], nid)
|
|
62
|
+
if nid not in nodes:
|
|
63
|
+
nodes[nid] = label
|
|
64
|
+
|
|
65
|
+
return nodes, edges, direction
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ---------------------------------------------------------------------------
|
|
69
|
+
# Layout
|
|
70
|
+
# ---------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
def _layout(nodes, edges, direction, node_w=130, node_h=40, h_gap=70, v_gap=28):
|
|
73
|
+
if not nodes:
|
|
74
|
+
return {}, node_w, node_h
|
|
75
|
+
|
|
76
|
+
succ: dict = defaultdict(list)
|
|
77
|
+
pred: dict = defaultdict(list)
|
|
78
|
+
for s, d, _ in edges:
|
|
79
|
+
succ[s].append(d)
|
|
80
|
+
pred[d].append(s)
|
|
81
|
+
|
|
82
|
+
roots = [n for n in nodes if not pred[n]] or [next(iter(nodes))]
|
|
83
|
+
levels: dict = {n: 0 for n in roots}
|
|
84
|
+
queue = list(roots)
|
|
85
|
+
max_level = len(nodes)
|
|
86
|
+
while queue:
|
|
87
|
+
n = queue.pop(0)
|
|
88
|
+
for nb in succ[n]:
|
|
89
|
+
lv = levels[n] + 1
|
|
90
|
+
if lv > max_level:
|
|
91
|
+
continue
|
|
92
|
+
if nb not in levels or levels[nb] < lv:
|
|
93
|
+
levels[nb] = lv
|
|
94
|
+
queue.append(nb)
|
|
95
|
+
for n in nodes:
|
|
96
|
+
if n not in levels:
|
|
97
|
+
levels[n] = 0
|
|
98
|
+
|
|
99
|
+
by_level: dict = defaultdict(list)
|
|
100
|
+
for n, lv in levels.items():
|
|
101
|
+
by_level[lv].append(n)
|
|
102
|
+
|
|
103
|
+
pos: dict = {}
|
|
104
|
+
for lv, nlist in sorted(by_level.items()):
|
|
105
|
+
for i, n in enumerate(nlist):
|
|
106
|
+
if direction in ("LR", "RL"):
|
|
107
|
+
pos[n] = (lv * (node_w + h_gap), i * (node_h + v_gap))
|
|
108
|
+
else:
|
|
109
|
+
pos[n] = (i * (node_w + h_gap), lv * (node_h + v_gap))
|
|
110
|
+
|
|
111
|
+
return pos, node_w, node_h
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ---------------------------------------------------------------------------
|
|
115
|
+
# SVG builder
|
|
116
|
+
# ---------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
def _build_svg(nodes, edges, pos, node_w, node_h, uid):
|
|
119
|
+
if not pos:
|
|
120
|
+
return "<svg><text y='20'>empty diagram</text></svg>"
|
|
121
|
+
|
|
122
|
+
pad = 24
|
|
123
|
+
hw, hh = node_w // 2, node_h // 2
|
|
124
|
+
xs = [x for x, _ in pos.values()]
|
|
125
|
+
ys = [y for _, y in pos.values()]
|
|
126
|
+
svg_w = max(xs) + node_w + pad * 2
|
|
127
|
+
svg_h = max(ys) + node_h + pad * 2
|
|
128
|
+
|
|
129
|
+
parts = [
|
|
130
|
+
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {svg_w} {svg_h}" '
|
|
131
|
+
f'width="100%" style="font-family:sans-serif;font-size:13px;max-width:{svg_w}px;display:block;margin:0 auto;">',
|
|
132
|
+
'<defs>',
|
|
133
|
+
f' <marker id="arr-{uid}" markerWidth="10" markerHeight="7" '
|
|
134
|
+
f'refX="9" refY="3.5" orient="auto">',
|
|
135
|
+
f' <polygon points="0 0,10 3.5,0 7" fill="#6b7280"/>',
|
|
136
|
+
' </marker>',
|
|
137
|
+
'</defs>',
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
for src, dst, label in edges:
|
|
141
|
+
if src not in pos or dst not in pos:
|
|
142
|
+
continue
|
|
143
|
+
x1 = pos[src][0] + pad + hw
|
|
144
|
+
y1 = pos[src][1] + pad + hh
|
|
145
|
+
x2 = pos[dst][0] + pad + hw
|
|
146
|
+
y2 = pos[dst][1] + pad + hh
|
|
147
|
+
angle = math.atan2(y2 - y1, x2 - x1)
|
|
148
|
+
x2 -= int(math.cos(angle) * (hw + 3))
|
|
149
|
+
y2 -= int(math.sin(angle) * (hh + 3))
|
|
150
|
+
parts.append(
|
|
151
|
+
f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" '
|
|
152
|
+
f'stroke="#9ca3af" stroke-width="1.5" marker-end="url(#arr-{uid})"/>'
|
|
153
|
+
)
|
|
154
|
+
if label:
|
|
155
|
+
mx, my = (x1 + x2) // 2, (y1 + y2) // 2 - 5
|
|
156
|
+
parts.append(
|
|
157
|
+
f'<text x="{mx}" y="{my}" text-anchor="middle" '
|
|
158
|
+
f'fill="#6b7280" font-size="11">{label}</text>'
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
for nid, label in nodes.items():
|
|
162
|
+
if nid not in pos:
|
|
163
|
+
continue
|
|
164
|
+
nx = pos[nid][0] + pad
|
|
165
|
+
ny = pos[nid][1] + pad
|
|
166
|
+
parts.append(
|
|
167
|
+
f'<g class="ag-node" data-hl="0" style="cursor:pointer">'
|
|
168
|
+
f'<rect x="{nx}" y="{ny}" width="{node_w}" height="{node_h}" '
|
|
169
|
+
f'rx="6" fill="#e5e7eb" stroke="#9ca3af" stroke-width="1.5"/>'
|
|
170
|
+
f'<text x="{nx + hw}" y="{ny + hh + 5}" '
|
|
171
|
+
f'text-anchor="middle" fill="#111827">{label}</text>'
|
|
172
|
+
f'</g>'
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
parts.append("</svg>")
|
|
176
|
+
return "\n".join(parts)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# ---------------------------------------------------------------------------
|
|
180
|
+
# Widget
|
|
181
|
+
# ---------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
class _GraphWidget(anywidget.AnyWidget):
|
|
184
|
+
_esm = """
|
|
185
|
+
function render({ model, el }) {
|
|
186
|
+
const color = model.get("color");
|
|
187
|
+
el.innerHTML = model.get("svg");
|
|
188
|
+
|
|
189
|
+
el.querySelectorAll(".ag-node").forEach(function(g) {
|
|
190
|
+
g.addEventListener("click", function() {
|
|
191
|
+
const r = g.querySelector("rect");
|
|
192
|
+
const on = g.dataset.hl === "1";
|
|
193
|
+
r.style.fill = on ? "" : color;
|
|
194
|
+
r.style.filter = on ? "" : "brightness(1.15)";
|
|
195
|
+
g.dataset.hl = on ? "0" : "1";
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
export default { render };
|
|
200
|
+
"""
|
|
201
|
+
_css = """
|
|
202
|
+
.ag-node { cursor: pointer; }
|
|
203
|
+
"""
|
|
204
|
+
svg = traitlets.Unicode("").tag(sync=True)
|
|
205
|
+
color = traitlets.Unicode("#ea580c").tag(sync=True)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# ---------------------------------------------------------------------------
|
|
209
|
+
# Public class
|
|
210
|
+
# ---------------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
class AnimatedGraph:
|
|
213
|
+
"""Interactive graph where nodes highlight on click.
|
|
214
|
+
|
|
215
|
+
Accepts ``graph LR`` / ``graph TD`` Mermaid syntax. Rendered as an
|
|
216
|
+
anywidget — no external JS libraries, no shadow DOM issues.
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
diagram: Mermaid ``graph LR`` or ``graph TD`` source.
|
|
220
|
+
highlight_color: CSS color applied to highlighted nodes.
|
|
221
|
+
Defaults to ``"#ea580c"``.
|
|
222
|
+
|
|
223
|
+
Example:
|
|
224
|
+
```python
|
|
225
|
+
from banners.content import AnimatedGraph
|
|
226
|
+
|
|
227
|
+
AnimatedGraph(\"\"\"
|
|
228
|
+
graph LR
|
|
229
|
+
A[Ingest] --> B[Validate]
|
|
230
|
+
B --> C[Transform]
|
|
231
|
+
C --> D[Load]
|
|
232
|
+
\"\"\")
|
|
233
|
+
```
|
|
234
|
+
"""
|
|
235
|
+
|
|
236
|
+
def __init__(self, diagram: str, highlight_color: str = "#ea580c") -> None:
|
|
237
|
+
self.diagram = diagram
|
|
238
|
+
self.highlight_color = highlight_color
|
|
239
|
+
|
|
240
|
+
def render(self):
|
|
241
|
+
"""Render the interactive graph as a marimo widget."""
|
|
242
|
+
uid = uuid.uuid4().hex[:8]
|
|
243
|
+
nodes, edges, direction = _parse(self.diagram)
|
|
244
|
+
pos, node_w, node_h = _layout(nodes, edges, direction)
|
|
245
|
+
svg = _build_svg(nodes, edges, pos, node_w, node_h, uid)
|
|
246
|
+
return _GraphWidget(svg=svg, color=self.highlight_color)
|