predictygraph 0.3.1__tar.gz → 0.3.3__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.1 → predictygraph-0.3.3}/PKG-INFO +3 -1
  2. {predictygraph-0.3.1 → predictygraph-0.3.3}/pyproject.toml +4 -1
  3. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/layout.py +7 -3
  4. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/parser.py +2 -1
  5. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/scene.py +63 -5
  6. predictygraph-0.3.3/src/predictygraph/sketch.py +143 -0
  7. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/style.py +7 -0
  8. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/text.py +20 -0
  9. predictygraph-0.3.3/tests/test_sketch.py +85 -0
  10. {predictygraph-0.3.1 → predictygraph-0.3.3}/LICENSE +0 -0
  11. {predictygraph-0.3.1 → predictygraph-0.3.3}/NOTICE +0 -0
  12. {predictygraph-0.3.1 → predictygraph-0.3.3}/README.md +0 -0
  13. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/__init__.py +0 -0
  14. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/__main__.py +0 -0
  15. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/anim.py +0 -0
  16. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/cli.py +0 -0
  17. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/default.css +0 -0
  18. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/Carlito-Bold.ttf +0 -0
  19. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/Carlito-Regular.ttf +0 -0
  20. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/DejaVuSans-Bold.ttf +0 -0
  21. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/DejaVuSans.ttf +0 -0
  22. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/LiberationMono-Bold.ttf +0 -0
  23. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/LiberationMono-Regular.ttf +0 -0
  24. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/LiberationSans-Bold.ttf +0 -0
  25. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/LiberationSans-Regular.ttf +0 -0
  26. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/LiberationSerif-Bold.ttf +0 -0
  27. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/LiberationSerif-Regular.ttf +0 -0
  28. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/licenses/Bitstream-Vera.txt +0 -0
  29. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/licenses/OFL-1.1.txt +0 -0
  30. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts/licenses/README.md +0 -0
  31. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/fonts.py +0 -0
  32. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/ir.py +0 -0
  33. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/model.py +0 -0
  34. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/render/__init__.py +0 -0
  35. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/render/apng.py +0 -0
  36. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/render/svg.py +0 -0
  37. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/route.py +0 -0
  38. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/safe.py +0 -0
  39. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/styleutil.py +0 -0
  40. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/theme.py +0 -0
  41. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/catppuccin-frappe.toml +0 -0
  42. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/catppuccin-latte.toml +0 -0
  43. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/catppuccin-macchiato.toml +0 -0
  44. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/catppuccin-mocha.toml +0 -0
  45. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/default.toml +0 -0
  46. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/dracula.toml +0 -0
  47. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/github-light.toml +0 -0
  48. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/gruvbox-dark.toml +0 -0
  49. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/hami.toml +0 -0
  50. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/nord.toml +0 -0
  51. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/solarized-dark.toml +0 -0
  52. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/solarized-light.toml +0 -0
  53. {predictygraph-0.3.1 → predictygraph-0.3.3}/src/predictygraph/themes/trunkline.toml +0 -0
  54. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_annotations.py +0 -0
  55. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_blocks.py +0 -0
  56. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_diagonal.py +0 -0
  57. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_fixes.py +0 -0
  58. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_hardening.py +0 -0
  59. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_predictygraph.py +0 -0
  60. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_routing.py +0 -0
  61. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_scene.py +0 -0
  62. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_stack.py +0 -0
  63. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_targets.py +0 -0
  64. {predictygraph-0.3.1 → predictygraph-0.3.3}/tests/test_trunkline.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: predictygraph
3
- Version: 0.3.1
3
+ Version: 0.3.3
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
  <!--
@@ -12,7 +12,7 @@ dependencies = [
12
12
  ]
13
13
  requires-python = ">=3.11"
14
14
  readme = "README.md"
15
- version = "0.3.1"
15
+ version = "0.3.3"
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,8 +21,10 @@ 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
27
+ from .text import load_image
26
28
 
27
29
  TITLE_PAD = 6.0
28
30
  ER_HEADS = ("one", "many", "zero-one", "zero-many", "one-many")
@@ -302,10 +304,35 @@ class SceneBuilder:
302
304
  el.tracks = border_tracks(mode, sw, dash, dur)
303
305
  return [el]
304
306
 
307
+ def _sketch_on(self, st: dict) -> bool:
308
+ return st.get("sketch", self.doc.root.attrs.get("sketch", "0")).strip().lower() in ("1", "true", "yes", "on")
309
+
310
+ def sketched(self, elems: list[Elem], st: dict, seed: str) -> list[Elem]:
311
+ """`sketch: 1` (CSS, attribute or graph line): draw.io's hand-drawn look."""
312
+ if not self._sketch_on(st):
313
+ return elems
314
+ rough = px(st.get("roughness", self.doc.root.attrs.get("roughness")), 1.5)
315
+ out = []
316
+ for i, el in enumerate(elems):
317
+ out += [el] if el.kind == "text" or el.cls == "pdg-hatch" else sketchify(el, f"{seed}:{i}", rough)
318
+ return out
319
+
320
+ def hatched(self, it, st, body: list[Elem]) -> list[Elem]:
321
+ """`hatch: #333`: diagonal lines between the fill and the outline (reserved, unused)."""
322
+ color = st.get("hatch", "none").strip()
323
+ if color in ("none", "") or not body:
324
+ return body
325
+ lines = hatch(it.ax, it.ay, it.w, it.h, color, px(st.get("hatch-gap"), 10), px(st.get("hatch-width"), 1))
326
+ first = body[0]
327
+ fill = Elem(first.kind, cls=first.cls, geom=first.geom, paint={**first.paint, "stroke": "none"})
328
+ line = {k: v for k, v in first.paint.items() if k != "filter"} | {"fill": "none"}
329
+ return [fill, lines, Elem(first.kind, cls=first.cls, geom=first.geom, paint=line, tracks=first.tracks), *body[1:]]
330
+
305
331
  def node(self, n: Node) -> Elem:
306
332
  st = n.style
307
333
  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))
334
+ body = self.hatched(n, st, self.shape(n, shape, st))
335
+ out = Elem("group", id=n.id, cls=" ".join(["pdg-node"] + n.classes), children=self.sketched(body, st, n.id))
309
336
  out.children += self.accent(n, st) + self.corner_marks(n, st)
310
337
  fs = font_size(st, 14)
311
338
  if n.image:
@@ -357,7 +384,7 @@ class SceneBuilder:
357
384
  cls=" ".join(["pdg-group"] + g.classes),
358
385
  children=self.shape(self._frame(g, st), g.attrs.get("shape", "box"), st),
359
386
  )
360
- out.children += self.accent(g, st)
387
+ out.children = self.sketched(out.children, st, g.id) + self.accent(g, st)
361
388
  if g.label and title_position(st) == "left":
362
389
  out.children.append(self._side_title(g, st))
363
390
  elif g.label:
@@ -601,13 +628,22 @@ class SceneBuilder:
601
628
  tracks=tracks,
602
629
  )
603
630
  )
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")))
631
+ out.children = self.sketched(out.children, st, e.id)
632
+ bg = self.doc.root.style.get("background", "#ffffff")
633
+ hs = [self.head(kind, tip, dvec, hl, color, width, bg) for kind, tip, dvec in heads]
634
+ if self._sketch_on(st): # outline filled heads so their edges wobble too
635
+ for h in hs:
636
+ if h.kind == "polygon" and h.paint.get("stroke", "none") == "none":
637
+ h.paint.update({"stroke": color, "stroke-width": width * 0.6})
638
+ hs = self.sketched(hs, st, e.id + ":head")
639
+ out.children += hs
606
640
  if e.label:
607
641
  lab = self.edge_label(e, self.edge_polys[e.id])
608
642
  out.children += lab
643
+ if e.attrs.get("image"):
644
+ out.children.append(self.edge_image(e, self.edge_polys[e.id]))
609
645
  if e.attrs.get("step"):
610
- box = lab[0].geom if e.label else None
646
+ box = lab[0].geom if e.label and lab[0].cls == "pdg-label-bg" else None
611
647
  out.children += self.step_badge(e, self.edge_polys[e.id], box)
612
648
  return out
613
649
 
@@ -739,6 +775,21 @@ class SceneBuilder:
739
775
  tag, pts, paint = shapes.get(kind, ("polygon", [P(0, 0), P(hl, hw), P(hl, -hw)], {"fill": color}))
740
776
  return Elem(tag, cls="pdg-head", geom={"points": pts}, paint=paint)
741
777
 
778
+ def edge_image(self, e, poly) -> Elem:
779
+ """`image=logo.png` on an edge: beside the middle of its longest run (right of a
780
+ vertical run, below a horizontal one), like a badge on a draw.io connector."""
781
+ img = load_image(e.attrs["image"], self.doc.base_dir, self.doc.allow_outside)
782
+ w = px(e.attrs.get("img-width"), 0) or min(img["w"], 48.0)
783
+ h = px(e.attrs.get("img-height"), 0) or w * img["h"] / (img["w"] or 1)
784
+ (ax, ay), (bx, by) = max(zip(poly, poly[1:]), key=lambda s: math.dist(*s))
785
+ mx, my = (ax + bx) / 2, (ay + by) / 2
786
+ gap = 8.0
787
+ if abs(bx - ax) < abs(by - ay):
788
+ x, y = mx + gap, my - h / 2
789
+ else:
790
+ x, y = mx - w / 2, my + gap
791
+ return Elem("image", cls="pdg-edge-image", geom={"x": x, "y": y, "w": w, "h": h, "href": img["href"]})
792
+
742
793
  def edge_label(self, e, poly) -> list[Elem]:
743
794
  st = e.label_style or e.style
744
795
  fs = font_size(st, 11)
@@ -748,6 +799,13 @@ class SceneBuilder:
748
799
  segs = list(zip(poly, poly[1:]))
749
800
  fits = len(segs) > 1 and math.dist(*segs[-1]) >= h + 4
750
801
  best = segs[-1] if fits else max(segs, key=lambda s: math.dist(*s))
802
+ at = e.attrs.get("label-at", "")
803
+ if at in ("start", "end") and len(segs) > 1: # sit above that run, clear of the line
804
+ (ax, ay), (bx, by) = segs[0] if at == "start" else segs[-1]
805
+ if abs(by - ay) < 0.5:
806
+ mx = max((ax + bx) / 2, min(ax, bx) + w / 2 + 4) # never back over the source
807
+ return self.text(lines, mx, ay - h - 6, fs, st)
808
+ best = segs[0] if at == "start" else segs[-1]
751
809
  (ax, ay), (bx, by) = best
752
810
  t = 0.5
753
811
  lvl = (
@@ -0,0 +1,143 @@
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 straight points so a sampled curve wobbles as a few strokes, not many.
54
+ A point is kept once the path turns more than ~15° there, so corners survive."""
55
+ out = [poly[0]]
56
+ for i in range(1, len(poly) - 1):
57
+ a, b, c = out[-1], poly[i], poly[i + 1]
58
+ h1 = math.atan2(b[1] - a[1], b[0] - a[0])
59
+ h2 = math.atan2(c[1] - b[1], c[0] - b[0])
60
+ turn = abs((h2 - h1 + math.pi) % (2 * math.pi) - math.pi)
61
+ if turn > 0.26 or math.dist(a, b) > 160:
62
+ out.append(b)
63
+ out.append(poly[-1])
64
+ return out
65
+
66
+
67
+ def rough_segs(polys: list[list[Pt]], rng: random.Random, roughness: float) -> list:
68
+ """One wobbly pass: each straight run becomes a cubic with jittered ends and controls."""
69
+ segs: list = []
70
+ for poly in polys:
71
+ poly = _simplify(poly)
72
+ j = lambda r: rng.uniform(-r, r) # noqa: E731
73
+ x, y = poly[0]
74
+ segs.append(("M", x + j(roughness * 0.6), y + j(roughness * 0.6)))
75
+ for a, b in zip(poly, poly[1:]):
76
+ L = math.dist(a, b)
77
+ if L < 0.5:
78
+ continue
79
+ r = roughness * (1 + min(L, 300) / 150) # long strokes bow a little more, like rough.js
80
+ nx, ny = (a[1] - b[1]) / L, (b[0] - a[0]) / L # unit normal
81
+ c1, c2 = rng.uniform(-r, r), rng.uniform(-r, r)
82
+ p1 = (a[0] + (b[0] - a[0]) * 0.35 + nx * c1, a[1] + (b[1] - a[1]) * 0.35 + ny * c1)
83
+ p2 = (a[0] + (b[0] - a[0]) * 0.7 + nx * c2, a[1] + (b[1] - a[1]) * 0.7 + ny * c2)
84
+ segs.append(("C", *p1, *p2, b[0] + j(r * 0.5), b[1] + j(r * 0.5)))
85
+ return segs
86
+
87
+
88
+ def outline(el: Elem) -> list[list[Pt]] | None:
89
+ """Closed outline polylines of a shape element (rect corners are kept square)."""
90
+ g = el.geom
91
+ if el.kind == "rect":
92
+ x, y, w, h = g["x"], g["y"], g["w"], g["h"]
93
+ return [[(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)]]
94
+ if el.kind == "polygon":
95
+ pts = list(g["points"])
96
+ return [pts + pts[:1]]
97
+ if el.kind == "ellipse":
98
+ n = 16
99
+ return [
100
+ [(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)]
101
+ ]
102
+ if el.kind == "path":
103
+ return flatten(g["segs"])
104
+ return None
105
+
106
+
107
+ def sketchify(el: Elem, seed: str, roughness: float = 1.5) -> list[Elem]:
108
+ """Replace a static element by its hand-drawn version: fill pass + two wobbly strokes.
109
+
110
+ Animated elements and anything without an outline are returned unchanged."""
111
+ polys = outline(el)
112
+ if polys is None or el.tracks or roughness <= 0:
113
+ return [el]
114
+ rng = random.Random(zlib.crc32(seed.encode()))
115
+ out = []
116
+ fill = el.paint.get("fill", "none")
117
+ stroke = el.paint.get("stroke", "none")
118
+ if fill not in ("none", "transparent"):
119
+ closed = [p for p in polys if math.dist(p[0], p[-1]) < 1]
120
+ if closed:
121
+ out.append(
122
+ Elem("path", cls=el.cls, geom={"segs": rough_segs(closed, rng, roughness * 0.4)}, paint={**el.paint, "stroke": "none"})
123
+ )
124
+ if stroke != "none":
125
+ line = {k: v for k, v in el.paint.items() if k not in ("fill", "filter")}
126
+ line.update({"fill": "none", "stroke-linecap": "round", "stroke-linejoin": "round"})
127
+ for _ in range(2):
128
+ out.append(Elem("path", cls=el.cls, geom={"segs": rough_segs(polys, rng, roughness)}, paint=dict(line)))
129
+ if el.paint.get("filter") and out:
130
+ out[0].paint["filter"] = el.paint["filter"]
131
+ return out or [el]
132
+
133
+
134
+ def hatch(x: float, y: float, w: float, h: float, color: str, gap: float = 8.0, width: float = 1.0) -> Elem:
135
+ """45° lines (bottom-left to top-right) clipped to the rectangle."""
136
+ segs = []
137
+ gap = max(2.0, gap)
138
+ c = gap / 2
139
+ while c < w + h: # the line where (px - x) + (py - y) = c, rising to the right on screen
140
+ u0, u1 = max(0.0, c - h), min(c, w)
141
+ segs += [("M", x + u0, y + c - u0), ("L", x + u1, y + c - u1)]
142
+ c += gap
143
+ 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()
@@ -0,0 +1,85 @@
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
64
+
65
+
66
+ def test_edge_image(tmp_path):
67
+ from PIL import Image
68
+
69
+ Image.new("RGBA", (10, 10), "green").save(tmp_path / "logo.png")
70
+ (tmp_path / "d.pdg").write_text("a -> b image=logo.png img-width=20")
71
+ svg = render((tmp_path / "d.pdg").read_text(), base_dir=str(tmp_path))
72
+ edge = svg.split('<g id="e0"', 1)[1].split("</g>", 1)[0]
73
+ assert 'class="pdg-edge-image"' in edge and 'width="20"' in edge
74
+
75
+
76
+ def test_sketch_keeps_corners():
77
+ svg = render("graph route=ortho\na\nb at=0,0\na -> b exit=right enter=top sketch=1 roughness=0.01")
78
+ edge = svg.split('<g id="e0"', 1)[1].split("</g>", 1)[0]
79
+ assert edge.count(" C ") >= 4 # two passes x at least two runs
80
+
81
+
82
+ def test_label_at_start_has_no_background():
83
+ svg = render('graph route=ortho\na\nb\na -> b "x" exit=right enter=top label-at=start')
84
+ edge = svg.split('<g id="e0"', 1)[1].split("</g>", 1)[0]
85
+ assert "pdg-label-bg" not in edge and ">x<" in edge
File without changes
File without changes
File without changes