diff --git a/evals/README.md b/evals/README.md index 039ee17..c903e87 100644 --- a/evals/README.md +++ b/evals/README.md @@ -1,6 +1,6 @@ # Cold-run briefs -Twelve briefs that show what the downloadable skill produces for someone who has never seen this repository. Run them after any change to `skills/plotter`, then compare the drawings with the previous run and with the catalogue. +Seventeen briefs that show what the downloadable skill produces for someone who has never seen this repository. Run them after any change to `skills/plotter`, then compare the drawings with the previous run and with the catalogue. ```sh bun run downloads # rebuild the archive under test @@ -11,13 +11,15 @@ evals/run.sh claude sonnet 07 # one brief, by number Each brief runs in its own fresh session in a temporary folder outside this checkout, printed when the run ends; set `PLOTTER_EVAL_OUT` to choose another. A session started inside the checkout would read this repository’s `AGENTS.md` and stop being a clean install. The session's files are the deliverables; `transcript.jsonl` records what the agent read, ran, and reported. -| Briefs | What they test | -| ------ | -------------------------------------------------------------------------------------- | -| 01–03 | README briefs. Each describes a catalogue drawing, so they mostly test retrieval. | -| 04–05 | Open briefs. The agent should stop and offer three options. | -| 06–10 | Plain-language subjects with no catalogue match, including a small size and TSX. | -| 11 | Animating a supplied drawing into one self-contained HTML file. | -| 12 | Critique. `upload-card.svg` has eight planted faults, listed below; none may be fixed. | +| Briefs | What they test | +| ------ | ------------------------------------------------------------------------------------------------------ | +| 01–03 | README briefs. Each describes a catalogue drawing, so they mostly test retrieval. | +| 04–05 | Open briefs. The agent should stop and offer three options. | +| 06–10 | Plain-language subjects, including a small size and TSX. | +| 11 | Animating a supplied drawing into one self-contained HTML file. | +| 12 | Critique. `upload-card.svg` has eight planted faults, listed below; none may be fixed. | +| 13–16 | Small placements and feature subjects. No pictogram as the main form; a compact version, not a redraw. | +| 17 | “Draw a magnifying glass.” The object is the brief, so a large constructed magnifier is correct here. | Planted faults in `attachments/upload-card.svg`: a gradient and drop shadow on the card; a skewed icon; hatching that leaves its region; a 240-unit span labelled 200; a dashed arrowhead on an arrow used for alignment; a heavy unexplained grid with every stroke at full weight; a letter-spaced bold title with straight quotes and a hyphen; a rule through the title. diff --git a/evals/briefs/13-empty-notifications-small.txt b/evals/briefs/13-empty-notifications-small.txt new file mode 100644 index 0000000..da8a4d6 --- /dev/null +++ b/evals/briefs/13-empty-notifications-small.txt @@ -0,0 +1 @@ +Empty state for the notifications panel when there is nothing new. It shows at 200px wide. SVG. diff --git a/evals/briefs/14-empty-payment-small.txt b/evals/briefs/14-empty-payment-small.txt new file mode 100644 index 0000000..07d19e6 --- /dev/null +++ b/evals/briefs/14-empty-payment-small.txt @@ -0,0 +1 @@ +Small illustration for a “no payment methods yet” card, about 240px wide. SVG. diff --git a/evals/briefs/15-404-card-small.txt b/evals/briefs/15-404-card-small.txt new file mode 100644 index 0000000..66ed11f --- /dev/null +++ b/evals/briefs/15-404-card-small.txt @@ -0,0 +1 @@ +404 illustration for a 320px-wide card. SVG. diff --git a/evals/briefs/16-search-hero.txt b/evals/briefs/16-search-hero.txt new file mode 100644 index 0000000..af04890 --- /dev/null +++ b/evals/briefs/16-search-hero.txt @@ -0,0 +1 @@ +Illustration for our search feature page hero. diff --git a/evals/briefs/17-object-magnifier.txt b/evals/briefs/17-object-magnifier.txt new file mode 100644 index 0000000..4ff25d3 --- /dev/null +++ b/evals/briefs/17-object-magnifier.txt @@ -0,0 +1 @@ +Draw a magnifying glass. diff --git a/public/plotter/downloads/plotter.zip b/public/plotter/downloads/plotter.zip index 43ca575..ca66350 100644 Binary files a/public/plotter/downloads/plotter.zip and b/public/plotter/downloads/plotter.zip differ diff --git a/scripts/check-plotter.tsx b/scripts/check-plotter.tsx index 025ca7c..472887d 100644 --- a/scripts/check-plotter.tsx +++ b/scripts/check-plotter.tsx @@ -109,6 +109,25 @@ if (fontCopies[0] !== fontCopies[1]) { throw new Error("The skill's bundled Cal Sans differs from the website's."); } statSync(resolve(skillRoot, "assets/fonts/OFL.txt")); +// The drawing checker must accept every current catalogue and grammar drawing. +const checked = Bun.spawnSync([ + "python3", + resolve(skillRoot, "scripts/check.py"), + ...["references/catalogue", "references/grammar"].flatMap((folder) => + readdirSync(resolve(skillRoot, folder)) + .filter((file) => file.endsWith(".svg")) + .map((file) => resolve(skillRoot, folder, file)), + ), +]); +if (checked.exitCode !== 0) { + throw new Error( + `scripts/check.py rejects a bundled drawing:\n${checked.stdout + .toString() + .split("\n") + .filter((line) => line.includes(": error")) + .join("\n")}`, + ); +} const bundled = readdirSync(catalogueRoot).filter((file) => file.endsWith(".svg"), ); diff --git a/skills/plotter/README.md b/skills/plotter/README.md index 4c586db..bec6f82 100644 --- a/skills/plotter/README.md +++ b/skills/plotter/README.md @@ -31,6 +31,7 @@ Seven bundled SVG anchors support construction-reference selection, and the [cat | Static registration, using the shared arrow/dimension helpers | `node assets/examples/registration.mjs > registration.svg` | | Resolved static SVG with editable labels | `python3 scripts/export-svg.py registration.svg registration-export.svg --id-prefix registration` | | PNG preview for inspection, light and dark | `python3 scripts/render.py registration-export.svg --theme both` | +| Rule check: text, strokes, canvas, and sparseness | `python3 scripts/check.py registration-export.svg` | | Animation and static fallback, with shared role CSS | Open `assets/examples/assembly-motion.html` in a modern browser; keep `assets/foundation/roles.css` in place. | Node.js is needed for the authoring example; Python 3 is needed for the static exporter and the preview renderer. The renderer uses an installed Chromium-based browser such as Chrome, Edge, or Brave, and falls back to `rsvg-convert`, `resvg`, Inkscape, ImageMagick, or macOS Quick Look. Recipients opening a resolved SVG need neither. The motion example uses browser SVG animation and a small player without a build or server. Keep its local stylesheet alongside it, or inline that generated stylesheet when delivering one HTML file. Cal Sans is bundled under the SIL Open Font License at `assets/fonts/`: previews render with it, and `export-svg.py --embed-font` carries it inside a standalone SVG. Without it on the host, labels fall back to sans-serif. diff --git a/skills/plotter/SKILL.md b/skills/plotter/SKILL.md index f349688..ac67c90 100644 --- a/skills/plotter/SKILL.md +++ b/skills/plotter/SKILL.md @@ -1,12 +1,49 @@ --- name: plotter -description: Create, critique, refine, or animate editable flat monochrome blueprint illustrations. Use for construction studies, conceptual diagrams, technical heroes, and empty states in this visual language, including requests to animate an existing Plotter drawing. Not general interface animation or engineering certification. +description: Draw, critique, refine, or animate flat monochrome blueprint illustrations as editable SVG — thin technical line drawings that explain an idea through one construction relationship. Use when the user wants an illustration, hero image, spot illustration, empty-state or 404 image, or an explanatory drawing for docs, a landing page, a feature page, or a README in a blueprint, technical-drawing, schematic, or line-art style; when they name Plotter or a catalogue code such as TIM-05; or when they ask to animate or review a Plotter drawing. Not for data charts, flowcharts in Mermaid or similar tools, icon sets, photorealistic or isometric art, general interface animation, or engineering certification. --- # Plotter Make one construction relationship carry the idea: alignment, proportion, assembly, routing, tangency, or intersection. Deliver editable vectors; animation adds behavior to a readable static composition. +## Hard rules + +These hold for every drawing, option sheet, and animation frame. The references explain them; they do not relax them. + +1. **One relationship, named before drawing.** State it in a sentence: what aligns, fits, overlaps, or is missing. A subject such as “agents” is not yet a composition, and marks added to a subject without a relationship are decoration. +2. **An object is never a sign for an idea.** A magnifier for search, a bell for notifications, a gear for settings: a conventional icon names the concept and explains nothing, with or without drafting marks around it. For a concept, draw the structure it works on and what happens to that structure, such as an ordered index with one position unfilled. Draw an object as the main form only when the brief is that object and the drawing shows how its shape is built. A glyph may sit inside a UI fragment at its real size, as a magnifier does inside a search field. +3. **A small size never changes the canvas or the language.** Compose at `560 × 440` whatever the display size, then derive a [compact version](references/drawing.md#small-placements) from the same geometry. Redrawing the idea on a small canvas produces an icon. +4. **Flat only.** Plan, elevation, or a conceptual plane. Never perspective, isometric depth, skew, gradients, shadows, or lighting: depth cues turn a construction into a rendering. +5. **Transparent forms.** Shapes are `fill="none"`. The one exception is a translucent highlight on a named selection, intersection, or result, painted once. A drawing has to read on any page color, and an opaque patch hides what crosses it. +6. **One ink, one weight.** Draw in `currentColor` with 1-unit strokes. Opacity sets the hierarchy and a dash pattern carries a meaning; never thicken a line for emphasis. +7. **Main form first.** The main form reads first, construction second, sparse dimensions and labels third. The drawing must still read with every supporting mark removed. +8. **Every mark earns its place.** Name the relationship each guide, arrow, hatch, grid, or dimension explains. If removing it leaves that relationship equally clear, remove it. +9. **Dimensions tell the truth.** Derive a label and its witnesses from the same geometry. A label that disagrees with the span it measures is an error. +10. **Arrows mean change.** Use one only for movement or direction, with a solid head even on a dashed shaft. Alignment and equal size use projections or dimensions. +11. **Every label looks the same: small, regular, and quiet.** Editable `` in `Cal Sans, sans-serif` at weight 400 and 10 to 12 units, at 0.72 ink for names and 0.5 for values and notes, with `stroke="none"`: text inherits the drawing’s stroke unless you turn it off, and stroked letters read as bold. No label is ever bold, larger, full ink, all caps, letter-spaced, italic, or upside down, whatever it names. Use typeset punctuation (’ – − “ ”). No title block or sheet number inside the drawing: the host page supplies those. +12. **One owner per edge, hatch inside its region.** Draw each coincident segment once, and clip hatching to the bounded region it identifies. +13. **Check and look before delivering.** Run `python3 scripts/check.py drawing.svg` and fix every error it reports. Then render, inspect, and do both again after the last edit. Without a render, say the visual review is pending. + +## Numbers + +Lengths are SVG units on a `560 × 440` canvas. + + +- Every stroke is **1** unit wide. +- Opacity: **1** primary form, section cut; **0.32** secondary form, dimension, leader, transfer, hidden, absent, or proposed outline; **0.18** hatch; **0.14** reference guide, centerline; **0.06** grid. +- Region highlight: `fill-opacity` **0.055**. +- Dashes: `8 3 1 3` centerline; `3 5` hidden, absent, or proposed; `4 6` movement or transfer. Everything else is continuous. +- Arrowhead: two solid **6**-unit legs at **45°**, meeting the shaft’s last dash at the tip. +- Dimension: **8**-unit slashes; at least **3** units clear around every label’s glyphs. +- Hatch: **12**-unit pitch along an edge, at −45°. + + +- Text is **10–12** units at weight **400**, filled and unstroked, at **0.72** ink for names and **0.5** for values and notes, as in every catalogue drawing. +- A guide that does not connect to a contour stops **8** units short of it. + +These are the defaults behind the role tokens. In the editable source, apply them with `data-plotter-role` and the generated stylesheet, as the [foundation](references/foundation.md) describes, so the user can retheme the drawing; literal values belong in the resolved export. + ## Choose the workflow Resolve this skill’s installed directory first. All links below are relative to it. The complete folder includes visual references, helper implementation, examples, and render and export tools; standalone work needs no website checkout or prior conversation. @@ -23,7 +60,7 @@ Resolve this skill’s installed directory first. All links below are relative t For drawing, critique, or animation: -1. Read [current direction](references/direction.md) and the [approved reference index](references/approved-references.md). Select and inspect the closest **bundled SVG** by its construction relationship. When the brief names a catalogue code such as `TIM-06`, also open that drawing from the [catalogue](references/catalogue/index.md); it is an example of a relationship, not a style reference. +1. Read [current direction](references/direction.md) and the [approved reference index](references/approved-references.md). Select and inspect the closest **bundled SVG** by its construction relationship. Then search the [catalogue index](references/catalogue/index.md), which gives each of its drawings one line, for the brief’s subject: search, schedule, upload, 404, and so on. When a catalogue drawing already covers the subject, or the brief names a code such as `TIM-06`, open that SVG and start from its relationship. It shows how this subject has been solved, not a layout to copy. 2. Read the [visual grammar](references/visual-grammar.md) to choose meaningful marks. Inspect the linked teaching SVG for each mark you add or revise. Existing unchanged marks do not require loading every teaching example. 3. Read the [drafting standard](references/drafting-standard.md): scope, stroke palette, and geometry/dimensions; include hatch grammar when hatching is involved and symbols/topology when making connectivity or product-behavior claims. @@ -36,8 +73,32 @@ Load additional material only for its branch: | Writing role-based SVG, using arrow/dimension/hatch helpers, overriding tokens, or exporting | [Portable foundation](references/foundation.md), including its supported cases and examples | | Explicitly asked for technical verification | [Verification prompt](references/verification-prompt.md), supplied with current source and renders | +## Faults to catch + +Each of these appeared in drawings made from this skill. Check the render for them before delivering. + +- A dimension, guide, or leader running through a label, including the dimension’s own value. Split the line around the text or move the label. +- Labels touching each other or a contour. +- A dimension on every part. Keep the two or three that explain the construction; a full chain of measurements buries the relationship. +- An object standing in for a concept, such as a magnifier for search or a bell for notifications, however carefully it is constructed. +- A small display size answered with a new small canvas, thick strokes, and icon shapes instead of the compact version. +- A subject the catalogue already covers, drawn without opening that drawing. +- The composition pushed against one edge of the canvas, or the focal form off-center without a reason. +- Text that inherits the drawing’s stroke and reads bold, or any label that is bold, oversized, full ink, all caps, or upside down. +- A title block or a sheet number. +- A shape or object study that is only an outline and a dimension, with none of the geometry that builds it. +- One highlight painted on two shapes, so the overlap reads twice. +- An edit made after the last render. + ## Finish the requested artifact Use the selected workflow's completion criteria. Save deliverables where the user is working, not in a temporary folder, and give their paths. Deliver the editable source, the requested preview/export, and a concise account of the relationship, relevant limitations, and what was actually inspected. If rendering or interaction was unavailable, identify that gap instead of claiming visual or motion verification. Honor the requested verification scope; automated checks and tests are not prerequisites when the user excludes them. -Write that account for someone who has not seen this package. Name a borrowed drawing by its title and what you took from it; a bare catalogue code or the word “approved” tells them nothing. +Write the report for someone who has not seen this package, in this order, and keep it under about 150 words. A critique may run longer. + +1. **Files:** each deliverable’s path. +2. **What it shows:** the relationship in one or two sentences. Name a borrowed drawing by its title and what you took from it; a bare catalogue code or the word “approved” tells the reader nothing. +3. **Checked:** what you rendered and looked at, with sizes and themes. +4. **Not checked:** what remains unverified, and any assumption the reader should confirm. + +When offering options, list them after the files and end with the question. For a critique, give the verdict first, then the faults ranked by how much they hurt, each with where it is and the fix. diff --git a/skills/plotter/references/drawing.md b/skills/plotter/references/drawing.md index 8a3eb18..98031f6 100644 --- a/skills/plotter/references/drawing.md +++ b/skills/plotter/references/drawing.md @@ -28,6 +28,31 @@ For a collection, establish this reference comparison on one representative comp **Complete when:** the forms and essential labels carry the idea, every supporting mark has a named purpose, and removing decorative detail does not destroy the subject. +## Shape and object studies + +When the brief is a shape or an object, the drawing explains how that form is built. An outline with a width and a height is sparse: it shows what the object looks like, which the reader already knew. Catalogue studies such as [Anatomy of a letter](catalogue/TYP-01.svg), [The corner rule](catalogue/GEO-03.svg), and [An unbuilt arch](catalogue/EMP-04.svg) carry these layers, and a study needs most of them: + +- **Axes.** A centerline through every center and along each axis of symmetry, extended past the form. +- **Generating geometry.** For each curve, its center mark and a radius leader labelled `R…` or `r`. Where the outline uses part of a circle, draw the rest of that circle, or its continuation, in guide weight. +- **Construction points.** Small node marks where construction meets the outline: tangent points, anchors, and the ends of arcs. +- **A module.** Level guides or a quiet grid that the form’s key edges sit on, with one dimension naming the unit `u`. +- **Two or three dimensions** in that unit, relating the parts to each other. Never a chain along every edge. +- **One or two callouts** naming parts the shape cannot name itself, each on a leader. +- **One selected region**, hatched or highlighted, when a part needs singling out. + +Each layer still has to explain the construction. Do not add one the form does not have. + +## Small placements + +A display width under about 400 px shrinks 11-unit labels below 8 px, and the full drawing stops reading. Never answer that by redrawing the idea on a small canvas: the result is an icon. Finish the `560 × 440` drawing first, then derive a compact version from the same geometry, as the Plotter website does for its empty states. + +- Keep the main forms and the one mark that carries the idea. Remove the labels, dimensions, grids, and guides that cannot be read at the target size. Text is removed, never shrunk. +- Crop the `viewBox` to the kept forms with a margin of about 16 units, still in the drawing’s own units. Do not rescale or redraw coordinates, and let no kept form touch or cross the crop edge. +- Set `vector-effect="non-scaling-stroke"` on every stroked element, so each stroke stays one pixel wide at any size. Dash patterns then measure in screen pixels: use `2 2` where the full drawing used a longer dash. +- Run `scripts/check.py --compact` on it, then render it at the target width and check that each kept form is still distinct. + +Deliver both files and say which is which. The compact version is a view of the drawing, not a second composition. + ## Implement the editable source Read [foundation.md](foundation.md) for shared roles, helpers, and export. Use native SVG for the composition and for unsupported constructions such as curved arrows or curved hatch regions. The helper API covers straight arrows, axis-aligned dimensions, and rectangular H1/H2 hatching; it does not choose the composition. @@ -44,7 +69,14 @@ Use an accessible title and description for meaningful standalone output. In a h Render the candidate beside the selected reference at a common intended size, then inspect the thumbnail. For a revision, also compare with its own previous render. Inspect both themes when the host uses them and the actual narrow layout when embedding it. -Render with the packaged script, resolved from the skill directory, and open the PNG it names: +First run the checker, resolved from the skill directory, and fix every error. It catches what a glance at a render misses: stroked, bold, or full-ink text, a label outside 10 to 12 units or turned upside down, a stroke that is not 1 unit, a gradient, a skew, or the wrong canvas. A “sparse” warning means the drawing has fewer marks than nine in ten catalogue drawings. For a shape or object study it is an error: add the missing layers. For any other drawing, add the missing construction or say in the report why it is complete. + +```sh +python3 scripts/check.py drawing.svg +python3 scripts/check.py compact.svg --compact # for a compact version +``` + +Then render with the packaged script and open the PNG it names: ```sh python3 scripts/render.py drawing.svg # native size, light surface diff --git a/skills/plotter/scripts/build-standard.py b/skills/plotter/scripts/build-standard.py index 30d4de2..cff9ecf 100644 --- a/skills/plotter/scripts/build-standard.py +++ b/skills/plotter/scripts/build-standard.py @@ -80,4 +80,45 @@ def number(value): if count != 1: raise ValueError(f"Expected one {name} table marker in {guide}.") guide.write_text(text) + +# The entry file repeats the numbers an agent needs before it opens a reference. +names = { + "primary": "primary form", "section": "section cut", "secondary": "secondary form", + "dimension": "dimension", "leader": "leader", "transfer": "transfer", + "hidden": "hidden, absent, or proposed outline", "hatch": "hatch", + "guide": "reference guide", "centerline": "centerline", "grid": "grid", +} +widths = {tokens[role["width"]] for role in roles.values()} +if len(widths) != 1: + raise ValueError("SKILL.md states one stroke width; the standard now has several.") +by_opacity = {} +for key, name in names.items(): + by_opacity.setdefault(tokens[roles[key]["opacity"]], []).append(name) +opacities = "; ".join( + f"**{number(value)}** {', '.join(by_opacity[value])}" for value in sorted(by_opacity, reverse=True) +) +dashes = "; ".join( + f"`{roles[key]['dash']}` {label}" + for key, label in (("centerline", "centerline"), ("hidden", "hidden, absent, or proposed"), ("transfer", "movement or transfer")) +) +geometry = standard["geometry"] +numbers = [ + f"- Every stroke is **{number(widths.pop())}** unit wide.", + f"- Opacity: {opacities}.", + f"- Region highlight: `fill-opacity` **{number(tokens['--plotter-opacity-highlight'])}**.", + f"- Dashes: {dashes}. Everything else is continuous.", + f"- Arrowhead: two solid **{number(geometry['arrow']['legLength'])}**-unit legs at **{number(geometry['arrow']['angle'])}°**, meeting the shaft’s last dash at the tip.", + f"- Dimension: **{number(geometry['dimension']['slashExtent'])}**-unit slashes; at least **{number(geometry['dimension']['labelClearance'])}** units clear around every label’s glyphs.", + f"- Hatch: **{number(geometry['hatch']['edgePitch'])}**-unit pitch along an edge, at −45°.", +] +entry = ROOT / "SKILL.md" +begin, end = "", "" +entry_text, count = re.subn( + re.escape(begin) + r"[\s\S]*?" + re.escape(end), + lambda _: begin + "\n" + "\n".join(numbers) + "\n" + end, + entry.read_text(), +) +if count != 1: + raise ValueError(f"Expected one numbers marker in {entry}.") +entry.write_text(entry_text) print("Generated Plotter role CSS, runtime standard, and numeric reference tables.") diff --git a/skills/plotter/scripts/check.py b/skills/plotter/scripts/check.py new file mode 100644 index 0000000..6ad55fe --- /dev/null +++ b/skills/plotter/scripts/check.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Check a Plotter SVG against the rules a render cannot be trusted to show.""" + +import argparse +import json +import re +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + + +SHAPES = {"path", "line", "circle", "rect", "ellipse", "polyline", "polygon"} +STANDARD = json.loads((Path(__file__).resolve().parents[1] / "assets" / "foundation" / "standard.json").read_text()) +# Every catalogue label sits between these: about 0.72 for names, 0.5 for values and notes. +INK_MIN, INK_MAX = 0.45, 0.8 +INHERITED = ( + "stroke", "stroke-width", "font-weight", "font-size", "font-style", + "letter-spacing", "text-transform", "fill-opacity", +) +# The tenth percentile of the bundled catalogue: fewer marks than this is sparse. +SPARSE_SHAPES, SPARSE_LABELS = 10, 3 + + +def local(tag): + return tag.rsplit("}", 1)[-1] if isinstance(tag, str) else "" + + +def own_styles(node): + styles = {name: node.get(name) for name in (*INHERITED, "vector-effect", "transform", "opacity") if node.get(name) is not None} + for declaration in (node.get("style") or "").split(";"): + name, separator, value = declaration.partition(":") + if separator: + styles[name.strip()] = value.strip() + return styles + + +def number(value): + match = re.match(r"\s*(-?[\d.]+)", value or "") + return float(match.group(1)) if match else None + + +def check(source, compact=False): + errors, warnings = [], [] + try: + root = ET.fromstring(source) + except ET.ParseError as error: + return [f"Not well-formed SVG: {error}"], [] + + view_box = (root.get("viewBox") or "").replace(",", " ").split() + if not compact and view_box[2:] != ["560", "440"]: + errors.append( + f"Canvas is viewBox {' '.join(view_box) or 'missing'}; draw at 0 0 560 440. " + "For a small placement, derive a compact version and check it with --compact." + ) + + counts = {"shapes": 0, "labels": 0, "stroked": 0, "non_scaling": 0} + + def walk(node, inherited, in_defs, opacity=1.0, turn=0.0): + name = local(node.tag) + styles = own_styles(node) + current = {**inherited, **{key: value for key, value in styles.items() if key in INHERITED}} + in_defs = in_defs or name == "defs" + role = STANDARD["roles"].get(node.get("data-plotter-role") or "") + if "opacity" in styles: + opacity *= number(styles["opacity"]) or 1.0 + elif role: + opacity *= STANDARD["tokens"][role["opacity"]] + turn += sum(float(angle) for angle in re.findall(r"rotate\(\s*(-?[\d.]+)", styles.get("transform", ""))) + + if name in ("linearGradient", "radialGradient", "filter"): + errors.append(f"<{name}> found: no gradients, shadows, or lighting.") + if re.search(r"skew|matrix|rotate3d|perspective", styles.get("transform", "")): + errors.append(f"<{name}> uses transform “{styles['transform']}”: no skew or perspective.") + + if name == "text": + label = " ".join("".join(node.itertext()).split()) + shown = f"“{label[:40]}”" + if not in_defs: + counts["labels"] += 1 + if current.get("stroke", "none") != "none": + errors.append(f"Text {shown} is stroked, which makes it look bold. Set stroke=\"none\" on the text or its group.") + weight = current.get("font-weight", "400") + if weight not in ("400", "normal"): + errors.append(f"Text {shown} has font-weight {weight}; every label is weight 400.") + size = number(current.get("font-size")) + if not compact and (size is None or size < 10 or size > 12): + errors.append(f"Text {shown} has font-size {current.get('font-size', 'unset')}; labels are 10 to 12 units.") + ink = opacity * (number(current.get("fill-opacity")) if current.get("fill-opacity") else 1.0) + if not compact and not INK_MIN <= ink <= INK_MAX: + errors.append( + f"Text {shown} is at {ink:.2f} ink; labels are never full ink. " + "Use opacity 0.72 for names and 0.5 for values and notes." + ) + if 90 < turn % 360 < 270: + errors.append(f"Text {shown} is rotated {turn:g}° and reads upside down; turn it to read from the bottom or the right.") + if current.get("font-style", "normal") != "normal": + errors.append(f"Text {shown} is {current['font-style']}; no italic.") + if current.get("letter-spacing", "normal") not in ("normal", "0", "0px"): + errors.append(f"Text {shown} has letter-spacing; none is added.") + if current.get("text-transform", "none") != "none" or (re.search(r"[A-Z]{4,}", label) and label.upper() == label): + errors.append(f"Text {shown} is all caps; labels are never all caps.") + if compact: + warnings.append(f"Compact version still contains text {shown}; remove text that cannot be read at the target size.") + + if name in SHAPES and not in_defs: + counts["shapes"] += 1 + if current.get("stroke", "none") != "none": + counts["stroked"] += 1 + counts["non_scaling"] += styles.get("vector-effect") == "non-scaling-stroke" + width = current.get("stroke-width", "1") + if "var(" not in width and number(width) not in (1.0, None): + errors.append(f"<{name}> has stroke-width {width}; every stroke is 1 unit, and emphasis comes from opacity.") + + for child in node: + walk(child, current, in_defs, opacity, turn) + + walk(root, {}, False) + + if compact and counts["stroked"] and counts["non_scaling"] < counts["stroked"]: + errors.append( + f"{counts['stroked'] - counts['non_scaling']} stroked elements lack vector-effect=\"non-scaling-stroke\"; " + "a compact version keeps every stroke one pixel wide." + ) + if not compact and (counts["shapes"] < SPARSE_SHAPES or counts["labels"] < SPARSE_LABELS): + warnings.append( + f"Sparse: {counts['shapes']} shapes and {counts['labels']} labels, fewer than nine in ten catalogue drawings. " + "Show how the form is built: axes, generating circles, radius leaders, tangent points, a unit, and part names." + ) + return errors, warnings + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("input", type=Path, nargs="+") + parser.add_argument("--compact", action="store_true", help="Check a compact version: any canvas, non-scaling strokes, no text.") + args = parser.parse_args() + failed = False + for path in args.input: + errors, warnings = check(path.read_text(encoding="utf-8"), args.compact) + seen = set() + for kind, messages in (("error", errors), ("warning", warnings)): + for message in messages: + if message not in seen: + seen.add(message) + print(f"{path}: {kind}: {message}") + if errors: + failed = True + elif not warnings: + print(f"{path}: ok") + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main()