Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Add practical command guides and a contribution template (#5237) (#6772)

Victor Santos Oliveira91638cb1f38b
diff --git a/attribution/pending/command-guides.md b/attribution/pending/command-guides.md
new file mode 100644
index 0000000000..c349d28f21
--- /dev/null
+++ b/attribution/pending/command-guides.md
@@ -0,0 +1,2 @@
+| docs/book/src/generated/hem.png | SolidCraft contributors | rendered by `cargo xtask book` (`solidcraft-cli snapshot docs/book/scripts/hem.json`; gitignored), original sheet metal demonstration | MIT OR Apache-2.0 |
+| docs/book/scripts/hem.json | SolidCraft contributors | original parametric recipe for an 80 × 50 mm sheet with an 8 mm returned edge, authored for the command guide | MIT OR Apache-2.0 |
diff --git a/docs/book/command-guide-template.md b/docs/book/command-guide-template.md
new file mode 100644
index 0000000000..632a309c3b
--- /dev/null
+++ b/docs/book/command-guide-template.md
@@ -0,0 +1,39 @@
+One sentence explaining what this command does and when someone would use it.
+
+#### Before you start
+
+- Explain the required body, sketch, region, edge, face or point in ordinary words.
+- State whether a selection is required and what cannot be used instead.
+
+#### Options
+
+| Choice in the dialog | Meaning | Example or reason to choose it |
+| --- | --- | --- |
+| Replace with a real option | Explain the effect without copying parameter syntax. | A useful value with units. |
+
+#### Try it
+
+1. Start from a small reproducible design.
+2. Name the selection, command, settings and expected visible result.
+
+#### Tips and common mistakes
+
+- **Do** explain a useful habit and its benefit.
+- **Don't** describe an unsupported selection as if it worked.
+
+#### Examples and community resources
+
+Add only rows for resources you have checked. Replace placeholders before
+submitting; do not publish an empty resource table.
+
+| Kind | Resource and what it teaches | Author and licence |
+| --- | --- | --- |
+| Tip | Link to a focused explanation. | Credit and permission to reuse. |
+| Demo | Link to a short recording or reproducible recipe. | Credit and licence. |
+| Model | Link to an original SolidCraft design or an openly licensed model. | Credit and licence. |
+| Screenshot | Link to or embed an actual SolidCraft result, with descriptive alternative text. | Credit and licence. |
+
+#### See also
+
+Use `{{#command solid.extrude}}` with a real related command's ID and explain
+why it is related. The generator supplies its current label and a direct link.
diff --git a/docs/book/command-guides/sheet.flange.md b/docs/book/command-guides/sheet.flange.md
new file mode 100644
index 0000000000..b9b1154948
--- /dev/null
+++ b/docs/book/command-guides/sheet.flange.md
@@ -0,0 +1,67 @@
+Create a sheet metal base, bend an existing edge into a wall, or build a contour
+from an open sketch. The sheet metal rule supplies the material thickness and
+bend settings so the folded and flat versions describe the same part.
+
+#### Before you start
+
+| Flange type | What you need to select | Result |
+| --- | --- | --- |
+| Base | A closed region in a finished sketch. | A new flat sheet metal body. |
+| Edge | One or more supported edges of an existing sheet metal body. | Bent walls along those edges. A sketch is not required for this mode. |
+| Contour | An open chain of straight sketch lines. | A sheet following that outline, extended by the chosen distance. |
+
+Choose or create a **Sheet Metal Rule** before building the part. To work from
+an ordinary solid plate, use **Convert to Sheet Metal** first. An arbitrary
+solid edge does not become a sheet metal edge just by selecting Flange.
+
+#### Options
+
+| Choice | Meaning |
+| --- | --- |
+| Type | Base, Edge or Contour. The selection determines which input is appropriate. |
+| Rule | Sets thickness, bend radius, K-factor and the gaps/reliefs that keep bends manufacturable. Change thickness in the rule, not as a flange height. |
+| Height | Sets the edge flange's height. Check the height reference and preview when matching a drawing dimension. |
+| Angle | Sets how far the edge bends; **90°** makes a right-angle wall. |
+| Per-edge angle and height | Lets selected edges in one feature have different dimensions. Empty values use the common setting. |
+| Position | Places the flange relative to the selected edge. The preview shows which material remains inside or outside the original outline. |
+| Flip | Bends toward the other side of the sheet. |
+| Corner Relief Shape and size | Use the rule's setting or override relief between edge flanges of this feature. These overrides are not available for base or contour flanges. |
+| Distance | Sets the length of a contour flange's extrusion along the open sketch. |
+
+#### Try it: two sides of a tray
+
+1. Set a sheet rule with **1.5 mm** thickness and **1.5 mm** bend radius.
+2. Draw and finish an **80 × 50 mm** rectangular sketch.
+3. Choose **Flange**, select the rectangle's region and make a **Base** flange.
+4. Choose **Flange** again, select an edge and set its height to **20 mm**.
+5. Add another 20 mm flange on the opposite edge. Check the bend directions
+ before confirming each feature.
+6. Use **Create Flat Pattern** to inspect the developed part and bend lines.
+
+#### Tips and common mistakes
+
+- **Do** use one edge flange feature for adjoining walls whose shared corners
+ should close together. Flanges made as separate features keep their own ends.
+- **Do** inspect warnings and the flat pattern; a relief that cannot fit may be
+ left out with a warning.
+- **Don't** confuse height with sheet thickness. The rule owns thickness.
+- **Don't** select a sketch point for an edge flange: choose an edge of the
+ sheet. For a base flange, select a closed sketch region instead.
+
+#### Examples and community resources
+
+![An 80 by 50 mm sheet with two opposite 20 mm edge flanges](../generated/sheet-metal.png)
+
+| Resource | What to explore | Author and licence |
+| --- | --- | --- |
+| [Editable sheet metal demo](https://github.com/tangency-labs/solidcraft/blob/main/docs/book/scripts/sheet-metal.json) | The rule, base sketch and two edge flanges used in this illustration. | SolidCraft contributors; MIT OR Apache-2.0. |
+
+[Contribute a tip, demo, model or screenshot](../dev/command-guides.md), explaining
+the edge or region that must be selected.
+
+#### See also
+
+{{#command sheet.hem}} returns an edge back toward the sheet.
+{{#command sheet.fold}} bends a sheet along a chosen line.
+{{#command sheet.manage_rules}} controls thickness and bend settings.
+{{#command sheet.flat_pattern}} shows the developed part.
diff --git a/docs/book/command-guides/sheet.hem.md b/docs/book/command-guides/sheet.hem.md
new file mode 100644
index 0000000000..2a7c9203d9
--- /dev/null
+++ b/docs/book/command-guides/sheet.hem.md
@@ -0,0 +1,53 @@
+Fold a sheet metal edge back through a half turn to form a return. Use a hem
+when you need a doubled-over edge, rather than an upright wall.
+
+#### Before you start
+
+- You need an existing **sheet metal body** and a supported free sheet edge.
+ Make a base flange or convert a suitable solid plate first.
+- Select the **edge**, not a sketch line, face or point. Hem does not require
+ a new sketch. A bend along a line inside the sheet uses Fold instead.
+- Leave room for the return so it does not run into another wall or return.
+
+#### Options
+
+| Choice | Meaning |
+| --- | --- |
+| Edges | The sheet edges to turn back. Check that the preview changes the intended edge. |
+| Length | The return's length, measured to its outer face. It is not the thickness of the sheet. |
+| Gap | Controls the inner radius of the return bend. Leave it empty to use the sheet rule's hem setting. |
+| Flip | Turns the return toward the other side of the sheet. |
+
+#### Try it: a returned edge
+
+1. Create an **80 × 50 mm** base flange in **1.5 mm** sheet.
+2. Choose **Hem** and select a free 80 mm edge of the sheet.
+3. Set **Length** to **8 mm** and **Gap** to **1.5 mm**.
+4. Check which side receives the return; use **Flip** if necessary, then confirm.
+5. Inspect **Create Flat Pattern** to see the material needed for the bend.
+
+#### Tips and common mistakes
+
+- **Do** check the bend in the preview: an edge returning toward another feature
+ needs enough clearance.
+- **Don't** draw a sketch line to tell Hem where to bend. Its input is an
+ existing sheet edge; use Fold for a bend line through a panel.
+- **Don't** use Hem for an ordinary right-angle wall. That is an edge Flange.
+
+#### Examples and community resources
+
+![A sheet metal plate with one edge returned back toward the plate](../generated/hem.png)
+
+| Resource | What to explore | Author and licence |
+| --- | --- | --- |
+| [Editable hem demo](https://github.com/tangency-labs/solidcraft/blob/main/docs/book/scripts/hem.json) | The sheet rule, base flange and 8 mm return used in this illustration. | SolidCraft contributors; MIT OR Apache-2.0. |
+
+[Contribute a tip, demo, model or screenshot](../dev/command-guides.md), explaining
+the selected edge and dimensions.
+
+#### See also
+
+{{#command sheet.flange}} makes a base sheet or an angled wall.
+{{#command sheet.fold}} bends along a line in the sheet.
+{{#command sheet.manage_rules}} sets the default hem gap.
+{{#command sheet.flat_pattern}} shows the developed part and bend lines.
diff --git a/docs/book/command-guides/solid.extrude.md b/docs/book/command-guides/solid.extrude.md
new file mode 100644
index 0000000000..0062ec22ba
--- /dev/null
+++ b/docs/book/command-guides/solid.extrude.md
@@ -0,0 +1,71 @@
+Turn a flat sketch region into a solid, or add or remove material from an existing
+body. For example, a rectangle extruded 20 mm becomes a rectangular block.
+
+#### Before you start
+
+- For a solid extrusion, finish a sketch with at least one closed region. Select
+ the region you want, rather than an individual edge or point.
+- You can also select a planar face of an existing body instead of a sketch.
+- To add or remove material, an existing body must meet the extrusion. Choose
+ **New Body** when you want an independent piece.
+- **Thin Extrude** uses sketch curves instead of filled regions; open chains are
+ allowed. This is useful for a wall or a ring.
+
+#### Options
+
+| Choice | What it does | When to use it |
+| --- | --- | --- |
+| Profiles | Chooses the filled sketch regions to extrude. A loop inside another loop makes a hole. | Select just the regions you need when a sketch contains several. |
+| Distance | Sets how far the shape extends. Values can include units, such as **20 mm**, or a named design parameter. | Make a part to a known size. |
+| Reverse Direction | Sends the extrusion to the other side of the sketch. | The preview points away from the intended body. |
+| Symmetric | Splits the entered total distance equally across the sketch plane. **10 mm** extends **5 mm on each side**. | Keep the sketch at the middle of a part. |
+| Two Sides | Sets a separate distance on each side. | The sketch is between two unequal extensions. |
+| Through All | Reaches through the target body. | Cut a hole that must stay open when the body becomes thicker. |
+| To Object | Stops at a selected target face, vertex or point. An offset can stop before or beyond that target. | Let the end follow another part of the design. |
+| Start | Starts at the sketch, at an offset from it, or from a selected object. | Leave a gap before the extrusion begins. |
+| Taper Angle | Slopes the side walls. | Make drafted sides; reduce the angle if the profile's narrow details cannot support it. |
+| Operation | **New Body** makes a separate piece; **Join** adds material; **Cut** removes it; **Intersect** keeps only the overlap. | Choose the intended result explicitly when the automatic preview is not what you want. |
+| Target bodies | Chooses which existing bodies take part in a join, cut or intersection. | Several bodies lie in the extrusion's path. |
+| Thin Extrude | Builds walls along curves; thickness and side control where the material lies. Two-sided walls can have different thicknesses. | Make ribs, walls or rings without drawing both wall boundaries. |
+
+#### Try it: a 20 mm block
+
+1. Create a sketch on the XY plane and draw a closed rectangle.
+2. Finish the sketch and choose **Extrude**.
+3. Select the rectangular region, set **Distance** to **20 mm**, and choose
+ **New Body**.
+4. Check the preview's direction and confirm. You should have one solid block.
+5. Edit the extrusion in the timeline to change its distance later.
+
+#### Tips and common mistakes
+
+- **Do** check the operation before confirming. Automatic operation can join an
+ addition or cut into an existing body; it is not a promise of a separate part.
+- **Do** use Through All for a cut that should follow later thickness changes.
+- **Don't** expect an open outline to make a filled solid. Close it, or choose
+ Thin Extrude for a wall.
+- **Don't** assume a symmetric distance is the distance on each side. New
+ symmetric extrusions use the total distance; older saved designs can retain
+ their earlier convention.
+- Taper with a two-sided or symmetric extent is not supported. A very steep
+ taper can also be refused rather than creating an invalid result.
+
+#### Examples and community resources
+
+![Bracket made with an extrusion and a second extrusion that cuts the holes](../generated/bracket.png)
+
+The bracket starts with a closed L-shaped profile; another extrusion removes
+the two holes. Its dimensions are controlled by design parameters.
+
+| Resource | What to explore | Author and licence |
+| --- | --- | --- |
+| [Editable bracket recipe](https://github.com/tangency-labs/solidcraft/blob/main/examples/bracket.json) | A complete SolidCraft example using an extrusion, a fillet and a cut. | SolidCraft contributors; MIT OR Apache-2.0. |
+
+[Contribute a tip, demo, model or screenshot](../dev/command-guides.md) to add a
+reviewed resource beside this explanation.
+
+#### See also
+
+{{#command solid.revolve}} turns a profile around an axis.
+{{#command solid.sweep}} carries a profile along a path.
+{{#command sheet.flange}} creates sheet metal with a thickness rule.
diff --git a/docs/book/scripts/hem.json b/docs/book/scripts/hem.json
new file mode 100644
index 0000000000..d1d8e6445e
--- /dev/null
+++ b/docs/book/scripts/hem.json
@@ -0,0 +1,8 @@
+{"commands": [
+ {"command": "sheet.manage_rules", "params": {"name": "Hem demo", "thickness": "1.5 mm", "bend_radius": "1.5 mm", "k_factor": 0.44, "active": true}},
+ {"command": "sketch.create", "params": {"plane": "XY", "name": "Base"}},
+ {"command": "sketch.rectangle.two_point", "params": {"p0": [0, 0], "p1": [80, 50]}},
+ {"command": "sketch.finish", "params": {}},
+ {"command": "sheet.flange", "params": {"type": "base"}},
+ {"command": "sheet.hem", "params": {"edges": [[40, 0, 1.5]], "length": "8 mm", "gap": "1.5 mm"}}
+]}
diff --git a/docs/book/src/SUMMARY.md b/docs/book/src/SUMMARY.md
index b74ed45d31..6c309d6357 100644
--- a/docs/book/src/SUMMARY.md
+++ b/docs/book/src/SUMMARY.md
@@ -23,6 +23,7 @@
# Developer guide
- [Contributing](dev/contributing.md)
+- [Command guides and community resources](dev/command-guides.md)
- [Architecture](dev/architecture.md)
- [UI kit](dev/ui-kit.md)
- [Extensible library proposal](dev/libraries.md)
diff --git a/docs/book/src/dev/command-guides.md b/docs/book/src/dev/command-guides.md
new file mode 100644
index 0000000000..2b3d21b6bb
--- /dev/null
+++ b/docs/book/src/dev/command-guides.md
@@ -0,0 +1,68 @@
+# Contributing command guides and resources
+
+The command reference combines the live command registry with reviewed Markdown
+guides. A guide appears **inside its command's entry**, before the collapsed
+automation syntax. You can improve one entry without rewriting the whole manual.
+The reference's **Practical guides** list automatically links to every available
+guide; adding a guide does not require editing an index or Rust code.
+
+## Add or improve an entry
+
+1. Find the command in the [reference](../reference/commands.md). Its ID is in
+ **Automation details**.
+2. Copy the [guide template](https://github.com/tangency-labs/solidcraft/blob/main/docs/book/command-guide-template.md)
+ to `docs/book/command-guides/<command-id>.md`, or edit its existing file.
+ For example, Extrude lives in `solid.extrude.md`.
+3. Explain what the tool does, what must exist or be selected first, the dialog's
+ choices in a table, a short example, and useful DOs and DON'Ts. Use plain
+ language rather than copying the raw automation parameters.
+4. Add related commands and any checked community resources, then open a pull
+ request. Documentation changes are reviewed like code.
+
+Do not edit the generated `src/reference/commands.md`: rebuilding replaces it.
+The generator rejects guide filenames whose command is absent from the registry.
+Names, groups, shortcuts and automation parameters continue to come from that
+registry; handwritten explanations remain editable independently.
+
+Use fourth-level headings (`####`) inside an entry so the command remains the
+parent section. Write image and page paths relative to the **generated reference
+page**, `docs/book/src/reference/commands.md`, not to the input guide file.
+For example, `../generated/sheet-metal.png` and `../guide/sheet-metal.md`.
+
+## Related commands
+
+Write a command link as `{{#command sheet.hem}}`. The generator inserts its
+current name and links directly to that command. Unknown or missing command IDs
+and unfinished directives fail the book build, helping contributors catch stale links.
+Normal Markdown links can point to guide pages or external resources.
+
+## Community resources
+
+You can add a focused tip, a short demo, a model or an illustrative screenshot
+to the entry's resource table. Explain what the reader learns from each link;
+include author and licence information. Links are reviewed, not automatically
+collected from the web. A resource need not cover the whole command.
+
+Use original SolidCraft examples or openly licensed resources with permission
+to share. Do not use designs, screenshots, help text or artwork extracted from
+commercial CAD products, or GPL/LGPL/AGPL code. Prefer small public-safe examples
+and remove private designs, paths and account information from evidence.
+
+For a new file asset, follow `assets/AGENTS.md` and add its attribution in a new
+`attribution/pending/<change>.md` file. A reproducible recipe in
+`docs/book/scripts/` can be rendered by the book builder; generated images stay
+out of Git. Existing examples demonstrate both inline pictures and resource links.
+
+## Preview and review
+
+Run `cargo xtask book` with mdBook installed, inspect the command entry and its
+links, and check the example in SolidCraft. Confirm the required selection,
+units, defaults and limitations against the implementation. Show reviewers an
+actual before/after screenshot of the rendered entry. Repository quality gates
+still apply before a commit.
+
+## Copyable template
+
+````markdown
+{{#include ../../command-guide-template.md}}
+````
diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md
index 023da7c0f1..2421ba7adf 100644
--- a/docs/book/src/guide/features.md
+++ b/docs/book/src/guide/features.md
@@ -1,5 +1,8 @@
# Solid features
+For prerequisites, a readable options table and a first example, open the
+[practical Extrude guide](../reference/commands.md#command-solid.extrude).
+
Features live on the **timeline** and rebuild incrementally from the first one that changed.
Each one can be edited (double-click), suppressed, renamed, reordered (if nothing it depends on
moves after it), rolled back to, and deleted. Deleting asks first when other features depend on
diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md
index e0ba1e641c..4a6441f817 100644
--- a/docs/book/src/guide/sheet-metal.md
+++ b/docs/book/src/guide/sheet-metal.md
@@ -4,9 +4,10 @@ MODEL → MODIFY offers Convert to Sheet Metal. The SHEET METAL tab is always av
and selected when the active body is a sheet), and builds parts from a sheet of constant thickness under a **sheet metal rule**
(thickness, bend radius, K-factor), set in **Sheet Metal Rules** (`sheet.manage_rules`).
-- **Flange** (`sheet.flange`): a base flange from a sketch profile, a contour flange from an open
+- [**Flange**](../reference/commands.md#command-sheet.flange): a base flange from a sketch profile, a contour flange from an open
sketch, or an edge flange from a part edge.
-- **Hem** (`sheet.hem`) and **Fold** (`sheet.fold`) along a sketch line.
+- [**Hem**](../reference/commands.md#command-sheet.hem) returns a sheet edge back toward the sheet; no new sketch is required.
+- **Fold** (`sheet.fold`) bends the sheet along a sketch line.
- **Unfold / Refold** (`sheet.unfold`, `sheet.refold`) for working on the flat part.
- **Convert** (`sheet.convert`) turns a plate of constant thickness into sheet metal, or, with
bend edges, a solid or a shelled body.
diff --git a/xtask/src/book.rs b/xtask/src/book.rs
index 5a301fbb43..d598a31cb2 100644
--- a/xtask/src/book.rs
+++ b/xtask/src/book.rs
@@ -7,6 +7,7 @@
//! gitignored and attributed in ATTRIBUTION.md. The book itself is built by `mdbook` (a separate
//! tool, not a dependency) into `target/book`.
+use std::collections::BTreeMap;
use std::path::Path;
use serde_json::Value;
@@ -29,7 +30,9 @@ pub fn run(root: &Path, build: bool) -> Result<(), String> {
return Err(format!("solidcraft-cli commands failed:\n{}", String::from_utf8_lossy(&out.stderr)));
}
let cmds: Value = serde_json::from_slice(&out.stdout).map_err(|e| format!("commands JSON: {e}"))?;
- let md = reference(cmds.as_array().map(Vec::as_slice).unwrap_or_default());
+ let cmds = cmds.as_array().ok_or("commands JSON must be an array")?;
+ let guides = load_guides(&book.join("command-guides"), cmds)?;
+ let md = reference(cmds, &guides);
write(&book.join("src/reference/commands.md"), &md)?;
let gen_dir = book.join("src/generated");
@@ -81,18 +84,28 @@ fn json_files(dir: &Path) -> Result<Vec<std::path::PathBuf>, String> {
}
/// The command reference page: one section per toolbar tab and panel, in registry order.
-fn reference(cmds: &[Value]) -> String {
+fn reference(cmds: &[Value], guides: &BTreeMap<String, String>) -> String {
let mut md = format!(
"# Command reference\n\nBrowse commands by their names and default keyboard shortcuts. \
Entries are organized by command group and panel; ungrouped commands follow by area.\n\n\
For step-by-step instructions, start with the [window tour](../guide/ui-tour.md), \
[sketching guide](../guide/sketching.md) or [solid features guide](../guide/features.md). \
- Each entry links to a related guide when one is available.\n\n\
+ Practical command guides below explain prerequisites, options and examples in place. \
+ Entries without a practical guide link to an overview instead. \
+ [Contribute a guide, tip, demo or model link](../dev/command-guides.md).\n\n\
Expand **Automation details** for the command ID and parameters used by scripts, the CLI and MCP. \
In that notation, `?` marks an optional parameter and `expr` means a number or an expression with units.\n\n\
This catalog is generated from `solidcraft-cli commands` by `cargo xtask book` ({} commands).\n",
cmds.len()
);
+ let practical: Vec<_> = cmds.iter().filter(|c| guides.contains_key(command_text(c, "id"))).collect();
+ if !practical.is_empty() {
+ md.push_str("\n**Practical guides:**\n\n");
+ for command in practical {
+ md.push_str(&format!("- {}\n", command_link(command)));
+ }
+ md.push('\n');
+ }
let mut sections: Vec<(String, Vec<&Value>)> = Vec::new();
for tab in TABS {
for c in cmds.iter().filter(|c| command_text(c, "tab") == *tab) {
@@ -109,6 +122,7 @@ fn reference(cmds: &[Value]) -> String {
for (title, list) in sections {
md.push_str(&format!("\n## {}\n\n", prose(&title)));
for c in list {
+ md.push_str(&format!("<a id=\"{}\"></a>\n\n", command_anchor(command_text(c, "id"))));
let label = command_text(c, "label").trim();
md.push_str(&format!("### {}\n\n", prose(if label.is_empty() { "Unnamed command" } else { label })));
let tab = command_text(c, "tab").trim();
@@ -121,7 +135,10 @@ fn reference(cmds: &[Value]) -> String {
if !shortcut.is_empty() {
md.push_str(&format!("**Default keyboard shortcut:** {}\n\n", prose(shortcut)));
}
- if let Some((label, path)) = guide(c) {
+ if let Some(text) = guides.get(command_text(c, "id")) {
+ md.push_str(text);
+ md.push_str("\n\n");
+ } else if let Some((label, path)) = guide(c) {
md.push_str(&format!("Read the [{label}]({path}).\n\n"));
}
md.push_str("<details>\n<summary>Automation details</summary>\n\n");
@@ -143,6 +160,73 @@ fn reference(cmds: &[Value]) -> String {
md
}
+/// Hand-authored Markdown is reviewed documentation, separate from registry metadata.
+/// Unknown filenames fail the build rather than silently dropping a renamed command's guide.
+fn load_guides(dir: &Path, cmds: &[Value]) -> Result<BTreeMap<String, String>, String> {
+ let mut guides = BTreeMap::new();
+ let entries = std::fs::read_dir(dir).map_err(|e| format!("command guides {}: {e}", dir.display()))?;
+ for entry in entries {
+ let path = entry.map_err(|e| format!("command guides: {e}"))?.path();
+ if path.extension().is_none_or(|ext| ext != "md") {
+ continue;
+ }
+ let id = path.file_stem().and_then(|stem| stem.to_str()).ok_or_else(|| format!("invalid guide filename: {}", path.display()))?;
+ if !cmds.iter().any(|c| command_text(c, "id") == id) {
+ return Err(format!("command guide {}: unknown command `{id}`", path.display()));
+ }
+ let text = std::fs::read_to_string(&path).map_err(|e| format!("command guide {}: {e}", path.display()))?;
+ if text.trim().is_empty() {
+ return Err(format!("command guide {} is empty", path.display()));
+ }
+ guides.insert(id.to_string(), command_links(&text, cmds).map_err(|e| format!("command guide {}: {e}", path.display()))?);
+ }
+ Ok(guides)
+}
+
+/// A small explicit book directive; ordinary Markdown links, tables and images stay untouched.
+fn command_links(text: &str, cmds: &[Value]) -> Result<String, String> {
+ let mut output = String::new();
+ let mut rest = text;
+ while let Some((before, link)) = rest.split_once("{{#command") {
+ output.push_str(before);
+ // Other directive names (for example {{#commands ...}}) are not ours.
+ if link.starts_with(|c: char| !c.is_whitespace() && c != '}') {
+ output.push_str("{{#command");
+ rest = link;
+ continue;
+ }
+ let (id, after) = link.split_once("}}").ok_or("unterminated {{#command ...}} link")?;
+ let id = id.trim();
+ if id.is_empty() {
+ return Err("missing command ID in {{#command ...}} link".into());
+ }
+ let command = cmds.iter().find(|c| command_text(c, "id") == id).ok_or_else(|| format!("unknown related command `{id}`"))?;
+ output.push_str(&command_link(command));
+ rest = after;
+ }
+ output.push_str(rest);
+ Ok(output)
+}
+
+fn command_link(command: &Value) -> String {
+ let id = command_text(command, "id");
+ let label = command_text(command, "label").trim();
+ format!("[{}](#{})", prose(if label.is_empty() { id } else { label }), command_anchor(id))
+}
+
+/// Keep dotted command IDs readable, with an unambiguous escape for any other input byte.
+fn command_anchor(id: &str) -> String {
+ let mut anchor = String::from("command-");
+ for byte in id.bytes() {
+ if byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'_') {
+ anchor.push(char::from(byte));
+ } else {
+ anchor.push_str(&format!("-{byte:02x}"));
+ }
+ }
+ anchor
+}
+
fn command_text<'a>(command: &'a Value, key: &str) -> &'a str {
command.get(key).and_then(Value::as_str).unwrap_or_default()
}
@@ -198,6 +282,10 @@ mod tests {
use super::*;
use serde_json::json;
+ fn reference(cmds: &[Value]) -> String {
+ super::reference(cmds, &BTreeMap::new())
+ }
+
fn decoded_code(text: &str) -> String {
text.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#39;", "'").replace("&amp;", "&")
}
@@ -288,4 +376,94 @@ mod tests {
}
assert!(guide(&json!({"id":"future.unlisted","tab":"NEW WORKSPACE"})).is_none());
}
+
+ #[test]
+ fn practical_content_is_inline_and_automation_stays_complete() {
+ let cmds = [
+ json!({"id":"solid.extrude","label":"Extrude","tab":"SOLID","params":"distance: expr"}),
+ json!({"id":"sheet.hem","label":"Hem","tab":"SHEET METAL","params":"edges; length"}),
+ ];
+ let text = "Choose a closed region.\n\n#### Options\n\n| Choice | Effect |\n|---|---|\n| Distance | Size of the block |\n\nSee {{#command sheet.hem}}.\n\n![Example](../generated/bracket.png)";
+ let guides = BTreeMap::from([("solid.extrude".into(), command_links(text, &cmds).unwrap())]);
+ let md = super::reference(&cmds, &guides);
+ assert!(md.contains("<a id=\"command-solid.extrude\"></a>"));
+ assert!(md.contains("| Distance | Size of the block |"));
+ assert!(md.contains("See [Hem](#command-sheet.hem)."));
+ assert!(md.contains("![Example](../generated/bracket.png)"));
+ assert!(!md.contains("Read the [solid features guide]"), "an inline guide replaces the generic overview link");
+ assert!(md.contains("Read the [sheet metal guide]"), "unwritten entries keep their overview");
+ assert!(md.find("Choose a closed region.").unwrap() < md.find("<details>").unwrap());
+ assert!(md.contains("<code>solid.extrude</code>"));
+ assert!(md.contains("distance: expr</code></pre>"));
+ assert_eq!(md.matches("<details>").count(), 2);
+ }
+
+ #[test]
+ fn related_command_links_use_current_labels_and_refuse_stale_ids() {
+ let cmds = [json!({"id":"sheet.hem","label":"Hem [updated]"})];
+ assert_eq!(
+ command_links("Use {{#command sheet.hem}} twice: {{#command sheet.hem}}.", &cmds).unwrap(),
+ "Use [Hem \\[updated\\]](#command-sheet.hem) twice: [Hem \\[updated\\]](#command-sheet.hem)."
+ );
+ assert!(command_links("{{#command missing.tool}}", &cmds).unwrap_err().contains("unknown related command"));
+ assert!(command_links("{{#command sheet.hem", &cmds).unwrap_err().contains("unterminated"));
+ for unfinished in ["{{#command", "{{#command\t", "{{#command sheet.hem}"] {
+ assert!(command_links(unfinished, &cmds).unwrap_err().contains("unterminated"));
+ }
+ for empty in ["{{#command}}", "{{#command }}", "{{#command\n}}"] {
+ assert!(command_links(empty, &cmds).unwrap_err().contains("missing command ID"));
+ }
+ assert_eq!(command_links("{{#command\t sheet.hem\n}}", &cmds).unwrap(), "[Hem \\[updated\\]](#command-sheet.hem)");
+ let other = "{{#commands sheet.hem}} then {{#command sheet.hem}}";
+ assert_eq!(command_links(other, &cmds).unwrap(), "{{#commands sheet.hem}} then [Hem \\[updated\\]](#command-sheet.hem)");
+ let ordinary = "[Demo](https://example.com/demo) and `distance: 20`";
+ assert_eq!(command_links(ordinary, &cmds).unwrap(), ordinary);
+ }
+
+ #[test]
+ fn practical_index_lists_only_available_guides_with_current_safe_labels() {
+ let cmds = [
+ json!({"id":"solid.extrude","label":"Extrude [updated]"}),
+ json!({"id":"sheet.flange","label":"Flange"}),
+ json!({"id":"sheet.hem","label":" "}),
+ ];
+ let guides = BTreeMap::from([("sheet.hem".into(), "Hem guide".into()), ("solid.extrude".into(), "Extrude guide".into())]);
+ let md = super::reference(&cmds, &guides);
+ let index = md.split("**Practical guides:**\n\n").nth(1).unwrap().split("\n## ").next().unwrap();
+ assert_eq!(index, "- [Extrude \\[updated\\]](#command-solid.extrude)\n- [sheet.hem](#command-sheet.hem)\n\n");
+ assert!(!reference(&cmds).contains("**Practical guides:**"));
+ }
+
+ #[test]
+ fn stable_command_anchors_cannot_inject_markup_or_collide_with_escaped_ids() {
+ assert_eq!(command_anchor("solid.extrude"), "command-solid.extrude");
+ assert_eq!(command_anchor("odd.<tag>&id"), "command-odd.-3ctag-3e-26id");
+ assert_ne!(command_anchor("odd.<tag>"), command_anchor("odd.-3ctag-3e"));
+ }
+
+ #[test]
+ fn guide_files_load_without_a_hardcoded_list_and_refuse_orphaned_or_empty_entries() {
+ struct Fixture(std::path::PathBuf);
+ impl Drop for Fixture {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+ }
+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
+ let path = std::env::temp_dir().join(format!("solidcraft-book-guides-{}-{stamp}", std::process::id()));
+ // Atomic creation establishes ownership of this fresh directory before cleanup.
+ std::fs::create_dir(&path).unwrap();
+ let dir = Fixture(path);
+ let cmds = [json!({"id":"solid.extrude","label":"Extrude"}), json!({"id":"sheet.hem","label":"Hem"})];
+ let source = "A readable guide.\n\nSee {{#command sheet.hem}}.";
+ std::fs::write(dir.0.join("solid.extrude.md"), source).unwrap();
+ std::fs::write(dir.0.join("notes.txt"), "not a guide").unwrap();
+ let guides = load_guides(&dir.0, &cmds).unwrap();
+ assert_eq!(guides.len(), 1);
+ assert_eq!(guides.get("solid.extrude").unwrap(), "A readable guide.\n\nSee [Hem](#command-sheet.hem).");
+ assert!(load_guides(&dir.0, &[]).unwrap_err().contains("unknown command"));
+ assert!(load_guides(&dir.0.join("missing-directory"), &cmds).is_err());
+ std::fs::write(dir.0.join("solid.extrude.md"), " \n").unwrap();
+ assert!(load_guides(&dir.0, &cmds).unwrap_err().contains("is empty"));
+ }
}