Hand edits
The playground’s Select mode edits the source (see Fix it by hand in the playground). Free edit changes only the drawn geometry. Its result is a changeset that records where the user put things the engine placed elsewhere. It is stored in two ways, one for each job:
- In the map file, to reproduce the user’s map: one
%%metro edits:line that every render applies (see Edits in the map file). - In an edits file (
.edits.json), to show the engine’s developers what the user wanted.
How edits apply
Section titled “How edits apply”Edits override the finished RenderPlan.
nf_metro.edits.rebase_and_apply applies them between build_render_plan and emit_render_plan.
Routing does not run again, so the output is exactly the edited geometry.
The normal renderer draws it and recomputes bridges, chevrons and the canvas size from the edited routes.
The editor snaps each drag to the grid and the angle rules, then sends it to the Pyodide worker as a gesture: the target and its after value.
The worker builds the engine’s plan once per map and set of render options (nf_metro.api.editable_engine_plan) and keeps it across edits.
nf_metro.api.render_editable folds each gesture into the changeset with fold_edit, applies it, and returns the SVG, the canonical changeset and the geometry for the overlay handles.
Editing rules
Section titled “Editing rules”A gesture can put things where the engine would not, but the result always follows these rules.
apply_edits ends with one pass (nf_metro.edits.rules) over every route an edit changed, so every gesture gets the same rules.
| Rule | What it means | Where it lives |
|---|---|---|
| Map angles | Every segment an edit makes is horizontal, vertical, 45 degrees, or an S-transition between parallel runs no wider than diagonal_run. Inside a section an S-transition may rise any distance, like engine fans. Between sections, a step of more than one row becomes a riser: straight across with a rounded turn at each end, like the engine’s L-shaped corridors. Any other segment is replaced by a connector in that style. Untouched engine segments stay as drawn. Dragging a transition slides it along its runs. | rules.normalize, rules.allowed_segment; transition sliding and octilinear bends in the editor |
| No doubling back | No zero-length segments, no spikes, no climb that reverses. When a moved end passes the point a climb started, the climb and its corner are dropped and the end attaches further along. | rules.normalize, rules.moved_endpoint |
| Anchors and riders | Stations anchor routes. Ports, junctions and terminus file icons ride with a dragged run. A file icon joined straight to a station moves with it; one joined through turns stays put. A section move carries its content and any free node that only fans its lines in or out. A free node moved sideways without room to turn is pushed along its line until an S-transition fits. | apply.carried_nodes, apply._rides_along, apply._riders |
| Minimal disturbance | A moved end reshapes its route only up to the nearest point it can attach to; the far end is untouched. The vertex before the end slides along its segment so both keep their angles. If that fails, the end becomes a 45-degree connector. A short route that is only a connector is redrawn whole, keeping its curve where it was while it fits. | rules.moved_endpoint |
| Bundles stay bundles | A bundle with a reshaped lane is rebuilt as parallel offsets of one lane (an untouched one if possible), keeping lane order and spacing. A bundle that closes up or opens out keeps each lane’s own shape. Corners are concentric: the inner lane takes the base radius and each outer lane adds its offset. A drag moves the whole bundle; hold Cmd/Ctrl to move one lane. A lane reorder covers the whole run of those lines and spreads to every bundle on that run where the lines had the same relative order. Hand-drawn lane shapes move with their lanes. Where edits leave one line’s route ends apart at a node, the ends move onto one of them (a hand-drawn route first, then a reordered lane, then the widest bundle), so a line never breaks at a node. Touched rows then settle (see Same line, same row). | rules.offset_polyline, _Working.rebuild_bundle, _Working.nest_corners, apply._reordered_with, _Working.reconnect_lines |
| Fans stay symmetric | Only diagonal transitions a move shifted are realigned; risers and engine transitions that still fit stay. A realigned route leaves or joins a shared node at the same transition distance as its untouched siblings (same line first). If every route there was reshaped, they share the tightest distance, so splits and merges stay mirrored. Lanes of one bundle move as one and are never aligned to each other. Sliding a transition by hand snaps to its siblings, with a guide. | _Working.align_fans, rules.aligned_transition; the editor (alignToFan) |
| Same line, same row | Along a row, each line joined by straight runs sits on one coordinate. Lines of one color joining a node from the same side share one transition. After a move or lane reorder, nodes joined by near-straight runs (within the map’s lane spread) settle so those runs are exactly straight, moving as little as possible. Stations weigh far more than ports and junctions, and the node just moved is favoured. Transitions on other lines absorb the step. Only steps the edits made are settled; engine-drawn steps (fans, rail spreads) stay. The threshold stays below the editor’s snap step, so a deliberate move is never undone. A settle that would stack two nodes, or a row whose runs disagree, is left as drawn. Ports never leave their section edge. | _settle_around, _row_shifts, _section_lane_step, _Working.align_fans |
| Grid | Moves snap to half the station pitch (geometry.pitch). Every move then snaps, within half a step, into a straight line with the fixed run at its far end; this beats section-edge alignment. A straight run dragged sideways snaps its bundle to the center of the gap between the sections on either side, within half a step. Alt turns off the grid, not the angle rules. | the editor (snapDelta) |
| Containment | A section grows to keep its stations at the engine’s clearance from its edges, unless the user resized it. | _Working.grow_sections |
| Stations stay clear | A changed route drawn through a station it does not serve is reported (ApplyReport.warnings, shown in the editor and by nf-metro render --edits). | rules.crossed_stations |
Every edit already follows these rules, so a difference from the engine is a layout decision to examine, not a drawing quirk.
Edits in the map file
Section titled “Edits in the map file”Save → Map + edits appends the changeset to the map as its last line.
In this map, Reporting was dragged half a row down to tuck in beside Alignment, something a grid directive cannot do since it moves whole rows, then the legend was dragged into the freed corner and the canvas fitted.
The page renders it with no extra options; the Without edits tab shows the engine’s layout:
Mermaid source
%%metro title: Hand edits%%metro line: dna | DNA%%metro line: rna | RNA
graph LR subgraph prep [Preprocessing] fastqc[FastQC] trim[Trimming] fastqc -->|dna,rna| trim end subgraph align [Alignment] bwa[BWA] star[STAR] end subgraph report [Reporting] multiqc[MultiQC] end trim -->|dna| bwa trim -->|rna| star bwa -->|dna| multiqc star -->|rna| multiqc
%%metro edits: v1.H4sIAAAAAAACE13M3QqDMAyG4XvJcZHOH4TeypBSNR2CtpJmnoj3vghatp2Fl3zPDsHbBZmi3ZDSFAMYqApdaFCA48QJzHOHuEpe4oY24cDnl4L7MkC4RmJJPfpIKIumLAutWmE6Bc4zUo6P5qyH-kZnfGEYBbgOA7lkspKZKut_spVa_4h-Yju4sLkk8-swkMsNejcnzBLTG4_u-AB37buCDwEAAARendered map
The payload is the JSON {"nf_metro_version": …, "edits": […]}, in one of two forms:
- Encoded (what the playground writes):
v<version>.followed by the gzipped JSON in unpadded base64url. - Raw: the JSON itself on one line, with a
"version"key, as Save → Map + edits (uncompressed) andembed_edits(..., raw=True)write it.
The edits are the same entries as in an edits file, before included, so the changeset rebases when the source or the engine changes.
Nobody edits the line by hand; nf-metro info counts the edits and nf-metro check-edits map.mmd measures them.
- Parsing. The
editsdirective decodes the payload ontoMetroGraph.hand_edits. An unreadable or newer payload is warned about and ignored, so the map renders with the engine’s layout. With two edits lines, the last wins. - Rendering.
render_graph_result,render_svg,render_htmland the gallery build go throughapply_hand_edits: the caller’s edits if given, elsegraph.hand_edits. So the CLI,render-manyand<Metro>embeds draw them with no option, andedits=()(orRenderConfig(edits=()),render --no-edits, therender-manykeyno_edits) draws the engine’s layout. A<Metro>embed of a map with edits shows both drawings, on two tabs.editable_engine_plannever applies them; the playground sends its changeset with each render. - The playground. Text entering the editor with an edits line (an opened file, a paste, an example, a link) loses the line, and its changeset replaces the current hand edits.
The editor shows the line the map would be saved with, read-only, under its last line.
Save → Map (labeled Map + edits while there are some) writes the line from the current changeset, and drops it when there are none.
A docs page’s “open in playground” link carries the whole source, so a map with an edits line opens with its edits, in Free edit (
?mode=free-edit). - Size. The decoded payload is capped at 4 MiB, the same cap as a share link.
The edits file
Section titled “The edits file”An edits file stores the net change from the engine’s layout to the user’s map, never the steps taken.
Each changed target has one entry with the engine’s value (before) and the user’s (after).
Ten drags of one section give one entry; a station dragged away and back gives none.
Undo history stays in the browser.
canonicalize applies these rules for every producer, including the CLI.
{ "format": "nf-metro-edits", "version": 1, "nf_metro_version": "3.0.0", "source_sha256": "…", "source": "%%metro title: …", "render_options": { "theme": "nfcore", "mode": null, "layout_options": { "permissive": true } }, "comment": "The QC branch should sit below the trunk, not above it", "baseline": { "sections": {}, "stations": {}, "ports": {}, "routes": {}, "bundles": {} }, "edits": [ { "op": "section_bbox", "section": "align", "before": { "x": 0, "y": 0, "w": 300, "h": 120 }, "after": { "x": 0, "y": 0, "w": 340, "h": 150 } }, { "op": "bundle_order", "bundle": "trim->align", "before": ["dna", "rna"], "after": ["rna", "dna"] }, { "op": "route_shape", "route": "fastqc->trim:qc", "before": [ [80, 136], [140, 136] ], "after": [ [80, 136], [100, 136], [124, 160], [140, 160] ] } ], "result": { "…": "same shape as baseline" }}The file includes the full source and the version of nf-metro that made it, so nobody needs the playground to read it.
The JSON Schema ships as nf_metro/edits/schema.json (nf_metro.edits.edits_schema()).
An optional files object maps a path the source names (a %%metro logo: image’s place in its repo) to the image the playground previewed there, as a data URI, so opening the file restores the preview; nf-metro itself always reads the real file.
baseline and result are geometry snapshots (snapshot_geometry) of the engine’s plan and the edited plan.
Sections, stations and ports are kept in full as layout context.
Routes and bundles are kept only where the edits changed them.
Edit operations
Section titled “Edit operations”op | Target | Values | Meaning |
|---|---|---|---|
move_section | section id | [x, y] box top-left | The section belongs here. Its stations, ports, labels and internal routes move with it, and routes crossing its border stay attached. |
section_bbox | section id | {x, y, w, h} | The section box should be this size and shape. Its content stays where it is; the header moves with the box’s top-left corner. |
move_station | station id | [x, y] marker center | The station belongs here. Its label moves with it, and the ends of its routes follow. |
move_port | port id (<section>__<entry/exit>_<side>, or a fork or merge junction) | [x, y] | The section’s entry or exit point belongs here. The ends of routes on it follow. |
move_junction | junction id (a hidden bypass or convergence node) | [x, y] | The line’s hidden turn or join belongs here. The ends of routes on it follow. |
move_legend | legend (always "legend") | [x, y] box top-left | The legend belongs here. The canvas grows to hold it. |
bundle_order | bundle id (<source>-><target>) | line ids, left to right across the direction of travel | The lines on this edge should run in this lane order. |
route_shape | route id (<source>-><target>:<line>) | the whole drawn polyline, end points included | This route should be drawn along this path. Source or target may be a port or junction id; the snapshot’s from/to give the real stations at either end. |
fit_canvas | canvas (always "canvas") | {x, y, w, h} window, or true | The window of the map the SVG shows: its viewBox, with the title and logo at its top-left. It grows on any side to keep content in view. The editor’s Fit canvas sets it once, trimmed round the content with the engine’s margins; true refits it on every render. Edits never move coordinates for it. Not measured by check-edits. |
Applying a changeset
Section titled “Applying a changeset”Ids are built from what the target is: its section, side, port and line.
A port is <section>__<entry/exit>_<side>.
The junction where an exit port’s lines split is __junction_<exit port>, and the one where a line merges into an entry port is __merge_<entry port>__<line>.
Both move with move_port.
Hidden bypass and convergence nodes, the move_junction targets, are named after the station they route around or lead into.
A route is <source>-><target>:<line>, with a #n suffix only for the rare repeat of one edge.
So a change elsewhere in the source leaves an id alone.
It changes when the thing it names does: a renamed station or section, or a re-layout that moves a port to another side.
rebase_and_apply runs three steps:
- Rebase.
rebase_editscarries the changeset onto the current plan. An edit whosebeforeno longer matches the engine (the theme, options or source changed) keeps the user’s adjustment relative to the engine’s new value. A move keeps its offset, a route shape follows its ends, and a lane order keeps the order of the lines it shares with the bundle. A line that joins the bundle takes the engine’s lane, and one that leaves it is dropped. These edits are reported as drifted. - Apply. Ops apply in the order of the table above. A section move carries its content before that content’s own edits apply. A route’s explicit shape wins over the end adjustment that a node move or lane reorder would make.
- Reattach and settle. Every route end is reattached to its node at the engine’s offset for its lane, so a line never comes away from a station, port, junction or file icon. Rows then settle (see Same line, same row). This happens on every load, not only after a gesture.
An edit whose target is missing is skipped and reported. A gesture that moves a node onto a visible station, or onto a node it shares a route with, is refused.
The playground keeps the changeset as the user last edited it, not a rebased copy. Switching to another theme and back restores the edits exactly.
Two playground actions are gestures that fold into existing ops:
- Fit box to content (
fit_section) sets the section’ssection_bboxto its content with the engine’s usual padding, and moves its ports onto the new edges. - A lane reorder writes one
bundle_orderentry for each bundle it covers.
Reading an edits file as engine feedback
Section titled “Reading an edits file as engine feedback”- Measure. Run
nf-metro check-edits FILE.edits.json. It renders the embeddedsourcewith itsrender_optionsand no edits, then reports how far the engine is from each edit’safter(in pixels, or lanes out of place for a bundle).--jsongives the same report for scripts. - Read each edit for its layout meaning. A resized or moved
section_bboxis usually a placement or spacing complaint, so check section placement and gaps. Abundle_orderis a lane-order decision (line order, fan and convergence planning). Aroute_shapeis a routing complaint: comparebeforeandafterfor a kink, detour, crossing or missing runway. Amove_portnames a port-side or port-position decision. Thecommentfield is the user’s own words. Usenf-metro explainandsrc/nf_metro/layout/CONTRACT.mdto find the stage that owns the decision. - Fix the engine, not the map. Write a failing invariant test that captures the edit’s intent, then fix the stage that owns the decision. Follow the usual layout-change gates in Testing.
- Accept by measurement. The fix is done when
check-editsreports the edit as reproduced and the gallery render diff shows no regressions. Some edits are aesthetic preferences rather than defects. Say so instead of bending the engine to fit one map.
nf-metro check-edits map.edits.jsonnf-metro render map.mmd --edits map.edits.json -o fixed.svgCode map
Section titled “Code map”| Piece | Where |
|---|---|
| Model, JSON, canonical form | src/nf_metro/edits/model.py |
The %%metro edits: line | src/nf_metro/edits/embed.py; the “free edit” section of website/public/playground/app.js |
| Ids and bundles | route_ids, bundle_members, RenderPlan.route_index and RenderPlan.bundles in src/nf_metro/render/plan.py |
| Snapshots, engine values | src/nf_metro/edits/geometry.py |
| Editing rules and routing | src/nf_metro/edits/rules.py |
| Applying and folding | src/nf_metro/edits/apply.py |
| Measuring against the engine | src/nf_metro/edits/check.py |
| Render hook | render_svg(..., edits=), RenderConfig.edits |
| Playground entry points | nf_metro.api.editable_engine_plan and render_editable, called from website/public/playground/worker.js |
| Playground UI | the “free edit” and “grid dragging” sections of website/public/playground/app.js |
| CLI | nf-metro render (applies a map’s own edits), nf-metro render --edits, nf-metro check-edits |