You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
SVG flatten: Viewer API, canvasnet flatten command and Pandoc filter support for composite SVGs - #130
This adds SVG flatten, so a composite SVG (an SVG whose <image href> links Mermaid, OpenSCAD, Vega-Lite, PDF, PPTX or VSDX) shows up in the docs PDF. Plain SVGs stay fully vector.
The problem: the docs pipeline is Pandoc → HTML → WeasyPrint → PDF. WeasyPrint draws plain SVGs as vectors, but it can't draw an <image href="flow.mmd">. So composite SVGs, such as the composition dashboard from #128, came out as empty panels.
The design (approved in review): the logic lives in the Viewer library, the CLI is a thin command, and the filter is a few lines.
Viewer (DemaConsulting.CanvasNet.Viewer.Imaging):SvgFlattener.Execute(SourceInfo, FlattenRequest) returns a FlattenResult.
It draws the SVG once through the existing SVG image resolver, with a recording wrapper around it. The renderer already supplies each image's placement size after viewBox, transforms and preserveAspectRatio.
Every link CanvasNet draws and a plain renderer can't is rendered at that size × Scale through the existing sandbox, fragments, budgets and loop protection. That includes .mmd, .scad, .vl.json, .pdf#page=, .pptx, .vsdx, and SVGs that themselves link these.
Only those href/xlink:href values are replaced, with data:image/png;base64,.... Everything else is copied byte for byte.
The result lists the replaced and rebased links plus diagnostics. Flattened == false means nothing was replaced, so keep the original.
CLI:canvasnet flatten <in.svg> -o <out.svg> [--scale N] [--strict] [--no-clobber] [--json]. Its JSON has render's shape plus flattened, replaced[] and rebased[]. It has a help topic, enforced against the user guide by the drift test.
Pandoc filter (canvasnet.lua, FILTER_VERSION 11):
It calls canvasnet flatten only when an .svg picture links a CanvasNet format; a plain SVG never even starts the tool.
The cache key includes the linked files' fingerprints, scale, the tool version and the drawing's folder.
Docs: Mermaid guide Example 56 now shows the composition dashboard inline. Requirements, design, verification, SysML2, review sets and the user guide sections are added.
Before / after (page 1 of the WeasyPrint 70 PDF, rendered by CanvasNet at 110 dpi)
Limits:
Input must be UTF-8; an SVG with a DOCTYPE is refused, the same as render refuses it.
Only <image> links are replaced; external <use>, CSS url() and feImage are left as written.
A link that is never drawn stays a link, with the svg-flatten-image-not-drawn warning.
Caps: 64 pictures, 4 levels of nesting, 64 million pixels, and a 64 MiB output.
data: links in the input are never followed.
When the copy goes to another folder, relative raster links are rebased so they still resolve.
Type of Change
Bug fix (non-breaking change which fixes an issue)
New feature (non-breaking change which adds functionality)
Breaking change (fix or feature that would cause existing functionality to not work as expected)
Documentation update
Code quality improvement
Related Issues
There is no issue to close; this was requested in review, as option B of the docs-filter SVG discussion.
Pre-Submission Checklist
Before submitting this pull request, ensure you have completed the following:
Build and Test
Code builds successfully and all tests pass: pwsh ./build.ps1 passed (72,576 tests, 0 failed, 33 skipped symbolic-link tests)
Code produces zero warnings
Code Quality
New code has appropriate XML documentation comments
Static analyzer warnings have been addressed
Quality Checks
Please run the following checks before submitting:
All linters pass: pwsh ./lint.ps1 passed (exit 0)
docs/filters/test-canvasnet.ps1 passed. It covers:
a plain SVG left untouched;
composite and nested composite SVGs flattened;
cache reuse, and invalidation on a new scale or an edited link;
a dotnet weasyprint end-to-end check.
Testing
Added unit tests for new functionality
Updated existing tests if behavior changed
All tests follow the AAA (Arrange, Act, Assert) pattern
Test coverage is maintained or improved
Documentation
Updated README.md (if applicable). Not applicable.
Updated docs/ documentation (if applicable)
Added code examples for new features (if applicable)
Updated requirements.yaml (if applicable)
Additional Notes
Option C, vector SVG/PDF output writers that would keep Mermaid and Vega-Lite vector inside composites, stays on the backlog.
… an SVG with PNG data URIs
SvgFlattener.Execute(SourceInfo, FlattenRequest) draws an SVG once with the resolver of render, records the links the drawing shows at their placement size, draws the Mermaid, OpenSCAD, Vega-Lite, PDF, PPTX, and VSDX links (and nested SVG files that link them) as PNG pictures, and writes a copy in which only those href values change. Relative links that are left are rebased when the copy is in another folder. Unit, subsystem, and system tests.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
flatten <in.svg> -o <out.svg> [--scale N] [--strict] [--no-clobber] is a thin front end of SvgFlattener with a text and a JSON result; nothing to flatten writes nothing and exits 0. The svg help topic gets a flatten section (mirrored by the Flatten Reference table of the user guide, checked by a drift test), the svg-flatten-image-not-drawn diagnostic, and a command example; the json and limits topics and the formats footer mention the command.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
An .svg picture whose image elements link a model, chart, diagram, or document page (directly or through nested SVG files) now points at a copy written by canvasnet flatten into docs/generated/canvasnet/, cached by a hash of the drawing and every file it links and honoring scale; a plain SVG is left alone without starting the tool, and a drawing with nothing to flatten leaves a .plain marker. FILTER_VERSION is 10. test-canvasnet.ps1 covers plain, composite, nested, hidden, cache, and scale cases, and checks with WeasyPrint that the flattened diagram reaches the PDF.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
… guide sections for SVG flatten
New units SvgFlattener (Viewer Imaging) and FlattenCommand (Tool Commands) with their reqstream requirements, design and verification documents, SysML2 part definitions, and review sets; the subsystem and system requirements, designs, verification documents, SysML2 models, and introductions list them. The tool, Viewer, and SVG user guides and the README describe the flatten command, the library operation, and the Pandoc filter support; xlink is added to the spelling dictionary.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…, JSON page
- canvasnet.lua: include the drawing's folder (relative to the cache folder) in the
flatten cache key, so the same drawing in another folder gets its own copy whose
rebased links lead to that folder; test-canvasnet.ps1 checks a moved drawing.
- SvgFlattener.RebaseLink: leave a link whose decoded path has a null character, or
that the file system cannot resolve (too long), as written instead of throwing.
- flatten --json: write a diagnostic's page, as render does.
- NamespaceDoc names SvgFlattener, FlattenRequest, and FlattenResult; Example 56 of
the Mermaid guide states the picture size precisely; .reviewmark.yaml spacing.
- Requirements, design, verification, and user guide updated with the new tests.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Three active moderate findings remain: the SVG dependency scan mishandles XML syntax and missing targets, and repeated links can render at a smaller placement than required.
This pull request adds SVG flattening across the Viewer library, the canvasnet flatten command, and the Pandoc documentation filter, rendering composite SVG links to CanvasNet-only formats as PNG data URIs while preserving vector content and ordinary links.
Changes:
Added the SvgFlattener API, placement-aware recording, link rewriting and rebasing, diagnostics, resource limits, and tests.
Added and registered the canvasnet flatten command with text and JSON output, help topics, documentation, and integration tests.
Updated the Pandoc filter to detect composite SVGs, invoke and cache flattening, track dependencies, and support WeasyPrint output.
…, one render per link
- canvasnet.lua: replace the regex scan of <image> tags with a small tokenizer that skips
comments, CDATA, processing instructions and a DOCTYPE, reads quoted attribute values
(a ">" inside one no longer ends the tag), and takes the effective link as SvgFlattener
does (href wins over xlink:href). A plain SVG still never starts the tool.
- canvasnet.lua: a link to a missing model/chart/diagram/document (directly or in a nested
SVG) now classifies the drawing as composite, so the tool reports svg-image-unresolved;
the cache key notes the file as missing, so creating it later flattens the drawing, and
the .plain marker keeps the tool's warnings and shows them on every build.
FILTER_VERSION 11.
- SvgFlattener.Recorder: the detection pass only records the largest placement of each
link; DrawRecorded then draws each link once at that size, so the image count and pixel
budget of FolderImageResolver are charged once per link. Single-use output is unchanged.
- Tests: filter checks for comment/CDATA/PI, quoted ">", and missing (also nested) diagrams;
Viewer tests for a repeated link against the image-count and pixel budgets.
- Design, verification, requirement test links and user guide updated.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
size starts as a byte count (document.Bytes.Length), but this update adds value.Length and link.Length, which are UTF-16 character counts. For a non-ASCII href this makes the pre-check disagree with the final UTF-8 output size and can reject a copy that is actually within MaxOutputBytes (for example, replacing a long Unicode path can reduce bytes while increasing character count). Compute both lengths with the strict UTF-8 encoding used by Encode before calling CheckSize.
NotDrawn is called with FindImageLinks(info.Path, ...), so it only checks the top-level SVG. If a shown nested SVG contains a hidden/unused CanvasNet-only <image> (for example outer.svg -> inner.svg, with inner.svg defining but never showing flow.mmd), Recorder never requests it and the nested SVG is not captured, but no svg-flatten-image-not-drawn diagnostic is produced. This silently leaves the link in a composite tree despite the documented guarantee that every never-drawn CanvasNet link is reported; diagnostics need to carry the nested SVG's links and origin as well.
…e pre-check, nested not-drawn links
- canvasnet.lua: the pre-scan takes a prefixed href as the legacy link only when its prefix
is bound to the XLink namespace (http://www.w3.org/1999/xlink) on the element or an
ancestor, tracking xmlns:<prefix> declarations per element scope as the XmlReader of
SvgFlattener.FindImageLinks does; an unrelated foo:href no longer starts the tool.
- SvgFlattener.Rewrite: the size checked while the copy is built is counted in UTF-8 bytes
(StrictUtf8.GetByteCount of the new and the old value), the same encoding Encode uses,
so a non-ASCII href no longer makes the pre-check disagree with the final size.
- FolderImageResolver.Requested (new RequestedImage record): every link any level asked
for, with the files that contain it and the name of the picture when drawn.
SvgFlattener.NotDrawnNested uses it to report svg-flatten-image-not-drawn for links of a
shown nested SVG file that it never shows, with the nested file as location and origin.
- Tests: filter checks for a foreign-namespace href (no tool) and a custom XLink prefix
(flattened); Viewer tests for a CJK href at the output limit and for hidden/shown
diagrams in a nested SVG; core tests for Requested and RequestedImage equality.
- Design, requirements, verification, SysML, review-set, user guides and svg help updated.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
UTF-8 size accounting (SvgFlattener.Links.cs): the size check during the rewrite now counts the new and old href values with the same strict UTF-8 encoding that Encode uses, so it agrees with the final CheckSize. Regression: NonAsciiHrefAtOutputLimit_CountsUtf8Bytes (a CJK href fits a limit of exactly the copy's size and is refused one byte under it).
Undrawn links in nested SVGs (SvgFlattener.cs): a new NotDrawnNested step finds each nested SVG the drawing showed and reports every CanvasNet-only link it never showed as svg-flatten-image-not-drawn. The location is that file's line and column, and the origin is the chain of files. Regressions: HiddenDiagramInNestedSvg_ReportsNotDrawnWithOrigin, plus a guard that a shown nested diagram is not reported.
This needed a small additive core API: FolderImageResolver.Requested, a read-only list of a new RequestedImage record (the link, the files that contain it, and the picture's name when drawn). The nested SVG's links are requested from inside the resolver, where the Viewer could not see them.
RequestedImage is a separate record rather than a change to EmbeddedImage, so existing equality is unaffected.
It is covered by core tests, a requirement (FolderImageResolver-Requested), design, verification and SysML updates, and the review set.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
A moderate active issue remains because the recorder classifies percent-encoded links before decoding, so valid Mermaid references can be rendered normally but omitted from flattening.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Decode href paths before classifying image extensions
The recorder classifies links from the raw href before percent-decoding, while FolderImageResolver decodes the path before choosing its source/extension. Thus a valid link such as href="flow%2Emmd" is resolved and drawn by normal SVG rendering, but KindOfName returns no Mermaid kind here, so the recorder never schedules it and flatten leaves it unchanged. Decode the path portion after removing the query/fragment before applying the same extension classification as the resolver.
…ent-decode
The recorder and the not-drawn checks classified a link from its raw text, while
FolderImageResolver cuts the query and fragment and percent-decodes the path before it
chooses a source, so href="flow%2Emmd" was drawn by normal SVG rendering but never
flattened.
- FolderImageResolver.DecodeReference (internal, shared with the Viewer through a new
InternalsVisibleTo grant): the cut-then-decode path the resolver chooses its source by;
ToRelativePath uses the same helper.
- SourceLoader.SvgImages.KindOfName classifies DecodeReference(href), so the Recorder and
the top-level and nested not-drawn checks agree with the resolver; a nested file is
classified by its file name with the new KindOfFile (no cutting or decoding).
- canvasnet.lua: the SVG pre-scan cuts at "?"/"#" first and then percent-decodes (one
candidate path, as the resolver reads it) for the hash and the composite detection.
- Tests: Viewer test for flow%2Emmd (flattened; hidden encoded link reported), core test
for DecodeReference, and a filter check that flow%2Emmd is flattened.
- Design, requirements and verification updated.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Previously missed finding (percent-encoded links), fixed in 832e24f. Flatten now classifies a link from the same path the resolver chooses its source by: query and fragment cut first, then percent-decoded, through the resolver's shared (internal) FolderImageResolver.DecodeReference. So href="flow%2Emmd" is a Mermaid diagram to both and is flattened. The Lua pre-scan cuts then decodes the same way. Regressions: PercentEncodedExtension_ClassifiedAsResolverReadsIt (Viewer, which fails on the old code), DecodeReference_CutsThenDecodes (core), and a filter check. A follow-up commit replaces the inline spell-check ignores for %2Emmd with one .cspell.yaml pattern for percent-escapes.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because the change has moderate and critical hidden issues involving incorrect handling of local file URIs and potential sandbox escapes during dependency scanning.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The change warrants human review because cross-platform link resolution can mishandle Windows drive-letter and UNC paths on Unix, potentially rebasing links unexpectedly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Pull Request
Description
This adds SVG flatten, so a composite SVG (an SVG whose
<image href>links Mermaid, OpenSCAD, Vega-Lite, PDF, PPTX or VSDX) shows up in the docs PDF. Plain SVGs stay fully vector.The problem: the docs pipeline is Pandoc → HTML → WeasyPrint → PDF. WeasyPrint draws plain SVGs as vectors, but it can't draw an
<image href="flow.mmd">. So composite SVGs, such as the composition dashboard from #128, came out as empty panels.The design (approved in review): the logic lives in the Viewer library, the CLI is a thin command, and the filter is a few lines.
DemaConsulting.CanvasNet.Viewer.Imaging):SvgFlattener.Execute(SourceInfo, FlattenRequest)returns aFlattenResult.Scalethrough the existing sandbox, fragments, budgets and loop protection. That includes.mmd,.scad,.vl.json,.pdf#page=,.pptx,.vsdx, and SVGs that themselves link these.href/xlink:hrefvalues are replaced, withdata:image/png;base64,.... Everything else is copied byte for byte.Flattened == falsemeans nothing was replaced, so keep the original.canvasnet flatten <in.svg> -o <out.svg> [--scale N] [--strict] [--no-clobber] [--json]. Its JSON hasrender's shape plusflattened,replaced[]andrebased[]. It has a help topic, enforced against the user guide by the drift test.canvasnet.lua,FILTER_VERSION11):canvasnet flattenonly when an.svgpicture links a CanvasNet format; a plain SVG never even starts the tool.scale, the tool version and the drawing's folder.Before / after (page 1 of the WeasyPrint 70 PDF, rendered by CanvasNet at 110 dpi)

Limits:
renderrefuses it.<image>links are replaced; external<use>, CSSurl()andfeImageare left as written.svg-flatten-image-not-drawnwarning.data:links in the input are never followed.Type of Change
Related Issues
There is no issue to close; this was requested in review, as option B of the docs-filter SVG discussion.
Pre-Submission Checklist
Before submitting this pull request, ensure you have completed the following:
Build and Test
pwsh ./build.ps1passed (72,576 tests, 0 failed, 33 skipped symbolic-link tests)Code Quality
Quality Checks
Please run the following checks before submitting:
pwsh ./lint.ps1passed (exit 0)docs/filters/test-canvasnet.ps1passed. It covers:scaleor an edited link;dotnet weasyprintend-to-end check.Testing
Documentation
Additional Notes
Option C, vector SVG/PDF output writers that would keep Mermaid and Vega-Lite vector inside composites, stays on the backlog.