pyramz 0.4.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.
- pyramz/__init__.py +217 -0
- pyramz/_paths.py +190 -0
- pyramz/_registry.py +1023 -0
- pyramz/_render.py +159 -0
- pyramz/_shapes.py +199 -0
- pyramz/cli.py +109 -0
- pyramz/gallery.py +98 -0
- pyramz/py.typed +0 -0
- pyramz-0.4.0.dist-info/METADATA +121 -0
- pyramz-0.4.0.dist-info/RECORD +14 -0
- pyramz-0.4.0.dist-info/WHEEL +5 -0
- pyramz-0.4.0.dist-info/entry_points.txt +2 -0
- pyramz-0.4.0.dist-info/licenses/LICENSE +202 -0
- pyramz-0.4.0.dist-info/top_level.txt +1 -0
pyramz/__init__.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Pyramz: original, duotone-ready SVG icons for Python.
|
|
2
|
+
|
|
3
|
+
>>> import pyramz
|
|
4
|
+
>>> svg = pyramz.icon("home", size=32, style="duotone", accent="#6366f1")
|
|
5
|
+
>>> str(svg)[:4]
|
|
6
|
+
'<svg'
|
|
7
|
+
>>> pyramz.icons.search(size=20) # attribute-style access
|
|
8
|
+
<pyramz.Icon 'search'>
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import difflib
|
|
14
|
+
from collections.abc import Iterable
|
|
15
|
+
from html import escape
|
|
16
|
+
|
|
17
|
+
from ._registry import aliases as _aliases
|
|
18
|
+
from ._registry import registry as _registry
|
|
19
|
+
from ._render import Icon
|
|
20
|
+
from ._render import render as _render
|
|
21
|
+
from ._shapes import IconDef, P
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"Icon",
|
|
25
|
+
"icon",
|
|
26
|
+
"names",
|
|
27
|
+
"search",
|
|
28
|
+
"categories",
|
|
29
|
+
"info",
|
|
30
|
+
"icons",
|
|
31
|
+
"aliases",
|
|
32
|
+
"sprite",
|
|
33
|
+
"set_defaults",
|
|
34
|
+
"reset_defaults",
|
|
35
|
+
"register",
|
|
36
|
+
"__version__",
|
|
37
|
+
]
|
|
38
|
+
__version__ = "0.4.0"
|
|
39
|
+
|
|
40
|
+
_FACTORY_DEFAULTS: dict[str, object] = {
|
|
41
|
+
"size": 24,
|
|
42
|
+
"color": "currentColor",
|
|
43
|
+
"stroke_width": 1.75,
|
|
44
|
+
"style": "outline",
|
|
45
|
+
"corners": "round",
|
|
46
|
+
}
|
|
47
|
+
_defaults: dict[str, object] = dict(_FACTORY_DEFAULTS)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _normalise(name: str) -> str:
|
|
51
|
+
return name.strip().lower().replace("_", "-").replace(" ", "-")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _get(name: str) -> IconDef:
|
|
55
|
+
key = _normalise(name)
|
|
56
|
+
key = _aliases().get(key, key)
|
|
57
|
+
reg = _registry()
|
|
58
|
+
if key not in reg:
|
|
59
|
+
close = difflib.get_close_matches(key, [*reg.keys(), *_aliases()], n=3, cutoff=0.55)
|
|
60
|
+
hint = f" Did you mean: {', '.join(close)}?" if close else ""
|
|
61
|
+
raise KeyError(f"Unknown icon {name!r}.{hint}")
|
|
62
|
+
return reg[key]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def icon(name: str, **options) -> Icon:
|
|
66
|
+
"""Render an icon by name.
|
|
67
|
+
|
|
68
|
+
Options: size, color, stroke_width, style ("outline" | "duotone"),
|
|
69
|
+
accent, accent_opacity, corners ("round" | "sharp"), absolute_stroke,
|
|
70
|
+
title (adds an accessible <title>), class_, plus any extra SVG
|
|
71
|
+
attribute (underscores become dashes, e.g. ``data_testid="x"``).
|
|
72
|
+
"""
|
|
73
|
+
merged = {**_defaults, **options}
|
|
74
|
+
return _render(_get(name), **merged)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def names(category: str | None = None) -> list[str]:
|
|
78
|
+
reg = _registry()
|
|
79
|
+
return sorted(n for n, d in reg.items() if category is None or d.category == category)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def aliases() -> dict[str, str]:
|
|
83
|
+
"""Alternative names mapped to Pyramz icon names."""
|
|
84
|
+
return dict(_aliases())
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def categories() -> list[str]:
|
|
88
|
+
return sorted({d.category for d in _registry().values()})
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def info(name: str) -> dict[str, object]:
|
|
92
|
+
d = _get(name)
|
|
93
|
+
return {"name": d.name, "category": d.category, "tags": list(d.tags)}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def search(query: str, limit: int = 20) -> list[str]:
|
|
97
|
+
"""Rank icons by name, tag and category match (with fuzzy fallback)."""
|
|
98
|
+
q = _normalise(query)
|
|
99
|
+
if not q:
|
|
100
|
+
return []
|
|
101
|
+
scored = []
|
|
102
|
+
target = _aliases().get(q)
|
|
103
|
+
for d in _registry().values():
|
|
104
|
+
if d.name == target:
|
|
105
|
+
scored.append((-90, d.name))
|
|
106
|
+
continue
|
|
107
|
+
score = 0
|
|
108
|
+
if d.name == q:
|
|
109
|
+
score = 100
|
|
110
|
+
elif d.name.startswith(q):
|
|
111
|
+
score = 80
|
|
112
|
+
elif q in d.name:
|
|
113
|
+
score = 60
|
|
114
|
+
elif q in d.tags:
|
|
115
|
+
score = 50
|
|
116
|
+
elif any(t.startswith(q) for t in d.tags):
|
|
117
|
+
score = 35
|
|
118
|
+
elif q == d.category:
|
|
119
|
+
score = 20
|
|
120
|
+
else:
|
|
121
|
+
words = (d.name, *d.tags)
|
|
122
|
+
if difflib.get_close_matches(q, words, n=1, cutoff=0.8):
|
|
123
|
+
score = 10
|
|
124
|
+
if score:
|
|
125
|
+
scored.append((-score, d.name))
|
|
126
|
+
# fuzzy (typo) matches are only a fallback when nothing matched directly
|
|
127
|
+
if any(-s > 10 for s, _ in scored):
|
|
128
|
+
scored = [(s, n) for s, n in scored if -s > 10]
|
|
129
|
+
return [n for _, n in sorted(scored)[:limit]]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def set_defaults(**options) -> None:
|
|
133
|
+
"""Set project-wide defaults, e.g. ``set_defaults(stroke_width=1.5)``."""
|
|
134
|
+
unknown = set(options) - {
|
|
135
|
+
"size",
|
|
136
|
+
"color",
|
|
137
|
+
"stroke_width",
|
|
138
|
+
"style",
|
|
139
|
+
"accent",
|
|
140
|
+
"accent_opacity",
|
|
141
|
+
"corners",
|
|
142
|
+
"absolute_stroke",
|
|
143
|
+
"class_",
|
|
144
|
+
}
|
|
145
|
+
if unknown:
|
|
146
|
+
raise TypeError(f"Unknown default(s): {', '.join(sorted(unknown))}")
|
|
147
|
+
_defaults.update(options)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def reset_defaults() -> None:
|
|
151
|
+
_defaults.clear()
|
|
152
|
+
_defaults.update(_FACTORY_DEFAULTS)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def register(
|
|
156
|
+
name: str, paths: Iterable[str], *, category: str = "custom", tags: Iterable[str] = (), tone: Iterable[int] = ()
|
|
157
|
+
) -> None:
|
|
158
|
+
"""Add your own icon to the set at runtime.
|
|
159
|
+
|
|
160
|
+
``paths`` are SVG path ``d`` strings on a 24x24 grid; ``tone`` lists the
|
|
161
|
+
indexes of paths that should be tinted in the duotone style.
|
|
162
|
+
"""
|
|
163
|
+
key = _normalise(name)
|
|
164
|
+
reg = _registry()
|
|
165
|
+
if key in reg or key in _aliases():
|
|
166
|
+
raise ValueError(f"Icon {key!r} already exists")
|
|
167
|
+
tone_idx = set(tone)
|
|
168
|
+
shapes = tuple(P(d, tone=i in tone_idx) for i, d in enumerate(paths))
|
|
169
|
+
if not shapes:
|
|
170
|
+
raise ValueError("register() needs at least one path")
|
|
171
|
+
reg[key] = IconDef(key, category, tuple(tags), shapes)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def sprite(icon_names: Iterable[str] | None = None, *, prefix: str = "pyramz-", **options) -> str:
|
|
175
|
+
"""Build an SVG sprite sheet of <symbol>s for ``<use href="#pyramz-home"/>``.
|
|
176
|
+
|
|
177
|
+
Embed it once per page; each use costs a few bytes instead of a full SVG.
|
|
178
|
+
"""
|
|
179
|
+
options.pop("size", None)
|
|
180
|
+
out = ['<svg xmlns="http://www.w3.org/2000/svg" style="display:none">']
|
|
181
|
+
for n in icon_names or names():
|
|
182
|
+
svg = str(icon(n, **options))
|
|
183
|
+
inner = svg[svg.index(">") + 1 : -len("</svg>")]
|
|
184
|
+
opts = {**_defaults, **options}
|
|
185
|
+
round_ = opts["corners"] == "round"
|
|
186
|
+
join = 'stroke-linejoin="round"' if round_ else 'stroke-linejoin="miter" stroke-miterlimit="4"'
|
|
187
|
+
cap = "round" if round_ else "square"
|
|
188
|
+
out.append(
|
|
189
|
+
f'<symbol id="{escape(prefix + _normalise(n))}" viewBox="0 0 24 24" fill="none" '
|
|
190
|
+
f'stroke="{escape(str(opts["color"]))}" stroke-width="{float(opts["stroke_width"]):g}" '
|
|
191
|
+
f'stroke-linecap="{cap}" {join}>{inner}</symbol>'
|
|
192
|
+
)
|
|
193
|
+
out.append("</svg>")
|
|
194
|
+
return "".join(out)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class _Namespace:
|
|
198
|
+
"""``pyramz.icons.arrow_right(size=20)``: attribute-style access with
|
|
199
|
+
tab completion in IPython."""
|
|
200
|
+
|
|
201
|
+
def __getattr__(self, attr: str):
|
|
202
|
+
if attr.startswith("__"):
|
|
203
|
+
raise AttributeError(attr)
|
|
204
|
+
definition = _get(attr)
|
|
205
|
+
|
|
206
|
+
def _make(**options) -> Icon:
|
|
207
|
+
return icon(definition.name, **options)
|
|
208
|
+
|
|
209
|
+
_make.__name__ = attr
|
|
210
|
+
_make.__doc__ = f"Render the '{definition.name}' icon."
|
|
211
|
+
return _make
|
|
212
|
+
|
|
213
|
+
def __dir__(self):
|
|
214
|
+
return [n.replace("-", "_") for n in names()]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
icons = _Namespace()
|
pyramz/_paths.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Minimal SVG path parsing, used to derive the ``corners="sharp"`` variant.
|
|
2
|
+
|
|
3
|
+
Every icon is drawn once, with round corners. In sharp mode, each
|
|
4
|
+
quarter-circle corner (an elliptical-arc segment with equal radii of at most
|
|
5
|
+
``MAX_CORNER`` that turns exactly 90 degrees) is tightened to ``SHARP_RADIUS``
|
|
6
|
+
around the same corner point. Large arcs (rings, curves) are left untouched.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from functools import lru_cache
|
|
13
|
+
|
|
14
|
+
SHARP_RADIUS = 0.75
|
|
15
|
+
MAX_CORNER = 5.0
|
|
16
|
+
_EPS = 0.06
|
|
17
|
+
|
|
18
|
+
_TOKEN = re.compile(r"[MmLlHhVvCcSsQqTtAaZz]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?")
|
|
19
|
+
_ARGS = {"M": 2, "L": 2, "H": 1, "V": 1, "C": 6, "S": 4, "Q": 4, "T": 2, "A": 7, "Z": 0}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _fmt(v: float) -> str:
|
|
23
|
+
s = f"{v:.3f}".rstrip("0").rstrip(".")
|
|
24
|
+
return "0" if s in ("-0", "") else s
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _tokens(d: str) -> list[str]:
|
|
28
|
+
out: list[str] = []
|
|
29
|
+
i = 0
|
|
30
|
+
while i < len(d):
|
|
31
|
+
m = _TOKEN.match(d, i)
|
|
32
|
+
if m is None:
|
|
33
|
+
i += 1 # separators: spaces and commas
|
|
34
|
+
continue
|
|
35
|
+
out.append(m.group())
|
|
36
|
+
i = m.end()
|
|
37
|
+
return out
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def to_absolute(d: str) -> list[tuple[str, list[float]]]:
|
|
41
|
+
"""Parse ``d`` into absolute segments: M L C Q A Z (H/V/S/T are expanded)."""
|
|
42
|
+
toks = _tokens(d)
|
|
43
|
+
segs: list[tuple[str, list[float]]] = []
|
|
44
|
+
cx = cy = sx = sy = 0.0
|
|
45
|
+
last_ctrl = None
|
|
46
|
+
i, cmd = 0, None
|
|
47
|
+
while i < len(toks):
|
|
48
|
+
if toks[i].isalpha():
|
|
49
|
+
cmd = toks[i]
|
|
50
|
+
i += 1
|
|
51
|
+
if cmd in "Zz":
|
|
52
|
+
segs.append(("Z", []))
|
|
53
|
+
cx, cy = sx, sy
|
|
54
|
+
last_ctrl = None
|
|
55
|
+
continue
|
|
56
|
+
if cmd is None:
|
|
57
|
+
raise ValueError(f"path data must start with a command: {d!r}")
|
|
58
|
+
up = cmd.upper()
|
|
59
|
+
n = _ARGS[up]
|
|
60
|
+
vals = [float(t) for t in toks[i : i + n]]
|
|
61
|
+
if len(vals) < n:
|
|
62
|
+
raise ValueError(f"incomplete path data: {d!r}")
|
|
63
|
+
i += n
|
|
64
|
+
rel = cmd.islower()
|
|
65
|
+
if up == "M":
|
|
66
|
+
x, y = vals
|
|
67
|
+
if rel:
|
|
68
|
+
x, y = cx + x, cy + y
|
|
69
|
+
segs.append(("M", [x, y]))
|
|
70
|
+
cx, cy = sx, sy = x, y
|
|
71
|
+
cmd = "l" if rel else "L" # implicit lineto after moveto
|
|
72
|
+
last_ctrl = None
|
|
73
|
+
elif up in "LHV":
|
|
74
|
+
if up == "L":
|
|
75
|
+
x, y = vals
|
|
76
|
+
if rel:
|
|
77
|
+
x, y = cx + x, cy + y
|
|
78
|
+
elif up == "H":
|
|
79
|
+
x, y = (cx + vals[0] if rel else vals[0]), cy
|
|
80
|
+
else:
|
|
81
|
+
x, y = cx, (cy + vals[0] if rel else vals[0])
|
|
82
|
+
segs.append(("L", [x, y]))
|
|
83
|
+
cx, cy = x, y
|
|
84
|
+
last_ctrl = None
|
|
85
|
+
elif up in "CS":
|
|
86
|
+
if up == "C":
|
|
87
|
+
x1, y1, x2, y2, x, y = vals
|
|
88
|
+
if rel:
|
|
89
|
+
x1, y1, x2, y2, x, y = cx + x1, cy + y1, cx + x2, cy + y2, cx + x, cy + y
|
|
90
|
+
else:
|
|
91
|
+
x2, y2, x, y = vals
|
|
92
|
+
if rel:
|
|
93
|
+
x2, y2, x, y = cx + x2, cy + y2, cx + x, cy + y
|
|
94
|
+
x1, y1 = (2 * cx - last_ctrl[0], 2 * cy - last_ctrl[1]) if last_ctrl else (cx, cy)
|
|
95
|
+
segs.append(("C", [x1, y1, x2, y2, x, y]))
|
|
96
|
+
last_ctrl = (x2, y2)
|
|
97
|
+
cx, cy = x, y
|
|
98
|
+
elif up in "QT":
|
|
99
|
+
if up == "Q":
|
|
100
|
+
x1, y1, x, y = vals
|
|
101
|
+
if rel:
|
|
102
|
+
x1, y1, x, y = cx + x1, cy + y1, cx + x, cy + y
|
|
103
|
+
else:
|
|
104
|
+
x, y = vals
|
|
105
|
+
if rel:
|
|
106
|
+
x, y = cx + x, cy + y
|
|
107
|
+
x1, y1 = (2 * cx - last_ctrl[0], 2 * cy - last_ctrl[1]) if last_ctrl else (cx, cy)
|
|
108
|
+
segs.append(("Q", [x1, y1, x, y]))
|
|
109
|
+
last_ctrl = (x1, y1)
|
|
110
|
+
cx, cy = x, y
|
|
111
|
+
else: # A
|
|
112
|
+
rx, ry, rot, large, sweep, x, y = vals
|
|
113
|
+
if rel:
|
|
114
|
+
x, y = cx + x, cy + y
|
|
115
|
+
segs.append(("A", [rx, ry, rot, large, sweep, x, y]))
|
|
116
|
+
cx, cy = x, y
|
|
117
|
+
last_ctrl = None
|
|
118
|
+
return segs
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def to_string(segs: list[tuple[str, list[float]]]) -> str:
|
|
122
|
+
return "".join(c + " ".join(_fmt(v) for v in vals) for c, vals in segs)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _quarter_corner(p0, seg):
|
|
126
|
+
"""If ``seg`` (an absolute A from ``p0``) is a 90-degree corner arc,
|
|
127
|
+
return (corner_point, sweep); otherwise None."""
|
|
128
|
+
rx, ry, rot, large, sweep, x, y = seg
|
|
129
|
+
if abs(rx - ry) > _EPS or rx > MAX_CORNER or rx <= SHARP_RADIUS or large or abs(rot) > _EPS:
|
|
130
|
+
return None
|
|
131
|
+
dx, dy = x - p0[0], y - p0[1]
|
|
132
|
+
if abs(abs(dx) - rx) > _EPS or abs(abs(dy) - rx) > _EPS:
|
|
133
|
+
return None
|
|
134
|
+
for centre, corner in (((p0[0], y), (x, p0[1])), ((x, p0[1]), (p0[0], y))):
|
|
135
|
+
a = (p0[0] - centre[0], p0[1] - centre[1])
|
|
136
|
+
b = (x - centre[0], y - centre[1])
|
|
137
|
+
cross = a[0] * b[1] - a[1] * b[0]
|
|
138
|
+
if (cross > 0) == bool(sweep):
|
|
139
|
+
return corner, sweep
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@lru_cache(maxsize=4096)
|
|
144
|
+
def sharpen(d: str, radius: float = SHARP_RADIUS) -> str:
|
|
145
|
+
"""Return ``d`` with every small quarter-circle corner tightened to ``radius``."""
|
|
146
|
+
segs = to_absolute(d)
|
|
147
|
+
out: list[tuple[str, list[float]]] = []
|
|
148
|
+
cur = (0.0, 0.0)
|
|
149
|
+
start = cur
|
|
150
|
+
changed = False
|
|
151
|
+
for cmd, vals in segs:
|
|
152
|
+
if cmd == "A":
|
|
153
|
+
hit = _quarter_corner(cur, vals)
|
|
154
|
+
if hit:
|
|
155
|
+
(vx, vy), sweep = hit
|
|
156
|
+
r = vals[0]
|
|
157
|
+
k = radius / r
|
|
158
|
+
ax, ay = vx + (cur[0] - vx) * k, vy + (cur[1] - vy) * k
|
|
159
|
+
ex, ey = vals[5], vals[6]
|
|
160
|
+
bx, by = vx + (ex - vx) * k, vy + (ey - vy) * k
|
|
161
|
+
out += [("L", [ax, ay]), ("A", [radius, radius, 0, 0, sweep, bx, by]), ("L", [ex, ey])]
|
|
162
|
+
cur = (ex, ey)
|
|
163
|
+
changed = True
|
|
164
|
+
continue
|
|
165
|
+
out.append((cmd, vals))
|
|
166
|
+
if cmd == "M":
|
|
167
|
+
cur = start = (vals[0], vals[1])
|
|
168
|
+
elif cmd == "Z":
|
|
169
|
+
cur = start
|
|
170
|
+
else:
|
|
171
|
+
cur = (vals[-2], vals[-1])
|
|
172
|
+
return to_string(out) if changed else d
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def corner_arcs(d: str) -> int:
|
|
176
|
+
"""Number of corners ``sharpen`` would tighten (used in tests)."""
|
|
177
|
+
segs = to_absolute(d)
|
|
178
|
+
cur = (0.0, 0.0)
|
|
179
|
+
start = cur
|
|
180
|
+
n = 0
|
|
181
|
+
for cmd, vals in segs:
|
|
182
|
+
if cmd == "A" and _quarter_corner(cur, vals):
|
|
183
|
+
n += 1
|
|
184
|
+
if cmd == "M":
|
|
185
|
+
cur = start = (vals[0], vals[1])
|
|
186
|
+
elif cmd == "Z":
|
|
187
|
+
cur = start
|
|
188
|
+
else:
|
|
189
|
+
cur = (vals[-2], vals[-1]) if vals else cur
|
|
190
|
+
return n
|