figurekit 0.5.1__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.
- figkit/__init__.py +141 -0
- figkit/access.py +144 -0
- figkit/check.py +227 -0
- figkit/cli.py +180 -0
- figkit/export.py +366 -0
- figkit/fonts/BricolageGrotesque-Regular.ttf +0 -0
- figkit/fonts/BricolageGrotesque-SemiBold.ttf +0 -0
- figkit/fonts/JetBrainsMono-Regular.ttf +0 -0
- figkit/fonts/JetBrainsMono-SemiBold.ttf +0 -0
- figkit/fonts/OFL-BricolageGrotesque.txt +93 -0
- figkit/fonts/OFL-JetBrainsMono.txt +93 -0
- figkit/helpers.py +404 -0
- figkit/language.py +126 -0
- figkit/manifest.py +188 -0
- figkit/preview.py +103 -0
- figkit/project.py +173 -0
- figkit/py.typed +0 -0
- figkit/theme.py +524 -0
- figkit/tokens.json +52 -0
- figkit/tokens.schema.json +95 -0
- figurekit-0.5.1.dist-info/METADATA +439 -0
- figurekit-0.5.1.dist-info/RECORD +27 -0
- figurekit-0.5.1.dist-info/WHEEL +4 -0
- figurekit-0.5.1.dist-info/entry_points.txt +2 -0
- figurekit-0.5.1.dist-info/licenses/LICENSE +21 -0
- figurekit-0.5.1.dist-info/licenses/src/figkit/fonts/OFL-BricolageGrotesque.txt +93 -0
- figurekit-0.5.1.dist-info/licenses/src/figkit/fonts/OFL-JetBrainsMono.txt +93 -0
figkit/theme.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
"""Themes and the matplotlib defaults that turn them into a figure style."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from functools import cache
|
|
9
|
+
from importlib import resources
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from types import MappingProxyType
|
|
12
|
+
from typing import Any, cast
|
|
13
|
+
|
|
14
|
+
import matplotlib.pyplot as plt
|
|
15
|
+
from cycler import cycler
|
|
16
|
+
from matplotlib import font_manager
|
|
17
|
+
|
|
18
|
+
FONTS = Path(str(resources.files("figkit") / "fonts"))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
TOKENS = Path(str(resources.files("figkit") / "tokens.json"))
|
|
22
|
+
SCHEMA = Path(str(resources.files("figkit") / "tokens.schema.json"))
|
|
23
|
+
_HEX = re.compile(r"^#[0-9a-fA-F]{6}$")
|
|
24
|
+
_COLOURS = ("surface", "ink", "secondary", "muted", "grid", "axis")
|
|
25
|
+
_LISTS = ("pages", "series", "ramp")
|
|
26
|
+
_STATUS = ("good", "warning", "serious", "critical")
|
|
27
|
+
_SIZES = ("size", "title", "label", "tick", "annotation", "minimum")
|
|
28
|
+
# Custom property of a stylesheet and the token it equals in both themes: (key, list index).
|
|
29
|
+
CSS_TOKENS: Mapping[str, tuple[str, int | None]] = MappingProxyType(
|
|
30
|
+
{
|
|
31
|
+
"bg": ("pages", 0),
|
|
32
|
+
"surface": ("surface", None),
|
|
33
|
+
"text": ("ink", None),
|
|
34
|
+
"muted": ("secondary", None),
|
|
35
|
+
"border": ("grid", None),
|
|
36
|
+
"border-strong": ("muted", None),
|
|
37
|
+
}
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class StyleError(ValueError):
|
|
42
|
+
"""A tokens file that does not describe a valid style.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
problems: Every problem found, each starting with the path of the value in the file,
|
|
46
|
+
such as ``themes.dark.series[2]: 'blue' is not a #rrggbb colour``.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, source: str, problems: Sequence[str]) -> None:
|
|
50
|
+
self.problems = tuple(problems)
|
|
51
|
+
super().__init__(f"{source}: invalid style\n" + "\n".join(f" {p}" for p in problems))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True, slots=True)
|
|
55
|
+
class Typography:
|
|
56
|
+
"""Font families and sizes in pt of one style.
|
|
57
|
+
|
|
58
|
+
Attributes:
|
|
59
|
+
sans: Family of text.
|
|
60
|
+
mono: Family of numbers and identifiers.
|
|
61
|
+
size: Default size of text.
|
|
62
|
+
title: Size of titles.
|
|
63
|
+
label: Size of axis labels, legends and subtitles.
|
|
64
|
+
tick: Size of tick labels.
|
|
65
|
+
annotation: Size of values and annotations on the plot.
|
|
66
|
+
minimum: Smallest size allowed; :func:`figkit.render` fails below it.
|
|
67
|
+
files: Font files of both families. Empty means the fonts bundled with figkit.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
sans: str
|
|
71
|
+
mono: str
|
|
72
|
+
size: float
|
|
73
|
+
title: float
|
|
74
|
+
label: float
|
|
75
|
+
tick: float
|
|
76
|
+
annotation: float
|
|
77
|
+
minimum: float
|
|
78
|
+
files: tuple[Path, ...] = ()
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def from_tokens(cls, raw: Mapping[str, Any], files: Sequence[Path] = ()) -> "Typography":
|
|
82
|
+
"""Typography of the ``font`` section of a tokens file that is already valid."""
|
|
83
|
+
return cls(
|
|
84
|
+
sans=raw["sans"],
|
|
85
|
+
mono=raw["mono"],
|
|
86
|
+
size=float(raw["size"]),
|
|
87
|
+
title=float(raw["title"]),
|
|
88
|
+
label=float(raw["label"]),
|
|
89
|
+
tick=float(raw["tick"]),
|
|
90
|
+
annotation=float(raw["annotation"]),
|
|
91
|
+
minimum=float(raw["minimum"]),
|
|
92
|
+
files=tuple(files),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True, slots=True)
|
|
97
|
+
class Theme:
|
|
98
|
+
"""Colours of one page mode.
|
|
99
|
+
|
|
100
|
+
Attributes:
|
|
101
|
+
name: Name of the mode, such as ``light`` or ``dark``. The files of the default theme of
|
|
102
|
+
the style have no suffix, every other theme adds ``-<name>``.
|
|
103
|
+
surface: Background of opaque output. Transparent output replaces it with ``none``.
|
|
104
|
+
pages: Page colours the transparent output is meant for; the colours were checked on them.
|
|
105
|
+
ink: Titles and values.
|
|
106
|
+
secondary: Axis labels, tick labels, legends and annotations.
|
|
107
|
+
muted: Reference lines and other marks that are not text.
|
|
108
|
+
grid: Hairline grid.
|
|
109
|
+
axis: Spines and baselines.
|
|
110
|
+
series: Categorical colours, used in this fixed order.
|
|
111
|
+
ramp: Sequential ramp from low to high, for heatmaps and confusion matrices.
|
|
112
|
+
status: ``good``, ``warning``, ``serious`` and ``critical``. Never used for a series.
|
|
113
|
+
Read-only and left out of the hash, so themes can be keys of a dict or a cache.
|
|
114
|
+
type: Fonts and sizes; every helper takes them from the theme it receives.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
name: str
|
|
118
|
+
surface: str
|
|
119
|
+
pages: tuple[str, ...]
|
|
120
|
+
ink: str
|
|
121
|
+
secondary: str
|
|
122
|
+
muted: str
|
|
123
|
+
grid: str
|
|
124
|
+
axis: str
|
|
125
|
+
series: tuple[str, ...]
|
|
126
|
+
ramp: tuple[str, ...]
|
|
127
|
+
status: Mapping[str, str] = field(hash=False)
|
|
128
|
+
type: Typography = field(default_factory=lambda: TYPE)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass(frozen=True, slots=True)
|
|
132
|
+
class Style:
|
|
133
|
+
"""A complete figure style: the themes of one website or project and their type.
|
|
134
|
+
|
|
135
|
+
Attributes:
|
|
136
|
+
themes: Themes in the order :func:`figkit.render` draws them, all with the same type.
|
|
137
|
+
default: Name of the theme for a single file, such as the light one.
|
|
138
|
+
pairs: Each theme and the theme a page swaps it with, such as light and dark.
|
|
139
|
+
Read-only and left out of the hash.
|
|
140
|
+
css: Custom properties of the website's stylesheet and the token each equals, as
|
|
141
|
+
``(key, index)``; ``index`` picks an entry of a list token such as ``pages``.
|
|
142
|
+
Empty when the tokens name none. Read-only and left out of the hash.
|
|
143
|
+
source: File the style was read from, ``None`` for one built in code.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
themes: tuple[Theme, ...]
|
|
147
|
+
default: str
|
|
148
|
+
pairs: Mapping[str, str] = field(hash=False)
|
|
149
|
+
css: Mapping[str, tuple[str, int | None]] = field(hash=False)
|
|
150
|
+
source: Path | None = None
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def type(self) -> Typography:
|
|
154
|
+
"""Typography of the style, shared by all themes."""
|
|
155
|
+
return self.themes[0].type
|
|
156
|
+
|
|
157
|
+
def theme(self, name: str) -> Theme:
|
|
158
|
+
"""The theme called ``name``.
|
|
159
|
+
|
|
160
|
+
Raises:
|
|
161
|
+
KeyError: If the style has no such theme.
|
|
162
|
+
"""
|
|
163
|
+
for theme in self.themes:
|
|
164
|
+
if theme.name == name:
|
|
165
|
+
return theme
|
|
166
|
+
msg = f"no theme {name!r}; the style has {', '.join(t.name for t in self.themes)}"
|
|
167
|
+
raise KeyError(msg)
|
|
168
|
+
|
|
169
|
+
def suffix(self, name: str) -> str:
|
|
170
|
+
"""Suffix of the files of theme ``name``: none for the default theme, else ``-<name>``."""
|
|
171
|
+
return "" if name == self.default else f"-{name}"
|
|
172
|
+
|
|
173
|
+
def split(self, stem: str) -> tuple[str, str]:
|
|
174
|
+
"""Split a file stem into the figure and the name of its theme.
|
|
175
|
+
|
|
176
|
+
``bars.de-dark`` gives ``("bars.de", "dark")``, ``bars.de`` gives the default theme. A
|
|
177
|
+
stem may only end in the suffix of a theme of this style.
|
|
178
|
+
"""
|
|
179
|
+
others = sorted((t.name for t in self.themes if t.name != self.default), key=len)
|
|
180
|
+
for name in reversed(others):
|
|
181
|
+
if stem.endswith(f"-{name}"):
|
|
182
|
+
return stem.removesuffix(f"-{name}"), name
|
|
183
|
+
return stem, self.default
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def load_style(path: Path) -> Style:
|
|
187
|
+
"""Read a style from a tokens file in the format of the bundled ``tokens.json``.
|
|
188
|
+
|
|
189
|
+
Patterns in ``font.files`` are relative to the tokens file. Without them the style uses the
|
|
190
|
+
bundled fonts.
|
|
191
|
+
|
|
192
|
+
Raises:
|
|
193
|
+
StyleError: If the file is not JSON or not a valid style; the error lists every problem.
|
|
194
|
+
OSError: If the file cannot be read.
|
|
195
|
+
"""
|
|
196
|
+
try:
|
|
197
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
198
|
+
except json.JSONDecodeError as error:
|
|
199
|
+
raise StyleError(str(path), [f"not JSON: {error}"]) from error
|
|
200
|
+
return parse_style(data, base=path.parent, source=path)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def parse_style(data: object, *, base: Path | None = None, source: Path | None = None) -> Style:
|
|
204
|
+
"""Build a style from the parsed contents of a tokens file.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
data: Parsed JSON in version 1 (one light and one dark theme, the format before 0.4) or 2.
|
|
208
|
+
base: Folder that the patterns of ``font.files`` are relative to, by default the working
|
|
209
|
+
directory.
|
|
210
|
+
source: File the data came from, kept on the style and named in errors.
|
|
211
|
+
|
|
212
|
+
Raises:
|
|
213
|
+
StyleError: If the data is not a valid style; the error lists every problem.
|
|
214
|
+
"""
|
|
215
|
+
label = str(source) if source is not None else "style"
|
|
216
|
+
problems = _problems(data)
|
|
217
|
+
if problems:
|
|
218
|
+
raise StyleError(label, problems)
|
|
219
|
+
raw = cast("dict[str, Any]", data)
|
|
220
|
+
files: list[Path] = []
|
|
221
|
+
for pattern in raw["font"].get("files", []):
|
|
222
|
+
found = sorted((base or Path.cwd()).glob(pattern))
|
|
223
|
+
if not found:
|
|
224
|
+
problems.append(f"font.files: {pattern!r} matches no file")
|
|
225
|
+
files.extend(found)
|
|
226
|
+
if problems:
|
|
227
|
+
raise StyleError(label, problems)
|
|
228
|
+
typography = Typography.from_tokens(raw["font"], files)
|
|
229
|
+
themes = tuple(_theme(name, value, typography) for name, value in raw["themes"].items())
|
|
230
|
+
if raw.get("version", 1) == 1:
|
|
231
|
+
pairs = {"light": "dark", "dark": "light"}
|
|
232
|
+
else:
|
|
233
|
+
pairs = {name: value["pair"] for name, value in raw["themes"].items() if "pair" in value}
|
|
234
|
+
# Version 1 is the portfolio's format; a project of version 2 names its own properties.
|
|
235
|
+
css = dict(CSS_TOKENS) if raw.get("version", 1) == 1 else {}
|
|
236
|
+
if "css" in raw:
|
|
237
|
+
css = {
|
|
238
|
+
key: (target[0], target[1] if len(target) > 1 else None)
|
|
239
|
+
for key, target in raw["css"].items()
|
|
240
|
+
}
|
|
241
|
+
return Style(
|
|
242
|
+
themes=themes,
|
|
243
|
+
# Version 1 always meant light as the default, whatever the order of its themes.
|
|
244
|
+
default=raw.get("default", "light" if raw.get("version", 1) == 1 else themes[0].name),
|
|
245
|
+
pairs=MappingProxyType(pairs),
|
|
246
|
+
css=MappingProxyType(css),
|
|
247
|
+
source=source,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _theme(name: str, raw: Mapping[str, Any], typography: Typography) -> Theme:
|
|
252
|
+
return Theme(
|
|
253
|
+
name=name,
|
|
254
|
+
surface=raw["surface"],
|
|
255
|
+
pages=tuple(raw["pages"]),
|
|
256
|
+
ink=raw["ink"],
|
|
257
|
+
secondary=raw["secondary"],
|
|
258
|
+
muted=raw["muted"],
|
|
259
|
+
grid=raw["grid"],
|
|
260
|
+
axis=raw["axis"],
|
|
261
|
+
series=tuple(raw["series"]),
|
|
262
|
+
ramp=tuple(raw["ramp"]),
|
|
263
|
+
status=MappingProxyType(dict(raw["status"])),
|
|
264
|
+
type=typography,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _problems(data: object) -> list[str]:
|
|
269
|
+
"""Every problem of a tokens file, each starting with the path of the value."""
|
|
270
|
+
if not isinstance(data, dict):
|
|
271
|
+
return ["the file must hold a JSON object"]
|
|
272
|
+
problems = _unknown("", data, ("$schema", "version", "default", "font", "themes", "css"))
|
|
273
|
+
version = data.get("version", 1)
|
|
274
|
+
if version not in (1, 2) or isinstance(version, bool):
|
|
275
|
+
problems.append(f"version: {version!r} is not 1 or 2")
|
|
276
|
+
problems += _font_problems(data.get("font"))
|
|
277
|
+
themes = data.get("themes")
|
|
278
|
+
if not isinstance(themes, dict) or not themes:
|
|
279
|
+
return [*problems, "themes: must be an object with at least one theme"]
|
|
280
|
+
if version == 1 and sorted(themes) != ["dark", "light"]:
|
|
281
|
+
problems.append("themes: version 1 has exactly light and dark; use version 2 for others")
|
|
282
|
+
for name, raw in themes.items():
|
|
283
|
+
problems += _theme_problems(name, raw, themes, version == 2)
|
|
284
|
+
default = data.get("default")
|
|
285
|
+
if default is not None and default not in themes:
|
|
286
|
+
problems.append(f"default: {default!r} is not a theme")
|
|
287
|
+
if "css" in data:
|
|
288
|
+
problems += _css_problems(data["css"], themes)
|
|
289
|
+
return problems
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _font_problems(font: object) -> list[str]:
|
|
293
|
+
if not isinstance(font, dict):
|
|
294
|
+
return ["font: must be an object"]
|
|
295
|
+
problems = _unknown("font.", font, ("sans", "mono", *_SIZES, "files"))
|
|
296
|
+
problems += [
|
|
297
|
+
f"font.{key}: must be a family name"
|
|
298
|
+
for key in ("sans", "mono")
|
|
299
|
+
if not isinstance(font.get(key), str) or not font[key]
|
|
300
|
+
]
|
|
301
|
+
bad = [
|
|
302
|
+
key
|
|
303
|
+
for key in _SIZES
|
|
304
|
+
if isinstance(font.get(key), bool)
|
|
305
|
+
or not isinstance(font.get(key), int | float)
|
|
306
|
+
or font[key] <= 0
|
|
307
|
+
]
|
|
308
|
+
problems += [f"font.{key}: must be a positive size in pt" for key in bad]
|
|
309
|
+
if not bad:
|
|
310
|
+
problems += [
|
|
311
|
+
f"font.{key}: {font[key]} is below font.minimum {font['minimum']}"
|
|
312
|
+
for key in ("size", "title", "label", "tick", "annotation")
|
|
313
|
+
if font[key] < font["minimum"]
|
|
314
|
+
]
|
|
315
|
+
files = font.get("files", [])
|
|
316
|
+
if not isinstance(files, list) or not all(isinstance(f, str) and f for f in files):
|
|
317
|
+
problems.append("font.files: must be a list of glob patterns")
|
|
318
|
+
else:
|
|
319
|
+
# Path.glob accepts only relative patterns; an anchored one would raise instead.
|
|
320
|
+
problems += [
|
|
321
|
+
f"font.files: {f!r} must be relative to the tokens file"
|
|
322
|
+
for f in files
|
|
323
|
+
if Path(f).anchor or Path(f).is_absolute()
|
|
324
|
+
]
|
|
325
|
+
return problems
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _theme_problems(
|
|
329
|
+
name: str, raw: object, themes: Mapping[str, Any], pairs_allowed: bool
|
|
330
|
+
) -> list[str]:
|
|
331
|
+
where = f"themes.{name}"
|
|
332
|
+
if not isinstance(raw, dict):
|
|
333
|
+
return [f"{where}: must be an object"]
|
|
334
|
+
problems = _unknown(f"{where}.", raw, (*_COLOURS, *_LISTS, "status", "pair"))
|
|
335
|
+
problems += [_colour(f"{where}.{key}", raw.get(key)) for key in _COLOURS]
|
|
336
|
+
for key, least in zip(_LISTS, (1, 1, 2), strict=True):
|
|
337
|
+
values = raw.get(key)
|
|
338
|
+
if not isinstance(values, list) or len(values) < least:
|
|
339
|
+
problems.append(f"{where}.{key}: must be a list of at least {least} colours")
|
|
340
|
+
continue
|
|
341
|
+
problems += [_colour(f"{where}.{key}[{i}]", v) for i, v in enumerate(values)]
|
|
342
|
+
status = raw.get("status")
|
|
343
|
+
if not isinstance(status, dict) or sorted(status) != sorted(_STATUS):
|
|
344
|
+
problems.append(f"{where}.status: must have exactly {', '.join(_STATUS)}")
|
|
345
|
+
else:
|
|
346
|
+
problems += [_colour(f"{where}.status.{key}", status[key]) for key in _STATUS]
|
|
347
|
+
if "pair" in raw:
|
|
348
|
+
problems += _pair_problems(name, raw, themes, pairs_allowed)
|
|
349
|
+
return [p for p in problems if p]
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _pair_problems(
|
|
353
|
+
name: str, raw: Mapping[str, Any], themes: Mapping[str, Any], allowed: bool
|
|
354
|
+
) -> list[str]:
|
|
355
|
+
where = f"themes.{name}.pair"
|
|
356
|
+
pair = raw["pair"]
|
|
357
|
+
partner = themes.get(pair) if isinstance(pair, str) else None
|
|
358
|
+
if not allowed:
|
|
359
|
+
return [f"{where}: needs version 2"]
|
|
360
|
+
if pair == name or not isinstance(partner, dict):
|
|
361
|
+
return [f"{where}: {pair!r} is not another theme"]
|
|
362
|
+
if partner.get("pair") != name:
|
|
363
|
+
return [f"{where}: {pair!r} does not pair back with {name!r}"]
|
|
364
|
+
series = raw.get("series")
|
|
365
|
+
if isinstance(series, list) and len(partner.get("series") or []) != len(series):
|
|
366
|
+
return [f"themes.{name}.series: must be as long as in its pair {pair!r}"]
|
|
367
|
+
return []
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _css_problems(css: object, themes: Mapping[str, Any]) -> list[str]:
|
|
371
|
+
if not isinstance(css, dict):
|
|
372
|
+
return ["css: must be an object"]
|
|
373
|
+
problems = []
|
|
374
|
+
for prop, target in css.items():
|
|
375
|
+
single = isinstance(target, list) and len(target) == 1 and target[0] in _COLOURS
|
|
376
|
+
indexed = (
|
|
377
|
+
isinstance(target, list)
|
|
378
|
+
and len(target) == 2
|
|
379
|
+
and target[0] in _LISTS
|
|
380
|
+
and isinstance(target[1], int)
|
|
381
|
+
and not isinstance(target[1], bool)
|
|
382
|
+
and target[1] >= 0
|
|
383
|
+
)
|
|
384
|
+
if not (single or indexed):
|
|
385
|
+
problems.append(f"css.{prop}: must be [colour token] or [list token, index]")
|
|
386
|
+
continue
|
|
387
|
+
if indexed:
|
|
388
|
+
key, index = target
|
|
389
|
+
# Every theme must hold the entry, or check_tokens would fail on the missing one.
|
|
390
|
+
problems += [
|
|
391
|
+
f"css.{prop}: themes.{name}.{key} has no entry {index}"
|
|
392
|
+
for name, raw in themes.items()
|
|
393
|
+
if isinstance(raw, dict)
|
|
394
|
+
and isinstance(raw.get(key), list)
|
|
395
|
+
and index >= len(raw[key])
|
|
396
|
+
]
|
|
397
|
+
return problems
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _unknown(where: str, raw: Mapping[str, Any], known: Sequence[str]) -> list[str]:
|
|
401
|
+
"""A problem per key that is neither known nor a ``$comment``, which catches typos."""
|
|
402
|
+
return [f"{where}{key}: unknown key" for key in raw if key not in known and key != "$comment"]
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _colour(where: str, value: object) -> str:
|
|
406
|
+
if isinstance(value, str) and _HEX.match(value):
|
|
407
|
+
return ""
|
|
408
|
+
return f"{where}: {value!r} is not a #rrggbb colour"
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
DEFAULT = load_style(TOKENS)
|
|
412
|
+
TYPE: Typography = DEFAULT.type
|
|
413
|
+
LIGHT = DEFAULT.theme("light")
|
|
414
|
+
DARK = DEFAULT.theme("dark")
|
|
415
|
+
THEMES = DEFAULT.themes
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@cache
|
|
419
|
+
def tokens() -> dict[str, Any]:
|
|
420
|
+
"""The contents of the bundled ``tokens.json``, the source of :data:`DEFAULT`."""
|
|
421
|
+
data: dict[str, Any] = json.loads(TOKENS.read_text(encoding="utf-8"))
|
|
422
|
+
return data
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
@cache
|
|
426
|
+
def register_fonts(typography: Typography | None = None) -> tuple[str, str]:
|
|
427
|
+
"""Add the fonts of a typography to matplotlib and return the sans and mono family names.
|
|
428
|
+
|
|
429
|
+
Args:
|
|
430
|
+
typography: Fonts to add; by default those of the bundled style.
|
|
431
|
+
|
|
432
|
+
Raises:
|
|
433
|
+
RuntimeError: If matplotlib does not resolve a family to one of the files. A silent
|
|
434
|
+
fallback to another font would change every figure without an error.
|
|
435
|
+
"""
|
|
436
|
+
typography = typography or TYPE
|
|
437
|
+
files = typography.files or tuple(sorted(FONTS.glob("*.ttf")))
|
|
438
|
+
for path in files:
|
|
439
|
+
font_manager.fontManager.addfont(str(path))
|
|
440
|
+
for family in (typography.sans, typography.mono):
|
|
441
|
+
found = Path(
|
|
442
|
+
font_manager.findfont(
|
|
443
|
+
font_manager.FontProperties(family=family), fallback_to_default=False
|
|
444
|
+
)
|
|
445
|
+
)
|
|
446
|
+
# The same file, however it is spelled: Windows may give the package a short 8.3
|
|
447
|
+
# path such as RUNNER~1 while matplotlib reports the long one.
|
|
448
|
+
if not any(found.samefile(path) for path in files):
|
|
449
|
+
msg = (
|
|
450
|
+
f"font {family!r} resolved to {found}, not to a file of the style; matplotlib "
|
|
451
|
+
"keeps one file per family, so two styles need fonts of different names"
|
|
452
|
+
)
|
|
453
|
+
raise RuntimeError(msg)
|
|
454
|
+
return typography.sans, typography.mono
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def rc(theme: Theme) -> dict[str, Any]:
|
|
458
|
+
"""Matplotlib settings for the theme: recessive axes, hairline grid, text in ink."""
|
|
459
|
+
register_fonts(theme.type)
|
|
460
|
+
size = theme.type
|
|
461
|
+
sans, mono = size.sans, size.mono
|
|
462
|
+
return {
|
|
463
|
+
"figure.facecolor": theme.surface,
|
|
464
|
+
"axes.facecolor": theme.surface,
|
|
465
|
+
"savefig.facecolor": theme.surface,
|
|
466
|
+
"axes.edgecolor": theme.axis,
|
|
467
|
+
"axes.linewidth": 0.8,
|
|
468
|
+
"axes.labelcolor": theme.secondary,
|
|
469
|
+
"axes.titlecolor": theme.ink,
|
|
470
|
+
"axes.titlesize": size.title,
|
|
471
|
+
"axes.titleweight": "semibold",
|
|
472
|
+
"axes.titlelocation": "left",
|
|
473
|
+
"axes.titlepad": 10,
|
|
474
|
+
"axes.labelsize": size.label,
|
|
475
|
+
"axes.labelpad": 6,
|
|
476
|
+
"axes.spines.top": False,
|
|
477
|
+
"axes.spines.right": False,
|
|
478
|
+
"axes.grid": False,
|
|
479
|
+
"axes.axisbelow": True,
|
|
480
|
+
"axes.prop_cycle": cycler(color=list(theme.series)),
|
|
481
|
+
"grid.color": theme.grid,
|
|
482
|
+
"grid.linewidth": 0.8,
|
|
483
|
+
"xtick.color": theme.axis,
|
|
484
|
+
"ytick.color": theme.axis,
|
|
485
|
+
"xtick.labelcolor": theme.secondary,
|
|
486
|
+
"ytick.labelcolor": theme.secondary,
|
|
487
|
+
"xtick.labelsize": size.tick,
|
|
488
|
+
"ytick.labelsize": size.tick,
|
|
489
|
+
"xtick.major.size": 3,
|
|
490
|
+
"ytick.major.size": 3,
|
|
491
|
+
"text.color": theme.ink,
|
|
492
|
+
"legend.frameon": False,
|
|
493
|
+
"legend.fontsize": size.label,
|
|
494
|
+
"legend.labelcolor": theme.secondary,
|
|
495
|
+
"legend.handlelength": 1.4,
|
|
496
|
+
"font.family": "sans-serif",
|
|
497
|
+
"font.sans-serif": [sans],
|
|
498
|
+
"font.monospace": [mono],
|
|
499
|
+
"font.size": size.size,
|
|
500
|
+
"mathtext.fontset": "custom",
|
|
501
|
+
# Mathtext loads every face of the custom set for each label, log ticks too. Faces left
|
|
502
|
+
# at their defaults fall back to generic families such as cursive, which a bare Linux
|
|
503
|
+
# system lacks, so all of them point to the bundled fonts. The bundle has semibold.
|
|
504
|
+
"mathtext.rm": sans,
|
|
505
|
+
"mathtext.it": f"{sans}:italic",
|
|
506
|
+
"mathtext.bf": f"{sans}:semibold",
|
|
507
|
+
"mathtext.bfit": f"{sans}:italic:semibold",
|
|
508
|
+
"mathtext.sf": sans,
|
|
509
|
+
"mathtext.tt": mono,
|
|
510
|
+
"mathtext.cal": sans,
|
|
511
|
+
"lines.linewidth": 2,
|
|
512
|
+
"lines.markersize": 6,
|
|
513
|
+
"lines.solid_capstyle": "round",
|
|
514
|
+
"patch.linewidth": 0,
|
|
515
|
+
"svg.fonttype": "path",
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
@contextmanager
|
|
520
|
+
def styled(theme: Theme) -> Iterator[None]:
|
|
521
|
+
"""Apply the theme's matplotlib settings inside the block."""
|
|
522
|
+
# The settings are checked by matplotlib at run time; its stubs list every key as a literal.
|
|
523
|
+
with plt.rc_context(cast("Any", rc(theme))):
|
|
524
|
+
yield
|
figkit/tokens.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "./tokens.schema.json",
|
|
3
|
+
"$comment": "Colours and type of the figures. Text and line colours follow the portfolio tokens (Portfolio/src/styles/tokens.css). The series were checked with the dataviz palette validator against both page colours of each mode, see docs/style-guide.md.",
|
|
4
|
+
"version": 2,
|
|
5
|
+
"default": "light",
|
|
6
|
+
"font": {
|
|
7
|
+
"sans": "Bricolage Grotesque",
|
|
8
|
+
"mono": "JetBrains Mono",
|
|
9
|
+
"size": 9,
|
|
10
|
+
"title": 11,
|
|
11
|
+
"label": 9,
|
|
12
|
+
"tick": 8.5,
|
|
13
|
+
"annotation": 8,
|
|
14
|
+
"minimum": 8
|
|
15
|
+
},
|
|
16
|
+
"themes": {
|
|
17
|
+
"light": {
|
|
18
|
+
"pair": "dark",
|
|
19
|
+
"pages": ["#faf8f4", "#ffffff"],
|
|
20
|
+
"surface": "#ffffff",
|
|
21
|
+
"ink": "#1d1e22",
|
|
22
|
+
"secondary": "#5e6270",
|
|
23
|
+
"muted": "#76859a",
|
|
24
|
+
"grid": "#ebe6dc",
|
|
25
|
+
"axis": "#c9c3b6",
|
|
26
|
+
"series": ["#2f5bd3", "#eb6834", "#1baf7a", "#eda100"],
|
|
27
|
+
"ramp": ["#f4f8fd", "#cde2fb", "#9ec5f4", "#6da7ec", "#3987e5", "#256abf", "#184f95", "#0d366b"],
|
|
28
|
+
"status": {"good": "#0ca30c", "warning": "#fab219", "serious": "#ec835a", "critical": "#d03b3b"}
|
|
29
|
+
},
|
|
30
|
+
"dark": {
|
|
31
|
+
"pair": "light",
|
|
32
|
+
"pages": ["#111318", "#1a1d24"],
|
|
33
|
+
"surface": "#1a1d24",
|
|
34
|
+
"ink": "#eceef3",
|
|
35
|
+
"secondary": "#a6abba",
|
|
36
|
+
"muted": "#76859a",
|
|
37
|
+
"grid": "#2a2e38",
|
|
38
|
+
"axis": "#3d4250",
|
|
39
|
+
"series": ["#5b84ea", "#d95926", "#199e70", "#c98500"],
|
|
40
|
+
"ramp": ["#141b29", "#173059", "#134789", "#1f60b1", "#317cd6", "#579ae9", "#88b7f0", "#b7d3f6"],
|
|
41
|
+
"status": {"good": "#0ca30c", "warning": "#fab219", "serious": "#ec835a", "critical": "#d03b3b"}
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"css": {
|
|
45
|
+
"bg": ["pages", 0],
|
|
46
|
+
"surface": ["surface"],
|
|
47
|
+
"text": ["ink"],
|
|
48
|
+
"muted": ["secondary"],
|
|
49
|
+
"border": ["grid"],
|
|
50
|
+
"border-strong": ["muted"]
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://github.com/BenBotsch/FigureKit/blob/main/src/figkit/tokens.schema.json",
|
|
4
|
+
"title": "figkit tokens",
|
|
5
|
+
"description": "Colours and type of a figkit style, version 2. figkit.load_style checks the same rules and also that font files exist and paired themes point at each other.",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"required": ["version", "font", "themes"],
|
|
8
|
+
"additionalProperties": false,
|
|
9
|
+
"properties": {
|
|
10
|
+
"$schema": {"type": "string"},
|
|
11
|
+
"$comment": {"type": "string"},
|
|
12
|
+
"version": {"const": 2},
|
|
13
|
+
"default": {"type": "string", "description": "Theme for a single file, such as light."},
|
|
14
|
+
"font": {
|
|
15
|
+
"type": "object",
|
|
16
|
+
"required": ["sans", "mono", "size", "title", "label", "tick", "annotation", "minimum"],
|
|
17
|
+
"additionalProperties": false,
|
|
18
|
+
"properties": {
|
|
19
|
+
"$comment": {"type": "string"},
|
|
20
|
+
"sans": {"type": "string", "minLength": 1},
|
|
21
|
+
"mono": {"type": "string", "minLength": 1},
|
|
22
|
+
"size": {"$ref": "#/$defs/pt"},
|
|
23
|
+
"title": {"$ref": "#/$defs/pt"},
|
|
24
|
+
"label": {"$ref": "#/$defs/pt"},
|
|
25
|
+
"tick": {"$ref": "#/$defs/pt"},
|
|
26
|
+
"annotation": {"$ref": "#/$defs/pt"},
|
|
27
|
+
"minimum": {"$ref": "#/$defs/pt"},
|
|
28
|
+
"files": {
|
|
29
|
+
"type": "array",
|
|
30
|
+
"description": "Glob patterns of the font files, relative to the tokens file. Without them figkit uses its bundled fonts.",
|
|
31
|
+
"items": {"type": "string", "minLength": 1}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"themes": {
|
|
36
|
+
"type": "object",
|
|
37
|
+
"minProperties": 1,
|
|
38
|
+
"additionalProperties": {"$ref": "#/$defs/theme"}
|
|
39
|
+
},
|
|
40
|
+
"css": {
|
|
41
|
+
"type": "object",
|
|
42
|
+
"description": "Custom properties of the website's stylesheet and the token each equals.",
|
|
43
|
+
"additionalProperties": {
|
|
44
|
+
"oneOf": [
|
|
45
|
+
{
|
|
46
|
+
"type": "array",
|
|
47
|
+
"prefixItems": [{"enum": ["surface", "ink", "secondary", "muted", "grid", "axis"]}],
|
|
48
|
+
"minItems": 1,
|
|
49
|
+
"maxItems": 1
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"type": "array",
|
|
53
|
+
"prefixItems": [{"enum": ["pages", "series", "ramp"]}, {"type": "integer", "minimum": 0}],
|
|
54
|
+
"minItems": 2,
|
|
55
|
+
"maxItems": 2
|
|
56
|
+
}
|
|
57
|
+
]
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"$defs": {
|
|
62
|
+
"pt": {"type": "number", "exclusiveMinimum": 0},
|
|
63
|
+
"colour": {"type": "string", "pattern": "^#[0-9a-fA-F]{6}$"},
|
|
64
|
+
"colours": {"type": "array", "items": {"$ref": "#/$defs/colour"}},
|
|
65
|
+
"theme": {
|
|
66
|
+
"type": "object",
|
|
67
|
+
"required": ["surface", "pages", "ink", "secondary", "muted", "grid", "axis", "series", "ramp", "status"],
|
|
68
|
+
"additionalProperties": false,
|
|
69
|
+
"properties": {
|
|
70
|
+
"$comment": {"type": "string"},
|
|
71
|
+
"pair": {"type": "string", "description": "Theme a page swaps this one with, such as dark for light."},
|
|
72
|
+
"surface": {"$ref": "#/$defs/colour"},
|
|
73
|
+
"pages": {"$ref": "#/$defs/colours", "minItems": 1},
|
|
74
|
+
"ink": {"$ref": "#/$defs/colour"},
|
|
75
|
+
"secondary": {"$ref": "#/$defs/colour"},
|
|
76
|
+
"muted": {"$ref": "#/$defs/colour"},
|
|
77
|
+
"grid": {"$ref": "#/$defs/colour"},
|
|
78
|
+
"axis": {"$ref": "#/$defs/colour"},
|
|
79
|
+
"series": {"$ref": "#/$defs/colours", "minItems": 1},
|
|
80
|
+
"ramp": {"$ref": "#/$defs/colours", "minItems": 2},
|
|
81
|
+
"status": {
|
|
82
|
+
"type": "object",
|
|
83
|
+
"required": ["good", "warning", "serious", "critical"],
|
|
84
|
+
"additionalProperties": false,
|
|
85
|
+
"properties": {
|
|
86
|
+
"good": {"$ref": "#/$defs/colour"},
|
|
87
|
+
"warning": {"$ref": "#/$defs/colour"},
|
|
88
|
+
"serious": {"$ref": "#/$defs/colour"},
|
|
89
|
+
"critical": {"$ref": "#/$defs/colour"}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|