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 ADDED
@@ -0,0 +1,141 @@
1
+ """One figure style for every project.
2
+
3
+ Draw a figure as a function of the :class:`Theme` and let :func:`render` write it::
4
+
5
+ import matplotlib.pyplot as plt
6
+ import figkit
7
+
8
+ def draw(theme: figkit.Theme) -> plt.Figure:
9
+ figure, ax = plt.subplots(figsize=(6.4, 3.4))
10
+ ax.plot([1, 2, 3], [0.4, 0.7, 0.8], color=theme.series[0], label="model")
11
+ figkit.title(ax, "Validation F1", theme)
12
+ return figure
13
+
14
+ figkit.render(Path("docs/figures"), "f1", draw)
15
+
16
+ This writes ``f1.svg``, ``f1-dark.svg``, ``f1.png`` and ``f1-dark.png``, all transparent. For a
17
+ website, :func:`page` writes the figure without its title per language, ``f1.de.svg`` and
18
+ ``f1.en.svg``, and :func:`write_manifest` lists them with their titles and alt texts.
19
+ """
20
+
21
+ from figkit.export import (
22
+ CARD,
23
+ CARD_INCHES,
24
+ PHOTO,
25
+ PNG,
26
+ RASTER_DPI,
27
+ SVG,
28
+ WEB,
29
+ WEB_WIDTH,
30
+ Draw,
31
+ Output,
32
+ canvas,
33
+ check_text,
34
+ path_for,
35
+ render,
36
+ save,
37
+ )
38
+ from figkit.helpers import (
39
+ band,
40
+ bar_labels,
41
+ callout,
42
+ category_axis,
43
+ error_bars,
44
+ grid,
45
+ hex_colour,
46
+ ink_on,
47
+ legend_top,
48
+ line_labels,
49
+ mono,
50
+ mono_ticks,
51
+ percent,
52
+ ramp_cmap,
53
+ reference_line,
54
+ small_multiples,
55
+ title,
56
+ value,
57
+ )
58
+ from figkit.language import headless, language, localize, number
59
+ from figkit.manifest import Caption, page
60
+ from figkit.manifest import entry as page_entry
61
+ from figkit.manifest import write as write_manifest
62
+ from figkit.project import Project, project, project_style
63
+ from figkit.theme import (
64
+ DARK,
65
+ DEFAULT,
66
+ LIGHT,
67
+ THEMES,
68
+ TYPE,
69
+ Style,
70
+ StyleError,
71
+ Theme,
72
+ Typography,
73
+ load_style,
74
+ parse_style,
75
+ rc,
76
+ register_fonts,
77
+ styled,
78
+ tokens,
79
+ )
80
+
81
+ __all__ = [
82
+ "CARD",
83
+ "CARD_INCHES",
84
+ "DARK",
85
+ "DEFAULT",
86
+ "LIGHT",
87
+ "PHOTO",
88
+ "PNG",
89
+ "RASTER_DPI",
90
+ "SVG",
91
+ "THEMES",
92
+ "TYPE",
93
+ "WEB",
94
+ "WEB_WIDTH",
95
+ "Caption",
96
+ "Draw",
97
+ "Output",
98
+ "Project",
99
+ "Style",
100
+ "StyleError",
101
+ "Theme",
102
+ "Typography",
103
+ "band",
104
+ "bar_labels",
105
+ "callout",
106
+ "canvas",
107
+ "category_axis",
108
+ "check_text",
109
+ "error_bars",
110
+ "grid",
111
+ "headless",
112
+ "hex_colour",
113
+ "ink_on",
114
+ "language",
115
+ "legend_top",
116
+ "line_labels",
117
+ "load_style",
118
+ "localize",
119
+ "mono",
120
+ "mono_ticks",
121
+ "number",
122
+ "page",
123
+ "page_entry",
124
+ "parse_style",
125
+ "path_for",
126
+ "percent",
127
+ "project",
128
+ "project_style",
129
+ "ramp_cmap",
130
+ "rc",
131
+ "reference_line",
132
+ "register_fonts",
133
+ "render",
134
+ "save",
135
+ "small_multiples",
136
+ "styled",
137
+ "title",
138
+ "tokens",
139
+ "value",
140
+ "write_manifest",
141
+ ]
figkit/access.py ADDED
@@ -0,0 +1,144 @@
1
+ """Accessibility of the colours of a style, for ``figkit check --a11y``.
2
+
3
+ Three rules, checked in every theme against every page colour the theme is meant for:
4
+
5
+ * Text contrast (WCAG 2.2): ``ink`` and ``secondary`` reach 4.5:1, the level of small text;
6
+ ``muted`` marks such as reference lines reach 3:1, the level of graphical objects.
7
+ * Series: neighbouring slots stay apart for readers with protanopia and deuteranopia, simulated
8
+ after Machado, Oliveira and Fernandes (2009) at full severity, and for everyone else. The
9
+ distance is Euclidean in OKLab times 100, with the floors of the dataviz palette validator
10
+ that the bundled series were checked with: 6 under simulation and 15 in normal vision.
11
+ * Ramp: lightness changes in one direction with a visible step between neighbours.
12
+
13
+ Series below 3:1 against the page are allowed, because figures label such marks directly; see
14
+ ``docs/style-guide.md``. Alt texts are checked with the manifest by :func:`figkit.check.check`.
15
+ """
16
+
17
+ import itertools
18
+ import math
19
+ from collections.abc import Sequence
20
+
21
+ from figkit.theme import DEFAULT, Style, Theme
22
+
23
+ TEXT_CONTRAST = 4.5
24
+ MARK_CONTRAST = 3.0
25
+ CVD_FLOOR = 6.0
26
+ NORMAL_FLOOR = 15.0
27
+ RAMP_STEP = 0.06 # OKLCH lightness between neighbouring ramp colours
28
+
29
+ Matrix = tuple[tuple[float, float, float], ...]
30
+
31
+ # Machado, Oliveira and Fernandes (2009), severity 1.0, applied to linear RGB.
32
+ _SIMULATION: dict[str, Matrix] = {
33
+ "protanopia": (
34
+ (0.152286, 1.052583, -0.204868),
35
+ (0.114503, 0.786281, 0.099216),
36
+ (-0.003882, -0.048116, 1.051998),
37
+ ),
38
+ "deuteranopia": (
39
+ (0.367322, 0.860646, -0.227968),
40
+ (0.280085, 0.672501, 0.047413),
41
+ (-0.011820, 0.042940, 0.968881),
42
+ ),
43
+ }
44
+
45
+
46
+ def _linear(colour: str) -> tuple[float, float, float]:
47
+ """Linear RGB of ``#rrggbb``."""
48
+ channels = (int(colour[i : i + 2], 16) / 255 for i in (1, 3, 5))
49
+ r, g, b = (c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in channels)
50
+ return r, g, b
51
+
52
+
53
+ def contrast(a: str, b: str) -> float:
54
+ """WCAG contrast ratio of two colours, from 1 to 21."""
55
+
56
+ def luminance(colour: str) -> float:
57
+ r, g, b = _linear(colour)
58
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
59
+
60
+ high, low = sorted((luminance(a), luminance(b)), reverse=True)
61
+ return (high + 0.05) / (low + 0.05)
62
+
63
+
64
+ def _oklab(rgb: Sequence[float]) -> tuple[float, float, float]:
65
+ r, g, b = rgb
66
+ l_ = math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
67
+ m_ = math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
68
+ s_ = math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
69
+ return (
70
+ 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
71
+ 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
72
+ 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
73
+ )
74
+
75
+
76
+ def _simulate(colour: str, vision: str | None) -> tuple[float, float, float]:
77
+ rgb = _linear(colour)
78
+ if vision is None:
79
+ return rgb
80
+ r, g, b = (
81
+ min(1.0, max(0.0, row[0] * rgb[0] + row[1] * rgb[1] + row[2] * rgb[2]))
82
+ for row in _SIMULATION[vision]
83
+ )
84
+ return r, g, b
85
+
86
+
87
+ def distance(a: str, b: str, vision: str | None = None) -> float:
88
+ """OKLab distance times 100 of two colours, seen with ``vision`` or with normal vision."""
89
+ return 100 * math.dist(_oklab(_simulate(a, vision)), _oklab(_simulate(b, vision)))
90
+
91
+
92
+ def lightness(colour: str) -> float:
93
+ """OKLCH lightness from 0 to 1."""
94
+ return _oklab(_linear(colour))[0]
95
+
96
+
97
+ def check_style(style: Style | None = None) -> list[str]:
98
+ """Accessibility problems of the colours of ``style``; an empty list means it passes.
99
+
100
+ Returns:
101
+ One message per problem, starting with the theme it concerns.
102
+ """
103
+ style = style or DEFAULT
104
+ return [problem for theme in style.themes for problem in _theme_problems(theme)]
105
+
106
+
107
+ def _theme_problems(theme: Theme) -> list[str]:
108
+ problems = []
109
+ for role, minimum in (
110
+ ("ink", TEXT_CONTRAST),
111
+ ("secondary", TEXT_CONTRAST),
112
+ ("muted", MARK_CONTRAST),
113
+ ):
114
+ colour: str = getattr(theme, role)
115
+ for page in theme.pages:
116
+ ratio = contrast(colour, page)
117
+ if ratio < minimum:
118
+ problems.append(
119
+ f"{theme.name}: {role} {colour} has {ratio:.2f}:1 on {page}, "
120
+ f"needs {minimum:g}:1"
121
+ )
122
+ for i, (a, b) in enumerate(itertools.pairwise(theme.series)):
123
+ pair = f"series {i + 1} {a} and {i + 2} {b}"
124
+ for vision in _SIMULATION:
125
+ gap = distance(a, b, vision)
126
+ if gap < CVD_FLOOR:
127
+ problems.append(
128
+ f"{theme.name}: {pair} are {gap:.1f} apart with {vision}, need {CVD_FLOOR:g}"
129
+ )
130
+ gap = distance(a, b)
131
+ if gap < NORMAL_FLOOR:
132
+ problems.append(f"{theme.name}: {pair} are {gap:.1f} apart, need {NORMAL_FLOOR:g}")
133
+ levels = [lightness(c) for c in theme.ramp]
134
+ steps = [b - a for a, b in itertools.pairwise(levels)]
135
+ if steps and not (all(s > 0 for s in steps) or all(s < 0 for s in steps)):
136
+ problems.append(f"{theme.name}: ramp lightness does not change in one direction")
137
+ else:
138
+ problems += [
139
+ f"{theme.name}: ramp {theme.ramp[i]} and {theme.ramp[i + 1]} differ by "
140
+ f"{abs(step):.3f} in lightness, need {RAMP_STEP:g}"
141
+ for i, step in enumerate(steps)
142
+ if abs(step) < RAMP_STEP
143
+ ]
144
+ return problems
figkit/check.py ADDED
@@ -0,0 +1,227 @@
1
+ """Checks of figures for CI.
2
+
3
+ A directory is checked for light/dark and language pairs, transparency, widths, file sizes and
4
+ its ``figures.json``; a stylesheet for the page colours that the figures share with it.
5
+ """
6
+
7
+ import re
8
+ from collections import defaultdict
9
+ from collections.abc import Iterable, Sequence
10
+ from pathlib import Path
11
+
12
+ from PIL import Image
13
+
14
+ from figkit import manifest
15
+ from figkit.export import RASTER_DPI, WEB_WIDTH
16
+ from figkit.theme import DEFAULT, Style
17
+
18
+ FORMATS = (".svg", ".png", ".webp")
19
+ # Bytes. Above these, a chart usually embeds a raster or far too many points.
20
+ BUDGET = {".svg": 150_000, ".png": 250_000, ".webp": 250_000}
21
+ # A PNG next to a WebP of the same name is the lossless copy of a photograph, which is larger.
22
+ PHOTO_PNG_BUDGET = 1_000_000
23
+ # The figure background is the first patch matplotlib writes into an SVG.
24
+ _BACKGROUND = re.compile(r'<g id="patch_1">\s*<path[^>]*style="([^"]*)"')
25
+ _SVG_WIDTH = re.compile(r'<svg[^>]* width="([\d.]+)pt"')
26
+ # ``failure-modes.de`` is the German file of ``failure-modes``.
27
+ _LANGUAGE = re.compile(r"^(?P<name>.+)\.(?P<language>[a-z]{2})$")
28
+ _CSS_COLOUR = re.compile(
29
+ r"--color-([\w-]+):\s*light-dark\(\s*(#[0-9a-fA-F]{6})\s*,\s*(#[0-9a-fA-F]{6})"
30
+ )
31
+
32
+
33
+ def _figure_name(path: Path, style: Style) -> str:
34
+ """Name of the figure without theme and language, ``card`` for ``card.de-dark.png``."""
35
+ stem, _ = style.split(path.stem)
36
+ match = _LANGUAGE.match(stem)
37
+ return match["name"] if match else stem
38
+
39
+
40
+ def check(
41
+ directory: Path,
42
+ opaque: Iterable[str] = ("card",),
43
+ width: float | None = WEB_WIDTH,
44
+ style: Style | None = None,
45
+ ) -> list[str]:
46
+ """Problems of the figures in ``directory``; an empty list means it passes.
47
+
48
+ Args:
49
+ directory: Folder with a file per theme of ``style``, ``<name>.<format>`` and
50
+ ``<name>-dark.<format>`` in the bundled one.
51
+ opaque: Figure names that are deliberately opaque, such as a social card, in every
52
+ language. Their width is not checked either.
53
+ width: Canvas width in inches that every other figure must have, so that pages show
54
+ all of them with the same text size; ``None`` skips the check.
55
+ style: Style that named the files; each file of a theme with a pair needs the file of
56
+ that pair. By default the bundled style.
57
+
58
+ Returns:
59
+ One message per problem, with the file it concerns.
60
+ """
61
+ style = style or DEFAULT
62
+ keep_opaque = set(opaque)
63
+ files = sorted(p for p in directory.iterdir() if p.suffix in FORMATS and p.is_file())
64
+ problems = []
65
+ names = {p.name for p in files}
66
+ for path in files:
67
+ stem, theme = style.split(path.stem)
68
+ pair = style.pairs.get(theme)
69
+ partner = f"{stem}{style.suffix(pair)}{path.suffix}" if pair else None
70
+ if partner is not None and partner not in names:
71
+ problems.append(f"{path.name}: missing its pair {partner}")
72
+ size, budget = path.stat().st_size, BUDGET[path.suffix]
73
+ if path.suffix == ".png" and f"{path.stem}.webp" in names:
74
+ budget = PHOTO_PNG_BUDGET
75
+ if size > budget:
76
+ problems.append(f"{path.name}: {size:,} bytes, budget {budget:,}")
77
+ if _figure_name(path, style) in keep_opaque:
78
+ continue
79
+ found = (
80
+ _svg_problems(path, width) if path.suffix == ".svg" else _raster_problems(path, width)
81
+ )
82
+ problems += [f"{path.name}: {problem}" for problem in found]
83
+ problems += _language_problems(files, style)
84
+ problems += _manifest_problems(directory, names, [t.name for t in style.themes])
85
+ return problems
86
+
87
+
88
+ def _language_problems(files: Iterable[Path], style: Style) -> list[str]:
89
+ """Every figure that exists in one language exists in all of them."""
90
+ languages: dict[tuple[str, str], set[str]] = defaultdict(set)
91
+ for path in files:
92
+ match = _LANGUAGE.match(style.split(path.stem)[0])
93
+ if match:
94
+ languages[match["name"], path.suffix].add(match["language"])
95
+ every = set().union(*languages.values()) if languages else set()
96
+ return [
97
+ f"{name}{suffix}: missing the {code} file {name}.{code}{suffix}"
98
+ for (name, suffix), found in sorted(languages.items())
99
+ for code in sorted(every - found)
100
+ ]
101
+
102
+
103
+ def _manifest_problems(directory: Path, names: set[str], modes: Sequence[str]) -> list[str]:
104
+ """``figures.json`` lists exactly the files of the directory, each with its texts.
105
+
106
+ The file may be edited by hand, so every part of it is checked for its type and a broken
107
+ part is reported instead of failing the check.
108
+ """
109
+ try:
110
+ data = manifest.load(directory)
111
+ except ValueError as error:
112
+ return [f"{manifest.FILE}: not valid JSON, {error}"]
113
+ if data is None:
114
+ return []
115
+ if not isinstance(data, dict):
116
+ return [f"{manifest.FILE}: the top level is not an object"]
117
+ codes = data.get("languages", [])
118
+ figures = data.get("figures", [])
119
+ if not isinstance(codes, list) or not all(isinstance(c, str) for c in codes):
120
+ return [f"{manifest.FILE}: languages is not a list of codes"]
121
+ if not isinstance(figures, list):
122
+ return [f"{manifest.FILE}: figures is not a list"]
123
+ problems = []
124
+ listed: set[str] = set()
125
+ for index, entry in enumerate(figures):
126
+ problems += _entry_problems(entry, index, codes, names, listed, modes)
127
+ page_files = {n for n in names if Path(n).suffix in (".svg", ".webp")}
128
+ problems += [
129
+ f"{file}: not in {manifest.FILE}, so the page has no alt text for it"
130
+ for file in sorted(page_files - listed)
131
+ ]
132
+ return problems
133
+
134
+
135
+ def _entry_problems(
136
+ entry: object,
137
+ index: int,
138
+ codes: list[str],
139
+ names: set[str],
140
+ listed: set[str],
141
+ modes: Sequence[str],
142
+ ) -> list[str]:
143
+ """Problems of one figure in the manifest; adds the files it lists to ``listed``."""
144
+ if not isinstance(entry, dict):
145
+ return [f"{manifest.FILE}: figure {index + 1} is not an object"]
146
+ name = entry.get("name") or f"figure {index + 1}"
147
+ problems = []
148
+ for code in codes:
149
+ for key in ("title", "alt"):
150
+ texts = entry.get(key)
151
+ text = texts.get(code) if isinstance(texts, dict) else None
152
+ if not isinstance(text, str) or not text.strip():
153
+ problems.append(f"{manifest.FILE}: {name} has no {key} in {code}")
154
+ every = entry.get("files")
155
+ files = every.get(code) if isinstance(every, dict) else None
156
+ if not isinstance(files, dict):
157
+ problems.append(f"{manifest.FILE}: {name} has no files in {code}")
158
+ continue
159
+ for mode in modes:
160
+ file = files.get(mode)
161
+ if not isinstance(file, str):
162
+ problems.append(f"{manifest.FILE}: {name} has no {mode} file in {code}")
163
+ continue
164
+ listed.add(file)
165
+ if file not in names:
166
+ problems.append(f"{manifest.FILE}: {name} lists {file}, which does not exist")
167
+ return problems
168
+
169
+
170
+ def check_tokens(css: Path, style: Style | None = None) -> list[str]:
171
+ """Colours of the figures that differ from the stylesheet of the website.
172
+
173
+ Text and lines of the figures use the page colours of ``css``, a file with properties such
174
+ as ``--color-text: light-dark(#1d1e22, #eceef3)``. A change on one side only shows as text in
175
+ a figure that no longer matches the page around it. The first colour of ``light-dark`` is
176
+ compared with the default theme of ``style``, the second with its pair; ``style.css`` names
177
+ the properties.
178
+ """
179
+ style = style or DEFAULT
180
+ if not style.css:
181
+ return [f"{css.name}: the style names no custom properties, add css to its tokens"]
182
+ pair = style.pairs.get(style.default)
183
+ if pair is None:
184
+ return [f"{css.name}: the default theme {style.default!r} has no pair for light-dark()"]
185
+ themes = (style.theme(style.default), style.theme(pair))
186
+ found = {
187
+ m[1]: (m[2].lower(), m[3].lower()) for m in _CSS_COLOUR.finditer(css.read_text("utf-8"))
188
+ }
189
+ problems = []
190
+ for prop, (key, index) in style.css.items():
191
+ if prop not in found:
192
+ problems.append(f"{css.name}: --color-{prop} is missing")
193
+ continue
194
+ for theme, colour in zip(themes, found[prop], strict=True):
195
+ token = getattr(theme, key)
196
+ value: str = token if index is None else token[index]
197
+ mode = theme.name
198
+ if value.lower() != colour:
199
+ problems.append(
200
+ f"{css.name}: --color-{prop} is {colour} in {mode}, the figures use {value}"
201
+ )
202
+ return problems
203
+
204
+
205
+ def _svg_problems(path: Path, width: float | None) -> list[str]:
206
+ text = path.read_text(encoding="utf-8")
207
+ problems = []
208
+ match = _BACKGROUND.search(text)
209
+ if match and "fill: none" not in match.group(1):
210
+ problems.append("opaque background, render with a transparent output")
211
+ size = _SVG_WIDTH.search(text)
212
+ if width is not None and size and abs(float(size.group(1)) - width * 72) > 0.1:
213
+ problems.append(f"{float(size.group(1)):g} pt wide, the canvas is {width * 72:g} pt")
214
+ return problems
215
+
216
+
217
+ def _raster_problems(path: Path, width: float | None) -> list[str]:
218
+ with Image.open(path) as image:
219
+ rgba = image.convert("RGBA")
220
+ problems = []
221
+ corners = [(0, 0), (rgba.width - 1, 0), (0, rgba.height - 1), (rgba.width - 1, rgba.height - 1)]
222
+ if any(rgba.getpixel(c)[3] != 0 for c in corners): # type: ignore[index]
223
+ problems.append("corners are not transparent")
224
+ pixels = None if width is None else round(width * RASTER_DPI)
225
+ if pixels is not None and abs(rgba.width - pixels) > 1:
226
+ problems.append(f"{rgba.width} px wide, the canvas is {pixels} px")
227
+ return problems
figkit/cli.py ADDED
@@ -0,0 +1,180 @@
1
+ """Command line: ``figkit check``, ``figkit init`` and ``figkit style preview``."""
2
+
3
+ import argparse
4
+ import sys
5
+ from collections.abc import Sequence
6
+ from pathlib import Path
7
+
8
+ from figkit.access import check_style
9
+ from figkit.check import check, check_tokens
10
+ from figkit.export import WEB_WIDTH
11
+ from figkit.preview import preview
12
+ from figkit.project import init, project
13
+ from figkit.theme import StyleError, load_style
14
+
15
+
16
+ def main(argv: Sequence[str] | None = None) -> int:
17
+ """Run the command and return its exit code."""
18
+ parser = argparse.ArgumentParser(prog="figkit", description=__doc__)
19
+ commands = parser.add_subparsers(dest="command", required=True)
20
+ checker = commands.add_parser(
21
+ "check",
22
+ help="check light/dark and language pairs, transparency, widths, sizes and the manifest",
23
+ description=(
24
+ "Without --style and --css the settings come from [tool.figkit] in the nearest "
25
+ "pyproject.toml, and without those from the bundled style."
26
+ ),
27
+ )
28
+ checker.add_argument("directories", nargs="*", type=Path)
29
+ checker.add_argument(
30
+ "--opaque",
31
+ action="append",
32
+ default=None,
33
+ metavar="NAME",
34
+ help="figure that is opaque on purpose (repeatable, default: card)",
35
+ )
36
+ checker.add_argument(
37
+ "--any-width",
38
+ action="store_true",
39
+ help="do not require the fixed canvas width of web figures",
40
+ )
41
+ checker.add_argument(
42
+ "--a11y",
43
+ action="store_true",
44
+ help="check the contrast of text, the colour-blind separation of series and the ramp",
45
+ )
46
+ checker.add_argument(
47
+ "--css",
48
+ "--tokens",
49
+ dest="css",
50
+ type=Path,
51
+ metavar="CSS",
52
+ help="stylesheet whose page colours the figures must share, such as tokens.css",
53
+ )
54
+ checker.add_argument(
55
+ "--style",
56
+ type=Path,
57
+ metavar="TOKENS",
58
+ help="tokens file of the style that wrote the figures, such as figures/tokens.json",
59
+ )
60
+ starter = commands.add_parser(
61
+ "init",
62
+ help="copy the bundled style into the project and name it in [tool.figkit]",
63
+ description=(
64
+ "Writes the tokens and their schema, unless the tokens file exists, and appends "
65
+ "[tool.figkit] to the pyproject.toml of the working directory."
66
+ ),
67
+ )
68
+ starter.add_argument(
69
+ "--tokens",
70
+ type=Path,
71
+ default=Path("figures/tokens.json"),
72
+ metavar="TOKENS",
73
+ help="tokens file of the project (default: figures/tokens.json)",
74
+ )
75
+ starter.add_argument(
76
+ "--css", type=Path, metavar="CSS", help="stylesheet that figkit check compares"
77
+ )
78
+ styles = commands.add_parser("style", help="work with the style of the project")
79
+ actions = styles.add_subparsers(dest="action", required=True)
80
+ previewer = actions.add_parser(
81
+ "preview",
82
+ help="render a specimen of every token in every theme",
83
+ description=(
84
+ "Without --style the style comes from [tool.figkit] in the nearest pyproject.toml, "
85
+ "and without that it is the bundled one."
86
+ ),
87
+ )
88
+ previewer.add_argument(
89
+ "directory",
90
+ nargs="?",
91
+ type=Path,
92
+ default=Path("figkit-preview"),
93
+ help="folder of the specimen files (default: figkit-preview)",
94
+ )
95
+ previewer.add_argument("--style", type=Path, metavar="TOKENS", help="tokens file to preview")
96
+ args = parser.parse_args(argv)
97
+
98
+ if args.command == "init":
99
+ return _init(args.tokens, args.css)
100
+ if args.command == "style":
101
+ return _preview(args.directory, args.style)
102
+ return _check(parser, args)
103
+
104
+
105
+ def _init(tokens: Path, css: Path | None) -> int:
106
+ try:
107
+ written = init(Path.cwd(), tokens, css)
108
+ except (StyleError, OSError) as error:
109
+ print(error, file=sys.stderr)
110
+ return 1
111
+ for path in written:
112
+ print(f"{path}: written")
113
+ return 0
114
+
115
+
116
+ def _preview(directory: Path, tokens: Path | None) -> int:
117
+ try:
118
+ style = project().style() if tokens is None else load_style(tokens)
119
+ paths = preview(directory, style)
120
+ except (StyleError, OSError, ValueError) as error:
121
+ print(error, file=sys.stderr)
122
+ for note in getattr(error, "__notes__", []):
123
+ print(note, file=sys.stderr)
124
+ return 1
125
+ for path in paths:
126
+ print(path)
127
+ return 0
128
+
129
+
130
+ def _report(problems: list[str], passed: str) -> bool:
131
+ """Print the problems, or ``passed`` without any; return whether there were problems."""
132
+ for problem in problems:
133
+ print(problem, file=sys.stderr)
134
+ if not problems:
135
+ print(passed)
136
+ return bool(problems)
137
+
138
+
139
+ def _check(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
140
+ try:
141
+ settings = project()
142
+ style = settings.style() if args.style is None else load_style(args.style)
143
+ except (StyleError, OSError) as error:
144
+ print(error, file=sys.stderr)
145
+ return 1
146
+ css = args.css or settings.css
147
+ if not args.directories and css is None and not args.a11y:
148
+ parser.error("check needs a directory, --a11y, --css or css in [tool.figkit]")
149
+
150
+ failed = False
151
+ if args.a11y:
152
+ label = str(style.source) if style.source is not None else "bundled style"
153
+ failed = _report([f"{label}: {p}" for p in check_style(style)], f"{label}: accessible")
154
+ if css is not None:
155
+ try:
156
+ problems = check_tokens(css, style)
157
+ except OSError as error:
158
+ problems = [f"{css}: cannot be read, {error.strerror or error}"]
159
+ failed = _report(problems, f"{css}: ok") or failed
160
+ for directory in args.directories:
161
+ if not directory.is_dir():
162
+ print(f"{directory}: not a directory", file=sys.stderr)
163
+ failed = True
164
+ continue
165
+ problems = check(
166
+ directory,
167
+ opaque=args.opaque or ("card",),
168
+ width=None if args.any_width else WEB_WIDTH,
169
+ style=style,
170
+ )
171
+ for problem in problems:
172
+ print(f"{directory / problem}", file=sys.stderr)
173
+ failed = failed or bool(problems)
174
+ if not problems:
175
+ print(f"{directory}: ok")
176
+ return 1 if failed else 0
177
+
178
+
179
+ if __name__ == "__main__":
180
+ sys.exit(main())