predictygraph 0.3.0__tar.gz → 0.3.2__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.
Files changed (64) hide show
  1. {predictygraph-0.3.0 → predictygraph-0.3.2}/PKG-INFO +4 -1
  2. {predictygraph-0.3.0 → predictygraph-0.3.2}/README.md +1 -0
  3. {predictygraph-0.3.0 → predictygraph-0.3.2}/pyproject.toml +4 -1
  4. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/layout.py +7 -3
  5. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/parser.py +2 -1
  6. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/scene.py +37 -4
  7. predictygraph-0.3.2/src/predictygraph/sketch.py +140 -0
  8. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/style.py +7 -0
  9. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/text.py +20 -0
  10. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/theme.py +1 -1
  11. predictygraph-0.3.2/tests/test_sketch.py +63 -0
  12. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_stack.py +8 -0
  13. {predictygraph-0.3.0 → predictygraph-0.3.2}/LICENSE +0 -0
  14. {predictygraph-0.3.0 → predictygraph-0.3.2}/NOTICE +0 -0
  15. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/__init__.py +0 -0
  16. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/__main__.py +0 -0
  17. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/anim.py +0 -0
  18. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/cli.py +0 -0
  19. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/default.css +0 -0
  20. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/Carlito-Bold.ttf +0 -0
  21. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/Carlito-Regular.ttf +0 -0
  22. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/DejaVuSans-Bold.ttf +0 -0
  23. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/DejaVuSans.ttf +0 -0
  24. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/LiberationMono-Bold.ttf +0 -0
  25. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/LiberationMono-Regular.ttf +0 -0
  26. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/LiberationSans-Bold.ttf +0 -0
  27. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/LiberationSans-Regular.ttf +0 -0
  28. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/LiberationSerif-Bold.ttf +0 -0
  29. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/LiberationSerif-Regular.ttf +0 -0
  30. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/licenses/Bitstream-Vera.txt +0 -0
  31. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/licenses/OFL-1.1.txt +0 -0
  32. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts/licenses/README.md +0 -0
  33. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/fonts.py +0 -0
  34. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/ir.py +0 -0
  35. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/model.py +0 -0
  36. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/render/__init__.py +0 -0
  37. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/render/apng.py +0 -0
  38. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/render/svg.py +0 -0
  39. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/route.py +0 -0
  40. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/safe.py +0 -0
  41. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/styleutil.py +0 -0
  42. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/catppuccin-frappe.toml +0 -0
  43. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/catppuccin-latte.toml +0 -0
  44. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/catppuccin-macchiato.toml +0 -0
  45. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/catppuccin-mocha.toml +0 -0
  46. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/default.toml +0 -0
  47. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/dracula.toml +0 -0
  48. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/github-light.toml +0 -0
  49. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/gruvbox-dark.toml +0 -0
  50. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/hami.toml +0 -0
  51. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/nord.toml +0 -0
  52. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/solarized-dark.toml +0 -0
  53. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/solarized-light.toml +0 -0
  54. {predictygraph-0.3.0 → predictygraph-0.3.2}/src/predictygraph/themes/trunkline.toml +0 -0
  55. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_annotations.py +0 -0
  56. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_blocks.py +0 -0
  57. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_diagonal.py +0 -0
  58. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_fixes.py +0 -0
  59. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_hardening.py +0 -0
  60. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_predictygraph.py +0 -0
  61. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_routing.py +0 -0
  62. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_scene.py +0 -0
  63. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_targets.py +0 -0
  64. {predictygraph-0.3.0 → predictygraph-0.3.2}/tests/test_trunkline.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: predictygraph
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: Predictable graphs: a readable, CSS-styled diagram DSL with per-group layouts, rendered to SVG/APNG
5
5
  Author-Email: Reza Jelveh <git@jelveh.me>
6
6
  License: Apache-2.0
@@ -10,6 +10,8 @@ Requires-Dist: typer>=0.26.8
10
10
  Requires-Dist: pillow>=11.0.0
11
11
  Provides-Extra: apng
12
12
  Requires-Dist: cairosvg>=2.7; extra == "apng"
13
+ Provides-Extra: icons
14
+ Requires-Dist: python-lucide>=0.5.0; extra == "icons"
13
15
  Description-Content-Type: text/markdown
14
16
 
15
17
  <!--
@@ -24,6 +26,7 @@ SPDX-License-Identifier: Apache-2.0
24
26
  plain-CSS styling, and static or animated SVG/APNG output (no browser).
25
27
  Spec: [docs/SPEC.md](docs/SPEC.md). Docs: [predictygraph.github.io](https://predictygraph.github.io/).
26
28
  Editor support: [tree-sitter-pdg](https://github.com/predictygraph/tree-sitter-pdg).
29
+ In the browser: [predictygraph-js](https://github.com/predictygraph/predictygraph-js).
27
30
  Rendered examples and the gallery: [predictygraph.github.io](https://predictygraph.github.io/). This repo keeps
28
31
  only `.pdg` sources; images live in the docs repo (git-lfs).
29
32
 
@@ -10,6 +10,7 @@ SPDX-License-Identifier: Apache-2.0
10
10
  plain-CSS styling, and static or animated SVG/APNG output (no browser).
11
11
  Spec: [docs/SPEC.md](docs/SPEC.md). Docs: [predictygraph.github.io](https://predictygraph.github.io/).
12
12
  Editor support: [tree-sitter-pdg](https://github.com/predictygraph/tree-sitter-pdg).
13
+ In the browser: [predictygraph-js](https://github.com/predictygraph/predictygraph-js).
13
14
  Rendered examples and the gallery: [predictygraph.github.io](https://predictygraph.github.io/). This repo keeps
14
15
  only `.pdg` sources; images live in the docs repo (git-lfs).
15
16
 
@@ -12,7 +12,7 @@ dependencies = [
12
12
  ]
13
13
  requires-python = ">=3.11"
14
14
  readme = "README.md"
15
- version = "0.3.0"
15
+ version = "0.3.2"
16
16
 
17
17
  [project.license]
18
18
  text = "Apache-2.0"
@@ -21,6 +21,9 @@ text = "Apache-2.0"
21
21
  apng = [
22
22
  "cairosvg>=2.7",
23
23
  ]
24
+ icons = [
25
+ "python-lucide>=0.5.0",
26
+ ]
24
27
 
25
28
  [project.scripts]
26
29
  predictygraph = "predictygraph.cli:app"
@@ -12,7 +12,7 @@ from collections import defaultdict
12
12
  from .model import Document, Group, Item, Node
13
13
  from .style import box4, px
14
14
  from .styleutil import has_title_band, node_padding, text_block, title_position
15
- from .text import load_image
15
+ from .text import load_icon, load_image
16
16
 
17
17
  SUB_GAP = 3.0 # px between a label and its `sub=` lines
18
18
 
@@ -26,8 +26,12 @@ def size_node(n: Node, doc: Document) -> None:
26
26
  n.text_w, n.text_h = max(n.text_w, sw), n.text_h + n.sub_h # text_h covers label + sub
27
27
  pt, pr, pb, pl = node_padding(st)
28
28
  shape = n.attrs.get("shape")
29
- if "image" in n.attrs:
30
- img = load_image(n.attrs["image"], doc.base_dir, doc.allow_outside)
29
+ if "image" in n.attrs or "icon" in n.attrs:
30
+ if "icon" in n.attrs:
31
+ img = load_icon(n.attrs["icon"], st)
32
+ img["w"] = img["h"] = 48.0 # Lucide's 24 px grid, drawn at 2x by default
33
+ else:
34
+ img = load_image(n.attrs["image"], doc.base_dir, doc.allow_outside)
31
35
  iw, ih = img["w"], img["h"]
32
36
  if "img-width" in n.attrs or "img-height" in n.attrs:
33
37
  tw, th = max(0.0, px(n.attrs.get("img-width"), 0)), max(0.0, px(n.attrs.get("img-height"), 0))
@@ -387,9 +387,10 @@ class Parser:
387
387
  raise PdgSyntaxError(f"unclosed def {name!r}", lineno)
388
388
  ln, text = lines[i]
389
389
  s = strip_comment(text).strip()
390
+ counted = VAR_RE.sub("v", s) # `$NAME` is only substituted at `use` time
390
391
  depth += sum(
391
392
  1 if t == ("punct", "{") else -1 if t == ("punct", "}") else 0
392
- for t in (tokenize(s, ln) if s and not s.startswith("css") else [])
393
+ for t in (tokenize(counted, ln) if s and not s.startswith("css") else [])
393
394
  )
394
395
  if s.startswith("css") and "{" in s:
395
396
  depth += s.count("{") - s.count("}")
@@ -21,6 +21,7 @@ from .ir import Elem, Scene
21
21
  from .layout import SUB_GAP
22
22
  from .model import Document, Edge, Group, Node
23
23
  from .route import Diagonal, Router, flow_dir, lca
24
+ from .sketch import hatch, sketchify
24
25
  from .style import box4, px
25
26
  from .styleutil import LINE_H, accent, font_size, has_title_band, node_padding, text_block, title_position
26
27
 
@@ -302,10 +303,35 @@ class SceneBuilder:
302
303
  el.tracks = border_tracks(mode, sw, dash, dur)
303
304
  return [el]
304
305
 
306
+ def _sketch_on(self, st: dict) -> bool:
307
+ return st.get("sketch", self.doc.root.attrs.get("sketch", "0")).strip().lower() in ("1", "true", "yes", "on")
308
+
309
+ def sketched(self, elems: list[Elem], st: dict, seed: str) -> list[Elem]:
310
+ """`sketch: 1` (CSS, attribute or graph line): draw.io's hand-drawn look."""
311
+ if not self._sketch_on(st):
312
+ return elems
313
+ rough = px(st.get("roughness", self.doc.root.attrs.get("roughness")), 1.5)
314
+ out = []
315
+ for i, el in enumerate(elems):
316
+ out += [el] if el.kind == "text" or el.cls == "pdg-hatch" else sketchify(el, f"{seed}:{i}", rough)
317
+ return out
318
+
319
+ def hatched(self, it, st, body: list[Elem]) -> list[Elem]:
320
+ """`hatch: #333`: diagonal lines between the fill and the outline (reserved, unused)."""
321
+ color = st.get("hatch", "none").strip()
322
+ if color in ("none", "") or not body:
323
+ return body
324
+ lines = hatch(it.ax, it.ay, it.w, it.h, color, px(st.get("hatch-gap"), 10), px(st.get("hatch-width"), 1))
325
+ first = body[0]
326
+ fill = Elem(first.kind, cls=first.cls, geom=first.geom, paint={**first.paint, "stroke": "none"})
327
+ line = {k: v for k, v in first.paint.items() if k != "filter"} | {"fill": "none"}
328
+ return [fill, lines, Elem(first.kind, cls=first.cls, geom=first.geom, paint=line, tracks=first.tracks), *body[1:]]
329
+
305
330
  def node(self, n: Node) -> Elem:
306
331
  st = n.style
307
332
  shape = n.attrs.get("shape", "box")
308
- out = Elem("group", id=n.id, cls=" ".join(["pdg-node"] + n.classes), children=self.shape(n, shape, st))
333
+ body = self.hatched(n, st, self.shape(n, shape, st))
334
+ out = Elem("group", id=n.id, cls=" ".join(["pdg-node"] + n.classes), children=self.sketched(body, st, n.id))
309
335
  out.children += self.accent(n, st) + self.corner_marks(n, st)
310
336
  fs = font_size(st, 14)
311
337
  if n.image:
@@ -357,7 +383,7 @@ class SceneBuilder:
357
383
  cls=" ".join(["pdg-group"] + g.classes),
358
384
  children=self.shape(self._frame(g, st), g.attrs.get("shape", "box"), st),
359
385
  )
360
- out.children += self.accent(g, st)
386
+ out.children = self.sketched(out.children, st, g.id) + self.accent(g, st)
361
387
  if g.label and title_position(st) == "left":
362
388
  out.children.append(self._side_title(g, st))
363
389
  elif g.label:
@@ -601,8 +627,15 @@ class SceneBuilder:
601
627
  tracks=tracks,
602
628
  )
603
629
  )
604
- for kind, tip, dvec in heads:
605
- out.children.append(self.head(kind, tip, dvec, hl, color, width, self.doc.root.style.get("background", "#ffffff")))
630
+ out.children = self.sketched(out.children, st, e.id)
631
+ bg = self.doc.root.style.get("background", "#ffffff")
632
+ hs = [self.head(kind, tip, dvec, hl, color, width, bg) for kind, tip, dvec in heads]
633
+ if self._sketch_on(st): # outline filled heads so their edges wobble too
634
+ for h in hs:
635
+ if h.kind == "polygon" and h.paint.get("stroke", "none") == "none":
636
+ h.paint.update({"stroke": color, "stroke-width": width * 0.6})
637
+ hs = self.sketched(hs, st, e.id + ":head")
638
+ out.children += hs
606
639
  if e.label:
607
640
  lab = self.edge_label(e, self.edge_polys[e.id])
608
641
  out.children += lab
@@ -0,0 +1,140 @@
1
+ # SPDX-FileCopyrightText: 2026 Reza Jelveh
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """Hand-drawn look (draw.io ``sketch=1``) and hatch fills, as plain path geometry.
6
+
7
+ Sketch: every outline or edge is flattened to a polyline and redrawn as two
8
+ slightly wobbly bezier strokes, like draw.io's rough.js renderer. The wobble is
9
+ seeded from the element id, so the same diagram always draws the same way.
10
+ Hatch: diagonal lines clipped to a rectangle, computed here (no SVG patterns or
11
+ clip paths, so every renderer shows it the same).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ import random
18
+ import zlib
19
+
20
+ from .ir import Elem
21
+
22
+ Pt = tuple[float, float]
23
+
24
+
25
+ def flatten(segs) -> list[list[Pt]]:
26
+ """Path segments -> polylines (one per subpath). Curves are sampled, arcs become chords."""
27
+ out: list[list[Pt]] = []
28
+ cur: list[Pt] = []
29
+ for s in segs:
30
+ op = s[0]
31
+ if op == "M":
32
+ if len(cur) > 1:
33
+ out.append(cur)
34
+ cur = [(s[1], s[2])]
35
+ elif op == "L" or op == "A":
36
+ cur.append((s[-2], s[-1]))
37
+ elif op in ("Q", "C"):
38
+ p0, ctrl = cur[-1], [(s[i], s[i + 1]) for i in range(1, len(s), 2)]
39
+ for k in range(1, 9):
40
+ t = k / 8
41
+ pts = [p0, *ctrl]
42
+ while len(pts) > 1: # de Casteljau
43
+ pts = [(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t) for a, b in zip(pts, pts[1:])]
44
+ cur.append(pts[0])
45
+ elif op == "Z" and cur:
46
+ cur.append(cur[0])
47
+ if len(cur) > 1:
48
+ out.append(cur)
49
+ return out
50
+
51
+
52
+ def _simplify(poly: list[Pt]) -> list[Pt]:
53
+ """Merge nearly collinear points so a sampled curve wobbles as a few strokes, not many."""
54
+ out = [poly[0]]
55
+ for i in range(1, len(poly) - 1):
56
+ a, b, c = out[-1], poly[i], poly[i + 1]
57
+ cross = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
58
+ if abs(cross) > 0.04 * (math.dist(a, c) ** 2) or math.dist(a, b) > 160:
59
+ out.append(b)
60
+ out.append(poly[-1])
61
+ return out
62
+
63
+
64
+ def rough_segs(polys: list[list[Pt]], rng: random.Random, roughness: float) -> list:
65
+ """One wobbly pass: each straight run becomes a cubic with jittered ends and controls."""
66
+ segs: list = []
67
+ for poly in polys:
68
+ poly = _simplify(poly)
69
+ j = lambda r: rng.uniform(-r, r) # noqa: E731
70
+ x, y = poly[0]
71
+ segs.append(("M", x + j(roughness * 0.6), y + j(roughness * 0.6)))
72
+ for a, b in zip(poly, poly[1:]):
73
+ L = math.dist(a, b)
74
+ if L < 0.5:
75
+ continue
76
+ r = roughness * (1 + min(L, 400) / 50) # long strokes bow more, like rough.js
77
+ nx, ny = (a[1] - b[1]) / L, (b[0] - a[0]) / L # unit normal
78
+ c1, c2 = rng.uniform(-r, r), rng.uniform(-r, r)
79
+ p1 = (a[0] + (b[0] - a[0]) * 0.35 + nx * c1, a[1] + (b[1] - a[1]) * 0.35 + ny * c1)
80
+ p2 = (a[0] + (b[0] - a[0]) * 0.7 + nx * c2, a[1] + (b[1] - a[1]) * 0.7 + ny * c2)
81
+ segs.append(("C", *p1, *p2, b[0] + j(r * 0.5), b[1] + j(r * 0.5)))
82
+ return segs
83
+
84
+
85
+ def outline(el: Elem) -> list[list[Pt]] | None:
86
+ """Closed outline polylines of a shape element (rect corners are kept square)."""
87
+ g = el.geom
88
+ if el.kind == "rect":
89
+ x, y, w, h = g["x"], g["y"], g["w"], g["h"]
90
+ return [[(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)]]
91
+ if el.kind == "polygon":
92
+ pts = list(g["points"])
93
+ return [pts + pts[:1]]
94
+ if el.kind == "ellipse":
95
+ n = 16
96
+ return [
97
+ [(g["cx"] + g["rx"] * math.cos(2 * math.pi * k / n), g["cy"] + g["ry"] * math.sin(2 * math.pi * k / n)) for k in range(n + 1)]
98
+ ]
99
+ if el.kind == "path":
100
+ return flatten(g["segs"])
101
+ return None
102
+
103
+
104
+ def sketchify(el: Elem, seed: str, roughness: float = 1.5) -> list[Elem]:
105
+ """Replace a static element by its hand-drawn version: fill pass + two wobbly strokes.
106
+
107
+ Animated elements and anything without an outline are returned unchanged."""
108
+ polys = outline(el)
109
+ if polys is None or el.tracks or roughness <= 0:
110
+ return [el]
111
+ rng = random.Random(zlib.crc32(seed.encode()))
112
+ out = []
113
+ fill = el.paint.get("fill", "none")
114
+ stroke = el.paint.get("stroke", "none")
115
+ if fill not in ("none", "transparent"):
116
+ closed = [p for p in polys if math.dist(p[0], p[-1]) < 1]
117
+ if closed:
118
+ out.append(
119
+ Elem("path", cls=el.cls, geom={"segs": rough_segs(closed, rng, roughness * 0.4)}, paint={**el.paint, "stroke": "none"})
120
+ )
121
+ if stroke != "none":
122
+ line = {k: v for k, v in el.paint.items() if k not in ("fill", "filter")}
123
+ line.update({"fill": "none", "stroke-linecap": "round", "stroke-linejoin": "round"})
124
+ for _ in range(2):
125
+ out.append(Elem("path", cls=el.cls, geom={"segs": rough_segs(polys, rng, roughness)}, paint=dict(line)))
126
+ if el.paint.get("filter") and out:
127
+ out[0].paint["filter"] = el.paint["filter"]
128
+ return out or [el]
129
+
130
+
131
+ def hatch(x: float, y: float, w: float, h: float, color: str, gap: float = 8.0, width: float = 1.0) -> Elem:
132
+ """45° lines (bottom-left to top-right) clipped to the rectangle."""
133
+ segs = []
134
+ gap = max(2.0, gap)
135
+ c = gap / 2
136
+ while c < w + h: # the line where (px - x) + (py - y) = c, rising to the right on screen
137
+ u0, u1 = max(0.0, c - h), min(c, w)
138
+ segs += [("M", x + u0, y + c - u0), ("L", x + u1, y + c - u1)]
139
+ c += gap
140
+ return Elem("path", cls="pdg-hatch", geom={"segs": segs}, paint={"fill": "none", "stroke": color, "stroke-width": width})
@@ -151,8 +151,15 @@ BOX_KEYS = (
151
151
  "accent-side",
152
152
  "title-fill",
153
153
  "corner-marks",
154
+ "sketch",
155
+ "roughness",
156
+ "hatch",
157
+ "hatch-gap",
158
+ "hatch-width",
154
159
  )
155
160
  EDGE_KEYS = (
161
+ "sketch",
162
+ "roughness",
156
163
  "arrow",
157
164
  "head",
158
165
  "head-start",
@@ -57,6 +57,26 @@ def measure(text: str, family: str, size: float, bold: bool = False) -> tuple[fl
57
57
  return w, line_h * len(lines), lines
58
58
 
59
59
 
60
+ def load_icon(name: str, st: dict) -> dict:
61
+ """`icon=user`: a Lucide icon (needs `predictygraph[icons]`), coloured like the node:
62
+ `fill` fills it, `stroke`/`stroke-width` draw it (Lucide's 24 px grid)."""
63
+ try:
64
+ from lucide import lucide_icon
65
+ except ImportError as exc:
66
+ raise ValueError("icon= needs the Lucide icons: pip install 'predictygraph[icons]'") from exc
67
+ if not re.fullmatch(r"[a-z0-9-]{1,64}", name):
68
+ raise ValueError(f"bad icon name {name!r}")
69
+ svg = lucide_icon(
70
+ name,
71
+ fill=st.get("fill", "none"),
72
+ stroke=st.get("stroke", "currentColor"),
73
+ stroke_width=st.get("stroke-width", "1.5").removesuffix("px"),
74
+ )
75
+ if "data-missing-icon" in svg:
76
+ raise ValueError(f"unknown Lucide icon {name!r}")
77
+ return {"href": f"data:image/svg+xml;base64,{base64.b64encode(svg.encode()).decode()}", "w": 24.0, "h": 24.0}
78
+
79
+
60
80
  def load_image(path: str, base_dir: str, allow_outside: bool = False) -> dict:
61
81
  p = safe_path(base_dir, path, allow_outside)
62
82
  data = p.read_bytes()
@@ -62,7 +62,7 @@ def load_theme(name: str, base_dir: str = ".", _seen=()) -> dict:
62
62
  if data["extends"] in _seen:
63
63
  raise ThemeError(f"{path}: extends cycle")
64
64
  parent = load_theme(data["extends"], str(path.parent), _seen + (name,))
65
- for sect in ("palette", "roles", "shape"):
65
+ for sect in ("palette", "roles", "shape", "seaborn"): # [seaborn]: chart settings for decktile, unused here
66
66
  parent.setdefault(sect, {}).update(data.get(sect, {}))
67
67
  if "css" in data: # extra rules stack: parent's first, then the child's
68
68
  parent["css"] = parent.get("css", "") + "\n" + data["css"]
@@ -0,0 +1,63 @@
1
+ # SPDX-FileCopyrightText: 2026 Reza Jelveh
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """`sketch:` hand-drawn strokes, `hatch:` fills, Lucide `icon=`, `$var` classes in defs."""
6
+
7
+ import re
8
+
9
+ import pytest
10
+
11
+ from predictygraph import render
12
+ from predictygraph.sketch import hatch
13
+
14
+
15
+ def _node(svg, nid):
16
+ return svg.split(f'<g id="{nid}"', 1)[1].split("</g>", 1)[0]
17
+
18
+
19
+ def test_hatch_lines_stay_inside_the_box():
20
+ el = hatch(10, 20, 100, 50, "#333", gap=10)
21
+ pts = [(s[1], s[2]) for s in el.geom["segs"]]
22
+ assert len(pts) == 2 * 15 # (w + h) / gap lines
23
+ assert all(10 - 1e-6 <= x <= 110 + 1e-6 and 20 - 1e-6 <= y <= 70 + 1e-6 for x, y in pts)
24
+ for m, line in zip(el.geom["segs"][::2], el.geom["segs"][1::2]): # 45 degrees, rising
25
+ assert abs((line[1] - m[1]) + (line[2] - m[2])) < 1e-6
26
+
27
+
28
+ def test_hatch_draws_between_fill_and_outline():
29
+ svg = render('css { .w { hatch: #123456; } }\na "" .w width=80 height=60')
30
+ body = _node(svg, "a")
31
+ i_fill, i_hatch = body.index('stroke="none"'), body.index('stroke="#123456"')
32
+ assert i_fill < i_hatch < body.index('fill="none"', i_hatch + 1)
33
+
34
+
35
+ def test_sketch_is_deterministic_and_doubles_strokes():
36
+ src = "graph sketch=1\na -> b"
37
+ one, two = render(src), render(src)
38
+ assert one == two
39
+ edge = one.split('<g id="e0"', 1)[1].split("</g>", 1)[0]
40
+ assert len(re.findall(r"<path ", edge)) >= 2
41
+ assert " C " in edge
42
+
43
+
44
+ def test_sketch_off_by_default():
45
+ edge = render("a -> b").split('<g id="e0"', 1)[1].split("</g>", 1)[0]
46
+ assert len(re.findall(r"<path ", edge)) == 1
47
+
48
+
49
+ def test_lucide_icon():
50
+ pytest.importorskip("lucide")
51
+ svg = render('css { .u { fill: #ffe6cc; stroke: #d79b00; } }\nu "User" .u icon=user')
52
+ assert "data:image/svg+xml;base64," in _node(svg, "u")
53
+
54
+
55
+ def test_unknown_lucide_icon_is_an_error():
56
+ pytest.importorskip("lucide")
57
+ with pytest.raises(ValueError, match="unknown Lucide icon"):
58
+ render("u icon=no-such-icon-xyz")
59
+
60
+
61
+ def test_def_class_from_variable():
62
+ svg = render('css { .w { fill: #abcdef; } }\ndef g c=x {\n t "" .$c\n}\nuse g k c=w')
63
+ assert 'class="pdg-node w"' in svg
@@ -95,3 +95,11 @@ def test_align_x_keeps_gaps_by_moving_neighbours():
95
95
 
96
96
  assert abs(gap(doc) - gap(plain)) < 0.01 # b moved with a: the label still fits
97
97
  assert doc.items["a"].ax > plain.items["a"].ax
98
+
99
+
100
+ def test_extends_merges_seaborn_section(tmp_path):
101
+ from predictygraph.theme import load_theme
102
+
103
+ (tmp_path / "brand.toml").write_text('schema = 1\nextends = "hami"\n[seaborn]\npalette = ["blue"]\n')
104
+ t = load_theme("brand.toml", str(tmp_path))
105
+ assert t["seaborn"] == {"palette": ["blue"]} and t["palette"]["green"] == "#16a34a"
File without changes
File without changes